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 | agpl-3.0 | 5911d8b27b0026faef4706e01682370848596494 | 0 | EntryPointKR/K-SPAM,EntryPointKR/K-Security | package cloud.swiftnode.kspam.listener;
import cloud.swiftnode.kspam.abstraction.SpamExecutor;
import cloud.swiftnode.kspam.abstraction.SpamProcessor;
import cloud.swiftnode.kspam.abstraction.deniable.DeniableInfoAdapter;
import cloud.swiftnode.kspam.abstraction.processor.AsyncLoginProcessor;
import cloud.swiftnode.kspam.abstraction.processor.SyncJoinProcessor;
import cloud.swiftnode.kspam.abstraction.processor.SyncLoginProcessor;
import cloud.swiftnode.kspam.util.Lang;
import cloud.swiftnode.kspam.util.Static;
import cloud.swiftnode.kspam.util.StaticStorage;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
/**
* Created by Junhyeong Lim on 2017-01-10.
*/
public class PlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public void onLogin(PlayerLoginEvent e) {
if (e.getResult() != PlayerLoginEvent.Result.ALLOWED) {
return;
}
final SpamExecutor executor = Static.getDefaultExecutor();
final DeniableInfoAdapter adapter = new DeniableInfoAdapter(false, e);
final Player player = e.getPlayer();
SpamProcessor processor = new SyncLoginProcessor(executor, adapter);
if (!processor.process()) {
adapter.setObj(player);
adapter.setDelayed(true);
Static.runTaskLaterAsync(new Runnable() {
@Override
public void run() {
if (player.isOnline()) {
new AsyncLoginProcessor(executor, adapter).process();
}
}
}, 20L);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onJoinHighest(PlayerJoinEvent e) {
/*
K-SPAM ์ AGPL ๋ผ์ด์ ์ค์ด๋ฉฐ ๊ฐ๋ฐ์, ํ๋ฌ๊ทธ์ธ ์ ๋ณด, ์์ค ์ ๊ณต์ด ์๋ฌด์
๋๋ค.
๋ฐ ๋ฉ์ธ์ง ์ ์ก ์ฝ๋๋ฅผ ์ ๊ฑฐ ์ ๋ฒ์ ์ฑ
์์ ๋ฌผ์ ์ ์์ต๋๋ค.
*/
Player player = e.getPlayer();
player.sendMessage(Lang.LAW_INFO.builder().prefix().build());
if (player.isOp() && StaticStorage.getNewVer().after(StaticStorage.getCurrVer())) {
player.sendMessage(Lang.UPDATE_INFO_NEW.builder().prefix().build());
player.sendMessage(Lang.NEW_VERSION.builder()
.single(Lang.Key.NEW_VERSION, StaticStorage.getNewVer())
.prefix().build());
player.sendMessage(Lang.CURRENT_VERSION.builder()
.single(Lang.Key.KSPAM_VERSION, StaticStorage.getCurrVer())
.prefix().build());
player.sendMessage(Lang.DOWNLOAD_URL.builder().prefix().build());
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onJoinLowest(PlayerJoinEvent e) {
SpamExecutor executor = Static.getDefaultExecutor();
DeniableInfoAdapter adapter = new DeniableInfoAdapter(false, e.getPlayer());
SpamProcessor processor = new SyncJoinProcessor(executor, adapter);
if (processor.process()) {
e.setJoinMessage(null);
}
}
@EventHandler
public void onQuit(PlayerQuitEvent e) {
StaticStorage.firstKickCachedSet.remove(e.getPlayer().getName().toLowerCase());
}
}
| src/main/java/cloud/swiftnode/kspam/listener/PlayerListener.java | package cloud.swiftnode.kspam.listener;
import cloud.swiftnode.kspam.abstraction.SpamExecutor;
import cloud.swiftnode.kspam.abstraction.SpamProcessor;
import cloud.swiftnode.kspam.abstraction.deniable.DeniableInfoAdapter;
import cloud.swiftnode.kspam.abstraction.processor.AsyncLoginProcessor;
import cloud.swiftnode.kspam.abstraction.processor.SyncJoinProcessor;
import cloud.swiftnode.kspam.abstraction.processor.SyncLoginProcessor;
import cloud.swiftnode.kspam.util.Lang;
import cloud.swiftnode.kspam.util.Static;
import cloud.swiftnode.kspam.util.StaticStorage;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
/**
* Created by Junhyeong Lim on 2017-01-10.
*/
public class PlayerListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public void onLogin(PlayerLoginEvent e) {
if (e.getResult() != PlayerLoginEvent.Result.ALLOWED) {
return;
}
final SpamExecutor executor = Static.getDefaultExecutor();
final DeniableInfoAdapter adapter = new DeniableInfoAdapter(false, e);
final Player player = e.getPlayer();
SpamProcessor processor = new SyncLoginProcessor(executor, adapter);
if (!processor.process()) {
adapter.setObj(player);
adapter.setDelayed(true);
Static.runTaskLaterAsync(new Runnable() {
@Override
public void run() {
if (player.isOnline()) {
new AsyncLoginProcessor(executor, adapter).process();
}
}
}, 20L);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onJoin(PlayerJoinEvent e) {
/*
K-SPAM ์ AGPL ๋ผ์ด์ ์ค์ด๋ฉฐ ๊ฐ๋ฐ์, ํ๋ฌ๊ทธ์ธ ์ ๋ณด, ์์ค ์ ๊ณต์ด ์๋ฌด์
๋๋ค.
๋ฐ ๋ฉ์ธ์ง ์ ์ก ์ฝ๋๋ฅผ ์ ๊ฑฐ ์ ๋ฒ์ ์ฑ
์์ ๋ฌผ์ ์ ์์ต๋๋ค.
*/
Player player = e.getPlayer();
player.sendMessage(Lang.LAW_INFO.builder().prefix().build());
SpamExecutor executor = Static.getDefaultExecutor();
DeniableInfoAdapter adapter = new DeniableInfoAdapter(false, player);
SpamProcessor processor = new SyncJoinProcessor(executor, adapter);
if (processor.process()) {
e.setJoinMessage(null);
}
if (player.isOp() && StaticStorage.getNewVer().after(StaticStorage.getCurrVer())) {
player.sendMessage(Lang.UPDATE_INFO_NEW.builder().prefix().build());
player.sendMessage(Lang.NEW_VERSION.builder()
.single(Lang.Key.NEW_VERSION, StaticStorage.getNewVer())
.prefix().build());
player.sendMessage(Lang.CURRENT_VERSION.builder()
.single(Lang.Key.KSPAM_VERSION, StaticStorage.getCurrVer())
.prefix().build());
player.sendMessage(Lang.DOWNLOAD_URL.builder().prefix().build());
}
}
@EventHandler
public void onQuit(PlayerQuitEvent e) {
StaticStorage.firstKickCachedSet.remove(e.getPlayer().getName().toLowerCase());
}
}
| Fix listener code
| src/main/java/cloud/swiftnode/kspam/listener/PlayerListener.java | Fix listener code | <ide><path>rc/main/java/cloud/swiftnode/kspam/listener/PlayerListener.java
<ide> }
<ide>
<ide> @EventHandler(priority = EventPriority.HIGHEST)
<del> public void onJoin(PlayerJoinEvent e) {
<add> public void onJoinHighest(PlayerJoinEvent e) {
<ide> /*
<ide> K-SPAM ์ AGPL ๋ผ์ด์ ์ค์ด๋ฉฐ ๊ฐ๋ฐ์, ํ๋ฌ๊ทธ์ธ ์ ๋ณด, ์์ค ์ ๊ณต์ด ์๋ฌด์
๋๋ค.
<ide> ๋ฐ ๋ฉ์ธ์ง ์ ์ก ์ฝ๋๋ฅผ ์ ๊ฑฐ ์ ๋ฒ์ ์ฑ
์์ ๋ฌผ์ ์ ์์ต๋๋ค.
<ide> */
<ide> Player player = e.getPlayer();
<ide> player.sendMessage(Lang.LAW_INFO.builder().prefix().build());
<del> SpamExecutor executor = Static.getDefaultExecutor();
<del> DeniableInfoAdapter adapter = new DeniableInfoAdapter(false, player);
<del> SpamProcessor processor = new SyncJoinProcessor(executor, adapter);
<del> if (processor.process()) {
<del> e.setJoinMessage(null);
<del> }
<ide>
<ide> if (player.isOp() && StaticStorage.getNewVer().after(StaticStorage.getCurrVer())) {
<ide> player.sendMessage(Lang.UPDATE_INFO_NEW.builder().prefix().build());
<ide> }
<ide> }
<ide>
<add> @EventHandler(priority = EventPriority.LOWEST)
<add> public void onJoinLowest(PlayerJoinEvent e) {
<add> SpamExecutor executor = Static.getDefaultExecutor();
<add> DeniableInfoAdapter adapter = new DeniableInfoAdapter(false, e.getPlayer());
<add> SpamProcessor processor = new SyncJoinProcessor(executor, adapter);
<add> if (processor.process()) {
<add> e.setJoinMessage(null);
<add> }
<add> }
<add>
<ide> @EventHandler
<ide> public void onQuit(PlayerQuitEvent e) {
<ide> StaticStorage.firstKickCachedSet.remove(e.getPlayer().getName().toLowerCase()); |
|
Java | apache-2.0 | 8127dfc9a1a70293b7c2cd86ef8c61bc800f7345 | 0 | vsilaev/java-continuations,vsilaev/tascalate-javaflow | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.javaflow.core;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Stack to store the frame information along the invocation trace.
*
* @author <a href="mailto:[email protected]">Torsten Curdt</a>
* @author <a href="mailto:[email protected]">Stephan Michels</a>
* @version CVS $Id: Stack.java 733503 2009-01-11 19:51:40Z tcurdt $
*/
public class Stack implements Serializable {
private static final Log log = LogFactory.getLog(Stack.class);
private static final long serialVersionUID = 2L;
private int[] istack;
private float[] fstack;
private double[] dstack;
private long[] lstack;
private Object[] ostack;
private Object[] rstack;
private int iTop, fTop, dTop, lTop, oTop, rTop;
protected Runnable runnable;
public Stack(Runnable pRunnable) {
istack = new int[10];
lstack = new long[5];
dstack = new double[5];
fstack = new float[5];
ostack = new Object[10];
rstack = new Object[5];
runnable = pRunnable;
}
public Stack(final Stack pParent) {
istack = new int[pParent.istack.length];
lstack = new long[pParent.lstack.length];
dstack = new double[pParent.dstack.length];
fstack = new float[pParent.fstack.length];
ostack = new Object[pParent.ostack.length];
rstack = new Object[pParent.rstack.length];
iTop = pParent.iTop;
fTop = pParent.fTop;
dTop = pParent.dTop;
lTop = pParent.lTop;
oTop = pParent.oTop;
rTop = pParent.rTop;
System.arraycopy(pParent.istack, 0, istack, 0, iTop);
System.arraycopy(pParent.fstack, 0, fstack, 0, fTop);
System.arraycopy(pParent.dstack, 0, dstack, 0, dTop);
System.arraycopy(pParent.lstack, 0, lstack, 0, lTop);
System.arraycopy(pParent.ostack, 0, ostack, 0, oTop);
System.arraycopy(pParent.rstack, 0, rstack, 0, rTop);
runnable = pParent.runnable;
}
public boolean hasDouble() {
return dTop > 0;
}
public double popDouble() {
if (dTop == 0) {
throw new EmptyStackException("pop double");
}
final double d = dstack[--dTop];
log.debug("pop double " + d + " " + getStats());
return d;
}
public boolean hasFloat() {
return fTop > 0;
}
public float popFloat() {
if (fTop == 0) {
throw new EmptyStackException("pop float");
}
final float f = fstack[--fTop];
log.debug("pop float " + f + " " + getStats());
return f;
}
public boolean hasInt() {
return iTop > 0;
}
public int popInt() {
if (iTop == 0) {
throw new EmptyStackException("pop int");
}
final int i = istack[--iTop];
log.debug("pop int " + i + " " + getStats());
return i;
}
public boolean hasLong() {
return lTop > 0;
}
public long popLong() {
if (lTop == 0) {
throw new EmptyStackException("pop long");
}
final long l = lstack[--lTop];
log.debug("pop long " + l + " " + getStats());
return l;
}
public boolean hasObject() {
return oTop > 0;
}
public Object popObject() {
if (oTop == 0) {
throw new EmptyStackException("pop object");
}
final Object o = ostack[--oTop];
ostack[oTop] = null; // avoid unnecessary reference to object
if(log.isDebugEnabled()) {
final String clazz = ReflectionUtils.getClassName(o);
final String clazzLoader = ReflectionUtils.getClassLoaderName(o);
log.debug("pop object "+ clazz + "/" + clazzLoader + " [" + o + "] ");
}
return o;
}
public boolean hasReference() {
return rTop > 0;
}
public Object popReference() {
if (rTop == 0) {
throw new EmptyStackException("pop reference");
}
final Object o = rstack[--rTop];
rstack[rTop] = null; // avoid unnecessary reference to object
if(log.isDebugEnabled()) {
final String clazz = ReflectionUtils.getClassName(o);
final String clazzLoader = ReflectionUtils.getClassLoaderName(o);
log.debug("pop reference "+ clazz + "/" + clazzLoader + " [" + o + "] " + getStats());
}
return o;
}
public void pushDouble(double d) {
log.debug("push double " + d + " " + getStats());
if (dTop == dstack.length) {
double[] hlp = new double[Math.max(8,dstack.length*2)];
System.arraycopy(dstack, 0, hlp, 0, dstack.length);
dstack = hlp;
}
dstack[dTop++] = d;
}
public void pushFloat(float f) {
log.debug("push float " + f + " " + getStats());
if (fTop == fstack.length) {
float[] hlp = new float[Math.max(8,fstack.length*2)];
System.arraycopy(fstack, 0, hlp, 0, fstack.length);
fstack = hlp;
}
fstack[fTop++] = f;
}
public void pushInt(int i) {
log.debug("push int " + i + " " + getStats());
if (iTop == istack.length) {
int[] hlp = new int[Math.max(8,istack.length*2)];
System.arraycopy(istack, 0, hlp, 0, istack.length);
istack = hlp;
}
istack[iTop++] = i;
}
public void pushLong(long l) {
log.debug("push long " + l + " " + getStats());
if (lTop == lstack.length) {
long[] hlp = new long[Math.max(8,lstack.length*2)];
System.arraycopy(lstack, 0, hlp, 0, lstack.length);
lstack = hlp;
}
lstack[lTop++] = l;
}
public void pushObject(Object o) {
if (log.isDebugEnabled()) {
final String clazz = ReflectionUtils.getClassName(o);
final String clazzLoader = ReflectionUtils.getClassLoaderName(o);
log.debug("push object " + clazz + "/" + clazzLoader + " [" + o + "] " + getStats());
}
if (oTop == ostack.length) {
Object[] hlp = new Object[Math.max(8,ostack.length*2)];
System.arraycopy(ostack, 0, hlp, 0, ostack.length);
ostack = hlp;
}
ostack[oTop++] = o;
}
public void pushReference(Object o) {
if (log.isDebugEnabled()) {
final String clazz = ReflectionUtils.getClassName(o);
final String clazzLoader = ReflectionUtils.getClassLoaderName(o);
log.debug("push reference " + clazz + "/" + clazzLoader + " [" + o + "] " + getStats());
}
if (rTop == rstack.length) {
Object[] hlp = new Object[Math.max(8,rstack.length*2)];
System.arraycopy(rstack, 0, hlp, 0, rstack.length);
rstack = hlp;
}
rstack[rTop++] = o;
}
public boolean isSerializable() {
for (int i = 0; i < rTop; i++) {
final Object r = rstack[i];
if (!(r instanceof Serializable)) {
return false;
}
}
for (int i = 0; i < oTop; i++) {
final Object o = ostack[i];
if (!(o instanceof Serializable)) {
return false;
}
}
return true;
}
public boolean isEmpty() {
return iTop==0 && lTop==0 && dTop==0 && fTop==0 && oTop==0 && rTop==0;
}
public Runnable getRunnable() {
return runnable;
}
private String getStats() {
final StringBuffer sb = new StringBuffer();
sb.append("i[").append(iTop).append("],");
sb.append("l[").append(lTop).append("],");
sb.append("d[").append(dTop).append("],");
sb.append("f[").append(fTop).append("],");
sb.append("o[").append(oTop).append("],");
sb.append("r[").append(rTop).append("]");
return sb.toString();
}
private String getContent() {
final StringBuffer sb = new StringBuffer();
sb.append("i[").append(iTop).append("]\n");
sb.append("l[").append(lTop).append("]\n");
sb.append("d[").append(dTop).append("]\n");
sb.append("f[").append(fTop).append("]\n");
sb.append("o[").append(oTop).append("]\n");
for(int i=0; i<oTop;i++) {
sb.append(' ').append(i).append(": ");
sb.append(ReflectionUtils.getClassName(ostack[i])).append('/').append(ReflectionUtils.getClassLoaderName(ostack[i]));
sb.append('\n');
}
sb.append("r[").append(rTop).append("]\n");
for(int i=0; i<rTop;i++) {
sb.append(' ').append(i).append(": ");
sb.append(ReflectionUtils.getClassName(rstack[i])).append('/').append(ReflectionUtils.getClassLoaderName(rstack[i]));
sb.append('\n');
}
return sb.toString();
}
public String toString() {
return getContent();
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.writeInt(iTop);
for( int i=0; i<iTop; i++ ) {
s.writeInt(istack[i]);
}
s.writeInt(lTop);
for( int i=0; i<lTop; i++ ) {
s.writeLong(lstack[i]);
}
s.writeInt(dTop);
for( int i=0; i<dTop; i++ ) {
s.writeDouble(dstack[i]);
}
s.writeInt(fTop);
for( int i=0; i<fTop; i++ ) {
s.writeDouble(fstack[i]);
}
s.writeInt(oTop);
for( int i=0; i<oTop; i++ ) {
s.writeObject(ostack[i]);
}
s.writeInt(rTop);
for( int i=0; i<rTop; i++ ) {
s.writeObject(rstack[i]);
}
s.writeObject(runnable);
}
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
iTop = s.readInt();
istack = new int[iTop];
for( int i=0; i<iTop; i++ ) {
istack[i] = s.readInt();
}
lTop = s.readInt();
lstack = new long[lTop];
for( int i=0; i<lTop; i++ ) {
lstack[i] = s.readLong();
}
dTop = s.readInt();
dstack = new double[dTop];
for( int i=0; i<dTop; i++ ) {
dstack[i] = s.readDouble();
}
fTop = s.readInt();
fstack = new float[fTop];
for( int i=0; i<fTop; i++ ) {
fstack[i] = s.readFloat();
}
oTop = s.readInt();
ostack = new Object[oTop];
for( int i=0; i<oTop; i++ ) {
ostack[i] = s.readObject();
}
rTop = s.readInt();
rstack = new Object[rTop];
for( int i=0; i<rTop; i++ ) {
rstack[i] = s.readObject();
}
runnable = (Runnable)s.readObject();
}
}
| net.tascalate.javaflow.api/src/main/java/org/apache/commons/javaflow/core/Stack.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.commons.javaflow.core;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Stack to store the frame information along the invocation trace.
*
* @author <a href="mailto:[email protected]">Torsten Curdt</a>
* @author <a href="mailto:[email protected]">Stephan Michels</a>
* @version CVS $Id: Stack.java 733503 2009-01-11 19:51:40Z tcurdt $
*/
public class Stack implements Serializable {
private static final Log log = LogFactory.getLog(Stack.class);
private static final long serialVersionUID = 2L;
private int[] istack;
private float[] fstack;
private double[] dstack;
private long[] lstack;
private Object[] ostack;
private Object[] rstack;
private int iTop, fTop, dTop, lTop, oTop, rTop;
protected Runnable runnable;
public Stack(Runnable pRunnable) {
istack = new int[10];
lstack = new long[5];
dstack = new double[5];
fstack = new float[5];
ostack = new Object[10];
rstack = new Object[5];
runnable = pRunnable;
}
public Stack(final Stack pParent) {
istack = new int[pParent.istack.length];
lstack = new long[pParent.lstack.length];
dstack = new double[pParent.dstack.length];
fstack = new float[pParent.fstack.length];
ostack = new Object[pParent.ostack.length];
rstack = new Object[pParent.rstack.length];
iTop = pParent.iTop;
fTop = pParent.fTop;
dTop = pParent.dTop;
lTop = pParent.lTop;
oTop = pParent.oTop;
rTop = pParent.rTop;
System.arraycopy(pParent.istack, 0, istack, 0, iTop);
System.arraycopy(pParent.fstack, 0, fstack, 0, fTop);
System.arraycopy(pParent.dstack, 0, dstack, 0, dTop);
System.arraycopy(pParent.lstack, 0, lstack, 0, lTop);
System.arraycopy(pParent.ostack, 0, ostack, 0, oTop);
System.arraycopy(pParent.rstack, 0, rstack, 0, rTop);
runnable = pParent.runnable;
}
public boolean hasDouble() {
return dTop > 0;
}
public double popDouble() {
if (dTop == 0) {
throw new EmptyStackException("pop double");
}
final double d = dstack[--dTop];
log.debug("pop double " + d + " " + getStats());
return d;
}
public boolean hasFloat() {
return fTop > 0;
}
public float popFloat() {
if (fTop == 0) {
throw new EmptyStackException("pop float");
}
final float f = fstack[--fTop];
log.debug("pop float " + f + " " + getStats());
return f;
}
public boolean hasInt() {
return iTop > 0;
}
public int popInt() {
if (iTop == 0) {
throw new EmptyStackException("pop int");
}
final int i = istack[--iTop];
log.debug("pop int " + i + " " + getStats());
return i;
}
public boolean hasLong() {
return lTop > 0;
}
public long popLong() {
if (lTop == 0) {
throw new EmptyStackException("pop long");
}
final long l = lstack[--lTop];
log.debug("pop long " + l + " " + getStats());
return l;
}
public boolean hasObject() {
return oTop > 0;
}
public Object popObject() {
if (oTop == 0) {
throw new EmptyStackException("pop object");
}
final Object o = ostack[--oTop];
ostack[oTop] = null; // avoid unnecessary reference to object
if(log.isDebugEnabled()) {
final String clazz = ReflectionUtils.getClassName(o);
final String clazzLoader = ReflectionUtils.getClassLoaderName(o);
log.debug("pop object "+ clazz + "/" + clazzLoader + " [" + o + "] ");
}
return o;
}
public boolean hasReference() {
return rTop > 0;
}
public Object popReference() {
if (rTop == 0) {
throw new EmptyStackException("pop reference");
}
final Object o = rstack[--rTop];
rstack[rTop] = null; // avoid unnecessary reference to object
if(log.isDebugEnabled()) {
final String clazz = ReflectionUtils.getClassName(o);
final String clazzLoader = ReflectionUtils.getClassLoaderName(o);
log.debug("pop reference "+ clazz + "/" + clazzLoader + " [" + o + "] " + getStats());
}
return o;
}
public void pushDouble(double d) {
log.debug("push double " + d + " " + getStats());
if (dTop == dstack.length) {
double[] hlp = new double[Math.max(8,dstack.length*2)];
System.arraycopy(dstack, 0, hlp, 0, dstack.length);
dstack = hlp;
}
dstack[dTop++] = d;
}
public void pushFloat(float f) {
log.debug("push float " + f + " " + getStats());
if (fTop == fstack.length) {
float[] hlp = new float[Math.max(8,fstack.length*2)];
System.arraycopy(fstack, 0, hlp, 0, fstack.length);
fstack = hlp;
}
fstack[fTop++] = f;
}
public void pushInt(int i) {
log.debug("push int " + i + " " + getStats());
if (iTop == istack.length) {
int[] hlp = new int[Math.max(8,istack.length*2)];
System.arraycopy(istack, 0, hlp, 0, istack.length);
istack = hlp;
}
istack[iTop++] = i;
}
public void pushLong(long l) {
log.debug("push long " + l + " " + getStats());
if (lTop == lstack.length) {
long[] hlp = new long[Math.max(8,lstack.length*2)];
System.arraycopy(lstack, 0, hlp, 0, lstack.length);
lstack = hlp;
}
lstack[lTop++] = l;
}
public void pushObject(Object o) {
if (log.isDebugEnabled()) {
final String clazz = ReflectionUtils.getClassName(o);
final String clazzLoader = ReflectionUtils.getClassLoaderName(o);
log.debug("push object " + clazz + "/" + clazzLoader + " [" + o + "] " + getStats());
}
if (oTop == ostack.length) {
Object[] hlp = new Object[Math.max(8,ostack.length*2)];
System.arraycopy(ostack, 0, hlp, 0, ostack.length);
ostack = hlp;
}
ostack[oTop++] = o;
}
public void pushReference(Object o) {
if (log.isDebugEnabled()) {
final String clazz = ReflectionUtils.getClassName(o);
final String clazzLoader = ReflectionUtils.getClassLoaderName(o);
log.debug("push reference " + clazz + "/" + clazzLoader + " [" + o + "] " + getStats());
}
if (rTop == rstack.length) {
Object[] hlp = new Object[Math.max(8,rstack.length*2)];
System.arraycopy(rstack, 0, hlp, 0, rstack.length);
rstack = hlp;
}
rstack[rTop++] = o;
}
public boolean isSerializable() {
for (int i = 0; i < rTop; i++) {
final Object r = rstack[i];
if (!(r instanceof Serializable)) {
return false;
}
}
for (int i = 0; i < oTop; i++) {
final Object o = ostack[i];
if (!(o instanceof Serializable)) {
return false;
}
}
return true;
}
public boolean isEmpty() {
return iTop==0 && lTop==0 && dTop==0 && fTop==0 && oTop==0 && rTop==0;
}
private String getStats() {
final StringBuffer sb = new StringBuffer();
sb.append("i[").append(iTop).append("],");
sb.append("l[").append(lTop).append("],");
sb.append("d[").append(dTop).append("],");
sb.append("f[").append(fTop).append("],");
sb.append("o[").append(oTop).append("],");
sb.append("r[").append(rTop).append("]");
return sb.toString();
}
private String getContent() {
final StringBuffer sb = new StringBuffer();
sb.append("i[").append(iTop).append("]\n");
sb.append("l[").append(lTop).append("]\n");
sb.append("d[").append(dTop).append("]\n");
sb.append("f[").append(fTop).append("]\n");
sb.append("o[").append(oTop).append("]\n");
for(int i=0; i<oTop;i++) {
sb.append(' ').append(i).append(": ");
sb.append(ReflectionUtils.getClassName(ostack[i])).append('/').append(ReflectionUtils.getClassLoaderName(ostack[i]));
sb.append('\n');
}
sb.append("r[").append(rTop).append("]\n");
for(int i=0; i<rTop;i++) {
sb.append(' ').append(i).append(": ");
sb.append(ReflectionUtils.getClassName(rstack[i])).append('/').append(ReflectionUtils.getClassLoaderName(rstack[i]));
sb.append('\n');
}
return sb.toString();
}
public String toString() {
return getContent();
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.writeInt(iTop);
for( int i=0; i<iTop; i++ ) {
s.writeInt(istack[i]);
}
s.writeInt(lTop);
for( int i=0; i<lTop; i++ ) {
s.writeLong(lstack[i]);
}
s.writeInt(dTop);
for( int i=0; i<dTop; i++ ) {
s.writeDouble(dstack[i]);
}
s.writeInt(fTop);
for( int i=0; i<fTop; i++ ) {
s.writeDouble(fstack[i]);
}
s.writeInt(oTop);
for( int i=0; i<oTop; i++ ) {
s.writeObject(ostack[i]);
}
s.writeInt(rTop);
for( int i=0; i<rTop; i++ ) {
s.writeObject(rstack[i]);
}
s.writeObject(runnable);
}
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
iTop = s.readInt();
istack = new int[iTop];
for( int i=0; i<iTop; i++ ) {
istack[i] = s.readInt();
}
lTop = s.readInt();
lstack = new long[lTop];
for( int i=0; i<lTop; i++ ) {
lstack[i] = s.readLong();
}
dTop = s.readInt();
dstack = new double[dTop];
for( int i=0; i<dTop; i++ ) {
dstack[i] = s.readDouble();
}
fTop = s.readInt();
fstack = new float[fTop];
for( int i=0; i<fTop; i++ ) {
fstack[i] = s.readFloat();
}
oTop = s.readInt();
ostack = new Object[oTop];
for( int i=0; i<oTop; i++ ) {
ostack[i] = s.readObject();
}
rTop = s.readInt();
rstack = new Object[rTop];
for( int i=0; i<rTop; i++ ) {
rstack[i] = s.readObject();
}
runnable = (Runnable)s.readObject();
}
}
| Add an option to access current runnable (necessary for async/await project)
| net.tascalate.javaflow.api/src/main/java/org/apache/commons/javaflow/core/Stack.java | Add an option to access current runnable (necessary for async/await project) | <ide><path>et.tascalate.javaflow.api/src/main/java/org/apache/commons/javaflow/core/Stack.java
<ide> public boolean isEmpty() {
<ide> return iTop==0 && lTop==0 && dTop==0 && fTop==0 && oTop==0 && rTop==0;
<ide> }
<add>
<add> public Runnable getRunnable() {
<add> return runnable;
<add> }
<add>
<ide>
<ide> private String getStats() {
<ide> final StringBuffer sb = new StringBuffer(); |
|
Java | apache-2.0 | f33c822becf49617e6f3e5d0b52adc68f93a6014 | 0 | Rutgers-IDM/openregistry,Rutgers-IDM/openregistry,Jasig/openregistry,Jasig/openregistry,sheliu/openregistry,Jasig/openregistry,Unicon/openregistry,Rutgers-IDM/openregistry,sheliu/openregistry,Rutgers-IDM/openregistry,msidd/openregistry,sheliu/openregistry,Rutgers-IDM/openregistry,msidd/openregistry,sheliu/openregistry,Unicon/openregistry,Jasig/openregistry,Unicon/openregistry,Jasig/openregistry,Unicon/openregistry,msidd/openregistry,Unicon/openregistry,msidd/openregistry,Jasig/openregistry,Unicon/openregistry,Unicon/openregistry,sheliu/openregistry,msidd/openregistry | package org.openregistry.core.repository.jpa;
import org.openregistry.core.repository.ReferenceRepository;
import org.openregistry.core.domain.*;
import org.openregistry.core.domain.jpa.*;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
/**
* Default implementation of temporary repository.
*/
@Repository(value = "referenceRepository")
public final class JpaReferenceRepository implements ReferenceRepository {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public List<Person> getPeople() {
return (List<Person>) this.entityManager.createQuery("select p from person p join p.names n where n.preferredName = 1 order by n.family, n.given").getResultList();
}
@Transactional
public Person getPersonById(final Long id) {
return (Person) this.entityManager.find(JpaPersonImpl.class, id);
}
@Transactional
public List<OrganizationalUnit> getOrganizationalUnits() {
return (List<OrganizationalUnit>) this.entityManager.createQuery("select d from organizational_unit d order by d.name").getResultList();
}
@Transactional
public OrganizationalUnit getOrganizationalUnitById(final Long id) {
return this.entityManager.find(JpaOrganizationalUnitImpl.class, id);
}
@Transactional
public List<Campus> getCampuses() {
return (List<Campus>) this.entityManager.createQuery("select c from campus c order by c.name").getResultList();
}
@Transactional
public Campus getCampusById(final Long id) {
return this.entityManager.find(JpaCampusImpl.class, id);
}
@Transactional
public Country getCountryById(final Long id) {
return this.entityManager.find(JpaCountryImpl.class, id);
}
@Transactional
public List<Country> getCountries() {
return (List<Country>) this.entityManager.createQuery("select c from country c").getResultList();
}
@Transactional
public List<RoleInfo> getRoleInfos() {
return (List<RoleInfo>) this.entityManager.createQuery("select r from roleInfo r order by r.title").getResultList();
}
@Transactional
public RoleInfo getRoleInfo(final Long id) {
return this.entityManager.find(JpaRoleInfoImpl.class, id);
}
@Transactional
public List<Region> getRegions() {
return (List<Region>) this.entityManager.createQuery("select r from region r").getResultList();
}
@Transactional
public Region getRegionById(final Long id) {
return this.entityManager.find(JpaRegionImpl.class, id);
}
@Transactional
public List<Type> getEmailTypes() {
return (List<Type>) this.entityManager.createQuery("select r from type r where dataType='EmailAddress'").getResultList();
}
@Transactional
public List<Type> getAddressTypes() {
return (List<Type>) this.entityManager.createQuery("select r from type r where dataType='Address'").getResultList();
}
@Transactional
public List<Type> getPhoneTypes() {
return (List<Type>) this.entityManager.createQuery("select r from type r where dataType='Phone'").getResultList();
}
@Transactional
public Type findType(String data_type, String description) {
Query q = this.entityManager.createQuery("select distinct r from type r where dataType=:data_type and description=:description");
q.setParameter("data_type", data_type);
q.setParameter("description", description);
Type result = (Type)q.getSingleResult();
return result;
}
@Transactional
public List<IdentifierType> getIdentifierTypes(){
return (List<IdentifierType>) this.entityManager.createQuery("select r from identifier_type r").getResultList();
}
@Transactional
public IdentifierType findIdentifierType(final String identifierName){
final Query q = this.entityManager.createQuery("select distinct r from identifier_type r where name=:name").setParameter("name", identifierName);
return (IdentifierType) q.getSingleResult();
}
}
| openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaReferenceRepository.java | package org.openregistry.core.repository.jpa;
import org.openregistry.core.repository.ReferenceRepository;
import org.openregistry.core.domain.*;
import org.openregistry.core.domain.jpa.*;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
/**
* Default implementation of temporary repository.
*/
@Repository(value = "referenceRepository")
public final class JpaReferenceRepository implements ReferenceRepository {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public List<Person> getPeople() {
return (List<Person>) this.entityManager.createQuery("select p from person p join p.names n where n.preferredName = 1 order by n.family, n.given").getResultList();
}
@Transactional
public Person getPersonById(final Long id) {
return (Person) this.entityManager.find(JpaPersonImpl.class, id);
}
@Transactional
public List<OrganizationalUnit> getOrganizationalUnits() {
return (List<OrganizationalUnit>) this.entityManager.createQuery("select d from organizational_unit d order by d.name").getResultList();
}
@Transactional
public OrganizationalUnit getOrganizationalUnitById(final Long id) {
return this.entityManager.find(JpaOrganizationalUnitImpl.class, id);
}
@Transactional
public List<Campus> getCampuses() {
return (List<Campus>) this.entityManager.createQuery("select c from campus c order by c.name").getResultList();
}
@Transactional
public Campus getCampusById(final Long id) {
return this.entityManager.find(JpaCampusImpl.class, id);
}
@Transactional
public Country getCountryById(final Long id) {
return this.entityManager.find(JpaCountryImpl.class, id);
}
@Transactional
public List<Country> getCountries() {
return (List<Country>) this.entityManager.createQuery("select c from country c").getResultList();
}
@Transactional
public List<RoleInfo> getRoleInfos() {
return (List<RoleInfo>) this.entityManager.createQuery("select r from roleInfo r order by r.title");
}
@Transactional
public RoleInfo getRoleInfo(final Long id) {
return this.entityManager.find(JpaRoleInfoImpl.class, id);
}
@Transactional
public List<Region> getRegions() {
return (List<Region>) this.entityManager.createQuery("select r from region r").getResultList();
}
@Transactional
public Region getRegionById(final Long id) {
return this.entityManager.find(JpaRegionImpl.class, id);
}
@Transactional
public List<Type> getEmailTypes() {
return (List<Type>) this.entityManager.createQuery("select r from type r where dataType='EmailAddress'").getResultList();
}
@Transactional
public List<Type> getAddressTypes() {
return (List<Type>) this.entityManager.createQuery("select r from type r where dataType='Address'").getResultList();
}
@Transactional
public List<Type> getPhoneTypes() {
return (List<Type>) this.entityManager.createQuery("select r from type r where dataType='Phone'").getResultList();
}
@Transactional
public Type findType(String data_type, String description) {
Query q = this.entityManager.createQuery("select distinct r from type r where dataType=:data_type and description=:description");
q.setParameter("data_type", data_type);
q.setParameter("description", description);
Type result = (Type)q.getSingleResult();
return result;
}
@Transactional
public List<IdentifierType> getIdentifierTypes(){
return (List<IdentifierType>) this.entityManager.createQuery("select r from identifier_type r").getResultList();
}
@Transactional
public IdentifierType findIdentifierType(final String identifierName){
final Query q = this.entityManager.createQuery("select distinct r from identifier_type r where name=:name").setParameter("name", identifierName);
return (IdentifierType) q.getSingleResult();
}
}
| NOJIRA add missing getResultList()
git-svn-id: 996c6d7d570f9e8d676b69394667d4ecb3e4cdb3@17765 1580c273-15eb-1042-8a87-dc5d815c88a0
| openregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaReferenceRepository.java | NOJIRA add missing getResultList() | <ide><path>penregistry-repository-jpa-impl/src/main/java/org/openregistry/core/repository/jpa/JpaReferenceRepository.java
<ide>
<ide> @Transactional
<ide> public List<RoleInfo> getRoleInfos() {
<del> return (List<RoleInfo>) this.entityManager.createQuery("select r from roleInfo r order by r.title");
<add> return (List<RoleInfo>) this.entityManager.createQuery("select r from roleInfo r order by r.title").getResultList();
<ide> }
<ide>
<ide> @Transactional |
|
Java | bsd-3-clause | 00e5d52bf63440928932166df6e395a5cc87a5e3 | 0 | Club-Rock-ISEN/EntryManager,Club-Rock-ISEN/EntryManager | package org.clubrockisen;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.clubrockisen.dao.abstracts.AbstractDAOFactory;
import org.clubrockisen.dao.abstracts.AbstractDAOFactory.DAOType;
import org.clubrockisen.service.ParametersManager;
import org.clubrockisen.view.MainWindow;
/**
* Launcher for the club rock ISEN application
*
* @author Alex
*/
public final class App {
private static Logger lg = Logger.getLogger(App.class.getName());
private App () {
}
/**
* Entry point for the launcher.
* @param args
* the arguments from the command line.
*/
public static void main (final String[] args) {
lg.info("Starting Club Rock ISEN application.");
String translationFile;
if (args.length < 1) {
translationFile = "data/locale/fr.xml";
lg.warning("No language file defined. Using default locale file : " + translationFile);
} else {
translationFile = args[0];
}
lg.fine("Language locale file defined: " + translationFile);
final DAOType daoType = DAOType.MYSQL;
try {
AbstractDAOFactory daoFactory;
daoFactory = AbstractDAOFactory.getFactory(daoType);
ParametersManager.create(daoFactory);
try {
MainWindow.setLookAndFeel();
} catch (final NullPointerException e) {
lg.warning("Could not set look and feel (" + e.getMessage() + ")");
}
final MainWindow window = new MainWindow(translationFile, daoFactory);
window.setVisible(true);
} catch (final InstantiationException e) {
JOptionPane.showMessageDialog(null, "Could not instantiate a DAO of type " + daoType
+ "\n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
| src/org/clubrockisen/App.java | package org.clubrockisen;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.clubrockisen.dao.AbstractDAOFactory;
import org.clubrockisen.dao.AbstractDAOFactory.DAOType;
import org.clubrockisen.gui.MainWindow;
import org.clubrockisen.services.ParametersManager;
/**
* Launcher for the club rock ISEN application
*
* @author Alex
*/
public final class App {
private static Logger lg = Logger.getLogger(App.class.getName());
private App () {
}
/**
* Entry point for the launcher.
* @param args
* the arguments from the command line.
*/
public static void main (final String[] args) {
lg.info("Starting Club Rock ISEN application.");
String translationFile;
if (args.length < 1) {
translationFile = "data/locale/fr.xml";
lg.warning("No language file defined. Using default locale file : " + translationFile);
} else {
translationFile = args[0];
}
lg.fine("Language locale file defined: " + translationFile);
final DAOType daoType = DAOType.MYSQL;
try {
AbstractDAOFactory daoFactory;
daoFactory = AbstractDAOFactory.getFactory(daoType);
ParametersManager.create(daoFactory);
try {
MainWindow.setLookAndFeel();
} catch (NullPointerException e) {
lg.warning("Could not set look and feel (" + e.getMessage() + ")");
}
final MainWindow window = new MainWindow(translationFile, daoFactory);
window.setVisible(true);
} catch (final InstantiationException e) {
JOptionPane.showMessageDialog(null, "Could not instantiate a DAO of type " + daoType
+ "\n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
| Interfaces and abstract classes for MVC pattern.
| src/org/clubrockisen/App.java | Interfaces and abstract classes for MVC pattern. | <ide><path>rc/org/clubrockisen/App.java
<ide>
<ide> import javax.swing.JOptionPane;
<ide>
<del>import org.clubrockisen.dao.AbstractDAOFactory;
<del>import org.clubrockisen.dao.AbstractDAOFactory.DAOType;
<del>import org.clubrockisen.gui.MainWindow;
<del>import org.clubrockisen.services.ParametersManager;
<add>import org.clubrockisen.dao.abstracts.AbstractDAOFactory;
<add>import org.clubrockisen.dao.abstracts.AbstractDAOFactory.DAOType;
<add>import org.clubrockisen.service.ParametersManager;
<add>import org.clubrockisen.view.MainWindow;
<ide>
<ide> /**
<ide> * Launcher for the club rock ISEN application
<ide> */
<ide> public final class App {
<ide> private static Logger lg = Logger.getLogger(App.class.getName());
<del>
<add>
<ide> private App () {
<ide> }
<del>
<add>
<ide> /**
<ide> * Entry point for the launcher.
<ide> * @param args
<ide> */
<ide> public static void main (final String[] args) {
<ide> lg.info("Starting Club Rock ISEN application.");
<del>
<add>
<ide> String translationFile;
<ide> if (args.length < 1) {
<ide> translationFile = "data/locale/fr.xml";
<ide> translationFile = args[0];
<ide> }
<ide> lg.fine("Language locale file defined: " + translationFile);
<del>
<add>
<ide> final DAOType daoType = DAOType.MYSQL;
<ide> try {
<ide> AbstractDAOFactory daoFactory;
<ide> ParametersManager.create(daoFactory);
<ide> try {
<ide> MainWindow.setLookAndFeel();
<del> } catch (NullPointerException e) {
<add> } catch (final NullPointerException e) {
<ide> lg.warning("Could not set look and feel (" + e.getMessage() + ")");
<ide> }
<ide> final MainWindow window = new MainWindow(translationFile, daoFactory);
<ide> + "\n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
<ide> }
<ide> }
<del>
<add>
<ide> } |
|
JavaScript | mit | af483dc878afe10a5520c222133d81b1a6e6c786 | 0 | Ryanair/css-class-shrinker,Ryanair/css-class-shrinker | import fs from 'fs';
import glob from 'glob';
export default class BaseShrkinker {
constructor(path, map) {
this._path = path;
this._map = map;
}
async _init(path) {
this.files = await this.fetchFiles(path);
}
async run() {
await this._init(this._path);
return Promise.all(this.files.map(async function(file) {
try {
return this.write(file, this.processFile(await this.read(file)));
} catch(e) {
/* istanbul ignore next */
console.log(e);
}
}.bind(this)));
}
read(file) {
return new Promise((resolve, reject) => {
fs.readFile(file, 'utf8', (err, contents) => {
/* istanbul ignore if */
if (err) {
reject(err);
} else {
resolve(contents);
}
});
});
}
write(file, contents) {
return new Promise((resolve, reject) => {
fs.writeFile(file, contents, 'utf8', (err) => {
/* istanbul ignore if */
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
fetchFiles(path) {
return new Promise((resolve, reject) => {
fs.lstat(path, function(er, stat) {
/* istanbul ignore if */
if (!er) {
resolve([path]);
} else {
glob(path, {}, (err, files) => {
/* istanbul ignore if */
if (err) {
reject(err);
} else {
resolve(files);
}
});
}
});
});
}
// NOTE: must be overridden. Logic left to implementors
processFile(contents) {
/* istanbul ignore next */
console.log(contents);
return contents;
}
}
| src/shrinkers/base-shrinker.js | import fs from 'fs';
import glob from 'glob';
export default class BaseShrkinker {
constructor(path, map) {
this._path = path;
this._map = map;
}
async _init(path) {
this.files = await this.fetchFiles(path);
}
async run() {
await this._init(this._path);
return Promise.all(this.files.map(async function(file) {
try {
return this.write(file, this.processFile(await this.read(file)));
} catch(e) {
console.log(e);
}
}.bind(this)));
}
read(file) {
return new Promise((resolve, reject) => {
fs.readFile(file, 'utf8', (err, contents) => {
if (err) {
reject(err);
} else {
resolve(contents);
}
});
});
}
write(file, contents) {
return new Promise((resolve, reject) => {
fs.writeFile(file, contents, 'utf8', (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
fetchFiles(path) {
return new Promise((resolve, reject) => {
fs.lstat(path, function(er, stat) {
if (!er) {
resolve([path]);
} else {
glob(path, {}, (err, files) => {
if (err) {
reject(err);
} else {
resolve(files);
}
});
}
});
});
}
processFile(contents) {
// NOTE: left to implementors
console.log(contents);
return contents;
}
}
| Adding some coverage ignores for unrelevant code bits.
| src/shrinkers/base-shrinker.js | Adding some coverage ignores for unrelevant code bits. | <ide><path>rc/shrinkers/base-shrinker.js
<ide> try {
<ide> return this.write(file, this.processFile(await this.read(file)));
<ide> } catch(e) {
<add> /* istanbul ignore next */
<ide> console.log(e);
<ide> }
<ide> }.bind(this)));
<ide> read(file) {
<ide> return new Promise((resolve, reject) => {
<ide> fs.readFile(file, 'utf8', (err, contents) => {
<add> /* istanbul ignore if */
<ide> if (err) {
<ide> reject(err);
<ide> } else {
<ide> write(file, contents) {
<ide> return new Promise((resolve, reject) => {
<ide> fs.writeFile(file, contents, 'utf8', (err) => {
<add> /* istanbul ignore if */
<ide> if (err) {
<ide> reject(err);
<ide> } else {
<ide> fetchFiles(path) {
<ide> return new Promise((resolve, reject) => {
<ide> fs.lstat(path, function(er, stat) {
<add> /* istanbul ignore if */
<ide> if (!er) {
<ide> resolve([path]);
<ide> } else {
<ide> glob(path, {}, (err, files) => {
<add> /* istanbul ignore if */
<ide> if (err) {
<ide> reject(err);
<ide> } else {
<ide> });
<ide> }
<ide>
<add> // NOTE: must be overridden. Logic left to implementors
<ide> processFile(contents) {
<del> // NOTE: left to implementors
<add> /* istanbul ignore next */
<ide> console.log(contents);
<ide> return contents;
<ide> } |
|
JavaScript | mit | 151f84f995c0559d86fabd0019c90886ae18b936 | 0 | postcss/autoprefixer,yisibl/autoprefixer | const Declaration = require('../declaration');
const DOTS = /^\.+$/;
function track(start, end) {
return { start, end, span: end - start };
}
function getRows(tpl) {
return tpl.trim().slice(1, -1).split(/['"]\s*['"]?/g);
}
function getColumns(line) {
return line.trim().split(/\s+/g);
}
function parseGridAreas(tpl) {
return getRows(tpl).reduce((areas, line, rowIndex) => {
if (line.trim() === '') return areas;
getColumns(line).forEach((area, columnIndex) => {
if (DOTS.test(area)) return;
if (typeof areas[area] === 'undefined') {
areas[area] = {
column: track(columnIndex + 1, columnIndex + 2),
row: track(rowIndex + 1, rowIndex + 2)
};
} else {
const { column, row } = areas[area];
column.start = Math.min(column.start, columnIndex + 1);
column.end = Math.max(column.end, columnIndex + 2);
column.span = column.end - column.start;
row.start = Math.min(row.start, rowIndex + 1);
row.end = Math.max(row.end, rowIndex + 2);
row.span = row.end - row.start;
}
});
return areas;
}, {});
}
class GridTemplateAreas extends Declaration {
static names = ['grid-template-areas'];
/**
* Translate grid-template-areas to separate -ms- prefixed properties
*/
insert(decl, prefix, prefixes) {
if (prefix !== '-ms-') return super.insert(decl, prefix, prefixes);
const areas = parseGridAreas(decl.value);
decl.root().walkDecls('grid-area', gridArea => {
const value = gridArea.value;
const area = areas[value];
delete areas[value];
if (gridArea.parent.some(i => i.prop === '-ms-grid-row')) {
return undefined;
}
if (area) {
gridArea.cloneBefore({
prop: '-ms-grid-row',
value: String(area.row.start)
});
if (area.row.span > 1) {
gridArea.cloneBefore({
prop: '-ms-grid-row-span',
value: String(area.row.span)
});
}
gridArea.cloneBefore({
prop: '-ms-grid-column',
value: String(area.column.start)
});
if (area.column.span > 1) {
gridArea.cloneBefore({
prop: '-ms-grid-column-span',
value: String(area.column.span)
});
}
}
return undefined;
});
const lastAreas = Object.keys(areas);
if (lastAreas.length > 0) {
console.warn(
`Grid areas with names ${lastAreas.join(', ')} didn't found`
);
}
return decl;
}
}
module.exports = GridTemplateAreas;
| lib/hacks/grid-template-areas.js | const Declaration = require('../declaration');
const track = (start, end) => ({
start,
end,
span: end - start
});
const sep = /['"]\s*['"]?/g;
const ws = /\s+/g;
const dots = /^\.+$/;
const getRows = tpl =>
tpl
.trim()
.slice(1, -1)
.split(sep);
const getColumns = line =>
line
.trim()
.split(ws);
const reduceLines = (
areas,
line,
rowIndex,
) => {
if (line.trim() !== '') {
getColumns(line).forEach((area, columnIndex) => {
if (!dots.test(area)) {
if (typeof areas[area] === 'undefined') {
areas[area] = {
column: track(columnIndex + 1, columnIndex + 2),
row: track(rowIndex + 1, rowIndex + 2)
};
} else {
const { column, row } = areas[area];
column.start = Math.min(column.start, columnIndex + 1);
column.end = Math.max(column.end, columnIndex + 2);
column.span = column.end - column.start;
row.start = Math.min(row.start, rowIndex + 1);
row.end = Math.max(row.end, rowIndex + 2);
row.span = row.end - row.start;
}
}
});
}
return areas;
};
const parseGridAreas = (tpl) => {
const lines = getRows(tpl);
const areas = lines.reduce(reduceLines, {});
return areas;
};
class GridTemplateAreas extends Declaration {
static names = [
'grid-template-areas'
];
/**
* Translate grid-template-areas to separate -ms- prefixed properties
*/
insert(decl, prefix, prefixes) {
if (prefix !== '-ms-') return super.insert(decl, prefix, prefixes);
const areas = parseGridAreas(decl.value);
decl.root().walkDecls('grid-area', gridArea => {
const value = gridArea.value;
const area = areas[value];
delete areas[value];
if (gridArea.parent.some(i => i.prop === '-ms-grid-row')) {
return undefined;
}
if (area) {
gridArea.cloneBefore({
prop: '-ms-grid-row',
value: String(area.row.start)
});
if (area.row.span > 1) {
gridArea.cloneBefore({
prop: '-ms-grid-row-span',
value: String(area.row.span)
});
}
gridArea.cloneBefore({
prop: '-ms-grid-column',
value: String(area.column.start)
});
if (area.column.span > 1) {
gridArea.cloneBefore({
prop: '-ms-grid-column-span',
value: String(area.column.span)
});
}
}
return undefined;
});
const lastAreas = Object.keys(areas);
if (lastAreas.length > 0) {
console.warn(
`Grid areas with names ${lastAreas.join(', ')} didn't found`
);
}
return decl;
}
}
module.exports = GridTemplateAreas;
| Clean up code
| lib/hacks/grid-template-areas.js | Clean up code | <ide><path>ib/hacks/grid-template-areas.js
<ide> const Declaration = require('../declaration');
<ide>
<del>const track = (start, end) => ({
<del> start,
<del> end,
<del> span: end - start
<del>});
<add>const DOTS = /^\.+$/;
<ide>
<del>const sep = /['"]\s*['"]?/g;
<del>const ws = /\s+/g;
<del>const dots = /^\.+$/;
<add>function track(start, end) {
<add> return { start, end, span: end - start };
<add>}
<ide>
<del>const getRows = tpl =>
<del> tpl
<del> .trim()
<del> .slice(1, -1)
<del> .split(sep);
<add>function getRows(tpl) {
<add> return tpl.trim().slice(1, -1).split(/['"]\s*['"]?/g);
<add>}
<ide>
<del>const getColumns = line =>
<del> line
<del> .trim()
<del> .split(ws);
<add>function getColumns(line) {
<add> return line.trim().split(/\s+/g);
<add>}
<ide>
<del>const reduceLines = (
<del> areas,
<del> line,
<del> rowIndex,
<del>) => {
<del> if (line.trim() !== '') {
<add>function parseGridAreas(tpl) {
<add> return getRows(tpl).reduce((areas, line, rowIndex) => {
<add> if (line.trim() === '') return areas;
<ide> getColumns(line).forEach((area, columnIndex) => {
<del> if (!dots.test(area)) {
<del> if (typeof areas[area] === 'undefined') {
<del> areas[area] = {
<del> column: track(columnIndex + 1, columnIndex + 2),
<del> row: track(rowIndex + 1, rowIndex + 2)
<del> };
<del> } else {
<del> const { column, row } = areas[area];
<add> if (DOTS.test(area)) return;
<add> if (typeof areas[area] === 'undefined') {
<add> areas[area] = {
<add> column: track(columnIndex + 1, columnIndex + 2),
<add> row: track(rowIndex + 1, rowIndex + 2)
<add> };
<add> } else {
<add> const { column, row } = areas[area];
<ide>
<del> column.start = Math.min(column.start, columnIndex + 1);
<del> column.end = Math.max(column.end, columnIndex + 2);
<del> column.span = column.end - column.start;
<add> column.start = Math.min(column.start, columnIndex + 1);
<add> column.end = Math.max(column.end, columnIndex + 2);
<add> column.span = column.end - column.start;
<ide>
<del> row.start = Math.min(row.start, rowIndex + 1);
<del> row.end = Math.max(row.end, rowIndex + 2);
<del> row.span = row.end - row.start;
<del> }
<add> row.start = Math.min(row.start, rowIndex + 1);
<add> row.end = Math.max(row.end, rowIndex + 2);
<add> row.span = row.end - row.start;
<ide> }
<ide> });
<del> }
<del>
<del> return areas;
<del>};
<del>
<del>const parseGridAreas = (tpl) => {
<del> const lines = getRows(tpl);
<del> const areas = lines.reduce(reduceLines, {});
<del>
<del> return areas;
<del>};
<add> return areas;
<add> }, {});
<add>}
<ide>
<ide> class GridTemplateAreas extends Declaration {
<ide>
<del> static names = [
<del> 'grid-template-areas'
<del> ];
<add> static names = ['grid-template-areas'];
<ide>
<ide> /**
<ide> * Translate grid-template-areas to separate -ms- prefixed properties
<ide> if (prefix !== '-ms-') return super.insert(decl, prefix, prefixes);
<ide>
<ide> const areas = parseGridAreas(decl.value);
<del>
<ide> decl.root().walkDecls('grid-area', gridArea => {
<del>
<ide> const value = gridArea.value;
<ide> const area = areas[value];
<ide> delete areas[value];
<ide>
<ide> return decl;
<ide> }
<add>
<ide> }
<ide>
<ide> module.exports = GridTemplateAreas; |
|
Java | agpl-3.0 | a056a3a679d2659e5d02e0ba2fc8bb99d9fe8034 | 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 | 21dcac1c-2e60-11e5-9284-b827eb9e62be | hello.java | 21d74d80-2e60-11e5-9284-b827eb9e62be | 21dcac1c-2e60-11e5-9284-b827eb9e62be | hello.java | 21dcac1c-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>21d74d80-2e60-11e5-9284-b827eb9e62be
<add>21dcac1c-2e60-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | cf924fb6b491a1e36436900f746c6f8c5364cb9b | 0 | bastiaanb/carbon-identity,bastiaanb/carbon-identity,pulasthi7/carbon-identity,liurl3/carbon-identity,harsha1979/carbon-identity,Pushpalanka/carbon-identity,keerthu/carbon-identity,laki88/carbon-identity,malithie/carbon-identity,thanujalk/carbon-identity,mefarazath/carbon-identity,nuwand/carbon-identity,IsuraD/carbon-identity,hasinthaindrajee/carbon-identity,darshanasbg/carbon-identity,uvindra/carbon-identity,thariyarox/carbon-identity,dulanjal/carbon-identity,johannnallathamby/carbon-identity,prabathabey/carbon-identity,ashalya/carbon-identity,harsha1979/carbon-identity,kesavany/carbon-identity,thilina27/carbon-identity,pulasthi7/carbon-identity,damithsenanayake/carbon-identity,isharak/carbon-identity,Niranjan-K/carbon-identity,nuwandi-is/carbon-identity,virajsenevirathne/carbon-identity,GayanM/carbon-identity,mefarazath/carbon-identity,godwinamila/carbon-identity,laki88/carbon-identity,dracusds123/carbon-identity,godwinamila/carbon-identity,hpmtissera/carbon-identity,thanujalk/carbon-identity,DMHP/carbon-identity,kasungayan/carbon-identity,wso2/carbon-identity,Pushpalanka/carbon-identity,hasinthaindrajee/carbon-identity,jacklotusho/carbon-identity,Shakila/carbon-identity,thilina27/carbon-identity,GayanM/carbon-identity,wso2/carbon-identity,chanukaranaba/carbon-identity,Niranjan-K/carbon-identity,GayanM/carbon-identity,IndunilRathnayake/carbon-identity,dracusds123/carbon-identity,Shakila/carbon-identity,dracusds123/carbon-identity,malithie/carbon-identity,thariyarox/carbon-identity,ravihansa3000/carbon-identity,nuwand/carbon-identity,Shakila/carbon-identity,madurangasiriwardena/carbon-identity,0xkasun/carbon-identity,DMHP/carbon-identity,thusithathilina/carbon-identity,nuwandi-is/carbon-identity,thusithathilina/carbon-identity,kasungayan/carbon-identity,JKAUSHALYA/carbon-identity,thariyarox/carbon-identity,johannnallathamby/carbon-identity,thanujalk/carbon-identity,0xkasun/carbon-identity,IsuraD/carbon-identity,laki88/carbon-identity,hpmtissera/carbon-identity,damithsenanayake/carbon-identity,kesavany/carbon-identity,darshanasbg/carbon-identity,jacklotusho/carbon-identity,madurangasiriwardena/carbon-identity,ravihansa3000/carbon-identity,johannnallathamby/carbon-identity,keerthu/carbon-identity,IndunilRathnayake/carbon-identity,malithie/carbon-identity,damithsenanayake/carbon-identity,liurl3/carbon-identity,thusithathilina/carbon-identity,IndunilRathnayake/carbon-identity,mefarazath/carbon-identity,dulanjal/carbon-identity,jacklotusho/carbon-identity,bastiaanb/carbon-identity,chanukaranaba/carbon-identity,ChamaraPhilipsuom/carbon-identity,prabathabey/carbon-identity,isharak/carbon-identity,ChamaraPhilipsuom/carbon-identity,liurl3/carbon-identity,darshanasbg/carbon-identity,dulanjal/carbon-identity,isharak/carbon-identity,chanukaranaba/carbon-identity,uvindra/carbon-identity,ChamaraPhilipsuom/carbon-identity,Pushpalanka/carbon-identity,ravihansa3000/carbon-identity,godwinamila/carbon-identity,keerthu/carbon-identity,thilina27/carbon-identity,nuwand/carbon-identity,JKAUSHALYA/carbon-identity,pulasthi7/carbon-identity,kesavany/carbon-identity,harsha1979/carbon-identity,ashalya/carbon-identity,madurangasiriwardena/carbon-identity,uvindra/carbon-identity,0xkasun/carbon-identity,wso2/carbon-identity,JKAUSHALYA/carbon-identity,DMHP/carbon-identity,kasungayan/carbon-identity,hpmtissera/carbon-identity,IsuraD/carbon-identity,ashalya/carbon-identity,prabathabey/carbon-identity,Niranjan-K/carbon-identity,hasinthaindrajee/carbon-identity,nuwandi-is/carbon-identity,virajsenevirathne/carbon-identity,virajsenevirathne/carbon-identity | /*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.application.mgt;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.impl.SAMLTokenIssuerConfig;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.core.RegistryResources;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.ApplicationBasicInfo;
import org.wso2.carbon.identity.application.common.model.ApplicationPermission;
import org.wso2.carbon.identity.application.common.model.AuthenticationStep;
import org.wso2.carbon.identity.application.common.model.IdentityProvider;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.PermissionsAndRoleConfig;
import org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCache;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCacheEntry;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCacheKey;
import org.wso2.carbon.identity.application.mgt.dao.ApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.IdentityProviderDAO;
import org.wso2.carbon.identity.application.mgt.dao.OAuthApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.SAMLApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.impl.FileBasedApplicationDAO;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationManagementServiceComponent;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationManagementServiceComponentHolder;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationMgtListenerServiceComponent;
import org.wso2.carbon.identity.application.mgt.listener.ApplicationMgtListener;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.security.SecurityConfigException;
import org.wso2.carbon.security.config.SecurityServiceAdmin;
import org.wso2.carbon.user.api.ClaimMapping;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Application management service implementation. Which can use as an osgi
* service and reuse this in admin service
*/
public class ApplicationManagementServiceImpl extends ApplicationManagementService {
private static Log log = LogFactory.getLog(ApplicationManagementServiceImpl.class);
private static volatile ApplicationManagementServiceImpl appMgtService;
/**
* Private constructor which not allow to create object from outside
*/
private ApplicationManagementServiceImpl() {
}
/**
* Get ApplicationManagementServiceImpl instance
*
* @return ApplicationManagementServiceImpl
*/
public static ApplicationManagementServiceImpl getInstance() {
if (appMgtService == null) {
synchronized (ApplicationManagementServiceImpl.class) {
if (appMgtService == null) {
appMgtService = new ApplicationManagementServiceImpl();
}
}
}
return appMgtService;
}
@Override
public int createApplication(ServiceProvider serviceProvider, String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
// invoking the listeners
List<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getListners();
for (ApplicationMgtListener listener : listeners) {
listener.createApplication(serviceProvider);
}
// first we need to create a role with the application name.
// only the users in this role will be able to edit/update the
// application.
ApplicationMgtUtil.createAppRole(serviceProvider.getApplicationName());
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ApplicationMgtUtil.storePermission(serviceProvider.getApplicationName(),
serviceProvider.getPermissionAndRoleConfig());
return appDAO.createApplication(serviceProvider, tenantDomain);
} catch (Exception e) {
String error = "Error occurred while creating the application, " + serviceProvider.getApplicationName();
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public ServiceProvider getApplicationExcludingFileBasedSPs(String applicationName, String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(applicationName, tenantDomain);
loadApplicationPermissions(applicationName, serviceProvider);
return serviceProvider;
} catch (Exception e) {
String error = "Error occurred while retrieving the application, " + applicationName;
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public ApplicationBasicInfo[] getAllApplicationBasicInfo(String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
return appDAO.getAllApplicationBasicInfo();
} catch (Exception e) {
String error = "Error occurred while retrieving the all applications";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public void updateApplication(ServiceProvider serviceProvider, String tenantDomain)
throws IdentityApplicationManagementException {
try {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProvider.getApplicationName());
IdentityServiceProviderCache.getInstance().clearCacheEntry(cacheKey);
} finally {
PrivilegedCarbonContext.endTenantFlow();
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
}
// invoking the listeners
List<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getListners();
for (ApplicationMgtListener listener : listeners) {
listener.updateApplication(serviceProvider);
}
// check whether use is authorized to update the application.
if (!ApplicationConstants.LOCAL_SP.equals(serviceProvider.getApplicationName()) &&
!ApplicationMgtUtil.isUserAuthorized(serviceProvider.getApplicationName(),
serviceProvider.getApplicationID())) {
log.warn("Illegal Access! User " +
CarbonContext.getThreadLocalCarbonContext().getUsername() +
" does not have access to the application " +
serviceProvider.getApplicationName());
throw new IdentityApplicationManagementException("User not authorized");
}
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
String storedAppName = appDAO.getApplicationName(serviceProvider.getApplicationID());
appDAO.updateApplication(serviceProvider);
ApplicationPermission[] permissions = serviceProvider.getPermissionAndRoleConfig().getPermissions();
String applicationNode = ApplicationMgtUtil.getApplicationPermissionPath() + RegistryConstants
.PATH_SEPARATOR + storedAppName;
org.wso2.carbon.registry.api.Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext()
.getRegistry(RegistryType.USER_GOVERNANCE);
boolean exist = tenantGovReg.resourceExists(applicationNode);
if (exist && !storedAppName.equals(serviceProvider.getApplicationName())) {
ApplicationMgtUtil.renameAppPermissionPathNode(storedAppName, serviceProvider.getApplicationName());
}
if (ArrayUtils.isNotEmpty(permissions)) {
ApplicationMgtUtil.updatePermissions(serviceProvider.getApplicationName(), permissions);
}
} catch (Exception e) {
String error = "Error occurred while updating the application";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
private void setTenantDomainInThreadLocalCarbonContext(String tenantDomain)
throws IdentityApplicationManagementException {
int tenantId = 0;
try {
tenantId = ApplicationManagementServiceComponentHolder.getInstance().getRealmService()
.getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new IdentityApplicationManagementException("Error when setting tenant domain. ", e);
}
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
}
@Override
public void deleteApplication(String applicationName, String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
// invoking the listeners
List<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getListners();
for (ApplicationMgtListener listener : listeners) {
listener.deleteApplication(applicationName);
}
if (!ApplicationMgtUtil.isUserAuthorized(applicationName)) {
log.warn("Illegal Access! User " + CarbonContext.getThreadLocalCarbonContext().getUsername() +
" does not have access to the application " + applicationName);
throw new IdentityApplicationManagementException("User not authorized");
}
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(applicationName, tenantDomain);
appDAO.deleteApplication(applicationName);
ApplicationMgtUtil.deleteAppRole(applicationName);
ApplicationMgtUtil.deletePermissions(applicationName);
if (serviceProvider != null &&
serviceProvider.getInboundAuthenticationConfig() != null &&
serviceProvider.getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs() != null) {
InboundAuthenticationRequestConfig[] configs = serviceProvider.getInboundAuthenticationConfig()
.getInboundAuthenticationRequestConfigs();
for (InboundAuthenticationRequestConfig config : configs) {
if (IdentityApplicationConstants.Authenticator.SAML2SSO.NAME.
equalsIgnoreCase(config.getInboundAuthType()) && config.getInboundAuthKey() != null) {
SAMLApplicationDAO samlDAO = ApplicationMgtSystemConfig.getInstance().getSAMLClientDAO();
samlDAO.removeServiceProviderConfiguration(config.getInboundAuthKey());
} else if (IdentityApplicationConstants.OAuth2.NAME.equalsIgnoreCase(config.getInboundAuthType()) &&
config.getInboundAuthKey() != null) {
OAuthApplicationDAO oathDAO = ApplicationMgtSystemConfig.getInstance().getOAuthOIDCClientDAO();
oathDAO.removeOAuthApplication(config.getInboundAuthKey());
} else if (IdentityApplicationConstants.Authenticator.WSTrust.NAME.equalsIgnoreCase(
config.getInboundAuthType()) && config.getInboundAuthKey() != null) {
try {
AxisService stsService = getAxisConfig().getService(ServerConstants.STS_NAME);
Parameter origParam =
stsService.getParameter(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG.getLocalPart());
if (origParam != null) {
OMElement samlConfigElem = origParam.getParameterElement()
.getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG);
SAMLTokenIssuerConfig samlConfig = new SAMLTokenIssuerConfig(samlConfigElem);
samlConfig.getTrustedServices().remove(config.getInboundAuthKey());
setSTSParameter(samlConfig);
removeTrustedService(ServerConstants.STS_NAME, ServerConstants.STS_NAME,
config.getInboundAuthKey());
} else {
throw new IdentityApplicationManagementException(
"missing parameter : " + SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG.getLocalPart());
}
} catch (Exception e) {
String error = "Error while removing a trusted service";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
}
}
} catch (Exception e) {
String error = "Error occurred while deleting the application";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public IdentityProvider getIdentityProvider(String federatedIdPName, String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
return idpdao.getIdentityProvider(federatedIdPName);
} catch (Exception e) {
String error = "Error occurred while retrieving Identity Provider";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public IdentityProvider[] getAllIdentityProviders(String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<IdentityProvider> fedIdpList = idpdao.getAllIdentityProviders();
if (fedIdpList != null) {
return fedIdpList.toArray(new IdentityProvider[fedIdpList.size()]);
}
return new IdentityProvider[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Identity Providers";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public LocalAuthenticatorConfig[] getAllLocalAuthenticators(String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<LocalAuthenticatorConfig> localAuthenticators = idpdao.getAllLocalAuthenticators();
if (localAuthenticators != null) {
return localAuthenticators.toArray(new LocalAuthenticatorConfig[localAuthenticators.size()]);
}
return new LocalAuthenticatorConfig[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Local Authenticators";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public RequestPathAuthenticatorConfig[] getAllRequestPathAuthenticators(String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<RequestPathAuthenticatorConfig> reqPathAuthenticators = idpdao.getAllRequestPathAuthenticators();
if (reqPathAuthenticators != null) {
return reqPathAuthenticators.toArray(new RequestPathAuthenticatorConfig[reqPathAuthenticators.size()]);
}
return new RequestPathAuthenticatorConfig[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Request Path Authenticators";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public String[] getAllLocalClaimUris(String tenantDomain) throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
String claimDialect = ApplicationMgtSystemConfig.getInstance().getClaimDialect();
ClaimMapping[] claimMappings = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getClaimManager()
.getAllClaimMappings(claimDialect);
List<String> claimUris = new ArrayList<>();
for (ClaimMapping claimMap : claimMappings) {
claimUris.add(claimMap.getClaim().getClaimUri());
}
return claimUris.toArray(new String[claimUris.size()]);
} catch (Exception e) {
String error = "Error while reading system claims";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public String getServiceProviderNameByClientIdExcludingFileBasedSPs(String clientId, String type, String
tenantDomain)
throws IdentityApplicationManagementException {
try {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
return appDAO.getServiceProviderNameByClientId(clientId, type, tenantDomain);
} catch (Exception e) {
String error = "Error occurred while retrieving the service provider for client id : " + clientId;
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
/**
* [sp-claim-uri,local-idp-claim-uri]
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public Map<String, String> getServiceProviderToLocalIdPClaimMapping(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
Map<String, String> claimMap = appDAO.getServiceProviderToLocalIdPClaimMapping(
serviceProviderName, tenantDomain);
if (claimMap == null
|| claimMap.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getServiceProviderToLocalIdPClaimMapping(
serviceProviderName, tenantDomain);
}
return claimMap;
}
/**
* [local-idp-claim-uri,sp-claim-uri]
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public Map<String, String> getLocalIdPToServiceProviderClaimMapping(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
Map<String, String> claimMap = appDAO.getLocalIdPToServiceProviderClaimMapping(
serviceProviderName, tenantDomain);
if (claimMap == null
|| claimMap.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getLocalIdPToServiceProviderClaimMapping(
serviceProviderName, tenantDomain);
}
return claimMap;
}
/**
* Returns back the requested set of claims by the provided service provider in local idp claim
* dialect.
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public List<String> getAllRequestedClaimsByServiceProvider(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
List<String> reqClaims = appDAO.getAllRequestedClaimsByServiceProvider(serviceProviderName,
tenantDomain);
if (reqClaims == null
|| reqClaims.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getAllRequestedClaimsByServiceProvider(
serviceProviderName, tenantDomain);
}
return reqClaims;
}
/**
* @param clientId
* @param clientType
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public String getServiceProviderNameByClientId(String clientId, String clientType,
String tenantDomain) throws IdentityApplicationManagementException {
String name;
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
name = appDAO.getServiceProviderNameByClientId(clientId, clientType, tenantDomain);
if (name == null) {
name = new FileBasedApplicationDAO().getServiceProviderNameByClientId(clientId,
clientType, tenantDomain);
}
if (name == null) {
ServiceProvider defaultSP = ApplicationManagementServiceComponent.getFileBasedSPs()
.get(IdentityApplicationConstants.DEFAULT_SP_CONFIG);
name = defaultSP.getApplicationName();
}
return name;
}
/**
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public ServiceProvider getServiceProvider(String serviceProviderName, String tenantDomain)
throws IdentityApplicationManagementException {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(serviceProviderName, tenantDomain);
if (serviceProvider != null) {
loadApplicationPermissions(serviceProviderName, serviceProvider);
}
if (serviceProvider == null
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
serviceProvider = ApplicationManagementServiceComponent.getFileBasedSPs().get(
serviceProviderName);
}
return serviceProvider;
}
/**
* @param clientId
* @param clientType
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public ServiceProvider getServiceProviderByClientId(String clientId, String clientType, String tenantDomain)
throws IdentityApplicationManagementException {
// client id can contain the @ to identify the tenant domain.
if (clientId != null && clientId.contains("@")) {
clientId = clientId.split("@")[0];
}
String serviceProviderName;
ServiceProvider serviceProvider = null;
serviceProviderName = getServiceProviderNameByClientId(clientId, clientType, tenantDomain);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
.getThreadLocalCarbonContext();
carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProviderName);
IdentityServiceProviderCacheEntry entry = ((IdentityServiceProviderCacheEntry) IdentityServiceProviderCache
.getInstance().getValueFromCache(cacheKey));
if (entry != null) {
return entry.getServiceProvider();
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
}
if (serviceProviderName != null) {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
serviceProvider = appDAO.getApplication(serviceProviderName, tenantDomain);
if (serviceProvider != null) {
// if "Authentication Type" is "Default" we must get the steps from the default SP
AuthenticationStep[] authenticationSteps = serviceProvider
.getLocalAndOutBoundAuthenticationConfig().getAuthenticationSteps();
loadApplicationPermissions(serviceProviderName, serviceProvider);
if (authenticationSteps == null || authenticationSteps.length == 0) {
ServiceProvider defaultSP = ApplicationManagementServiceComponent
.getFileBasedSPs().get(IdentityApplicationConstants.DEFAULT_SP_CONFIG);
authenticationSteps = defaultSP.getLocalAndOutBoundAuthenticationConfig()
.getAuthenticationSteps();
serviceProvider.getLocalAndOutBoundAuthenticationConfig()
.setAuthenticationSteps(authenticationSteps);
}
}
}
if (serviceProvider == null
&& serviceProviderName != null
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
serviceProvider = ApplicationManagementServiceComponent.getFileBasedSPs().get(
serviceProviderName);
}
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
.getThreadLocalCarbonContext();
carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProviderName);
IdentityServiceProviderCacheEntry entry = new IdentityServiceProviderCacheEntry();
entry.setServiceProvider(serviceProvider);
IdentityServiceProviderCache.getInstance().addToCache(cacheKey, entry);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return serviceProvider;
}
private void loadApplicationPermissions(String serviceProviderName, ServiceProvider serviceProvider)
throws IdentityApplicationManagementException {
List<ApplicationPermission> permissionList = ApplicationMgtUtil.loadPermissions(serviceProviderName);
if (permissionList != null) {
PermissionsAndRoleConfig permissionAndRoleConfig;
if (serviceProvider.getPermissionAndRoleConfig() == null) {
permissionAndRoleConfig = new PermissionsAndRoleConfig();
} else {
permissionAndRoleConfig = serviceProvider.getPermissionAndRoleConfig();
}
permissionAndRoleConfig.setPermissions(permissionList.toArray(
new ApplicationPermission[permissionList.size()]));
serviceProvider.setPermissionAndRoleConfig(permissionAndRoleConfig);
}
}
/**
* Set STS parameters
*
* @param samlConfig SAML config
* @throws org.apache.axis2.AxisFault
* @throws org.wso2.carbon.registry.api.RegistryException
*/
private void setSTSParameter(SAMLTokenIssuerConfig samlConfig) throws AxisFault,
RegistryException {
new SecurityServiceAdmin(getAxisConfig(), getConfigSystemRegistry()).
setServiceParameterElement(ServerConstants.STS_NAME, samlConfig.getParameter());
}
/**
* Remove trusted service
*
* @param groupName Group name
* @param serviceName Service name
* @param trustedService Trusted service name
* @throws org.wso2.carbon.security.SecurityConfigException
*/
private void removeTrustedService(String groupName, String serviceName, String trustedService)
throws SecurityConfigException {
Registry registry;
String resourcePath;
Resource resource;
try {
resourcePath = RegistryResources.SERVICE_GROUPS + groupName +
RegistryResources.SERVICES + serviceName + "/trustedServices";
registry = getConfigSystemRegistry();
if (registry != null) {
if (registry.resourceExists(resourcePath)) {
resource = registry.get(resourcePath);
if (resource.getProperty(trustedService) != null) {
resource.removeProperty(trustedService);
}
registry.put(resourcePath, resource);
}
}
} catch (Exception e) {
String error = "Error occurred while removing trusted service for STS";
log.error(error, e);
throw new SecurityConfigException(error, e);
}
}
/**
* Get axis config
*
* @return axis configuration
*/
private AxisConfiguration getAxisConfig() {
return ApplicationManagementServiceComponentHolder.getInstance().getConfigContextService()
.getServerConfigContext().getAxisConfiguration();
}
/**
* Get config system registry
*
* @return config system registry
* @throws org.wso2.carbon.registry.api.RegistryException
*/
private Registry getConfigSystemRegistry() throws RegistryException {
return (Registry) ApplicationManagementServiceComponentHolder.getInstance().getRegistryService()
.getConfigSystemRegistry();
}
}
| components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImpl.java | /*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.application.mgt;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.impl.SAMLTokenIssuerConfig;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.core.RegistryResources;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.ApplicationBasicInfo;
import org.wso2.carbon.identity.application.common.model.ApplicationPermission;
import org.wso2.carbon.identity.application.common.model.AuthenticationStep;
import org.wso2.carbon.identity.application.common.model.IdentityProvider;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.PermissionsAndRoleConfig;
import org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCache;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCacheEntry;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCacheKey;
import org.wso2.carbon.identity.application.mgt.dao.ApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.IdentityProviderDAO;
import org.wso2.carbon.identity.application.mgt.dao.OAuthApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.SAMLApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.impl.FileBasedApplicationDAO;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationManagementServiceComponent;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationManagementServiceComponentHolder;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationMgtListenerServiceComponent;
import org.wso2.carbon.identity.application.mgt.listener.ApplicationMgtListener;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.security.SecurityConfigException;
import org.wso2.carbon.security.config.SecurityServiceAdmin;
import org.wso2.carbon.user.api.ClaimMapping;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Application management service implementation. Which can use as an osgi
* service and reuse this in admin service
*/
public class ApplicationManagementServiceImpl extends ApplicationManagementService {
private static Log log = LogFactory.getLog(ApplicationManagementServiceImpl.class);
private static volatile ApplicationManagementServiceImpl appMgtService;
/**
* Private constructor which not allow to create object from outside
*/
private ApplicationManagementServiceImpl() {
}
/**
* Get ApplicationManagementServiceImpl instance
*
* @return ApplicationManagementServiceImpl
*/
public static ApplicationManagementServiceImpl getInstance() {
if (appMgtService == null) {
synchronized (ApplicationManagementServiceImpl.class) {
if (appMgtService == null) {
appMgtService = new ApplicationManagementServiceImpl();
}
}
}
return appMgtService;
}
@Override
public int createApplication(ServiceProvider serviceProvider, String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
// invoking the listeners
List<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getListners();
for (ApplicationMgtListener listener : listeners) {
listener.createApplication(serviceProvider);
}
// first we need to create a role with the application name.
// only the users in this role will be able to edit/update the
// application.
ApplicationMgtUtil.createAppRole(serviceProvider.getApplicationName());
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ApplicationMgtUtil.storePermission(serviceProvider.getApplicationName(),
serviceProvider.getPermissionAndRoleConfig());
return appDAO.createApplication(serviceProvider, tenantDomain);
} catch (Exception e) {
String error = "Error occurred while creating the application, " + serviceProvider.getApplicationName();
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public ServiceProvider getApplicationExcludingFileBasedSPs(String applicationName, String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(applicationName, tenantDomain);
loadApplicationPermissions(applicationName, serviceProvider);
return serviceProvider;
} catch (Exception e) {
String error = "Error occurred while retrieving the application, " + applicationName;
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public ApplicationBasicInfo[] getAllApplicationBasicInfo(String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
return appDAO.getAllApplicationBasicInfo();
} catch (Exception e) {
String error = "Error occurred while retrieving the all applications";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public void updateApplication(ServiceProvider serviceProvider, String tenantDomain)
throws IdentityApplicationManagementException {
try {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProvider.getApplicationName());
IdentityServiceProviderCache.getInstance().clearCacheEntry(cacheKey);
} finally {
PrivilegedCarbonContext.endTenantFlow();
if (tenantDomain != null) {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
}
}
// invoking the listeners
List<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getListners();
for (ApplicationMgtListener listener : listeners) {
listener.updateApplication(serviceProvider);
}
// check whether use is authorized to update the application.
if (!ApplicationConstants.LOCAL_SP.equals(serviceProvider.getApplicationName()) &&
!ApplicationMgtUtil.isUserAuthorized(serviceProvider.getApplicationName(),
serviceProvider.getApplicationID())) {
log.warn("Illegal Access! User " +
CarbonContext.getThreadLocalCarbonContext().getUsername() +
" does not have access to the application " +
serviceProvider.getApplicationName());
throw new IdentityApplicationManagementException("User not authorized");
}
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
String storedAppName = appDAO.getApplicationName(serviceProvider.getApplicationID());
appDAO.updateApplication(serviceProvider);
ApplicationPermission[] permissions = serviceProvider.getPermissionAndRoleConfig().getPermissions();
String applicationNode = ApplicationMgtUtil.getApplicationPermissionPath() + RegistryConstants
.PATH_SEPARATOR + storedAppName;
org.wso2.carbon.registry.api.Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext()
.getRegistry(RegistryType.USER_GOVERNANCE);
boolean exist = tenantGovReg.resourceExists(applicationNode);
if (exist && !storedAppName.equals(serviceProvider.getApplicationName())) {
ApplicationMgtUtil.renameAppPermissionPathNode(storedAppName, serviceProvider.getApplicationName());
}
if (ArrayUtils.isNotEmpty(permissions)) {
ApplicationMgtUtil.updatePermissions(serviceProvider.getApplicationName(), permissions);
}
} catch (Exception e) {
String error = "Error occurred while updating the application";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
private void setTenantDomainInThreadLocalCarbonContext(String tenantDomain)
throws IdentityApplicationManagementException {
int tenantId = 0;
try {
tenantId = ApplicationManagementServiceComponentHolder.getInstance().getRealmService()
.getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new IdentityApplicationManagementException("Error when setting tenant domain. ", e);
}
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
}
@Override
public void deleteApplication(String applicationName, String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
// invoking the listeners
List<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getListners();
for (ApplicationMgtListener listener : listeners) {
listener.deleteApplication(applicationName);
}
if (!ApplicationMgtUtil.isUserAuthorized(applicationName)) {
log.warn("Illegal Access! User " + CarbonContext.getThreadLocalCarbonContext().getUsername() +
" does not have access to the application " + applicationName);
throw new IdentityApplicationManagementException("User not authorized");
}
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(applicationName, tenantDomain);
appDAO.deleteApplication(applicationName);
ApplicationMgtUtil.deleteAppRole(applicationName);
ApplicationMgtUtil.deletePermissions(applicationName);
if (serviceProvider != null &&
serviceProvider.getInboundAuthenticationConfig() != null &&
serviceProvider.getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs() != null) {
InboundAuthenticationRequestConfig[] configs = serviceProvider.getInboundAuthenticationConfig()
.getInboundAuthenticationRequestConfigs();
for (InboundAuthenticationRequestConfig config : configs) {
if (IdentityApplicationConstants.Authenticator.SAML2SSO.NAME.
equalsIgnoreCase(config.getInboundAuthType()) && config.getInboundAuthKey() != null) {
SAMLApplicationDAO samlDAO = ApplicationMgtSystemConfig.getInstance().getSAMLClientDAO();
samlDAO.removeServiceProviderConfiguration(config.getInboundAuthKey());
} else if (IdentityApplicationConstants.OAuth2.NAME.equalsIgnoreCase(config.getInboundAuthType()) &&
config.getInboundAuthKey() != null) {
OAuthApplicationDAO oathDAO = ApplicationMgtSystemConfig.getInstance().getOAuthOIDCClientDAO();
oathDAO.removeOAuthApplication(config.getInboundAuthKey());
} else if (IdentityApplicationConstants.Authenticator.WSTrust.NAME.equalsIgnoreCase(
config.getInboundAuthType()) && config.getInboundAuthKey() != null) {
try {
AxisService stsService = getAxisConfig().getService(ServerConstants.STS_NAME);
Parameter origParam =
stsService.getParameter(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG.getLocalPart());
if (origParam != null) {
OMElement samlConfigElem = origParam.getParameterElement()
.getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG);
SAMLTokenIssuerConfig samlConfig = new SAMLTokenIssuerConfig(samlConfigElem);
samlConfig.getTrustedServices().remove(config.getInboundAuthKey());
setSTSParameter(samlConfig);
removeTrustedService(ServerConstants.STS_NAME, ServerConstants.STS_NAME,
config.getInboundAuthKey());
} else {
throw new IdentityApplicationManagementException(
"missing parameter : " + SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG.getLocalPart());
}
} catch (Exception e) {
String error = "Error while removing a trusted service";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
}
}
} catch (Exception e) {
String error = "Error occurred while deleting the application";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public IdentityProvider getIdentityProvider(String federatedIdPName, String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
return idpdao.getIdentityProvider(federatedIdPName);
} catch (Exception e) {
String error = "Error occurred while retrieving Identity Provider";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public IdentityProvider[] getAllIdentityProviders(String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<IdentityProvider> fedIdpList = idpdao.getAllIdentityProviders();
if (fedIdpList != null) {
return fedIdpList.toArray(new IdentityProvider[fedIdpList.size()]);
}
return new IdentityProvider[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Identity Providers";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public LocalAuthenticatorConfig[] getAllLocalAuthenticators(String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<LocalAuthenticatorConfig> localAuthenticators = idpdao.getAllLocalAuthenticators();
if (localAuthenticators != null) {
return localAuthenticators.toArray(new LocalAuthenticatorConfig[localAuthenticators.size()]);
}
return new LocalAuthenticatorConfig[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Local Authenticators";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public RequestPathAuthenticatorConfig[] getAllRequestPathAuthenticators(String tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<RequestPathAuthenticatorConfig> reqPathAuthenticators = idpdao.getAllRequestPathAuthenticators();
if (reqPathAuthenticators != null) {
return reqPathAuthenticators.toArray(new RequestPathAuthenticatorConfig[reqPathAuthenticators.size()]);
}
return new RequestPathAuthenticatorConfig[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Request Path Authenticators";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public String[] getAllLocalClaimUris(String tenantDomain) throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
String claimDialect = ApplicationMgtSystemConfig.getInstance().getClaimDialect();
ClaimMapping[] claimMappings = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getClaimManager()
.getAllClaimMappings(claimDialect);
List<String> claimUris = new ArrayList<>();
for (ClaimMapping claimMap : claimMappings) {
claimUris.add(claimMap.getClaim().getClaimUri());
}
return claimUris.toArray(new String[claimUris.size()]);
} catch (Exception e) {
String error = "Error while reading system claims";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
@Override
public String getServiceProviderNameByClientIdExcludingFileBasedSPs(String clientId, String type, String
tenantDomain)
throws IdentityApplicationManagementException {
try {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
return appDAO.getServiceProviderNameByClientId(clientId, type, tenantDomain);
} catch (Exception e) {
String error = "Error occurred while retrieving the service provider for client id : " + clientId;
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
/**
* [sp-claim-uri,local-idp-claim-uri]
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public Map<String, String> getServiceProviderToLocalIdPClaimMapping(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
Map<String, String> claimMap = appDAO.getServiceProviderToLocalIdPClaimMapping(
serviceProviderName, tenantDomain);
if (claimMap == null
|| claimMap.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getServiceProviderToLocalIdPClaimMapping(
serviceProviderName, tenantDomain);
}
return claimMap;
}
/**
* [local-idp-claim-uri,sp-claim-uri]
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public Map<String, String> getLocalIdPToServiceProviderClaimMapping(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
Map<String, String> claimMap = appDAO.getLocalIdPToServiceProviderClaimMapping(
serviceProviderName, tenantDomain);
if (claimMap == null
|| claimMap.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getLocalIdPToServiceProviderClaimMapping(
serviceProviderName, tenantDomain);
}
return claimMap;
}
/**
* Returns back the requested set of claims by the provided service provider in local idp claim
* dialect.
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public List<String> getAllRequestedClaimsByServiceProvider(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
List<String> reqClaims = appDAO.getAllRequestedClaimsByServiceProvider(serviceProviderName,
tenantDomain);
if (reqClaims == null
|| reqClaims.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getAllRequestedClaimsByServiceProvider(
serviceProviderName, tenantDomain);
}
return reqClaims;
}
/**
* @param clientId
* @param clientType
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public String getServiceProviderNameByClientId(String clientId, String clientType,
String tenantDomain) throws IdentityApplicationManagementException {
String name;
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
name = appDAO.getServiceProviderNameByClientId(clientId, clientType, tenantDomain);
if (name == null) {
name = new FileBasedApplicationDAO().getServiceProviderNameByClientId(clientId,
clientType, tenantDomain);
}
if (name == null) {
ServiceProvider defaultSP = ApplicationManagementServiceComponent.getFileBasedSPs()
.get(IdentityApplicationConstants.DEFAULT_SP_CONFIG);
name = defaultSP.getApplicationName();
}
return name;
}
/**
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public ServiceProvider getServiceProvider(String serviceProviderName, String tenantDomain)
throws IdentityApplicationManagementException {
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(serviceProviderName, tenantDomain);
if (serviceProvider != null) {
loadApplicationPermissions(serviceProviderName, serviceProvider);
}
if (serviceProvider == null
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
serviceProvider = ApplicationManagementServiceComponent.getFileBasedSPs().get(
serviceProviderName);
}
return serviceProvider;
}
/**
* @param clientId
* @param clientType
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public ServiceProvider getServiceProviderByClientId(String clientId, String clientType, String tenantDomain)
throws IdentityApplicationManagementException {
// client id can contain the @ to identify the tenant domain.
if (clientId != null && clientId.contains("@")) {
clientId = clientId.split("@")[0];
}
String serviceProviderName = null;
ServiceProvider serviceProvider = null;
serviceProviderName = getServiceProviderNameByClientId(clientId, clientType, tenantDomain);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
.getThreadLocalCarbonContext();
carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProviderName);
IdentityServiceProviderCacheEntry entry = ((IdentityServiceProviderCacheEntry) IdentityServiceProviderCache
.getInstance().getValueFromCache(cacheKey));
if (entry != null) {
return entry.getServiceProvider();
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
setTenantDomainInThreadLocalCarbonContext(tenantDomain);
}
if (serviceProviderName != null) {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
serviceProvider = appDAO.getApplication(serviceProviderName, tenantDomain);
if (serviceProvider != null) {
// if "Authentication Type" is "Default" we must get the steps from the default SP
AuthenticationStep[] authenticationSteps = serviceProvider
.getLocalAndOutBoundAuthenticationConfig().getAuthenticationSteps();
loadApplicationPermissions(serviceProviderName, serviceProvider);
if (authenticationSteps == null || authenticationSteps.length == 0) {
ServiceProvider defaultSP = ApplicationManagementServiceComponent
.getFileBasedSPs().get(IdentityApplicationConstants.DEFAULT_SP_CONFIG);
authenticationSteps = defaultSP.getLocalAndOutBoundAuthenticationConfig()
.getAuthenticationSteps();
serviceProvider.getLocalAndOutBoundAuthenticationConfig()
.setAuthenticationSteps(authenticationSteps);
}
}
}
if (serviceProvider == null
&& serviceProviderName != null
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
serviceProvider = ApplicationManagementServiceComponent.getFileBasedSPs().get(
serviceProviderName);
}
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
.getThreadLocalCarbonContext();
carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProviderName);
IdentityServiceProviderCacheEntry entry = new IdentityServiceProviderCacheEntry();
entry.setServiceProvider(serviceProvider);
IdentityServiceProviderCache.getInstance().addToCache(cacheKey, entry);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return serviceProvider;
}
private void loadApplicationPermissions(String serviceProviderName, ServiceProvider serviceProvider)
throws IdentityApplicationManagementException {
List<ApplicationPermission> permissionList = ApplicationMgtUtil.loadPermissions(serviceProviderName);
if (permissionList != null) {
PermissionsAndRoleConfig permissionAndRoleConfig;
if (serviceProvider.getPermissionAndRoleConfig() == null) {
permissionAndRoleConfig = new PermissionsAndRoleConfig();
} else {
permissionAndRoleConfig = serviceProvider.getPermissionAndRoleConfig();
}
permissionAndRoleConfig.setPermissions(permissionList.toArray(
new ApplicationPermission[permissionList.size()]));
serviceProvider.setPermissionAndRoleConfig(permissionAndRoleConfig);
}
}
/**
* Set STS parameters
*
* @param samlConfig SAML config
* @throws org.apache.axis2.AxisFault
* @throws org.wso2.carbon.registry.api.RegistryException
*/
private void setSTSParameter(SAMLTokenIssuerConfig samlConfig) throws AxisFault,
RegistryException {
new SecurityServiceAdmin(getAxisConfig(), getConfigSystemRegistry()).
setServiceParameterElement(ServerConstants.STS_NAME, samlConfig.getParameter());
}
/**
* Remove trusted service
*
* @param groupName Group name
* @param serviceName Service name
* @param trustedService Trusted service name
* @throws org.wso2.carbon.security.SecurityConfigException
*/
private void removeTrustedService(String groupName, String serviceName, String trustedService)
throws SecurityConfigException {
Registry registry;
String resourcePath;
Resource resource;
try {
resourcePath = RegistryResources.SERVICE_GROUPS + groupName +
RegistryResources.SERVICES + serviceName + "/trustedServices";
registry = getConfigSystemRegistry();
if (registry != null) {
if (registry.resourceExists(resourcePath)) {
resource = registry.get(resourcePath);
if (resource.getProperty(trustedService) != null) {
resource.removeProperty(trustedService);
}
registry.put(resourcePath, resource);
}
}
} catch (Exception e) {
String error = "Error occurred while removing trusted service for STS";
log.error(error, e);
throw new SecurityConfigException(error, e);
}
}
/**
* Get axis config
*
* @return axis configuration
*/
private AxisConfiguration getAxisConfig() {
return ApplicationManagementServiceComponentHolder.getInstance().getConfigContextService()
.getServerConfigContext().getAxisConfiguration();
}
/**
* Get config system registry
*
* @return config system registry
* @throws org.wso2.carbon.registry.api.RegistryException
*/
private Registry getConfigSystemRegistry() throws RegistryException {
return (Registry) ApplicationManagementServiceComponentHolder.getInstance().getRegistryService()
.getConfigSystemRegistry();
}
}
| Fixing IDENTITY-3075
| components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImpl.java | Fixing IDENTITY-3075 | <ide><path>omponents/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImpl.java
<ide>
<ide> } finally {
<ide> PrivilegedCarbonContext.endTenantFlow();
<del>
<del> if (tenantDomain != null) {
<del> setTenantDomainInThreadLocalCarbonContext(tenantDomain);
<del> }
<add> setTenantDomainInThreadLocalCarbonContext(tenantDomain);
<ide> }
<ide>
<ide> // invoking the listeners
<ide> tenantDomain)
<ide> throws IdentityApplicationManagementException {
<ide> try {
<del> setTenantDomainInThreadLocalCarbonContext(tenantDomain);
<ide> ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
<ide> return appDAO.getServiceProviderNameByClientId(clientId, type, tenantDomain);
<ide>
<ide> clientId = clientId.split("@")[0];
<ide> }
<ide>
<del> String serviceProviderName = null;
<add> String serviceProviderName;
<ide> ServiceProvider serviceProvider = null;
<ide>
<ide> serviceProviderName = getServiceProviderNameByClientId(clientId, clientType, tenantDomain); |
|
JavaScript | mit | f18c9b22c44a720b132bbbddfbd13c228437b654 | 0 | Sosowski/Screeps_Custom,Sosowski/Screeps_Custom | var creep_farMining = {
/** @param {Creep} creep **/
run: function(creep) {
switch (creep.memory.priority) {
case 'farClaimer':
case 'farClaimerNearDeath':
if (!creep.memory.deathWarn) {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
if (creep.ticksToLive <= creep.memory.deathWarn && creep.memory.priority != 'farClaimerNearDeath') {
creep.memory.priority = 'farClaimerNearDeath';
}
if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
} else {
if (creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.moveTo(creep.room.controller, {
reusePath: 25
});
} else {
if (creep.room.controller.sign && creep.room.controller.sign.username != "Montblanc") {
creep.signController(creep.room.controller, "Remote mining this! Not a fan of me being here? Let me know instead of obliterating me!");
} else if (!creep.room.controller.sign) {
creep.signController(creep.room.controller, "Remote mining this! Not a fan of me being here? Let me know instead of obliterating me!");
}
}
}
evadeAttacker(creep, 5);
break;
case 'farMiner':
case 'farMinerNearDeath':
if (!creep.memory.deathWarn) {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
if (creep.ticksToLive <= creep.memory.deathWarn && creep.memory.priority != 'farMinerNearDeath') {
creep.memory.priority = 'farMinerNearDeath';
}
var hostiles = [];
if (creep.hits < creep.hitsMax) {
hostiles = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 3, {
filter: (creep) => (creep.getActiveBodyparts(WORK) > 0 || creep.getActiveBodyparts(CARRY) > 0 || creep.getActiveBodyparts(ATTACK) > 0 || creep.getActiveBodyparts(RANGED_ATTACK) > 0 || creep.getActiveBodyparts(HEAL) > 0) || (creep.hits <= 500)
});
}
if (creep.hits < 400) {
//Determine if attacker is player, if so, delete flag.
if (hostiles.length > 0 && hostiles[0].owner.username != 'Invader' && hostiles[0].owner.username != 'Source Keeper' && Game.flags[creep.memory.targetFlag]) {
Game.notify(creep.memory.tragetFlag + ' was removed due to an attack by ' + hostiles[0].owner.username);
if (!Memory.warMode) {
Memory.warMode = true;
Game.notify('War mode has been enabled.');
}
Game.flags[creep.memory.targetFlag].remove();
}
}
if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
reusePath: 25
});
} else {
if (creep.room.controller && creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
if (creep.room.controller.reservation.ticksToEnd <= 1000 && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
} else if (creep.room.name == creep.memory.destination && creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (!creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
var mineTarget = undefined;
var thisUnit = undefined;
if (creep.memory.storageUnit) {
thisUnit = Game.getObjectById(creep.memory.storageUnit);
}
if (creep.memory.mineSource) {
mineTarget = Game.getObjectById(creep.memory.mineSource);
var StorageOK = true;
if (thisUnit && _.sum(thisUnit.store) == thisUnit.storeCapacity) {
StorageOK = false;
}
if (mineTarget && _.sum(creep.carry) <= 40 && mineTarget.energy > 0 && StorageOK) {
if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(mineTarget, {
reusePath: 25,
maxRooms: 1
});
}
} else if (mineTarget && !creep.pos.isNearTo(mineTarget)) {
creep.moveTo(mineTarget, {
reusePath: 25,
maxRooms: 1
});
}
} else {
//Get the source ID while in the room
var markedSources = [];
if (Game.flags[creep.memory.targetFlag]) {
markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
}
if (markedSources.length) {
creep.memory.mineSource = markedSources[0].id;
}
mineTarget = Game.getObjectById(creep.memory.mineSource);
if (mineTarget) {
if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(mineTarget, {
reusePath: 25,
maxRooms: 1
});
}
}
}
if (creep.memory.storageUnit) {
if (thisUnit) {
if (thisUnit.hits < thisUnit.hitsMax && hostiles.length == 0) {
creep.repair(thisUnit);
} else if (creep.carry.energy >= 36) {
if (creep.transfer(thisUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisUnit, {
reusePath: 25
});
}
}
}
} else {
if (mineTarget) {
if (creep.pos.inRangeTo(mineTarget, 2)) {
var containers = creep.pos.findInRange(FIND_STRUCTURES, 2, {
filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
});
if (containers.length) {
if (creep.transfer(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(containers[0], {
reusePath: 25
});
}
creep.memory.storageUnit = containers[0].id;
} else {
if (creep.carry[RESOURCE_ENERGY] >= 36) {
var sites = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 2)
if (sites.length) {
if (creep.build(sites[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(sites[0], {
reusePath: 25
});
}
} else {
//Create new container
if (creep.pos.isNearTo(mineTarget)) {
creep.room.createConstructionSite(creep.pos, STRUCTURE_CONTAINER)
}
}
}
}
}
}
}
}
evadeAttacker(creep, 2);
break;
case 'farMule':
case 'farMuleNearDeath':
if (!creep.memory.deathWarn) {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
if ((creep.ticksToLive <= creep.memory.deathWarn || creep.getActiveBodyparts(CARRY) <= 2) && creep.memory.priority != 'farMuleNearDeath') {
creep.memory.priority = 'farMuleNearDeath';
}
if (creep.memory.storing == null) {
creep.memory.storing = false;
}
if (creep.memory.didRoadSearch == null) {
creep.memory.didRoadSearch = true;
}
var roadSearchTarget;
if (!creep.memory.lastRoom || creep.memory.lastRoom != creep.room.name) {
creep.memory.didRoadSearch = false;
creep.memory.lastRoom = creep.room.name;
//Autogenerate roads
var someSites = creep.room.find(FIND_CONSTRUCTION_SITES);
if (someSites.length) {
creep.memory.lookForSites = true;
} else {
creep.memory.lookForSites = false;
}
}
if (creep.carry.energy > 0) {
//All creeps check for road under them and repair if needed.
var someSite = [];
if (creep.memory.lookForSites) {
someSite = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 3);
}
if (someSite.length) {
creep.build(someSite[0]);
} else {
var someStructure = creep.pos.lookFor(LOOK_STRUCTURES);
if (someStructure.length && (someStructure[0].hitsMax - someStructure[0].hits >= 100) && someStructure[0].structureType == STRUCTURE_ROAD) {
creep.repair(someStructure[0]);
}
}
}
if ((creep.carry.energy > creep.carryCapacity - 300 || (creep.carry.energy > 0 && creep.ticksToLive <= 120)) && !creep.memory.storing) {
creep.memory.storing = true;
} else if (creep.carry.energy == 0 && creep.memory.storing) {
creep.memory.storing = false;
}
if (creep.room.name != creep.memory.destination && !creep.memory.storing) {
var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 3);
if (droppedSources.length) {
//Pick up dropped energy from dead mules, etc.
if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(droppedSources[0], {
reusePath: 25
});
}
} else {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
reusePath: 25
});
}
evadeAttacker(creep, 5);
} else if (creep.room.name != creep.memory.homeRoom && creep.memory.storing) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.homeRoom), {
reusePath: 25
});
if (creep.memory.didRoadSearch == false) {
if (creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) {
roadSearchTarget = new RoomPosition(25, 25, creep.memory.homeRoom);
} else if (creep.memory.containerTarget) {
var thisContainer = Game.getObjectById(creep.memory.containerTarget);
if (thisContainer && thisContainer.pos.roomName == creep.pos.roomName && creep.pos.isNearTo(thisContainer)) {
roadSearchTarget = new RoomPosition(25, 25, creep.memory.homeRoom);
}
}
}
} else {
if (creep.room.controller && creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
if (creep.room.controller.reservation.ticksToEnd <= 1000 && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
} else if (creep.room.name == creep.memory.destination && creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (!creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
if (!creep.memory.storing) {
var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 7);
if (droppedSources.length && !Memory.warMode) {
//Pick up dropped energy from dead mules, etc.
if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(droppedSources[0], {
reusePath: 25
});
}
} else {
//in farRoom, pick up container contents
if (creep.memory.containerTarget) {
var thisContainer = Game.getObjectById(creep.memory.containerTarget);
if (thisContainer) {
if (thisContainer.store[RESOURCE_ENERGY] > 0) {
if (creep.withdraw(thisContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisContainer, {
reusePath: 25,
maxRooms: 1
})
}
} else {
//Wait by controller
if (creep.room.controller) {
creep.moveTo(creep.room.controller);
} else {
creep.moveTo(25, 25);
}
}
}
} else {
//No container yet, move to be near source
if (!creep.memory.mineSource) {
var markedSources = [];
if (Game.flags[creep.memory.targetFlag]) {
markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
}
if (markedSources.length) {
creep.memory.mineSource = markedSources[0].id;
}
}
var thisSource = Game.getObjectById(creep.memory.mineSource);
if (thisSource) {
if (creep.pos.inRangeTo(thisSource, 2)) {
//Search for container
var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
});
if (containers.length > 1) {
containers = creep.pos.findInRange(FIND_STRUCTURES, 2, {
filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
});
}
if (containers.length) {
creep.memory.containerTarget = containers[0].id;
if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(containers[0], {
reusePath: 25,
maxRooms: 1
})
}
}
} else {
creep.moveTo(thisSource, {
reusePath: 25,
maxRooms: 1
})
}
}
}
}
evadeAttacker(creep, 5);
} else {
//in home room, drop off energy
var storageUnit = Game.getObjectById(creep.memory.storageSource)
if (storageUnit) {
if (creep.transfer(storageUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageUnit, {
reusePath: 25,
maxRooms: 1
})
}
if (creep.memory.didRoadSearch == false) {
roadSearchTarget = storageUnit.pos;
}
}
evadeAttacker(creep, 5);
}
}
if (!creep.memory.didRoadSearch && roadSearchTarget) {
creep.memory.didRoadSearch = true;
//Autogenerate roads
//.dest.x, .dest.y, .dest.room
var thisPath = creep.room.findPath(creep.pos, roadSearchTarget, {
ignoreCreeps: true
});
for (var thisPos in thisPath) {
if (creep.room.createConstructionSite(thisPath[thisPos].x, thisPath[thisPos].y, STRUCTURE_ROAD) == ERR_FULL) {
break;
}
if (thisPath[thisPos].x == 0 || thisPath[thisPos].x == 49 || thisPath[thisPos].y == 0 || thisPath[thisPos].y == 49) {
break;
}
}
}
break;
case 'farGuard':
case 'farGuardNearDeath':
creep.notifyWhenAttacked(false);
if (!creep.memory.deathWarn) {
if (Memory.warMode) {
creep.memory.deathWarn = _.size(creep.body) * 6;
} else {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
}
if ((creep.ticksToLive <= creep.memory.deathWarn || creep.hits < 400) && creep.memory.priority != 'farGuardNearDeath') {
creep.memory.priority = 'farGuardNearDeath';
}
//Recall guard into home room if it's under attack
if (Memory.roomsUnderAttack.indexOf(creep.memory.homeRoom) > -1 && Memory.attackDuration >= 100 && Game.flags[creep.memory.targetFlag] && !Game.flags[creep.memory.targetFlag + "TEMP"]) {
Game.flags[creep.memory.targetFlag].pos.createFlag(creep.memory.targetFlag + "TEMP");
Game.flags[creep.memory.targetFlag].remove();
var homePosition = new RoomPosition(25, 25, creep.memory.homeRoom);
homePosition.createFlag(creep.memory.targetFlag);
} else if (Memory.roomsUnderAttack.indexOf(creep.memory.homeRoom) > -1 && Memory.attackDuration >= 100 && !Game.flags[creep.memory.targetFlag] && Game.flags[creep.memory.targetFlag + "TEMP"]) {
var homePosition = new RoomPosition(25, 25, creep.memory.homeRoom);
homePosition.createFlag(creep.memory.targetFlag);
} else if (Game.flags[creep.memory.targetFlag + "TEMP"] && Memory.roomsUnderAttack.indexOf(creep.memory.homeRoom) == -1) {
if (Game.flags[creep.memory.targetFlag] && Game.flags[creep.memory.targetFlag + "TEMP"]) {
if (Game.flags[creep.memory.targetFlag].pos.roomName == Game.flags[creep.memory.targetFlag + "TEMP"].pos.roomName && Game.flags[creep.memory.targetFlag].pos.x == Game.flags[creep.memory.targetFlag + "TEMP"].pos.x && Game.flags[creep.memory.targetFlag].pos.y == Game.flags[creep.memory.targetFlag + "TEMP"].pos.y) {
Game.flags[creep.memory.targetFlag + "TEMP"].remove();
} else {
Game.flags[creep.memory.targetFlag].remove();
}
} else if (!Game.flags[creep.memory.targetFlag] && Game.flags[creep.memory.targetFlag + "TEMP"]) {
try {
Game.flags[creep.memory.targetFlag + "TEMP"].pos.createFlag(creep.memory.targetFlag);
} catch (e) {
}
}
}
if (Game.flags[creep.memory.targetFlag]) {
if (Game.flags[creep.memory.targetFlag].pos.roomName != creep.memory.destination) {
creep.memory.destination = Game.flags[creep.memory.targetFlag].pos.roomName;
}
} else if (Game.flags[creep.memory.targetFlag + "TEMP"]) {
if (Game.flags[creep.memory.targetFlag + "TEMP"].pos.roomName != creep.memory.destination) {
creep.memory.destination = Game.flags[creep.memory.targetFlag + "TEMP"].pos.roomName;
}
}
if (creep.room.controller && creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
if (creep.room.controller.reservation.ticksToEnd <= 1000 && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
} else if (creep.room.name == creep.memory.destination && creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (!creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
var Foe = [];
var closeFoe = [];
if (Game.flags[Game.flags[creep.memory.targetFlag].pos.roomName + "SKRoom"]) {
Foe = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 30, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username) && eCreep.owner.username != "Source Keeper")
});
closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username) && (eCreep.owner.username != "Source Keeper" || eCreep.hits < eCreep.hitsMax))
});
} else {
Foe = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 3, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
});
closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
});
}
if (Foe.length) {
Foe.sort(targetAttacker);
}
if (creep.room.controller && creep.room.controller.owner && creep.room.controller.owner.username != "Montblanc" && creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
reusePath: 25
});
if (creep.hits < creep.hitsMax) {
creep.heal(creep);
}
} else if (Foe.length) {
var closeRangeresult = "";
closeRangeResult = creep.rangedAttack(closeFoe);
creep.attack(closeFoe);
creep.rangedAttack(closeFoe);
if (Foe.length) {
creep.attack(Foe[0]);
creep.rangedAttack(Foe[0]);
}
if (creep.hits < creep.hitsMax) {
creep.heal(creep);
} else {
var hurtAlly = creep.pos.findInRange(FIND_MY_CREEPS, 3, {
filter: (thisCreep) => thisCreep.hits < thisCreep.hitsMax
});
if (hurtAlly.length > 0) {
if (closeRangeResult != OK) {
creep.rangedHeal(hurtAlly[0]);
}
creep.heal(hurtAlly[0]);
}
}
if (creep.pos.getRangeTo(closeFoe) > 3 || (closeFoe.getActiveBodyparts(ATTACK) > 0) || (creep.getActiveBodyparts(RANGED_ATTACK) == 0) || (creep.room.controller && creep.room.controller.safeMode)) {
if (Foe.length && Foe[0].getActiveBodyparts(ATTACK) - 2 > creep.getActiveBodyparts(ATTACK) && creep.pos.getRangeTo(Foe[0]) <= 3) {
var foeDirection = creep.pos.getDirectionTo(Foe[0]);
var y = 0;
var x = 0;
switch (foeDirection) {
case TOP:
y = 2;
break;
case TOP_RIGHT:
y = 2;
x = -2;
break;
case RIGHT:
x = -2;
break;
case BOTTOM_RIGHT:
y = -2;
x = -2;
break;
case BOTTOM:
y = -2;
break;
case BOTTOM_LEFT:
y = -2;
x = 2;
break;
case LEFT:
x = 2;
break;
case TOP_LEFT:
y = 2;
x = 2
break;
}
x = creep.pos.x + x;
y = creep.pos.y + y;
if (x < 1) {
x = 1;
if (y < 25 && y > 1) {
y = y - 1;
} else if (y < 48) {
y = y + 1;
}
} else if (x > 48) {
x = 48;
if (y < 25 && y > 1) {
y = y - 1;
} else if (y < 48) {
y = y + 1;
}
}
if (y < 1) {
y = 1;
if (x < 25 && x > 1) {
x = x - 1;
} else if (x < 48) {
x = x + 1;
}
} else if (y > 48) {
y = 48;
if (x < 25 && x > 1) {
x = x - 1;
} else if (x < 48) {
x = x + 1;
}
}
creep.moveTo(x, y, {
maxRooms: 1
});
} else {
creep.moveTo(closeFoe, {
maxRooms: 1
});
}
} else {
var foeDirection = creep.pos.getDirectionTo(closeFoe);
var y = 0;
var x = 0;
switch (foeDirection) {
case TOP:
y = 2;
break;
case TOP_RIGHT:
y = 2;
x = -2;
break;
case RIGHT:
x = -2;
break;
case BOTTOM_RIGHT:
y = -2;
x = -2;
break;
case BOTTOM:
y = -2;
break;
case BOTTOM_LEFT:
y = -2;
x = 2;
break;
case LEFT:
x = 2;
break;
case TOP_LEFT:
y = 2;
x = 2
break;
}
x = creep.pos.x + x;
y = creep.pos.y + y;
if (x < 1) {
x = 1;
if (y < 25 && y > 1) {
y = y - 1;
} else if (y < 48) {
y = y + 1;
}
} else if (x > 48) {
x = 48;
if (y < 25 && y > 1) {
y = y - 1;
} else if (y < 48) {
y = y + 1;
}
}
if (y < 1) {
y = 1;
if (x < 25 && x > 1) {
x = x - 1;
} else if (x < 48) {
x = x + 1;
}
} else if (y > 48) {
y = 48;
if (x < 25 && x > 1) {
x = x - 1;
} else if (x < 48) {
x = x + 1;
}
}
creep.moveTo(x, y, {
maxRooms: 1
});
}
} else if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
reusePath: 25
});
if (creep.hits < creep.hitsMax) {
creep.heal(creep);
}
} else if (Game.flags[creep.memory.targetFlag]) {
var closeRangeResult = "";
if (closeFoe) {
closeRangeResult = creep.rangedAttack(closeFoe);
}
if (creep.hits < creep.hitsMax) {
creep.heal(creep);
if (creep.pos != Game.flags[creep.memory.targetFlag].pos) {
creep.moveTo(Game.flags[creep.memory.targetFlag], {
maxRooms: 1
});
}
} else {
var hurtAlly = creep.room.find(FIND_MY_CREEPS, {
filter: (thisCreep) => thisCreep.hits < thisCreep.hitsMax
});
if (hurtAlly.length > 0) {
creep.moveTo(hurtAlly[0]);
if (closeRangeResult != OK) {
creep.rangedHeal(hurtAlly[0]);
}
creep.heal(hurtAlly[0]);
} else if (creep.pos != Game.flags[creep.memory.targetFlag].pos) {
creep.moveTo(Game.flags[creep.memory.targetFlag], {
maxRooms: 1
});
}
}
} else if (creep.hits < creep.hitsMax) {
creep.heal(creep);
}
break;
case 'SKAttackGuard':
case 'SKAttackGuardNearDeath':
creep.notifyWhenAttacked(false);
if (!creep.memory.deathWarn) {
if (Memory.warMode) {
creep.memory.deathWarn = _.size(creep.body) * 6;
} else {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
}
if (creep.ticksToLive <= creep.memory.deathWarn || creep.hits < 400) {
creep.memory.priority = 'SKAttackGuardNearDeath';
creep.room.visual.text("\u2620\u27A1\u2694", creep.pos.x, creep.pos.y, {
align: 'left',
color: '#7DE3B5'
});
} else {
creep.room.visual.text("\u27A1\u2694", creep.pos.x, creep.pos.y, {
align: 'left',
color: '#7DE3B5'
});
}
if (!creep.memory.healerID) {
var nearbyHealer = creep.pos.findInRange(FIND_MY_CREEPS, 2, {
filter: (mCreep) => (mCreep.memory.priority == "SKHealGuard" && mCreep.memory.targetFlag == creep.memory.targetFlag)
});
if (nearbyHealer.length) {
creep.memory.healerID = nearbyHealer[0].id;
}
}
var closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
});
var thisHealer = Game.getObjectById(creep.memory.healerID);
var healerIsNear = false;
if (thisHealer) {
healerIsNear = creep.pos.isNearTo(thisHealer);
}
if (!healerIsNear) {
if (creep.memory.getOutOfStartRoom) {
//Probably in a new room, hold.
if (creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) {
var xTarget = 0;
var yTarget = 0;
if (creep.pos.x == 0) {
xTarget = 2;
yTarget = creep.pos.y;
} else if (creep.pos.x == 49) {
xTarget = 47;
yTarget = creep.pos.y;
}
if (creep.pos.y == 0) {
yTarget = 2;
xTarget = creep.pos.x;
} else if (creep.pos.y == 49) {
yTarget = 47;
xTarget = creep.pos.x;
}
creep.moveTo(xTarget, yTarget);
}
} else {
if (Game.flags[creep.memory.targetFlag + "Rally"]) {
creep.moveTo(Game.flags[creep.memory.targetFlag + "Rally"]);
}
}
} else if (healerIsNear) {
creep.memory.getOutOfStartRoom = true;
if (Game.flags[creep.memory.targetFlag] && Game.flags[creep.memory.targetFlag].pos.roomName != creep.pos.roomName) {
creep.moveTo(new RoomPosition(25, 25, Game.flags[creep.memory.targetFlag].pos.roomName));
} else {
//In target room
if (closeFoe) {
creep.moveTo(closeFoe, {
maxRooms: 1
});
creep.attack(closeFoe);
creep.memory.targetLair = undefined;
} else if (creep.memory.targetLair) {
var thisLair = Game.getObjectById(creep.memory.targetLair);
if (!creep.isNearTo(thisLair)) {
creep.moveTo(thisLair, {
maxRooms: 1
});
}
} else {
var SKLairs = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => structure.structureType == STRUCTURE_KEEPER_LAIR
});
if (SKLairs.length) {
SKLairs.sort(SKCompare);
creep.memory.targetLair = SKLairs[0].id;
if (!creep.isNearTo(SKLairs[0])) {
creep.moveTo(SKLairs[0], {
maxRooms: 1
});
}
}
}
}
}
break;
case 'SKHealGuard':
case 'SKHealGuardNearDeath':
creep.notifyWhenAttacked(false);
if (!creep.memory.deathWarn) {
if (Memory.warMode) {
creep.memory.deathWarn = _.size(creep.body) * 6;
} else {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
}
if (creep.ticksToLive <= creep.memory.deathWarn || creep.hits < 400) {
creep.memory.priority = 'SKHealGuardNearDeath';
creep.room.visual.text("\u2620\u27A1\u2694", creep.pos.x, creep.pos.y, {
align: 'left',
color: '#7DE3B5'
});
} else {
creep.room.visual.text("\u27A1\u2694", creep.pos.x, creep.pos.y, {
align: 'left',
color: '#7DE3B5'
});
}
var targetAttacker = Game.getObjectById(creep.memory.parentAttacker);
if (targetAttacker) {
if ((creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) && targetAttacker.room.name == creep.room.name) {
var xTarget = 0;
var yTarget = 0;
if (creep.pos.x == 0) {
xTarget = 2;
yTarget = creep.pos.y;
} else if (creep.pos.x == 49) {
xTarget = 47;
yTarget = creep.pos.y;
}
if (creep.pos.y == 0) {
yTarget = 2;
xTarget = creep.pos.x;
} else if (creep.pos.y == 49) {
yTarget = 47;
xTarget = creep.pos.x;
}
creep.moveTo(xTarget, yTarget);
} else {
if (creep.pos.inRangeTo(targetAttacker, 2)) {
creep.move(creep.pos.getDirectionTo(targetAttacker));
} else {
if (targetAttacker.room.name == creep.room.name) {
creep.moveTo(targetAttacker, {
reusePath: 2,
maxRooms: 1
});
} else {
creep.moveTo(targetAttacker, {
reusePath: 0
});
}
}
}
if (creep.hits < creep.hitsMax - 99) {
creep.heal(creep);
} else if (targetAttacker.hits < targetAttacker.hitsMax) {
if (creep.pos.getRangeTo(targetAttacker) > 1) {
creep.rangedHeal(targetAttacker);
} else {
creep.heal(targetAttacker);
}
} else {
var hurtAlly = creep.pos.findInRange(FIND_MY_CREEPS, 3, {
filter: (thisCreep) => thisCreep.hits < thisCreep.hitsMax
});
if (hurtAlly.length > 0) {
if (creep.pos.getRangeTo(hurtAlly[0]) > 1) {
creep.rangedHeal(hurtAlly[0]);
} else {
creep.heal(hurtAlly[0]);
}
}
}
} else {
if (Game.flags[creep.memory.targetFlag + "Rally"]) {
creep.moveTo(Game.flags[creep.memory.targetFlag + "Rally"]);
}
var newTarget = creep.pos.findInRange(FIND_MY_CREEPS, 2, {
filter: (mCreep) => (mCreep.memory.priority == "SKAttackGuard")
});
if (newTarget.length) {
creep.memory.parentAttacker = newTarget[0].id;
}
}
break;
}
}
};
function evadeAttacker(creep, evadeRange) {
var Foe = creep.pos.findInRange(FIND_HOSTILE_CREEPS, evadeRange, {
filter: (eCreep) => ((eCreep.getActiveBodyparts(ATTACK) > 0 || eCreep.getActiveBodyparts(RANGED_ATTACK) > 0) && !Memory.whiteList.includes(eCreep.owner.username))
});
var closeFoe = undefined;
if (creep.hits < creep.hitsMax) {
creep.heal(creep);
}
if (creep.getActiveBodyparts(RANGED_ATTACK) > 0) {
closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
});
if (closeFoe) {
creep.rangedAttack(closeFoe);
}
}
if (Foe.length) {
if (!closeFoe) {
closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
filter: (eCreep) => ((eCreep.getActiveBodyparts(ATTACK) > 0 || eCreep.getActiveBodyparts(RANGED_ATTACK) > 0) && !Memory.whiteList.includes(eCreep.owner.username))
});
}
var foeDirection = creep.pos.getDirectionTo(closeFoe);
var y = 0;
var x = 0;
switch (foeDirection) {
case TOP:
y = 2;
break;
case TOP_RIGHT:
y = 2;
x = -2;
break;
case RIGHT:
x = -2;
break;
case BOTTOM_RIGHT:
y = -2;
x = -2;
break;
case BOTTOM:
y = -2;
break;
case BOTTOM_LEFT:
y = -2;
x = 2;
break;
case LEFT:
x = 2;
break;
case TOP_LEFT:
y = 2;
x = 2
break;
}
x = creep.pos.x + x;
y = creep.pos.y + y;
if (x < 0) {
x = 0;
if (y < 25 && y > 0) {
y = y - 1;
} else if (y < 49) {
y = y + 1;
}
} else if (x > 49) {
x = 49;
if (y < 25 && y > 0) {
y = y - 1;
} else if (y < 49) {
y = y + 1;
}
}
if (y < 0) {
y = 0;
if (x < 25 && x > 0) {
x = x - 1;
} else if (x < 49) {
x = x + 1;
}
} else if (y > 49) {
y = 49;
if (x < 25 && x > 0) {
x = x - 1;
} else if (x < 49) {
x = x + 1;
}
}
creep.moveTo(x, y);
}
}
function targetAttacker(a, b) {
if (a.getActiveBodyparts(ATTACK) > b.getActiveBodyparts(ATTACK))
return -1;
if (a.getActiveBodyparts(ATTACK) < b.getActiveBodyparts(ATTACK))
return 1;
return 0;
}
function SKCompare(a, b) {
if (a.ticksToSpawn < b.ticksToSpawn)
return -1;
if (a.ticksToSpawn > b.ticksToSpawn)
return 1;
return 0;
}
module.exports = creep_farMining; | MainCode/creep.farMining.js | var creep_farMining = {
/** @param {Creep} creep **/
run: function(creep) {
switch (creep.memory.priority) {
case 'farClaimer':
case 'farClaimerNearDeath':
if (!creep.memory.deathWarn) {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
if (creep.ticksToLive <= creep.memory.deathWarn && creep.memory.priority != 'farClaimerNearDeath') {
creep.memory.priority = 'farClaimerNearDeath';
}
if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination));
} else {
if (creep.reserveController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.moveTo(creep.room.controller, {
reusePath: 25
});
} else {
if (creep.room.controller.sign && creep.room.controller.sign.username != "Montblanc") {
creep.signController(creep.room.controller, "Remote mining this! Not a fan of me being here? Let me know instead of obliterating me!");
} else if (!creep.room.controller.sign) {
creep.signController(creep.room.controller, "Remote mining this! Not a fan of me being here? Let me know instead of obliterating me!");
}
}
}
evadeAttacker(creep, 5);
break;
case 'farMiner':
case 'farMinerNearDeath':
if (!creep.memory.deathWarn) {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
if (creep.ticksToLive <= creep.memory.deathWarn && creep.memory.priority != 'farMinerNearDeath') {
creep.memory.priority = 'farMinerNearDeath';
}
var hostiles = [];
if (creep.hits < creep.hitsMax) {
hostiles = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 3, {
filter: (creep) => (creep.getActiveBodyparts(WORK) > 0 || creep.getActiveBodyparts(CARRY) > 0 || creep.getActiveBodyparts(ATTACK) > 0 || creep.getActiveBodyparts(RANGED_ATTACK) > 0 || creep.getActiveBodyparts(HEAL) > 0) || (creep.hits <= 500)
});
}
if (creep.hits < 400) {
//Determine if attacker is player, if so, delete flag.
if (hostiles.length > 0 && hostiles[0].owner.username != 'Invader' && hostiles[0].owner.username != 'Source Keeper' && Game.flags[creep.memory.targetFlag]) {
Game.notify(creep.memory.tragetFlag + ' was removed due to an attack by ' + hostiles[0].owner.username);
if (!Memory.warMode) {
Memory.warMode = true;
Game.notify('War mode has been enabled.');
}
Game.flags[creep.memory.targetFlag].remove();
}
}
if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
reusePath: 25
});
} else {
if (creep.room.controller && creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
if (creep.room.controller.reservation.ticksToEnd <= 1000 && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
} else if (creep.room.name == creep.memory.destination && creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (!creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
var mineTarget = undefined;
var thisUnit = undefined;
if (creep.memory.storageUnit) {
thisUnit = Game.getObjectById(creep.memory.storageUnit);
}
if (creep.memory.mineSource) {
mineTarget = Game.getObjectById(creep.memory.mineSource);
var StorageOK = true;
if (thisUnit && _.sum(thisUnit.store) == thisUnit.storeCapacity) {
StorageOK = false;
}
if (mineTarget && _.sum(creep.carry) <= 40 && mineTarget.energy > 0 && StorageOK) {
if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(mineTarget, {
reusePath: 25,
maxRooms: 1
});
}
} else if (mineTarget && !creep.pos.isNearTo(mineTarget)) {
creep.moveTo(mineTarget, {
reusePath: 25,
maxRooms: 1
});
}
} else {
//Get the source ID while in the room
var markedSources = [];
if (Game.flags[creep.memory.targetFlag]) {
markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
}
if (markedSources.length) {
creep.memory.mineSource = markedSources[0].id;
}
mineTarget = Game.getObjectById(creep.memory.mineSource);
if (mineTarget) {
if (creep.harvest(mineTarget) == ERR_NOT_IN_RANGE) {
creep.moveTo(mineTarget, {
reusePath: 25,
maxRooms: 1
});
}
}
}
if (creep.memory.storageUnit) {
if (thisUnit) {
if (thisUnit.hits < thisUnit.hitsMax && hostiles.length == 0) {
creep.repair(thisUnit);
} else if (creep.carry.energy >= 36) {
if (creep.transfer(thisUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisUnit, {
reusePath: 25
});
}
}
}
} else {
if (mineTarget) {
if (creep.pos.inRangeTo(mineTarget, 2)) {
var containers = creep.pos.findInRange(FIND_STRUCTURES, 2, {
filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
});
if (containers.length) {
if (creep.transfer(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(containers[0], {
reusePath: 25
});
}
creep.memory.storageUnit = containers[0].id;
} else {
if (creep.carry[RESOURCE_ENERGY] >= 36) {
var sites = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 2)
if (sites.length) {
if (creep.build(sites[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(sites[0], {
reusePath: 25
});
}
} else {
//Create new container
if (creep.pos.isNearTo(mineTarget)) {
creep.room.createConstructionSite(creep.pos, STRUCTURE_CONTAINER)
}
}
}
}
}
}
}
}
evadeAttacker(creep, 2);
break;
case 'farMule':
case 'farMuleNearDeath':
if (!creep.memory.deathWarn) {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
if ((creep.ticksToLive <= creep.memory.deathWarn || creep.getActiveBodyparts(CARRY) <= 2) && creep.memory.priority != 'farMuleNearDeath') {
creep.memory.priority = 'farMuleNearDeath';
}
if (creep.memory.storing == null) {
creep.memory.storing = false;
}
if (creep.memory.didRoadSearch == null) {
creep.memory.didRoadSearch = true;
}
var roadSearchTarget;
if (!creep.memory.lastRoom || creep.memory.lastRoom != creep.room.name) {
creep.memory.didRoadSearch = false;
creep.memory.lastRoom = creep.room.name;
//Autogenerate roads
var someSites = creep.room.find(FIND_CONSTRUCTION_SITES);
if (someSites.length) {
creep.memory.lookForSites = true;
} else {
creep.memory.lookForSites = false;
}
}
if (creep.carry.energy > 0) {
//All creeps check for road under them and repair if needed.
var someSite = [];
if (creep.memory.lookForSites) {
someSite = creep.pos.findInRange(FIND_CONSTRUCTION_SITES, 3);
}
if (someSite.length) {
creep.build(someSite[0]);
} else {
var someStructure = creep.pos.lookFor(LOOK_STRUCTURES);
if (someStructure.length && (someStructure[0].hitsMax - someStructure[0].hits >= 100) && someStructure[0].structureType == STRUCTURE_ROAD) {
creep.repair(someStructure[0]);
}
}
}
if ((creep.carry.energy > creep.carryCapacity - 300 || (creep.carry.energy > 0 && creep.ticksToLive <= 120)) && !creep.memory.storing) {
creep.memory.storing = true;
} else if (creep.carry.energy == 0 && creep.memory.storing) {
creep.memory.storing = false;
}
if (creep.room.name != creep.memory.destination && !creep.memory.storing) {
var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 3);
if (droppedSources.length) {
//Pick up dropped energy from dead mules, etc.
if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(droppedSources[0], {
reusePath: 25
});
}
} else {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
reusePath: 25
});
}
evadeAttacker(creep, 5);
} else if (creep.room.name != creep.memory.homeRoom && creep.memory.storing) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.homeRoom), {
reusePath: 25
});
if (creep.memory.didRoadSearch == false) {
roadSearchTarget = new RoomPosition(25, 25, creep.memory.homeRoom);
}
} else {
if (creep.room.controller && creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
if (creep.room.controller.reservation.ticksToEnd <= 1000 && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
} else if (creep.room.name == creep.memory.destination && creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (!creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
if (!creep.memory.storing) {
var droppedSources = creep.pos.findInRange(FIND_DROPPED_ENERGY, 7);
if (droppedSources.length && !Memory.warMode) {
//Pick up dropped energy from dead mules, etc.
if (creep.pickup(droppedSources[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(droppedSources[0], {
reusePath: 25
});
}
} else {
//in farRoom, pick up container contents
if (creep.memory.containerTarget) {
var thisContainer = Game.getObjectById(creep.memory.containerTarget);
if (thisContainer) {
if (thisContainer.store[RESOURCE_ENERGY] > 0) {
if (creep.withdraw(thisContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(thisContainer, {
reusePath: 25,
maxRooms: 1
})
}
} else {
//Wait by controller
if (creep.room.controller) {
creep.moveTo(creep.room.controller);
} else {
creep.moveTo(25, 25);
}
}
}
} else {
//No container yet, move to be near source
if (!creep.memory.mineSource) {
var markedSources = [];
if (Game.flags[creep.memory.targetFlag]) {
markedSources = Game.flags[creep.memory.targetFlag].pos.lookFor(LOOK_SOURCES);
}
if (markedSources.length) {
creep.memory.mineSource = markedSources[0].id;
}
}
var thisSource = Game.getObjectById(creep.memory.mineSource);
if (thisSource) {
if (creep.pos.inRangeTo(thisSource, 2)) {
//Search for container
var containers = creep.pos.findInRange(FIND_STRUCTURES, 5, {
filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
});
if (containers.length > 1) {
containers = creep.pos.findInRange(FIND_STRUCTURES, 2, {
filter: (structure) => structure.structureType == STRUCTURE_CONTAINER
});
}
if (containers.length) {
creep.memory.containerTarget = containers[0].id;
if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(containers[0], {
reusePath: 25,
maxRooms: 1
})
}
}
} else {
creep.moveTo(thisSource, {
reusePath: 25,
maxRooms: 1
})
}
}
}
}
evadeAttacker(creep, 5);
} else {
//in home room, drop off energy
var storageUnit = Game.getObjectById(creep.memory.storageSource)
if (storageUnit) {
if (creep.transfer(storageUnit, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(storageUnit, {
reusePath: 25,
maxRooms: 1
})
}
if (creep.memory.didRoadSearch == false) {
roadSearchTarget = storageUnit.pos;
}
}
evadeAttacker(creep, 5);
}
}
if (!creep.memory.didRoadSearch && roadSearchTarget) {
creep.memory.didRoadSearch = true;
//Autogenerate roads
//.dest.x, .dest.y, .dest.room
var thisPath = creep.room.findPath(creep.pos, roadSearchTarget, {
ignoreCreeps: true
});
for (var thisPos in thisPath) {
if (creep.room.createConstructionSite(thisPath[thisPos].x, thisPath[thisPos].y, STRUCTURE_ROAD) == ERR_FULL) {
break;
}
if (thisPath[thisPos].x == 0 || thisPath[thisPos].x == 49 || thisPath[thisPos].y == 0 || thisPath[thisPos].y == 49) {
break;
}
}
}
break;
case 'farGuard':
case 'farGuardNearDeath':
creep.notifyWhenAttacked(false);
if (!creep.memory.deathWarn) {
if (Memory.warMode) {
creep.memory.deathWarn = _.size(creep.body) * 6;
} else {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
}
if ((creep.ticksToLive <= creep.memory.deathWarn || creep.hits < 400) && creep.memory.priority != 'farGuardNearDeath') {
creep.memory.priority = 'farGuardNearDeath';
}
//Recall guard into home room if it's under attack
if (Memory.roomsUnderAttack.indexOf(creep.memory.homeRoom) > -1 && Memory.attackDuration >= 100 && Game.flags[creep.memory.targetFlag] && !Game.flags[creep.memory.targetFlag + "TEMP"]) {
Game.flags[creep.memory.targetFlag].pos.createFlag(creep.memory.targetFlag + "TEMP");
Game.flags[creep.memory.targetFlag].remove();
var homePosition = new RoomPosition(25, 25, creep.memory.homeRoom);
homePosition.createFlag(creep.memory.targetFlag);
} else if (Memory.roomsUnderAttack.indexOf(creep.memory.homeRoom) > -1 && Memory.attackDuration >= 100 && !Game.flags[creep.memory.targetFlag] && Game.flags[creep.memory.targetFlag + "TEMP"]) {
var homePosition = new RoomPosition(25, 25, creep.memory.homeRoom);
homePosition.createFlag(creep.memory.targetFlag);
} else if (Game.flags[creep.memory.targetFlag + "TEMP"] && Memory.roomsUnderAttack.indexOf(creep.memory.homeRoom) == -1) {
if (Game.flags[creep.memory.targetFlag] && Game.flags[creep.memory.targetFlag + "TEMP"]) {
if (Game.flags[creep.memory.targetFlag].pos.roomName == Game.flags[creep.memory.targetFlag + "TEMP"].pos.roomName && Game.flags[creep.memory.targetFlag].pos.x == Game.flags[creep.memory.targetFlag + "TEMP"].pos.x && Game.flags[creep.memory.targetFlag].pos.y == Game.flags[creep.memory.targetFlag + "TEMP"].pos.y) {
Game.flags[creep.memory.targetFlag + "TEMP"].remove();
} else {
Game.flags[creep.memory.targetFlag].remove();
}
} else if (!Game.flags[creep.memory.targetFlag] && Game.flags[creep.memory.targetFlag + "TEMP"]) {
try {
Game.flags[creep.memory.targetFlag + "TEMP"].pos.createFlag(creep.memory.targetFlag);
} catch (e) {
}
}
}
if (Game.flags[creep.memory.targetFlag]) {
if (Game.flags[creep.memory.targetFlag].pos.roomName != creep.memory.destination) {
creep.memory.destination = Game.flags[creep.memory.targetFlag].pos.roomName;
}
} else if (Game.flags[creep.memory.targetFlag + "TEMP"]) {
if (Game.flags[creep.memory.targetFlag + "TEMP"].pos.roomName != creep.memory.destination) {
creep.memory.destination = Game.flags[creep.memory.targetFlag + "TEMP"].pos.roomName;
}
}
if (creep.room.controller && creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) {
if (creep.room.controller.reservation.ticksToEnd <= 1000 && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
} else if (creep.room.name == creep.memory.destination && creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != true) {
Memory.FarClaimerNeeded[creep.room.name] = true;
} else if (!creep.room.controller && Memory.FarClaimerNeeded[creep.room.name] != false) {
Memory.FarClaimerNeeded[creep.room.name] = false;
}
var Foe = [];
var closeFoe = [];
if (Game.flags[Game.flags[creep.memory.targetFlag].pos.roomName + "SKRoom"]) {
Foe = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 30, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username) && eCreep.owner.username != "Source Keeper")
});
closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username) && (eCreep.owner.username != "Source Keeper" || eCreep.hits < eCreep.hitsMax))
});
} else {
Foe = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 3, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
});
closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
});
}
if (Foe.length) {
Foe.sort(targetAttacker);
}
if (creep.room.controller && creep.room.controller.owner && creep.room.controller.owner.username != "Montblanc" && creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
reusePath: 25
});
if (creep.hits < creep.hitsMax) {
creep.heal(creep);
}
} else if (Foe.length) {
var closeRangeresult = "";
closeRangeResult = creep.rangedAttack(closeFoe);
creep.attack(closeFoe);
creep.rangedAttack(closeFoe);
if (Foe.length) {
creep.attack(Foe[0]);
creep.rangedAttack(Foe[0]);
}
if (creep.hits < creep.hitsMax) {
creep.heal(creep);
} else {
var hurtAlly = creep.pos.findInRange(FIND_MY_CREEPS, 3, {
filter: (thisCreep) => thisCreep.hits < thisCreep.hitsMax
});
if (hurtAlly.length > 0) {
if (closeRangeResult != OK) {
creep.rangedHeal(hurtAlly[0]);
}
creep.heal(hurtAlly[0]);
}
}
if (creep.pos.getRangeTo(closeFoe) > 3 || (closeFoe.getActiveBodyparts(ATTACK) > 0) || (creep.getActiveBodyparts(RANGED_ATTACK) == 0) || (creep.room.controller && creep.room.controller.safeMode)) {
if (Foe.length && Foe[0].getActiveBodyparts(ATTACK) - 2 > creep.getActiveBodyparts(ATTACK) && creep.pos.getRangeTo(Foe[0]) <= 3) {
var foeDirection = creep.pos.getDirectionTo(Foe[0]);
var y = 0;
var x = 0;
switch (foeDirection) {
case TOP:
y = 2;
break;
case TOP_RIGHT:
y = 2;
x = -2;
break;
case RIGHT:
x = -2;
break;
case BOTTOM_RIGHT:
y = -2;
x = -2;
break;
case BOTTOM:
y = -2;
break;
case BOTTOM_LEFT:
y = -2;
x = 2;
break;
case LEFT:
x = 2;
break;
case TOP_LEFT:
y = 2;
x = 2
break;
}
x = creep.pos.x + x;
y = creep.pos.y + y;
if (x < 1) {
x = 1;
if (y < 25 && y > 1) {
y = y - 1;
} else if (y < 48) {
y = y + 1;
}
} else if (x > 48) {
x = 48;
if (y < 25 && y > 1) {
y = y - 1;
} else if (y < 48) {
y = y + 1;
}
}
if (y < 1) {
y = 1;
if (x < 25 && x > 1) {
x = x - 1;
} else if (x < 48) {
x = x + 1;
}
} else if (y > 48) {
y = 48;
if (x < 25 && x > 1) {
x = x - 1;
} else if (x < 48) {
x = x + 1;
}
}
creep.moveTo(x, y, {
maxRooms: 1
});
} else {
creep.moveTo(closeFoe, {
maxRooms: 1
});
}
} else {
var foeDirection = creep.pos.getDirectionTo(closeFoe);
var y = 0;
var x = 0;
switch (foeDirection) {
case TOP:
y = 2;
break;
case TOP_RIGHT:
y = 2;
x = -2;
break;
case RIGHT:
x = -2;
break;
case BOTTOM_RIGHT:
y = -2;
x = -2;
break;
case BOTTOM:
y = -2;
break;
case BOTTOM_LEFT:
y = -2;
x = 2;
break;
case LEFT:
x = 2;
break;
case TOP_LEFT:
y = 2;
x = 2
break;
}
x = creep.pos.x + x;
y = creep.pos.y + y;
if (x < 1) {
x = 1;
if (y < 25 && y > 1) {
y = y - 1;
} else if (y < 48) {
y = y + 1;
}
} else if (x > 48) {
x = 48;
if (y < 25 && y > 1) {
y = y - 1;
} else if (y < 48) {
y = y + 1;
}
}
if (y < 1) {
y = 1;
if (x < 25 && x > 1) {
x = x - 1;
} else if (x < 48) {
x = x + 1;
}
} else if (y > 48) {
y = 48;
if (x < 25 && x > 1) {
x = x - 1;
} else if (x < 48) {
x = x + 1;
}
}
creep.moveTo(x, y, {
maxRooms: 1
});
}
} else if (creep.room.name != creep.memory.destination) {
creep.moveTo(new RoomPosition(25, 25, creep.memory.destination), {
reusePath: 25
});
if (creep.hits < creep.hitsMax) {
creep.heal(creep);
}
} else if (Game.flags[creep.memory.targetFlag]) {
var closeRangeResult = "";
if (closeFoe) {
closeRangeResult = creep.rangedAttack(closeFoe);
}
if (creep.hits < creep.hitsMax) {
creep.heal(creep);
if (creep.pos != Game.flags[creep.memory.targetFlag].pos) {
creep.moveTo(Game.flags[creep.memory.targetFlag], {
maxRooms: 1
});
}
} else {
var hurtAlly = creep.room.find(FIND_MY_CREEPS, {
filter: (thisCreep) => thisCreep.hits < thisCreep.hitsMax
});
if (hurtAlly.length > 0) {
creep.moveTo(hurtAlly[0]);
if (closeRangeResult != OK) {
creep.rangedHeal(hurtAlly[0]);
}
creep.heal(hurtAlly[0]);
} else if (creep.pos != Game.flags[creep.memory.targetFlag].pos) {
creep.moveTo(Game.flags[creep.memory.targetFlag], {
maxRooms: 1
});
}
}
} else if (creep.hits < creep.hitsMax) {
creep.heal(creep);
}
break;
case 'SKAttackGuard':
case 'SKAttackGuardNearDeath':
creep.notifyWhenAttacked(false);
if (!creep.memory.deathWarn) {
if (Memory.warMode) {
creep.memory.deathWarn = _.size(creep.body) * 6;
} else {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
}
if (creep.ticksToLive <= creep.memory.deathWarn || creep.hits < 400) {
creep.memory.priority = 'SKAttackGuardNearDeath';
creep.room.visual.text("\u2620\u27A1\u2694", creep.pos.x, creep.pos.y, {
align: 'left',
color: '#7DE3B5'
});
} else {
creep.room.visual.text("\u27A1\u2694", creep.pos.x, creep.pos.y, {
align: 'left',
color: '#7DE3B5'
});
}
if (!creep.memory.healerID) {
var nearbyHealer = creep.pos.findInRange(FIND_MY_CREEPS, 2, {
filter: (mCreep) => (mCreep.memory.priority == "SKHealGuard" && mCreep.memory.targetFlag == creep.memory.targetFlag)
});
if (nearbyHealer.length) {
creep.memory.healerID = nearbyHealer[0].id;
}
}
var closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
});
var thisHealer = Game.getObjectById(creep.memory.healerID);
var healerIsNear = false;
if (thisHealer) {
healerIsNear = creep.pos.isNearTo(thisHealer);
}
if (!healerIsNear) {
if (creep.memory.getOutOfStartRoom) {
//Probably in a new room, hold.
if (creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) {
var xTarget = 0;
var yTarget = 0;
if (creep.pos.x == 0) {
xTarget = 2;
yTarget = creep.pos.y;
} else if (creep.pos.x == 49) {
xTarget = 47;
yTarget = creep.pos.y;
}
if (creep.pos.y == 0) {
yTarget = 2;
xTarget = creep.pos.x;
} else if (creep.pos.y == 49) {
yTarget = 47;
xTarget = creep.pos.x;
}
creep.moveTo(xTarget, yTarget);
}
} else {
if (Game.flags[creep.memory.targetFlag + "Rally"]) {
creep.moveTo(Game.flags[creep.memory.targetFlag + "Rally"]);
}
}
} else if (healerIsNear) {
creep.memory.getOutOfStartRoom = true;
if (Game.flags[creep.memory.targetFlag] && Game.flags[creep.memory.targetFlag].pos.roomName != creep.pos.roomName) {
creep.moveTo(new RoomPosition(25, 25, Game.flags[creep.memory.targetFlag].pos.roomName));
} else {
//In target room
if (closeFoe) {
creep.moveTo(closeFoe, {
maxRooms: 1
});
creep.attack(closeFoe);
creep.memory.targetLair = undefined;
} else if (creep.memory.targetLair) {
var thisLair = Game.getObjectById(creep.memory.targetLair);
if (!creep.isNearTo(thisLair)) {
creep.moveTo(thisLair, {
maxRooms: 1
});
}
} else {
var SKLairs = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => structure.structureType == STRUCTURE_KEEPER_LAIR
});
if (SKLairs.length) {
SKLairs.sort(SKCompare);
creep.memory.targetLair = SKLairs[0].id;
if (!creep.isNearTo(SKLairs[0])) {
creep.moveTo(SKLairs[0], {
maxRooms: 1
});
}
}
}
}
}
break;
case 'SKHealGuard':
case 'SKHealGuardNearDeath':
creep.notifyWhenAttacked(false);
if (!creep.memory.deathWarn) {
if (Memory.warMode) {
creep.memory.deathWarn = _.size(creep.body) * 6;
} else {
creep.memory.deathWarn = _.size(creep.body) * 5;
}
}
if (creep.ticksToLive <= creep.memory.deathWarn || creep.hits < 400) {
creep.memory.priority = 'SKHealGuardNearDeath';
creep.room.visual.text("\u2620\u27A1\u2694", creep.pos.x, creep.pos.y, {
align: 'left',
color: '#7DE3B5'
});
} else {
creep.room.visual.text("\u27A1\u2694", creep.pos.x, creep.pos.y, {
align: 'left',
color: '#7DE3B5'
});
}
var targetAttacker = Game.getObjectById(creep.memory.parentAttacker);
if (targetAttacker) {
if ((creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) && targetAttacker.room.name == creep.room.name) {
var xTarget = 0;
var yTarget = 0;
if (creep.pos.x == 0) {
xTarget = 2;
yTarget = creep.pos.y;
} else if (creep.pos.x == 49) {
xTarget = 47;
yTarget = creep.pos.y;
}
if (creep.pos.y == 0) {
yTarget = 2;
xTarget = creep.pos.x;
} else if (creep.pos.y == 49) {
yTarget = 47;
xTarget = creep.pos.x;
}
creep.moveTo(xTarget, yTarget);
} else {
if (creep.pos.inRangeTo(targetAttacker, 2)) {
creep.move(creep.pos.getDirectionTo(targetAttacker));
} else {
if (targetAttacker.room.name == creep.room.name) {
creep.moveTo(targetAttacker, {
reusePath: 2,
maxRooms: 1
});
} else {
creep.moveTo(targetAttacker, {
reusePath: 0
});
}
}
}
if (creep.hits < creep.hitsMax - 99) {
creep.heal(creep);
} else if (targetAttacker.hits < targetAttacker.hitsMax) {
if (creep.pos.getRangeTo(targetAttacker) > 1) {
creep.rangedHeal(targetAttacker);
} else {
creep.heal(targetAttacker);
}
} else {
var hurtAlly = creep.pos.findInRange(FIND_MY_CREEPS, 3, {
filter: (thisCreep) => thisCreep.hits < thisCreep.hitsMax
});
if (hurtAlly.length > 0) {
if (creep.pos.getRangeTo(hurtAlly[0]) > 1) {
creep.rangedHeal(hurtAlly[0]);
} else {
creep.heal(hurtAlly[0]);
}
}
}
} else {
if (Game.flags[creep.memory.targetFlag + "Rally"]) {
creep.moveTo(Game.flags[creep.memory.targetFlag + "Rally"]);
}
var newTarget = creep.pos.findInRange(FIND_MY_CREEPS, 2, {
filter: (mCreep) => (mCreep.memory.priority == "SKAttackGuard")
});
if (newTarget.length) {
creep.memory.parentAttacker = newTarget[0].id;
}
}
break;
}
}
};
function evadeAttacker(creep, evadeRange) {
var Foe = creep.pos.findInRange(FIND_HOSTILE_CREEPS, evadeRange, {
filter: (eCreep) => ((eCreep.getActiveBodyparts(ATTACK) > 0 || eCreep.getActiveBodyparts(RANGED_ATTACK) > 0) && !Memory.whiteList.includes(eCreep.owner.username))
});
var closeFoe = undefined;
if (creep.hits < creep.hitsMax) {
creep.heal(creep);
}
if (creep.getActiveBodyparts(RANGED_ATTACK) > 0) {
closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
});
if (closeFoe) {
creep.rangedAttack(closeFoe);
}
}
if (Foe.length) {
if (!closeFoe) {
closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
filter: (eCreep) => ((eCreep.getActiveBodyparts(ATTACK) > 0 || eCreep.getActiveBodyparts(RANGED_ATTACK) > 0) && !Memory.whiteList.includes(eCreep.owner.username))
});
}
var foeDirection = creep.pos.getDirectionTo(closeFoe);
var y = 0;
var x = 0;
switch (foeDirection) {
case TOP:
y = 2;
break;
case TOP_RIGHT:
y = 2;
x = -2;
break;
case RIGHT:
x = -2;
break;
case BOTTOM_RIGHT:
y = -2;
x = -2;
break;
case BOTTOM:
y = -2;
break;
case BOTTOM_LEFT:
y = -2;
x = 2;
break;
case LEFT:
x = 2;
break;
case TOP_LEFT:
y = 2;
x = 2
break;
}
x = creep.pos.x + x;
y = creep.pos.y + y;
if (x < 0) {
x = 0;
if (y < 25 && y > 0) {
y = y - 1;
} else if (y < 49) {
y = y + 1;
}
} else if (x > 49) {
x = 49;
if (y < 25 && y > 0) {
y = y - 1;
} else if (y < 49) {
y = y + 1;
}
}
if (y < 0) {
y = 0;
if (x < 25 && x > 0) {
x = x - 1;
} else if (x < 49) {
x = x + 1;
}
} else if (y > 49) {
y = 49;
if (x < 25 && x > 0) {
x = x - 1;
} else if (x < 49) {
x = x + 1;
}
}
creep.moveTo(x, y);
}
}
function targetAttacker(a, b) {
if (a.getActiveBodyparts(ATTACK) > b.getActiveBodyparts(ATTACK))
return -1;
if (a.getActiveBodyparts(ATTACK) < b.getActiveBodyparts(ATTACK))
return 1;
return 0;
}
function SKCompare(a, b) {
if (a.ticksToSpawn < b.ticksToSpawn)
return -1;
if (a.ticksToSpawn > b.ticksToSpawn)
return 1;
return 0;
}
module.exports = creep_farMining; | stop frivolous road gen
| MainCode/creep.farMining.js | stop frivolous road gen | <ide><path>ainCode/creep.farMining.js
<ide> reusePath: 25
<ide> });
<ide> if (creep.memory.didRoadSearch == false) {
<del> roadSearchTarget = new RoomPosition(25, 25, creep.memory.homeRoom);
<add> if (creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) {
<add> roadSearchTarget = new RoomPosition(25, 25, creep.memory.homeRoom);
<add> } else if (creep.memory.containerTarget) {
<add> var thisContainer = Game.getObjectById(creep.memory.containerTarget);
<add> if (thisContainer && thisContainer.pos.roomName == creep.pos.roomName && creep.pos.isNearTo(thisContainer)) {
<add> roadSearchTarget = new RoomPosition(25, 25, creep.memory.homeRoom);
<add> }
<add> }
<ide> }
<ide> } else {
<ide> if (creep.room.controller && creep.room.controller.reservation && (creep.room.name == creep.memory.destination)) { |
|
Java | epl-1.0 | error: pathspec 'src/Algorithm/FontSize.java' did not match any file(s) known to git
| 85dab9a4cebcc9442dcfde27b120b72fc56eb549 | 1 | cyanstone/LeetCode | package Algorithm;
import java.util.Scanner;
public class FontSize {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n;
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
for(int i = 0; i < n; i++) {
int N = scanner.nextInt();
int P = scanner.nextInt();
int W = scanner.nextInt();
int H = scanner.nextInt();
int array[] = new int[N];
for(int j = 0; j < N; j++) {
array[j] = scanner.nextInt();
}
System.out.println(maxFontSize(N, P, W, H, array));
}
}
public static int maxFontSize(int N, int P, int W,int H,int[]array) {
Double lastAnswer = Double.MIN_VALUE;
for(int s = 1; s < Integer.MAX_VALUE; s++) {
double rowCharacter = Math.floor(W/s);
int totalLine = 0;
for(int j = 0; j < N; j++){
totalLine += Math.ceil(Math.ceil(array[j]/rowCharacter));
}
double pages = Math.ceil(totalLine/Math.floor(H/s));
if(lastAnswer <= P && pages > P) return s - 1;
lastAnswer = pages;
}
return Integer.MIN_VALUE;
}
}
| src/Algorithm/FontSize.java | SoftWare/FontSize | src/Algorithm/FontSize.java | SoftWare/FontSize | <ide><path>rc/Algorithm/FontSize.java
<add>package Algorithm;
<add>import java.util.Scanner;
<add>
<add>
<add>public class FontSize {
<add>
<add> public static void main(String[] args) {
<add> // TODO Auto-generated method stub
<add> int n;
<add> Scanner scanner = new Scanner(System.in);
<add> n = scanner.nextInt();
<add> for(int i = 0; i < n; i++) {
<add> int N = scanner.nextInt();
<add> int P = scanner.nextInt();
<add> int W = scanner.nextInt();
<add> int H = scanner.nextInt();
<add> int array[] = new int[N];
<add> for(int j = 0; j < N; j++) {
<add> array[j] = scanner.nextInt();
<add> }
<add> System.out.println(maxFontSize(N, P, W, H, array));
<add> }
<add> }
<add>
<add> public static int maxFontSize(int N, int P, int W,int H,int[]array) {
<add>
<add> Double lastAnswer = Double.MIN_VALUE;
<add> for(int s = 1; s < Integer.MAX_VALUE; s++) {
<add> double rowCharacter = Math.floor(W/s);
<add> int totalLine = 0;
<add> for(int j = 0; j < N; j++){
<add> totalLine += Math.ceil(Math.ceil(array[j]/rowCharacter));
<add> }
<add> double pages = Math.ceil(totalLine/Math.floor(H/s));
<add> if(lastAnswer <= P && pages > P) return s - 1;
<add> lastAnswer = pages;
<add> }
<add> return Integer.MIN_VALUE;
<add> }
<add>} |
|
Java | mit | 570fda3329963ae48f4a99cebff84d644498ff5b | 0 | bluesnap/bluesnap-android-int | package com.bluesnap.androidapi.views.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.bluesnap.androidapi.R;
import com.bluesnap.androidapi.http.BlueSnapHTTPResponse;
import com.bluesnap.androidapi.models.BillingContactInfo;
import com.bluesnap.androidapi.models.CreditCardInfo;
import com.bluesnap.androidapi.models.PriceDetails;
import com.bluesnap.androidapi.models.SDKConfiguration;
import com.bluesnap.androidapi.models.SdkRequestBase;
import com.bluesnap.androidapi.models.SdkRequestSubscriptionCharge;
import com.bluesnap.androidapi.models.SdkResult;
import com.bluesnap.androidapi.models.Shopper;
import com.bluesnap.androidapi.models.SupportedPaymentMethods;
import com.bluesnap.androidapi.services.BSPaymentRequestException;
import com.bluesnap.androidapi.services.BlueSnapService;
import com.bluesnap.androidapi.services.BluesnapAlertDialog;
import com.bluesnap.androidapi.services.BluesnapServiceCallback;
import com.bluesnap.androidapi.services.GooglePayService;
import com.bluesnap.androidapi.services.TokenServiceCallback;
import com.bluesnap.androidapi.views.adapters.OneLineCCViewAdapter;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.wallet.AutoResolveHelper;
import com.google.android.gms.wallet.PaymentData;
import com.google.android.gms.wallet.PaymentsClient;
import org.json.JSONObject;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
/**
* Created by roy.biber on 21/02/2018.
*/
public class BluesnapCheckoutActivity extends AppCompatActivity {
private static final String TAG = BluesnapCheckoutActivity.class.getSimpleName();
public static final String SDK_ERROR_MSG = "SDK_ERROR_MESSAGE";
public static final String EXTRA_PAYMENT_RESULT = "com.bluesnap.intent.BSNAP_PAYMENT_RESULT";
public static final String EXTRA_SHIPPING_DETAILS = "com.bluesnap.intent.BSNAP_SHIPPING_DETAILS";
public static final String EXTRA_BILLING_DETAILS = "com.bluesnap.intent.BSNAP_BILLING_DETAILS";
public static final String EXTRA_SUBSCRIPTION_RESULT = "com.bluesnap.intent.BSNAP_SUBSCRIPTION_RESULT";
public static final int REQUEST_CODE_DEFAULT = 1;
public static final int REQUEST_CODE_SUBSCRIPTION = 2;
public static final int RESULT_SDK_FAILED = -2;
private static final int GOOGLE_PAY_PAYMENT_DATA_REQUEST_CODE = 991;
/**
* activity result: operation succeeded.
*/
public static final int BS_CHECKOUT_RESULT_OK = -11;
public static String FRAGMENT_TYPE = "FRAGMENT_TYPE";
public static String NEW_CC = "NEW_CC";
public static String RETURNING_CC = "RETURNING_CC";
protected ProgressBar progressBar;
protected SdkRequestBase sdkRequest;
protected SDKConfiguration sdkConfiguration;
protected OneLineCCViewAdapter oneLineCCViewAdapter;
protected final BlueSnapService blueSnapService = BlueSnapService.getInstance();
protected PaymentsClient googlePayClient;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && BlueSnapService.getInstance().getSdkRequest() == null) {
Log.e(TAG, "savedInstanceState missing");
setResult(BluesnapCheckoutActivity.RESULT_SDK_FAILED, new Intent().putExtra(BluesnapCheckoutActivity.SDK_ERROR_MSG, "The checkout process was interrupted."));
finish();
return;
}
setContentView(R.layout.choose_payment_method);
sdkRequest = blueSnapService.getSdkRequest();
sdkConfiguration = blueSnapService.getsDKConfiguration();
// validate the SDK request, finish the activity with error result in case of failure.
if (!verifySDKRequest()) {
Log.d(TAG, "Closing Activity");
return;
}
loadShopperFromSDKConfiguration();
LinearLayout newCardButton = findViewById(R.id.newCardButton);
newCardButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startCreditCardActivityForResult(FRAGMENT_TYPE, NEW_CC, CreditCardActivity.CREDIT_CARD_ACTIVITY_REQUEST_CODE);
}
});
LinearLayout payPalButton = findViewById(R.id.payPalButton);
progressBar = findViewById(R.id.progressBar);
SupportedPaymentMethods supportedPaymentMethods = sdkConfiguration.getSupportedPaymentMethods();
boolean shopperHasExistingCC = false;
final Shopper shopper = sdkConfiguration.getShopper();
if (shopper.getPreviousPaymentSources() != null && shopper.getPreviousPaymentSources().getCreditCardInfos() != null) {
List<CreditCardInfo> returningShopperCreditCardInfoArray = shopper.getPreviousPaymentSources().getCreditCardInfos();
shopperHasExistingCC = !returningShopperCreditCardInfoArray.isEmpty();
}
if (!shopperHasExistingCC && !supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.PAYPAL) && !supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY_TOKENIZED_CARD)
&& !supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY)) {
startCreditCardActivityForResult(FRAGMENT_TYPE, NEW_CC, CreditCardActivity.CREDIT_CARD_ACTIVITY_DEFAULT_REQUEST_CODE);
}
if (!supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.PAYPAL) || sdkRequest instanceof SdkRequestSubscriptionCharge) {
payPalButton.setVisibility(View.GONE);
} else {
payPalButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startPayPalActivityForResult();
}
});
}
if (supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY_TOKENIZED_CARD)
|| supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY)) {
checkIsGooglePayAvailable();
} else {
setGooglePayAvailable(false);
}
}
private void checkIsGooglePayAvailable() {
GooglePayService googlePayService = GooglePayService.getInstance();
// It's recommended to create the PaymentsClient object inside of the onCreate method.
googlePayClient = googlePayService.createPaymentsClient(this);
if (googlePayClient == null) {
setGooglePayAvailable(false);
} else {
// The call to isReadyToPay is asynchronous and returns a Task. We need to provide an
// OnCompleteListener to be triggered when the result of the call is known.
googlePayService.isReadyToPay(googlePayClient).addOnCompleteListener(
new OnCompleteListener<Boolean>() {
public void onComplete(Task<Boolean> task) {
try {
boolean result = task.getResult(ApiException.class);
setGooglePayAvailable(result);
} catch (ApiException exception) {
// Process error
Log.w(TAG, "isReadyToPay failed", exception);
setGooglePayAvailable(false);
}
}
});
}
}
protected void setGooglePayAvailable(boolean available) {
LinearLayout googlePayButton = findViewById(R.id.googlePayButton);
if (available) {
googlePayButton.setVisibility(View.VISIBLE);
googlePayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startGooglePayActivityForResult();
}
});
} else {
googlePayButton.setVisibility(View.GONE);
}
}
@Override
protected void onStart() {
super.onStart();
verifySDKRequest();
}
/**
* start Credit Card Activity For Result
*
* @param intentExtraName - The name of the extra data, with package prefix.
* @param intentExtravalue - The String data value.
*/
protected void startCreditCardActivityForResult(String intentExtraName, String intentExtravalue, int requestCode) {
Intent intent = new Intent(getApplicationContext(), CreditCardActivity.class);
intent.putExtra(intentExtraName, intentExtravalue);
startActivityForResult(intent, requestCode);
}
/**
* start PayPal Activity For Result
*/
protected void startPayPalActivityForResult() {
String payPalToken = BlueSnapService.getPayPalToken();
if ("".equals(payPalToken)) {
Log.d(TAG, "create payPalToken");
startPayPal();
} else {
Log.d(TAG, "startWebViewActivity");
startWebViewActivity(payPalToken);
}
}
/**
* start GooglePay Activity For Result
*/
protected void startGooglePayActivityForResult() {
Log.d(TAG, "start GooglePay flow");
// Disables the button to prevent multiple clicks.
LinearLayout googlePayButton = findViewById(R.id.googlePayButton);
if (googlePayButton != null) {
googlePayButton.setClickable(false);
}
Task<PaymentData> futurePaymentData = GooglePayService.getInstance().createPaymentDataRequest(googlePayClient);
// Since loadPaymentData may show the UI asking the user to select a payment method, we use
// AutoResolveHelper to wait for the user interacting with it. Once completed,
// onActivityResult will be called with the result.
AutoResolveHelper.resolveTask(futurePaymentData, this, GOOGLE_PAY_PAYMENT_DATA_REQUEST_CODE);
}
/**
* gets Shopper from SDK configuration and populate returning shopper cards (from populateFromCard function) or create a new shopper if shopper object does not exists
*/
protected void loadShopperFromSDKConfiguration() {
final Shopper shopper = sdkConfiguration.getShopper();
updateShopperCCViews(shopper);
}
protected void updateShopperCCViews(@NonNull final Shopper shopper) {
if (null == shopper.getPreviousPaymentSources() || null == shopper.getPreviousPaymentSources().getCreditCardInfos()) {
Log.d(TAG, "Existing shopper contains no previous paymentSources or Previous card info");
return;
}
//create an ArrayList<CreditCardInfo> for the ListView.
List<CreditCardInfo> returningShopperCreditCardInfoArray = shopper.getPreviousPaymentSources().getCreditCardInfos();
//create an adapter to describe how the items are displayed.
ListView oneLineCCViewComponentsListView = findViewById(R.id.oneLineCCViewComponentsListView);
oneLineCCViewAdapter = new OneLineCCViewAdapter(this, returningShopperCreditCardInfoArray);
//set the spinners adapter to the previously created one.
oneLineCCViewComponentsListView.setAdapter(oneLineCCViewAdapter);
oneLineCCViewComponentsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
shopper.setNewCreditCardInfo((CreditCardInfo) oneLineCCViewAdapter.getItem(position));
BillingContactInfo billingContactInfo = shopper.getNewCreditCardInfo().getBillingContactInfo();
if (!sdkRequest.getShopperCheckoutRequirements().isEmailRequired())
billingContactInfo.setEmail(null);
else
billingContactInfo.setEmail(shopper.getEmail());
if (!sdkRequest.getShopperCheckoutRequirements().isBillingRequired()) {
billingContactInfo.setAddress(null);
billingContactInfo.setCity(null);
billingContactInfo.setState(null);
}
startCreditCardActivityForResult(FRAGMENT_TYPE, RETURNING_CC, CreditCardActivity.CREDIT_CARD_ACTIVITY_REQUEST_CODE);
}
});
oneLineCCViewComponentsListView.setVisibility(View.VISIBLE);
}
/**
* verify SDK Request
*
* @return boolean
*/
protected boolean verifySDKRequest() {
if (sdkRequest == null) {
Log.e(TAG, "sdkrequest is null");
setResult(RESULT_SDK_FAILED, new Intent().putExtra(SDK_ERROR_MSG, "Activity has been aborted."));
finish();
return false;
} else try {
return sdkRequest.verify();
} catch (BSPaymentRequestException e) {
String errorMsg = "payment request not validated:" + e.getMessage();
e.printStackTrace();
Log.d(TAG, errorMsg);
setResult(RESULT_SDK_FAILED, new Intent().putExtra(SDK_ERROR_MSG, errorMsg));
finish();
return false;
}
}
/**
* start PayPal
* createsPayPal Token and redirects to Web View Activity
*/
protected void startPayPal() {
startPayPal(sdkRequest.getPriceDetails());
}
/**
* start PayPal
* createsPayPal Token and redirects to Web View Activity
*
* @param priceDetails {@link PriceDetails}
*/
protected void startPayPal(final PriceDetails priceDetails) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
}
});
BlueSnapService.getInstance().createPayPalToken(priceDetails.getAmount(), priceDetails.getCurrencyCode(), new BluesnapServiceCallback() {
@Override
public void onSuccess() {
try {
startWebViewActivity(BlueSnapService.getPayPalToken());
} catch (Exception e) {
Log.w(TAG, "Unable to start webview activity", e);
}
}
@Override
public void onFailure() {
try {
JSONObject errorDescription = BlueSnapService.getErrorDescription();
Log.e(TAG, errorDescription.toString());
String message = null;
String title = null;
if (errorDescription.getString("code").equals("20027")) {
/* { "message": [ { "errorName": "PAYPAL_UNSUPPORTED_CURRENCY", "code": "20027", "description": "The given currency 'ILS' is not supported with PayPal." } ] } */
// not supported PayPal currency
String errorCurrency = priceDetails.getCurrencyCode();
// all supported PayPal currencies
ArrayList<String> payPalCurrencies = blueSnapService.getsDKConfiguration().getSupportedPaymentMethods().getPaypalCurrencies();
// check if array is either bigger than one or if equals one than that it is not the already tried currency
if (null != payPalCurrencies && (payPalCurrencies.size() > 1 || !payPalCurrencies.contains(errorCurrency))) {
// get merchant store currency
String currency = blueSnapService.getsDKConfiguration().getRates().getMerchantStoreCurrency();
/* If a store currency is supported in PP - fallback to that currency
Otherwise, if USD is supported in PP - fallback to USD
Otherwise, fallback to any supported PP currency */
currency = payPalCurrencies.contains(currency)
? currency
: (
payPalCurrencies.contains(SupportedPaymentMethods.USD) && !SupportedPaymentMethods.USD.equals(errorCurrency)
? SupportedPaymentMethods.USD
: payPalCurrencies.get(0)
);
Log.d(TAG, "Given currency not supported with PayPal - changing to PayPal supported Currency: " + currency);
PriceDetails localPriceDetails = blueSnapService.getConvertedPriceDetails(sdkRequest.getPriceDetails(), currency);
startPayPal(localPriceDetails);
} else {
message = getString(R.string.CURRENCY_NOT_SUPPORTED_PART_1)
+ " "
+ sdkRequest.getPriceDetails().getCurrencyCode()
+ " "
+ getString(R.string.CURRENCY_NOT_SUPPORTED_PART_2)
+ " "
+ getString(R.string.SUPPORT_PLEASE)
+ " "
+ getString(R.string.CURRENCY_NOT_SUPPORTED_PART_3)
+ " "
+ getString(R.string.SUPPORT_OR)
+ " "
+ getString(R.string.SUPPORT);
title = getString(R.string.CURRENCY_NOT_SUPPORTED_PART_TITLE);
}
} else if (errorDescription.getString("code").equals("14050")) {
/* { "message": [ { "errorName": "PAYPAL_TOKEN_ALREADY_USED", "code": "14050", "description": "PayPal Token already used" } ] } */
blueSnapService.getTokenProvider().getNewToken(new TokenServiceCallback() {
@Override
public void complete(String newToken) {
blueSnapService.setNewToken(newToken);
try {
startPayPal(priceDetails);
} catch (Exception e) {
Log.e(TAG, "json parsing exception", e);
showDialogInUIThread("Paypal service error", "Error");
}
}
});
} else if (errorDescription.getString("code").equals("90015")) {
/* { "message": [ { "errorName": "INVALID_CURRENCY", "code": "90015", "description": "Currency: GGG is not a valid currency code according to the ISO 4217 standard." } ] } */
message = "INVALID CURRENCY";
title = getString(R.string.ERROR);
} else {
message = getString(R.string.SUPPORT_PLEASE)
+ " "
+ getString(R.string.SUPPORT);
title = getString(R.string.ERROR);
}
if (null != message) {
showDialogInUIThread(message, title);
}
} catch (Exception e) {
Log.e(TAG, "json parsing exception", e);
showDialogInUIThread("Paypal service error", "Error");
} finally {
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.INVISIBLE);
}
});
}
}
});
}
/**
* start WebView Activity for PayPal Checkout
*
* @param payPalUrl - received from createPayPalToken {@link com.bluesnap.androidapi.services.BlueSnapAPI}
*/
protected void startWebViewActivity(String payPalUrl) {
Intent newIntent;
newIntent = new Intent(getApplicationContext(), WebViewActivity.class);
// Todo change paypal header name to merchant name from payment request
newIntent.putExtra(getString(R.string.WEBVIEW_STRING), "PayPal");
newIntent.putExtra(getString(R.string.WEBVIEW_URL), payPalUrl);
newIntent.putExtra(getString(R.string.SET_JAVA_SCRIPT_ENABLED), true);
startActivityForResult(newIntent, WebViewActivity.PAYPAL_REQUEST_CODE);
progressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "got result " + resultCode);
Log.d(TAG, "got request " + requestCode);
switch (requestCode) {
case GOOGLE_PAY_PAYMENT_DATA_REQUEST_CODE: {
switch (resultCode) {
case Activity.RESULT_OK:
PaymentData paymentData = PaymentData.getFromIntent(data);
handleGooglePaySuccess(paymentData);
break;
case Activity.RESULT_CANCELED:
// Nothing to here normally - the user simply cancelled without selecting a
// payment method.
break;
case AutoResolveHelper.RESULT_ERROR:
Status status = AutoResolveHelper.getStatusFromIntent(data);
handleGooglePayError(status.getStatusCode());
break;
}
// Re-enables the Pay with Google button.
LinearLayout googlePayButton = findViewById(R.id.googlePayButton);
if (googlePayButton != null) {
googlePayButton.setClickable(true);
}
break;
}
case CreditCardActivity.CREDIT_CARD_ACTIVITY_REQUEST_CODE: {
if (resultCode == Activity.RESULT_OK) {
setResult(BS_CHECKOUT_RESULT_OK, data);
finish();
}
break;
}
case CreditCardActivity.CREDIT_CARD_ACTIVITY_DEFAULT_REQUEST_CODE: {
if (resultCode == Activity.RESULT_OK) {
setResult(BS_CHECKOUT_RESULT_OK, data);
} else {
setResult(resultCode, data);
}
finish();
break;
}
case WebViewActivity.PAYPAL_REQUEST_CODE: {
if (resultCode == Activity.RESULT_OK) {
setResult(BS_CHECKOUT_RESULT_OK, data);
finish();
}
break;
}
default: {
}
}
}
/**
* In case of success from the Google-Pay button, we create the token we will need
* to send to BlueSnap to actually create the payment transaction
*
* @param paymentData
*/
private void handleGooglePaySuccess(PaymentData paymentData) {
SdkResult sdkResult = GooglePayService.getInstance().createSDKResult(paymentData);
String encodedToken = sdkResult == null ? null : sdkResult.getGooglePayToken();
if (encodedToken == null) {
showDialogInUIThread("Error handling GPay, please try again or use a different payment method", "Error");
} else {
blueSnapService.getAppExecutors().networkIO().execute(new Runnable() {
@Override
public void run() {
// post the token
try {
BlueSnapHTTPResponse response = BlueSnapService.getInstance().submitTokenenizedPayment(encodedToken, SupportedPaymentMethods.GOOGLE_PAY);
if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
Log.d(TAG, "GPay token submitted successfully");
Intent resultIntent = new Intent();
resultIntent.putExtra(BluesnapCheckoutActivity.EXTRA_PAYMENT_RESULT, sdkResult);
setResult(BS_CHECKOUT_RESULT_OK, resultIntent);
finish();
} else {
String errorMsg = String.format("Service Error %s, %s", response.getResponseCode(), response.getResponseString());
Log.e(TAG, errorMsg);
showDialogInUIThread("Error handling GPay, please try again or use a different payment method", "Error");
}
} catch (Exception e) {
Log.e(TAG, "Error submitting GPay details", e);
showDialogInUIThread("Error handling GPay, please try again or use a different payment method", "Error");
}
}
});
}
}
private void handleGooglePayError(int statusCode) {
// At this stage, the user has already seen a popup informing them an error occurred.
// Normally, only logging is required.
// statusCode will hold the value of any constant from CommonStatusCode or one of the
// WalletConstants.ERROR_CODE_* constants.
Log.w(TAG, "loadPaymentData failed; " + String.format("Error code: %d", statusCode));
showDialogInUIThread("GPay service error", "Error");
}
private void showDialogInUIThread(String message, String title) {
runOnUiThread(new Runnable() {
@Override
public void run() {
BluesnapAlertDialog.setDialog(BluesnapCheckoutActivity.this, message, title);
}
});
}
}
| bluesnap-android/src/main/java/com/bluesnap/androidapi/views/activities/BluesnapCheckoutActivity.java | package com.bluesnap.androidapi.views.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.bluesnap.androidapi.R;
import com.bluesnap.androidapi.http.BlueSnapHTTPResponse;
import com.bluesnap.androidapi.models.BillingContactInfo;
import com.bluesnap.androidapi.models.CreditCardInfo;
import com.bluesnap.androidapi.models.PriceDetails;
import com.bluesnap.androidapi.models.SDKConfiguration;
import com.bluesnap.androidapi.models.SdkRequestBase;
import com.bluesnap.androidapi.models.SdkRequestSubscriptionCharge;
import com.bluesnap.androidapi.models.SdkResult;
import com.bluesnap.androidapi.models.Shopper;
import com.bluesnap.androidapi.models.SupportedPaymentMethods;
import com.bluesnap.androidapi.services.BSPaymentRequestException;
import com.bluesnap.androidapi.services.BlueSnapService;
import com.bluesnap.androidapi.services.BluesnapAlertDialog;
import com.bluesnap.androidapi.services.BluesnapServiceCallback;
import com.bluesnap.androidapi.services.GooglePayService;
import com.bluesnap.androidapi.services.TokenServiceCallback;
import com.bluesnap.androidapi.views.adapters.OneLineCCViewAdapter;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.wallet.AutoResolveHelper;
import com.google.android.gms.wallet.PaymentData;
import com.google.android.gms.wallet.PaymentsClient;
import org.json.JSONObject;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
/**
* Created by roy.biber on 21/02/2018.
*/
public class BluesnapCheckoutActivity extends AppCompatActivity {
private static final String TAG = BluesnapCheckoutActivity.class.getSimpleName();
public static final String SDK_ERROR_MSG = "SDK_ERROR_MESSAGE";
public static final String EXTRA_PAYMENT_RESULT = "com.bluesnap.intent.BSNAP_PAYMENT_RESULT";
public static final String EXTRA_SHIPPING_DETAILS = "com.bluesnap.intent.BSNAP_SHIPPING_DETAILS";
public static final String EXTRA_BILLING_DETAILS = "com.bluesnap.intent.BSNAP_BILLING_DETAILS";
public static final String EXTRA_SUBSCRIPTION_RESULT = "com.bluesnap.intent.BSNAP_SUBSCRIPTION_RESULT";
public static final int REQUEST_CODE_DEFAULT = 1;
public static final int REQUEST_CODE_SUBSCRIPTION = 2;
public static final int RESULT_SDK_FAILED = -2;
private static final int GOOGLE_PAY_PAYMENT_DATA_REQUEST_CODE = 991;
/**
* activity result: operation succeeded.
*/
public static final int BS_CHECKOUT_RESULT_OK = -11;
public static String FRAGMENT_TYPE = "FRAGMENT_TYPE";
public static String NEW_CC = "NEW_CC";
public static String RETURNING_CC = "RETURNING_CC";
protected ProgressBar progressBar;
protected SdkRequestBase sdkRequest;
protected SDKConfiguration sdkConfiguration;
protected OneLineCCViewAdapter oneLineCCViewAdapter;
protected final BlueSnapService blueSnapService = BlueSnapService.getInstance();
protected PaymentsClient googlePayClient;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && BlueSnapService.getInstance().getSdkRequest() == null) {
Log.e(TAG, "savedInstanceState missing");
setResult(BluesnapCheckoutActivity.RESULT_SDK_FAILED, new Intent().putExtra(BluesnapCheckoutActivity.SDK_ERROR_MSG, "The checkout process was interrupted."));
finish();
return;
}
setContentView(R.layout.choose_payment_method);
sdkRequest = blueSnapService.getSdkRequest();
sdkConfiguration = blueSnapService.getsDKConfiguration();
// validate the SDK request, finish the activity with error result in case of failure.
if (!verifySDKRequest()) {
Log.d(TAG, "Closing Activity");
return;
}
loadShopperFromSDKConfiguration();
LinearLayout newCardButton = findViewById(R.id.newCardButton);
newCardButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startCreditCardActivityForResult(FRAGMENT_TYPE, NEW_CC, CreditCardActivity.CREDIT_CARD_ACTIVITY_REQUEST_CODE);
}
});
LinearLayout payPalButton = findViewById(R.id.payPalButton);
progressBar = findViewById(R.id.progressBar);
SupportedPaymentMethods supportedPaymentMethods = sdkConfiguration.getSupportedPaymentMethods();
boolean shopperHasExistingCC = false;
final Shopper shopper = sdkConfiguration.getShopper();
if (shopper.getPreviousPaymentSources() != null && shopper.getPreviousPaymentSources().getCreditCardInfos() != null) {
List<CreditCardInfo> returningShopperCreditCardInfoArray = shopper.getPreviousPaymentSources().getCreditCardInfos();
shopperHasExistingCC = !returningShopperCreditCardInfoArray.isEmpty();
}
if (!shopperHasExistingCC && !supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.PAYPAL) && !supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY_TOKENIZED_CARD)
&& !supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY)) {
startCreditCardActivityForResult(FRAGMENT_TYPE, NEW_CC, CreditCardActivity.CREDIT_CARD_ACTIVITY_DEFAULT_REQUEST_CODE);
}
if (!supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.PAYPAL) || sdkRequest instanceof SdkRequestSubscriptionCharge) {
payPalButton.setVisibility(View.GONE);
} else {
payPalButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startPayPalActivityForResult();
}
});
}
if ((supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY_TOKENIZED_CARD)
|| supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY))
&& !(sdkRequest instanceof SdkRequestSubscriptionCharge)) {
checkIsGooglePayAvailable();
} else {
setGooglePayAvailable(false);
}
}
private void checkIsGooglePayAvailable() {
GooglePayService googlePayService = GooglePayService.getInstance();
// It's recommended to create the PaymentsClient object inside of the onCreate method.
googlePayClient = googlePayService.createPaymentsClient(this);
if (googlePayClient == null) {
setGooglePayAvailable(false);
} else {
// The call to isReadyToPay is asynchronous and returns a Task. We need to provide an
// OnCompleteListener to be triggered when the result of the call is known.
googlePayService.isReadyToPay(googlePayClient).addOnCompleteListener(
new OnCompleteListener<Boolean>() {
public void onComplete(Task<Boolean> task) {
try {
boolean result = task.getResult(ApiException.class);
setGooglePayAvailable(result);
} catch (ApiException exception) {
// Process error
Log.w(TAG, "isReadyToPay failed", exception);
setGooglePayAvailable(false);
}
}
});
}
}
protected void setGooglePayAvailable(boolean available) {
LinearLayout googlePayButton = findViewById(R.id.googlePayButton);
if (available) {
googlePayButton.setVisibility(View.VISIBLE);
googlePayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startGooglePayActivityForResult();
}
});
} else {
googlePayButton.setVisibility(View.GONE);
}
}
@Override
protected void onStart() {
super.onStart();
verifySDKRequest();
}
/**
* start Credit Card Activity For Result
*
* @param intentExtraName - The name of the extra data, with package prefix.
* @param intentExtravalue - The String data value.
*/
protected void startCreditCardActivityForResult(String intentExtraName, String intentExtravalue, int requestCode) {
Intent intent = new Intent(getApplicationContext(), CreditCardActivity.class);
intent.putExtra(intentExtraName, intentExtravalue);
startActivityForResult(intent, requestCode);
}
/**
* start PayPal Activity For Result
*/
protected void startPayPalActivityForResult() {
String payPalToken = BlueSnapService.getPayPalToken();
if ("".equals(payPalToken)) {
Log.d(TAG, "create payPalToken");
startPayPal();
} else {
Log.d(TAG, "startWebViewActivity");
startWebViewActivity(payPalToken);
}
}
/**
* start GooglePay Activity For Result
*/
protected void startGooglePayActivityForResult() {
Log.d(TAG, "start GooglePay flow");
// Disables the button to prevent multiple clicks.
LinearLayout googlePayButton = findViewById(R.id.googlePayButton);
if (googlePayButton != null) {
googlePayButton.setClickable(false);
}
Task<PaymentData> futurePaymentData = GooglePayService.getInstance().createPaymentDataRequest(googlePayClient);
// Since loadPaymentData may show the UI asking the user to select a payment method, we use
// AutoResolveHelper to wait for the user interacting with it. Once completed,
// onActivityResult will be called with the result.
AutoResolveHelper.resolveTask(futurePaymentData, this, GOOGLE_PAY_PAYMENT_DATA_REQUEST_CODE);
}
/**
* gets Shopper from SDK configuration and populate returning shopper cards (from populateFromCard function) or create a new shopper if shopper object does not exists
*/
protected void loadShopperFromSDKConfiguration() {
final Shopper shopper = sdkConfiguration.getShopper();
updateShopperCCViews(shopper);
}
protected void updateShopperCCViews(@NonNull final Shopper shopper) {
if (null == shopper.getPreviousPaymentSources() || null == shopper.getPreviousPaymentSources().getCreditCardInfos()) {
Log.d(TAG, "Existing shopper contains no previous paymentSources or Previous card info");
return;
}
//create an ArrayList<CreditCardInfo> for the ListView.
List<CreditCardInfo> returningShopperCreditCardInfoArray = shopper.getPreviousPaymentSources().getCreditCardInfos();
//create an adapter to describe how the items are displayed.
ListView oneLineCCViewComponentsListView = findViewById(R.id.oneLineCCViewComponentsListView);
oneLineCCViewAdapter = new OneLineCCViewAdapter(this, returningShopperCreditCardInfoArray);
//set the spinners adapter to the previously created one.
oneLineCCViewComponentsListView.setAdapter(oneLineCCViewAdapter);
oneLineCCViewComponentsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
shopper.setNewCreditCardInfo((CreditCardInfo) oneLineCCViewAdapter.getItem(position));
BillingContactInfo billingContactInfo = shopper.getNewCreditCardInfo().getBillingContactInfo();
if (!sdkRequest.getShopperCheckoutRequirements().isEmailRequired())
billingContactInfo.setEmail(null);
else
billingContactInfo.setEmail(shopper.getEmail());
if (!sdkRequest.getShopperCheckoutRequirements().isBillingRequired()) {
billingContactInfo.setAddress(null);
billingContactInfo.setCity(null);
billingContactInfo.setState(null);
}
startCreditCardActivityForResult(FRAGMENT_TYPE, RETURNING_CC, CreditCardActivity.CREDIT_CARD_ACTIVITY_REQUEST_CODE);
}
});
oneLineCCViewComponentsListView.setVisibility(View.VISIBLE);
}
/**
* verify SDK Request
*
* @return boolean
*/
protected boolean verifySDKRequest() {
if (sdkRequest == null) {
Log.e(TAG, "sdkrequest is null");
setResult(RESULT_SDK_FAILED, new Intent().putExtra(SDK_ERROR_MSG, "Activity has been aborted."));
finish();
return false;
} else try {
return sdkRequest.verify();
} catch (BSPaymentRequestException e) {
String errorMsg = "payment request not validated:" + e.getMessage();
e.printStackTrace();
Log.d(TAG, errorMsg);
setResult(RESULT_SDK_FAILED, new Intent().putExtra(SDK_ERROR_MSG, errorMsg));
finish();
return false;
}
}
/**
* start PayPal
* createsPayPal Token and redirects to Web View Activity
*/
protected void startPayPal() {
startPayPal(sdkRequest.getPriceDetails());
}
/**
* start PayPal
* createsPayPal Token and redirects to Web View Activity
*
* @param priceDetails {@link PriceDetails}
*/
protected void startPayPal(final PriceDetails priceDetails) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
}
});
BlueSnapService.getInstance().createPayPalToken(priceDetails.getAmount(), priceDetails.getCurrencyCode(), new BluesnapServiceCallback() {
@Override
public void onSuccess() {
try {
startWebViewActivity(BlueSnapService.getPayPalToken());
} catch (Exception e) {
Log.w(TAG, "Unable to start webview activity", e);
}
}
@Override
public void onFailure() {
try {
JSONObject errorDescription = BlueSnapService.getErrorDescription();
Log.e(TAG, errorDescription.toString());
String message = null;
String title = null;
if (errorDescription.getString("code").equals("20027")) {
/* { "message": [ { "errorName": "PAYPAL_UNSUPPORTED_CURRENCY", "code": "20027", "description": "The given currency 'ILS' is not supported with PayPal." } ] } */
// not supported PayPal currency
String errorCurrency = priceDetails.getCurrencyCode();
// all supported PayPal currencies
ArrayList<String> payPalCurrencies = blueSnapService.getsDKConfiguration().getSupportedPaymentMethods().getPaypalCurrencies();
// check if array is either bigger than one or if equals one than that it is not the already tried currency
if (null != payPalCurrencies && (payPalCurrencies.size() > 1 || !payPalCurrencies.contains(errorCurrency))) {
// get merchant store currency
String currency = blueSnapService.getsDKConfiguration().getRates().getMerchantStoreCurrency();
/* If a store currency is supported in PP - fallback to that currency
Otherwise, if USD is supported in PP - fallback to USD
Otherwise, fallback to any supported PP currency */
currency = payPalCurrencies.contains(currency)
? currency
: (
payPalCurrencies.contains(SupportedPaymentMethods.USD) && !SupportedPaymentMethods.USD.equals(errorCurrency)
? SupportedPaymentMethods.USD
: payPalCurrencies.get(0)
);
Log.d(TAG, "Given currency not supported with PayPal - changing to PayPal supported Currency: " + currency);
PriceDetails localPriceDetails = blueSnapService.getConvertedPriceDetails(sdkRequest.getPriceDetails(), currency);
startPayPal(localPriceDetails);
} else {
message = getString(R.string.CURRENCY_NOT_SUPPORTED_PART_1)
+ " "
+ sdkRequest.getPriceDetails().getCurrencyCode()
+ " "
+ getString(R.string.CURRENCY_NOT_SUPPORTED_PART_2)
+ " "
+ getString(R.string.SUPPORT_PLEASE)
+ " "
+ getString(R.string.CURRENCY_NOT_SUPPORTED_PART_3)
+ " "
+ getString(R.string.SUPPORT_OR)
+ " "
+ getString(R.string.SUPPORT);
title = getString(R.string.CURRENCY_NOT_SUPPORTED_PART_TITLE);
}
} else if (errorDescription.getString("code").equals("14050")) {
/* { "message": [ { "errorName": "PAYPAL_TOKEN_ALREADY_USED", "code": "14050", "description": "PayPal Token already used" } ] } */
blueSnapService.getTokenProvider().getNewToken(new TokenServiceCallback() {
@Override
public void complete(String newToken) {
blueSnapService.setNewToken(newToken);
try {
startPayPal(priceDetails);
} catch (Exception e) {
Log.e(TAG, "json parsing exception", e);
showDialogInUIThread("Paypal service error", "Error");
}
}
});
} else if (errorDescription.getString("code").equals("90015")) {
/* { "message": [ { "errorName": "INVALID_CURRENCY", "code": "90015", "description": "Currency: GGG is not a valid currency code according to the ISO 4217 standard." } ] } */
message = "INVALID CURRENCY";
title = getString(R.string.ERROR);
} else {
message = getString(R.string.SUPPORT_PLEASE)
+ " "
+ getString(R.string.SUPPORT);
title = getString(R.string.ERROR);
}
if (null != message) {
showDialogInUIThread(message, title);
}
} catch (Exception e) {
Log.e(TAG, "json parsing exception", e);
showDialogInUIThread("Paypal service error", "Error");
} finally {
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.INVISIBLE);
}
});
}
}
});
}
/**
* start WebView Activity for PayPal Checkout
*
* @param payPalUrl - received from createPayPalToken {@link com.bluesnap.androidapi.services.BlueSnapAPI}
*/
protected void startWebViewActivity(String payPalUrl) {
Intent newIntent;
newIntent = new Intent(getApplicationContext(), WebViewActivity.class);
// Todo change paypal header name to merchant name from payment request
newIntent.putExtra(getString(R.string.WEBVIEW_STRING), "PayPal");
newIntent.putExtra(getString(R.string.WEBVIEW_URL), payPalUrl);
newIntent.putExtra(getString(R.string.SET_JAVA_SCRIPT_ENABLED), true);
startActivityForResult(newIntent, WebViewActivity.PAYPAL_REQUEST_CODE);
progressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "got result " + resultCode);
Log.d(TAG, "got request " + requestCode);
switch (requestCode) {
case GOOGLE_PAY_PAYMENT_DATA_REQUEST_CODE: {
switch (resultCode) {
case Activity.RESULT_OK:
PaymentData paymentData = PaymentData.getFromIntent(data);
handleGooglePaySuccess(paymentData);
break;
case Activity.RESULT_CANCELED:
// Nothing to here normally - the user simply cancelled without selecting a
// payment method.
break;
case AutoResolveHelper.RESULT_ERROR:
Status status = AutoResolveHelper.getStatusFromIntent(data);
handleGooglePayError(status.getStatusCode());
break;
}
// Re-enables the Pay with Google button.
LinearLayout googlePayButton = findViewById(R.id.googlePayButton);
if (googlePayButton != null) {
googlePayButton.setClickable(true);
}
break;
}
case CreditCardActivity.CREDIT_CARD_ACTIVITY_REQUEST_CODE: {
if (resultCode == Activity.RESULT_OK) {
setResult(BS_CHECKOUT_RESULT_OK, data);
finish();
}
break;
}
case CreditCardActivity.CREDIT_CARD_ACTIVITY_DEFAULT_REQUEST_CODE: {
if (resultCode == Activity.RESULT_OK) {
setResult(BS_CHECKOUT_RESULT_OK, data);
} else {
setResult(resultCode, data);
}
finish();
break;
}
case WebViewActivity.PAYPAL_REQUEST_CODE: {
if (resultCode == Activity.RESULT_OK) {
setResult(BS_CHECKOUT_RESULT_OK, data);
finish();
}
break;
}
default: {
}
}
}
/**
* In case of success from the Google-Pay button, we create the token we will need
* to send to BlueSnap to actually create the payment transaction
*
* @param paymentData
*/
private void handleGooglePaySuccess(PaymentData paymentData) {
SdkResult sdkResult = GooglePayService.getInstance().createSDKResult(paymentData);
String encodedToken = sdkResult == null ? null : sdkResult.getGooglePayToken();
if (encodedToken == null) {
showDialogInUIThread("Error handling GPay, please try again or use a different payment method", "Error");
} else {
blueSnapService.getAppExecutors().networkIO().execute(new Runnable() {
@Override
public void run() {
// post the token
try {
BlueSnapHTTPResponse response = BlueSnapService.getInstance().submitTokenenizedPayment(encodedToken, SupportedPaymentMethods.GOOGLE_PAY);
if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
Log.d(TAG, "GPay token submitted successfully");
Intent resultIntent = new Intent();
resultIntent.putExtra(BluesnapCheckoutActivity.EXTRA_PAYMENT_RESULT, sdkResult);
setResult(BS_CHECKOUT_RESULT_OK, resultIntent);
finish();
} else {
String errorMsg = String.format("Service Error %s, %s", response.getResponseCode(), response.getResponseString());
Log.e(TAG, errorMsg);
showDialogInUIThread("Error handling GPay, please try again or use a different payment method", "Error");
}
} catch (Exception e) {
Log.e(TAG, "Error submitting GPay details", e);
showDialogInUIThread("Error handling GPay, please try again or use a different payment method", "Error");
}
}
});
}
}
private void handleGooglePayError(int statusCode) {
// At this stage, the user has already seen a popup informing them an error occurred.
// Normally, only logging is required.
// statusCode will hold the value of any constant from CommonStatusCode or one of the
// WalletConstants.ERROR_CODE_* constants.
Log.w(TAG, "loadPaymentData failed; " + String.format("Error code: %d", statusCode));
showDialogInUIThread("GPay service error", "Error");
}
private void showDialogInUIThread(String message, String title) {
runOnUiThread(new Runnable() {
@Override
public void run() {
BluesnapAlertDialog.setDialog(BluesnapCheckoutActivity.this, message, title);
}
});
}
}
| FE-78: restored GooglePay button for subscription mode
| bluesnap-android/src/main/java/com/bluesnap/androidapi/views/activities/BluesnapCheckoutActivity.java | FE-78: restored GooglePay button for subscription mode | <ide><path>luesnap-android/src/main/java/com/bluesnap/androidapi/views/activities/BluesnapCheckoutActivity.java
<ide> });
<ide> }
<ide>
<del> if ((supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY_TOKENIZED_CARD)
<del> || supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY))
<del> && !(sdkRequest instanceof SdkRequestSubscriptionCharge)) {
<add> if (supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY_TOKENIZED_CARD)
<add> || supportedPaymentMethods.isPaymentMethodActive(SupportedPaymentMethods.GOOGLE_PAY)) {
<ide> checkIsGooglePayAvailable();
<ide> } else {
<ide> setGooglePayAvailable(false); |
|
Java | apache-2.0 | b12a6f080b092b4d77afe45e42e59879d0139d79 | 0 | Aeronica/mxTune | package aeronicamc.mods.mxtune.blocks;
import aeronicamc.mods.mxtune.managers.PlayIdSupplier;
import aeronicamc.mods.mxtune.managers.PlayManager;
import aeronicamc.mods.mxtune.util.IInstrument;
import aeronicamc.mods.mxtune.util.SheetMusicHelper;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.common.util.FakePlayerFactory;
import net.minecraftforge.fml.network.NetworkHooks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import static net.minecraft.state.properties.BlockStateProperties.HORIZONTAL_FACING;
import static net.minecraftforge.common.util.Constants.BlockFlags;
import static net.minecraftforge.common.util.Constants.NBT;
@SuppressWarnings("deprecation")
public class MusicBlock extends Block implements IMusicPlayer
{
public static final BooleanProperty PLAYING = BooleanProperty.create("playing");
public static final BooleanProperty POWERED = BlockStateProperties.POWERED;
private static final Logger LOGGER = LogManager.getLogger(MusicBlock.class);
private static final Random rand = new Random();
public MusicBlock()
{
super(Properties.of(Material.METAL)
.sound(SoundType.METAL)
.strength(2.0F));
this.registerDefaultState(this.defaultBlockState()
.setValue(HORIZONTAL_FACING, Direction.NORTH)
.setValue(PLAYING, Boolean.FALSE)
.setValue(POWERED, Boolean.FALSE));
}
@Override
public void animateTick(BlockState pState, World pLevel, BlockPos pPos, Random pRand)
{
if (pState.getValue(PLAYING))
{
double d0 = (double)pPos.getX() + 0.5D;
double d1 = (double)pPos.getY() + 1.0625D;
double d2 = (double)pPos.getZ() + 0.5D;
double noteColor = rand.nextDouble();
double d4 = pRand.nextDouble() * 0.4D - 0.2D;
double d5 = 1D * 0D;
double d6 = pRand.nextDouble() * 6.0D / 16.0D;
double d7 = 1D * 0D;
// TODO: come up with out own particles for the BandAmp :D
pLevel.addParticle(ParticleTypes.NOTE, d0 + d4, d1 + d6, d2 + d4, noteColor, 0.0D, 0.0D);
pLevel.addParticle(ParticleTypes.ASH, d0 + d5, d1 + d6, d2 + d7, 0.0D, 0.0D, 0.0D);
}
}
@Override
public void tick(BlockState pState, ServerWorld pLevel, BlockPos pPos, Random pRand)
{
if (!pLevel.isClientSide())
{
getMusicBlockEntity(pLevel, pPos).ifPresent(
musicBlockEntity ->
{
if (pState.getValue(PLAYING))
{
pLevel.getBlockTicks().scheduleTick(pPos, this, 10);
if (PlayManager.getActiveBlockPlayId(pPos) == PlayIdSupplier.INVALID)
{
setPlayingState(pLevel, pPos, pState, false);
onePulseOutputState(pLevel, pPos, pState, musicBlockEntity);
}
}
else
onePulseOutputState(pLevel, pPos, pState, musicBlockEntity);
});
}
}
@Override
public ActionResultType use(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit)
{
if (!worldIn.isClientSide())
{
if (invertShiftIfLocked(player, worldIn, pos))
getMusicBlockEntity(worldIn, pos).ifPresent(
musicBlockEntity ->
{
// Use spam prevention.
// Server side: prevent runaway activation.
// Limits activation to a single use even if held.
// It's a shame to use ITickableTileEntity#ticks for this,
// but I have not found another solution yet.
if (musicBlockEntity.notHeld())
{
boolean isPlaying = canPlayOrStopMusic(worldIn, state, pos, false);
if (isPlaying)
musicBlockEntity.setLastPlay(true);
setPlayingState(worldIn, pos, state, isPlaying);
}
musicBlockEntity.useHeldCounterUpdate(true);
});
else
{
TileEntity blockEntity = worldIn.getBlockEntity(pos);
if (blockEntity instanceof INamedContainerProvider)
NetworkHooks.openGui((ServerPlayerEntity) player, (INamedContainerProvider) blockEntity, blockEntity.getBlockPos());
else
throw new IllegalStateException("Our named container provider is missing!");
}
return ActionResultType.SUCCESS;
} else
return ActionResultType.CONSUME;
}
private boolean invertShiftIfLocked(PlayerEntity player, World level, BlockPos blockPos)
{
return LockableHelper.isLocked(FakePlayerFactory.getMinecraft((ServerWorld) level), level, blockPos) != player.isShiftKeyDown();
}
private boolean canPlayOrStopMusic(World pLevel, BlockState pState, BlockPos pPos, Boolean noPlay)
{
int playId = PlayManager.getActiveBlockPlayId(pPos);
if (PlayManager.isActivePlayId(playId) || pState.getValue(PLAYING))
{
LOGGER.warn("STOP canPlayOrStopMusic playId {}", playId);
PlayManager.stopPlayId(playId);
return false;
}
if (!noPlay)
{
playId = PlayManager.playMusic(pLevel, pPos);
LOGGER.warn("PLAY canPlayOrStopMusic playId {}", playId);
return playId != PlayIdSupplier.INVALID && !pState.getValue(PLAYING);
}
return false;
}
private void onePulseOutputState(World pLevel, BlockPos pPos, BlockState pState, MusicBlockEntity musicBlockEntity)
{
if (!pState.getValue(POWERED) && musicBlockEntity.isLastPlay())
{
setOutputPowerState(pLevel, pPos, pState, true);
musicBlockEntity.setLastPlay(false);
} else if (pState.getValue(POWERED))
setOutputPowerState(pLevel, pPos, pState, false);
}
private void setPlayingState(World pLevel, BlockPos pPos, BlockState pState, boolean pIsPlaying)
{
pLevel.setBlock(pPos, pState.setValue(PLAYING, pIsPlaying), BlockFlags.BLOCK_UPDATE | BlockFlags.NOTIFY_NEIGHBORS);
pLevel.getBlockTicks().scheduleTick(pPos, this, 4);
}
private void setOutputPowerState(World pLevel, BlockPos pPos, BlockState pState, boolean pIsPowered)
{
pLevel.setBlock(pPos, pState.setValue(POWERED, pIsPowered), BlockFlags.BLOCK_UPDATE | BlockFlags.NOTIFY_NEIGHBORS);
pLevel.getBlockTicks().scheduleTick(pPos, this, 4);
}
@Override
public void neighborChanged(BlockState pState, World pLevel, BlockPos pPos, Block pBlock, BlockPos pFromPos, boolean pIsMoving)
{
getMusicBlockEntity(pLevel, pPos).filter(p -> !pLevel.isClientSide()).ifPresent(
musicBlockEntity ->
{
// get redStone input from the rear side
boolean isSidePowered = pLevel.hasSignal(pPos.relative(pState.getValue(HORIZONTAL_FACING).getOpposite()), pState.getValue(HORIZONTAL_FACING));
// Lever spam prevention. see use method above for more details.
if (musicBlockEntity.notFastRS())
{
if ((musicBlockEntity.getPreviousInputState() != isSidePowered) && musicBlockEntity.isRearRedstoneInputEnabled())
{
if (isSidePowered)
{
boolean isPlaying = canPlayOrStopMusic(pLevel, pState, pPos, false);
if (isPlaying)
musicBlockEntity.setLastPlay(true);
setPlayingState(pLevel, pPos, pState, isPlaying);
}
musicBlockEntity.setPreviousInputState(isSidePowered);
}
}
musicBlockEntity.fastRSCounterUpdate(pState.getValue(PLAYING));
});
}
@Override
public boolean canConnectRedstone(BlockState state, IBlockReader world, BlockPos pos, @Nullable Direction side)
{
return getMusicBlockEntity(world, pos).filter(p -> side != null).map(
musicBlockEntity ->
{
Direction direction = state.getValue(HORIZONTAL_FACING);
boolean canConnectBack = musicBlockEntity.isRearRedstoneInputEnabled() && direction == side;
boolean canConnectLeft = musicBlockEntity.isLeftRedstoneOutputEnabled() && direction.getCounterClockWise() == side;
boolean canConnectRight = musicBlockEntity.isRightRedstoneOutputEnabled() && direction.getClockWise() == side;
return canConnectBack || canConnectLeft || canConnectRight;
}).orElse(false);
}
@Override
public int getSignal(BlockState pBlockState, IBlockReader pBlockAccess, BlockPos pPos, Direction pSide)
{
return getMusicBlockEntity(pBlockAccess, pPos).map(
musicBlockEntity ->
{
Direction direction = pBlockState.getValue(HORIZONTAL_FACING);
boolean canConnectLeft = musicBlockEntity.isLeftRedstoneOutputEnabled() && direction.getCounterClockWise() == pSide;
boolean canConnectRight = musicBlockEntity.isRightRedstoneOutputEnabled() && direction.getClockWise() == pSide;
return (pBlockState.getValue(POWERED) && (canConnectLeft || canConnectRight) ? 15 : 0);
}).orElse(0);
}
@Override
public int getDirectSignal(BlockState pBlockState, IBlockReader pBlockAccess, BlockPos pPos, Direction pSide)
{
return super.getSignal(pBlockState, pBlockAccess, pPos, pSide);
}
// This prevents this block from conducting redstone signals.
@Override
public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side)
{
return false;
}
@Override
public boolean isSignalSource(BlockState pState)
{
return true;
}
@Override
public BlockState mirror(BlockState state, Mirror mirrorIn) {
return state.rotate(mirrorIn.getRotation(state.getValue(HORIZONTAL_FACING)));
}
@Override
public BlockState rotate(BlockState state, Rotation rot) {
return state.setValue(HORIZONTAL_FACING, rot.rotate(state.getValue(HORIZONTAL_FACING)));
}
@Nullable
@Override
public BlockState getStateForPlacement(BlockItemUseContext context)
{
return this.defaultBlockState()
.setValue(HORIZONTAL_FACING, context.getHorizontalDirection().getOpposite())
.setValue(PLAYING, Boolean.FALSE)
.setValue(POWERED, Boolean.FALSE);
}
@Override
protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder) {
builder.add(HORIZONTAL_FACING, PLAYING, POWERED);
}
@Override
public boolean hasTileEntity(BlockState state) {
return true;
}
@Nullable
@Override
public TileEntity createTileEntity(BlockState state, IBlockReader world) {
return new MusicBlockEntity();
}
@Override
public void setPlacedBy(World world, BlockPos pos, BlockState state, @Nullable LivingEntity entity, ItemStack stack)
{
getMusicBlockEntity(world, pos).ifPresent(
musicBlockEntity -> {
if (stack.hasCustomHoverName())
musicBlockEntity.setCustomName(stack.getHoverName());
if (entity != null) musicBlockEntity.setOwner(entity.getUUID());
}
);
}
@Override
public void playerWillDestroy(World pLevel, BlockPos pPos, BlockState pState, PlayerEntity pPlayer)
{
getMusicBlockEntity(pLevel, pPos).filter(p -> !pLevel.isClientSide() && !pPlayer.isCreative()).ifPresent(
musicBlockEntity ->
{
ItemStack itemStack = getCloneItemStack(pLevel, pPos, pState);
CompoundNBT cNBT = musicBlockEntity.save(new CompoundNBT());
if (!cNBT.isEmpty())
itemStack.addTagElement("BlockEntityTag", cNBT);
if (musicBlockEntity.hasCustomName())
itemStack.setHoverName(musicBlockEntity.getCustomName());
ItemEntity itemEntity = new ItemEntity(pLevel, pPos.getX(), pPos.getY(), pPos.getZ(), itemStack);
itemEntity.setDefaultPickUpDelay();
pLevel.addFreshEntity(itemEntity);
});
super.playerWillDestroy(pLevel, pPos, pState, pPlayer);
}
@Override
public ItemStack getCloneItemStack(IBlockReader pLevel, BlockPos pPos, BlockState pState)
{
ItemStack itemstack = super.getCloneItemStack(pLevel, pPos, pState);
getMusicBlockEntity(pLevel, pPos).ifPresent(
musicBlockEntity ->
{
CompoundNBT compoundnbt = musicBlockEntity.save(new CompoundNBT());
if (!compoundnbt.isEmpty())
itemstack.addTagElement("BlockEntityTag", compoundnbt);
});
return itemstack;
}
@Override
public void appendHoverText(ItemStack pStack, @Nullable IBlockReader pLevel, List<ITextComponent> pTooltip, ITooltipFlag pFlag)
{
super.appendHoverText(pStack, pLevel, pTooltip, pFlag);
CompoundNBT cNBT = pStack.getTagElement("BlockEntityTag");
if (cNBT != null)
{
CompoundNBT inventoryNBT = cNBT.getCompound("Inventory");
if (inventoryNBT.contains("Items", NBT.TAG_LIST))
{
int size = inventoryNBT.contains("Size", NBT.TAG_INT) ? inventoryNBT.getInt("Size") : 27;
NonNullList<ItemStack> nonNullList = NonNullList.withSize(size, ItemStack.EMPTY);
ItemStackHelper.loadAllItems(inventoryNBT, nonNullList);
ItemStack instrumentStack = nonNullList.stream().findFirst().orElse(ItemStack.EMPTY);
if (!instrumentStack.isEmpty())
pTooltip.add(SheetMusicHelper.getFormattedMusicTitle(SheetMusicHelper.getIMusicFromIInstrument(instrumentStack)));
else pTooltip.add(SheetMusicHelper.getFormattedMusicTitle(ItemStack.EMPTY));
long instrumentCount = nonNullList.stream().filter(p -> (p.getItem() instanceof IInstrument) && !SheetMusicHelper.getIMusicFromIInstrument(p).isEmpty()).count();
if (instrumentCount > 1)
pTooltip.add(new StringTextComponent(new TranslationTextComponent("container.mxtune.block_music.more", instrumentCount - 1).getString() + (TextFormatting.ITALIC)));
int duration = cNBT.contains("Duration", NBT.TAG_INT) ? cNBT.getInt("Duration") : 0;
if (duration > 0)
pTooltip.add(new StringTextComponent(SheetMusicHelper.formatDuration(duration)).withStyle(TextFormatting.YELLOW));
}
}
}
private Optional<MusicBlockEntity> getMusicBlockEntity(IBlockReader pLevel, BlockPos pPos)
{
return pLevel.getBlockEntity(pPos) instanceof MusicBlockEntity ? Optional.ofNullable(((MusicBlockEntity)(pLevel.getBlockEntity(pPos)))) : Optional.empty();
}
}
| src/main/java/aeronicamc/mods/mxtune/blocks/MusicBlock.java | package aeronicamc.mods.mxtune.blocks;
import aeronicamc.mods.mxtune.managers.PlayIdSupplier;
import aeronicamc.mods.mxtune.managers.PlayManager;
import aeronicamc.mods.mxtune.util.IInstrument;
import aeronicamc.mods.mxtune.util.SheetMusicHelper;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.state.BooleanProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.common.util.FakePlayerFactory;
import net.minecraftforge.fml.network.NetworkHooks;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import static net.minecraft.state.properties.BlockStateProperties.HORIZONTAL_FACING;
import static net.minecraftforge.common.util.Constants.BlockFlags;
import static net.minecraftforge.common.util.Constants.NBT;
@SuppressWarnings("deprecation")
public class MusicBlock extends Block implements IMusicPlayer
{
public static final BooleanProperty PLAYING = BooleanProperty.create("playing");
public static final BooleanProperty POWERED = BlockStateProperties.POWERED;
private static final Logger LOGGER = LogManager.getLogger(MusicBlock.class);
private static final Random rand = new Random();
public MusicBlock()
{
super(Properties.of(Material.METAL)
.sound(SoundType.METAL)
.strength(2.0F));
this.registerDefaultState(this.defaultBlockState()
.setValue(HORIZONTAL_FACING, Direction.NORTH)
.setValue(PLAYING, Boolean.FALSE)
.setValue(POWERED, Boolean.FALSE));
}
@Override
public void animateTick(BlockState pState, World pLevel, BlockPos pPos, Random pRand)
{
if (pState.getValue(PLAYING))
{
double d0 = (double)pPos.getX() + 0.5D;
double d1 = (double)pPos.getY() + 1.0625D;
double d2 = (double)pPos.getZ() + 0.5D;
double noteColor = rand.nextDouble();
double d4 = pRand.nextDouble() * 0.4D - 0.2D;
double d5 = 1D * 0D;
double d6 = pRand.nextDouble() * 6.0D / 16.0D;
double d7 = 1D * 0D;
// TODO: come up with out own particles for the BandAmp :D
pLevel.addParticle(ParticleTypes.NOTE, d0 + d4, d1 + d6, d2 + d4, noteColor, 0.0D, 0.0D);
pLevel.addParticle(ParticleTypes.ASH, d0 + d5, d1 + d6, d2 + d7, 0.0D, 0.0D, 0.0D);
}
}
@Override
public void tick(BlockState pState, ServerWorld pLevel, BlockPos pPos, Random pRand)
{
if (!pLevel.isClientSide())
{
getMusicBlockEntity(pLevel, pPos).ifPresent(
musicBlockEntity ->
{
if (pState.getValue(PLAYING))
{
pLevel.getBlockTicks().scheduleTick(pPos, this, 4);
if (PlayManager.getActiveBlockPlayId(pPos) == PlayIdSupplier.INVALID)
{
setPlayingState(pLevel, pPos, pState, false);
onePulseOutputState(pLevel, pPos, pState, musicBlockEntity);
}
}
else
onePulseOutputState(pLevel, pPos, pState, musicBlockEntity);
});
}
}
@Override
public ActionResultType use(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit)
{
if (!worldIn.isClientSide())
{
if (invertShiftIfLocked(player, worldIn, pos))
getMusicBlockEntity(worldIn, pos).ifPresent(
musicBlockEntity ->
{
// Use spam prevention.
// Server side: prevent runaway activation.
// Limits activation to a single use even if held.
// It's a shame to use ITickableTileEntity#ticks for this,
// but I have not found another solution yet.
if (musicBlockEntity.notHeld())
{
boolean isPlaying = canPlayOrStopMusic(worldIn, state, pos, false);
if (isPlaying)
musicBlockEntity.setLastPlay(true);
setPlayingState(worldIn, pos, state, isPlaying);
}
musicBlockEntity.useHeldCounterUpdate(true);
});
else
{
TileEntity blockEntity = worldIn.getBlockEntity(pos);
if (blockEntity instanceof INamedContainerProvider)
NetworkHooks.openGui((ServerPlayerEntity) player, (INamedContainerProvider) blockEntity, blockEntity.getBlockPos());
else
throw new IllegalStateException("Our named container provider is missing!");
}
return ActionResultType.SUCCESS;
} else
return ActionResultType.CONSUME;
}
private boolean invertShiftIfLocked(PlayerEntity player, World level, BlockPos blockPos)
{
return LockableHelper.isLocked(FakePlayerFactory.getMinecraft((ServerWorld) level), level, blockPos) != player.isShiftKeyDown();
}
private boolean canPlayOrStopMusic(World pLevel, BlockState pState, BlockPos pPos, Boolean noPlay)
{
int playId = PlayManager.getActiveBlockPlayId(pPos);
if (PlayManager.isActivePlayId(playId) || pState.getValue(PLAYING))
{
LOGGER.warn("STOP canPlayOrStopMusic playId {}", playId);
PlayManager.stopPlayId(playId);
return false;
}
if (!noPlay)
{
playId = PlayManager.playMusic(pLevel, pPos);
LOGGER.warn("PLAY canPlayOrStopMusic playId {}", playId);
return playId != PlayIdSupplier.INVALID && !pState.getValue(PLAYING);
}
return false;
}
private void onePulseOutputState(World pLevel, BlockPos pPos, BlockState pState, MusicBlockEntity musicBlockEntity)
{
if (!pState.getValue(POWERED) && musicBlockEntity.isLastPlay())
{
setOutputPowerState(pLevel, pPos, pState, true);
musicBlockEntity.setLastPlay(false);
} else if (pState.getValue(POWERED))
setOutputPowerState(pLevel, pPos, pState, false);
}
private void setPlayingState(World pLevel, BlockPos pPos, BlockState pState, boolean pIsPlaying)
{
pLevel.setBlock(pPos, pState.setValue(PLAYING, pIsPlaying), BlockFlags.BLOCK_UPDATE | BlockFlags.NOTIFY_NEIGHBORS);
pLevel.getBlockTicks().scheduleTick(pPos, this, 4);
}
private void setOutputPowerState(World pLevel, BlockPos pPos, BlockState pState, boolean pIsPowered)
{
pLevel.setBlock(pPos, pState.setValue(POWERED, pIsPowered), BlockFlags.BLOCK_UPDATE | BlockFlags.NOTIFY_NEIGHBORS);
pLevel.getBlockTicks().scheduleTick(pPos, this, 4);
}
@Override
public void neighborChanged(BlockState pState, World pLevel, BlockPos pPos, Block pBlock, BlockPos pFromPos, boolean pIsMoving)
{
getMusicBlockEntity(pLevel, pPos).filter(p -> !pLevel.isClientSide()).ifPresent(
musicBlockEntity ->
{
// get redStone input from the rear side
boolean isSidePowered = pLevel.hasSignal(pPos.relative(pState.getValue(HORIZONTAL_FACING).getOpposite()), pState.getValue(HORIZONTAL_FACING));
// Lever spam prevention. see use method above for more details.
if (musicBlockEntity.notFastRS())
{
if ((musicBlockEntity.getPreviousInputState() != isSidePowered) && musicBlockEntity.isRearRedstoneInputEnabled())
{
if (isSidePowered)
{
boolean isPlaying = canPlayOrStopMusic(pLevel, pState, pPos, false);
if (isPlaying)
musicBlockEntity.setLastPlay(true);
setPlayingState(pLevel, pPos, pState, isPlaying);
}
musicBlockEntity.setPreviousInputState(isSidePowered);
}
}
musicBlockEntity.fastRSCounterUpdate(pState.getValue(PLAYING));
});
}
@Override
public boolean canConnectRedstone(BlockState state, IBlockReader world, BlockPos pos, @Nullable Direction side)
{
return getMusicBlockEntity(world, pos).filter(p -> side != null).map(
musicBlockEntity ->
{
Direction direction = state.getValue(HORIZONTAL_FACING);
boolean canConnectBack = musicBlockEntity.isRearRedstoneInputEnabled() && direction == side;
boolean canConnectLeft = musicBlockEntity.isLeftRedstoneOutputEnabled() && direction.getCounterClockWise() == side;
boolean canConnectRight = musicBlockEntity.isRightRedstoneOutputEnabled() && direction.getClockWise() == side;
return canConnectBack || canConnectLeft || canConnectRight;
}).orElse(false);
}
@Override
public int getSignal(BlockState pBlockState, IBlockReader pBlockAccess, BlockPos pPos, Direction pSide)
{
return getMusicBlockEntity(pBlockAccess, pPos).map(
musicBlockEntity ->
{
Direction direction = pBlockState.getValue(HORIZONTAL_FACING);
boolean canConnectLeft = musicBlockEntity.isLeftRedstoneOutputEnabled() && direction.getCounterClockWise() == pSide;
boolean canConnectRight = musicBlockEntity.isRightRedstoneOutputEnabled() && direction.getClockWise() == pSide;
return (pBlockState.getValue(POWERED) && (canConnectLeft || canConnectRight) ? 15 : 0);
}).orElse(0);
}
@Override
public int getDirectSignal(BlockState pBlockState, IBlockReader pBlockAccess, BlockPos pPos, Direction pSide)
{
return super.getSignal(pBlockState, pBlockAccess, pPos, pSide);
}
// This prevents this block from conducting redstone signals.
@Override
public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side)
{
return false;
}
@Override
public boolean isSignalSource(BlockState pState)
{
return true;
}
@Override
public BlockState mirror(BlockState state, Mirror mirrorIn) {
return state.rotate(mirrorIn.getRotation(state.getValue(HORIZONTAL_FACING)));
}
@Override
public BlockState rotate(BlockState state, Rotation rot) {
return state.setValue(HORIZONTAL_FACING, rot.rotate(state.getValue(HORIZONTAL_FACING)));
}
@Nullable
@Override
public BlockState getStateForPlacement(BlockItemUseContext context)
{
return this.defaultBlockState()
.setValue(HORIZONTAL_FACING, context.getHorizontalDirection().getOpposite())
.setValue(PLAYING, Boolean.FALSE)
.setValue(POWERED, Boolean.FALSE);
}
@Override
protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder) {
builder.add(HORIZONTAL_FACING, PLAYING, POWERED);
}
@Override
public boolean hasTileEntity(BlockState state) {
return true;
}
@Nullable
@Override
public TileEntity createTileEntity(BlockState state, IBlockReader world) {
return new MusicBlockEntity();
}
@Override
public void setPlacedBy(World world, BlockPos pos, BlockState state, @Nullable LivingEntity entity, ItemStack stack)
{
getMusicBlockEntity(world, pos).ifPresent(
musicBlockEntity -> {
if (stack.hasCustomHoverName())
musicBlockEntity.setCustomName(stack.getHoverName());
if (entity != null) musicBlockEntity.setOwner(entity.getUUID());
}
);
}
@Override
public void playerWillDestroy(World pLevel, BlockPos pPos, BlockState pState, PlayerEntity pPlayer)
{
getMusicBlockEntity(pLevel, pPos).filter(p -> !pLevel.isClientSide() && !pPlayer.isCreative()).ifPresent(
musicBlockEntity ->
{
ItemStack itemStack = getCloneItemStack(pLevel, pPos, pState);
CompoundNBT cNBT = musicBlockEntity.save(new CompoundNBT());
if (!cNBT.isEmpty())
itemStack.addTagElement("BlockEntityTag", cNBT);
if (musicBlockEntity.hasCustomName())
itemStack.setHoverName(musicBlockEntity.getCustomName());
ItemEntity itemEntity = new ItemEntity(pLevel, pPos.getX(), pPos.getY(), pPos.getZ(), itemStack);
itemEntity.setDefaultPickUpDelay();
pLevel.addFreshEntity(itemEntity);
});
super.playerWillDestroy(pLevel, pPos, pState, pPlayer);
}
@Override
public ItemStack getCloneItemStack(IBlockReader pLevel, BlockPos pPos, BlockState pState)
{
ItemStack itemstack = super.getCloneItemStack(pLevel, pPos, pState);
getMusicBlockEntity(pLevel, pPos).ifPresent(
musicBlockEntity ->
{
CompoundNBT compoundnbt = musicBlockEntity.save(new CompoundNBT());
if (!compoundnbt.isEmpty())
itemstack.addTagElement("BlockEntityTag", compoundnbt);
});
return itemstack;
}
@Override
public void appendHoverText(ItemStack pStack, @Nullable IBlockReader pLevel, List<ITextComponent> pTooltip, ITooltipFlag pFlag)
{
super.appendHoverText(pStack, pLevel, pTooltip, pFlag);
CompoundNBT cNBT = pStack.getTagElement("BlockEntityTag");
if (cNBT != null)
{
CompoundNBT inventoryNBT = cNBT.getCompound("Inventory");
if (inventoryNBT.contains("Items", NBT.TAG_LIST))
{
int size = inventoryNBT.contains("Size", NBT.TAG_INT) ? inventoryNBT.getInt("Size") : 27;
NonNullList<ItemStack> nonNullList = NonNullList.withSize(size, ItemStack.EMPTY);
ItemStackHelper.loadAllItems(inventoryNBT, nonNullList);
ItemStack instrumentStack = nonNullList.stream().findFirst().orElse(ItemStack.EMPTY);
if (!instrumentStack.isEmpty())
pTooltip.add(SheetMusicHelper.getFormattedMusicTitle(SheetMusicHelper.getIMusicFromIInstrument(instrumentStack)));
else pTooltip.add(SheetMusicHelper.getFormattedMusicTitle(ItemStack.EMPTY));
long instrumentCount = nonNullList.stream().filter(p -> (p.getItem() instanceof IInstrument) && !SheetMusicHelper.getIMusicFromIInstrument(p).isEmpty()).count();
if (instrumentCount > 1)
pTooltip.add(new StringTextComponent(new TranslationTextComponent("container.mxtune.block_music.more", instrumentCount - 1).getString() + (TextFormatting.ITALIC)));
int duration = cNBT.contains("Duration", NBT.TAG_INT) ? cNBT.getInt("Duration") : 0;
if (duration > 0)
pTooltip.add(new StringTextComponent(SheetMusicHelper.formatDuration(duration)).withStyle(TextFormatting.YELLOW));
}
}
}
private Optional<MusicBlockEntity> getMusicBlockEntity(IBlockReader pLevel, BlockPos pPos)
{
return pLevel.getBlockEntity(pPos) instanceof MusicBlockEntity ? Optional.ofNullable(((MusicBlockEntity)(pLevel.getBlockEntity(pPos)))) : Optional.empty();
}
}
| Set one pulse redstone output to 10 ticks.
| src/main/java/aeronicamc/mods/mxtune/blocks/MusicBlock.java | Set one pulse redstone output to 10 ticks. | <ide><path>rc/main/java/aeronicamc/mods/mxtune/blocks/MusicBlock.java
<ide> {
<ide> if (pState.getValue(PLAYING))
<ide> {
<del> pLevel.getBlockTicks().scheduleTick(pPos, this, 4);
<add> pLevel.getBlockTicks().scheduleTick(pPos, this, 10);
<ide> if (PlayManager.getActiveBlockPlayId(pPos) == PlayIdSupplier.INVALID)
<ide> {
<ide> setPlayingState(pLevel, pPos, pState, false); |
|
Java | mit | a461ebf5e7f48fb0413f01465e32c6af3e604c73 | 0 | mbarbon/androidcash | /*
* Copyright (c) Mattia Barbon <[email protected]>
* distributed under the terms of the MIT license
*/
package org.barbon.acash;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ExpenseDatabase {
private static final int VERSION = 1;
private static final String DATABASE_NAME = "expenses";
private static final String ACCOUNTS_TABLE = "accounts";
private static final String EXPENSES_TABLE = "expenses";
public static final String GNUCASH_ACCOUNT_COLUMN = "gc_account";
public static final String ACCOUNT_DESCRIPTION_COLUMN =
"account_description";
public static final String FROM_ACCOUNT_COLUMN = "account_from";
public static final String TO_ACCOUNT_COLUMN = "account_to";
public static final String DATE_COLUMN = "transaction_date";
public static final String DATE_YEAR_COLUMN = "transaction_year";
public static final String DATE_MONTH_COLUMN = "transaction_month";
public static final String DATE_DAY_COLUMN = "transaction_day";
public static final String AMOUNT_COLUMN = "transaction_amount";
public static final String EXPENSE_DESCRIPTION_COLUMN =
"transaction_description";
private static ExpenseDatabase theInstance;
private static final SimpleDateFormat iso8601 =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private ExpenseOpenHelper openHelper;
private SQLiteDatabase database;
private ExpenseDatabase(Context context) {
openHelper = new ExpenseOpenHelper(context);
}
public static ExpenseDatabase getInstance(Context context) {
if (theInstance == null)
theInstance = new ExpenseDatabase(context);
return theInstance;
}
private SQLiteDatabase getDatabase() {
if (database == null)
database = openHelper.getWritableDatabase();
return database;
}
public Cursor getFromAccountList() {
SQLiteDatabase db = getDatabase();
return db.rawQuery(
"SELECT id AS _id, " + ACCOUNT_DESCRIPTION_COLUMN +
" FROM " + ACCOUNTS_TABLE +
" ORDER BY " + ACCOUNT_DESCRIPTION_COLUMN, null);
}
public Cursor getToAccountList() {
SQLiteDatabase db = getDatabase();
return db.rawQuery(
"SELECT id AS _id, " + ACCOUNT_DESCRIPTION_COLUMN +
" FROM " + ACCOUNTS_TABLE +
" ORDER BY " + ACCOUNT_DESCRIPTION_COLUMN, null);
}
public Cursor getAccountList() {
SQLiteDatabase db = getDatabase();
return db.rawQuery(
"SELECT id AS _id, " + ACCOUNT_DESCRIPTION_COLUMN +
" FROM " + ACCOUNTS_TABLE +
" ORDER BY " + ACCOUNT_DESCRIPTION_COLUMN, null);
}
public Cursor getExpenseList() {
SQLiteDatabase db = getDatabase();
return db.rawQuery(
"SELECT id AS _id, " + AMOUNT_COLUMN + ", " +
EXPENSE_DESCRIPTION_COLUMN +
" FROM " + EXPENSES_TABLE +
" ORDER BY " + DATE_COLUMN, null);
}
public boolean insertAccount(String description, String gnuCash) {
SQLiteDatabase db = getDatabase();
ContentValues vals = new ContentValues();
vals.put(ACCOUNT_DESCRIPTION_COLUMN, description);
vals.put(GNUCASH_ACCOUNT_COLUMN, gnuCash);
return db.insert(ACCOUNTS_TABLE, null, vals) == 1;
}
public boolean updateAccount(long id, String description, String gnuCash) {
SQLiteDatabase db = getDatabase();
ContentValues vals = new ContentValues();
vals.put(ACCOUNT_DESCRIPTION_COLUMN, description);
vals.put(GNUCASH_ACCOUNT_COLUMN, gnuCash);
return db.update(ACCOUNTS_TABLE, vals, "id = ?",
new String[] { Long.toString(id) }) == 1;
}
public boolean insertExpense(int from_account, int to_account,
double amount, Date date,
String description) {
SQLiteDatabase db = getDatabase();
ContentValues vals = new ContentValues();
vals.put(FROM_ACCOUNT_COLUMN, from_account);
vals.put(TO_ACCOUNT_COLUMN, to_account);
vals.put(DATE_COLUMN, iso8601.format(date));
vals.put(AMOUNT_COLUMN, amount);
vals.put(EXPENSE_DESCRIPTION_COLUMN, description);
return db.insert(EXPENSES_TABLE, null, vals) != -1;
}
public boolean updateExpense(long id,
int from_account, int to_account,
double amount, Date date,
String description) {
SQLiteDatabase db = getDatabase();
ContentValues vals = new ContentValues();
vals.put(FROM_ACCOUNT_COLUMN, from_account);
vals.put(TO_ACCOUNT_COLUMN, to_account);
vals.put(DATE_COLUMN, iso8601.format(date));
vals.put(AMOUNT_COLUMN, amount);
vals.put(EXPENSE_DESCRIPTION_COLUMN, description);
return db.update(EXPENSES_TABLE, vals, "id = ?",
new String[] { Long.toString(id) }) == 1;
}
public boolean deleteExpense(long id) {
SQLiteDatabase db = getDatabase();
return db.delete(EXPENSES_TABLE, "id = ?",
new String[] { Long.toString(id) }) == 1;
}
public ContentValues getAccount(long id) {
SQLiteDatabase db = getDatabase();
Cursor cursor = db.rawQuery(
"SELECT id AS _id, " + ACCOUNT_DESCRIPTION_COLUMN + ", " +
GNUCASH_ACCOUNT_COLUMN +
" FROM " + ACCOUNTS_TABLE +
" WHERE id = ?", new String[] { Long.toString(id) });
ContentValues vals = null;
if (cursor.moveToNext()) {
vals = new ContentValues();
vals.put(ACCOUNT_DESCRIPTION_COLUMN, cursor.getString(1));
vals.put(GNUCASH_ACCOUNT_COLUMN, cursor.getString(2));
}
cursor.close();
return vals;
}
public ContentValues getExpense(long id) {
SQLiteDatabase db = getDatabase();
Cursor cursor = db.rawQuery(
"SELECT id AS _id, " + AMOUNT_COLUMN + ", " +
EXPENSE_DESCRIPTION_COLUMN + ", " +
FROM_ACCOUNT_COLUMN + ", " +
TO_ACCOUNT_COLUMN + ", " +
" strftime('%Y', transaction_date)," +
" strftime('%m', transaction_date)," +
" strftime('%d', transaction_date)" +
" FROM " + EXPENSES_TABLE +
" WHERE id = ?", new String[] { Long.toString(id) });
ContentValues vals = null;
if (cursor.moveToNext()) {
vals = new ContentValues();
vals.put(AMOUNT_COLUMN, cursor.getDouble(1));
vals.put(EXPENSE_DESCRIPTION_COLUMN, cursor.getString(2));
vals.put(FROM_ACCOUNT_COLUMN, cursor.getInt(3));
vals.put(TO_ACCOUNT_COLUMN, cursor.getInt(4));
vals.put(DATE_YEAR_COLUMN, cursor.getInt(5));
vals.put(DATE_MONTH_COLUMN, cursor.getInt(6));
vals.put(DATE_DAY_COLUMN, cursor.getInt(7));
}
cursor.close();
return vals;
}
public boolean exportQif(File qifFile) {
PrintWriter qif = null;
try {
qif = new PrintWriter(new FileOutputStream(qifFile));
return exportQif(qif);
}
catch (FileNotFoundException e) {
return false;
}
finally {
if (qif != null)
qif.close();
}
}
public boolean exportQif(PrintWriter qif) {
SQLiteDatabase db = getDatabase();
Cursor expenses = db.rawQuery(
"SELECT af.gc_account, at.gc_account," +
" transaction_amount, transaction_description," +
" strftime('%Y', transaction_date)," +
" strftime('%m', transaction_date)," +
" strftime('%d', transaction_date)" +
" FROM " + EXPENSES_TABLE +
" INNER JOIN accounts AS af" +
" ON account_from = af.id" +
" INNER JOIN accounts AS at" +
" ON account_to = at.id" +
" ORDER BY af.id, transaction_date", null);
while (expenses.moveToNext()) {
// from account
qif.println("!Account");
qif.print('N');
qif.println(expenses.getString(0));
qif.println("^");
// start expense
qif.println("!Type:Cash");
// date
qif.print('D');
qif.print(expenses.getString(6));
qif.print('/');
qif.print(expenses.getString(5));
qif.print('/');
qif.println(expenses.getString(4));
// to account
qif.print('L');
qif.println(expenses.getString(1));
// amount
qif.print('T');
qif.println(-expenses.getFloat(2));
// description
qif.print('M');
qif.println(expenses.getString(3));
// end of record
qif.println('^');
}
return true;
}
public boolean deleteExpenses() {
SQLiteDatabase db = getDatabase();
return db.delete(EXPENSES_TABLE, null, null) != -1;
}
private static class ExpenseOpenHelper extends SQLiteOpenHelper {
private static final String ACCOUNTS_TABLE_CREATE =
"CREATE TABLE " + ACCOUNTS_TABLE + " ( " +
"id INTEGER PRIMARY KEY," +
GNUCASH_ACCOUNT_COLUMN + " TEXT UNIQUE, " +
ACCOUNT_DESCRIPTION_COLUMN + " TEXT UNIQUE" +
")";
private static final String EXPENSES_TABLE_CREATE =
"CREATE TABLE " + EXPENSES_TABLE + " ( " +
"id INTEGER PRIMARY KEY," +
FROM_ACCOUNT_COLUMN + " INTEGER, " +
TO_ACCOUNT_COLUMN + " INTEGER, " +
EXPENSE_DESCRIPTION_COLUMN + " TEXT, " +
DATE_COLUMN + " DATETIME, " +
AMOUNT_COLUMN + " FLOAT," +
"FOREIGN KEY(" + FROM_ACCOUNT_COLUMN + ") REFERENCES " +
ACCOUNTS_TABLE + "(id)," +
"FOREIGN KEY(" + FROM_ACCOUNT_COLUMN + ") REFERENCES " +
ACCOUNTS_TABLE + "(id)" +
")";
public ExpenseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ACCOUNTS_TABLE_CREATE);
db.execSQL(EXPENSES_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int from, int to) {
throw new UnsupportedOperationException(
"Unable to upgrade database");
}
}
}
| src/org/barbon/acash/ExpenseDatabase.java | /*
* Copyright (c) Mattia Barbon <[email protected]>
* distributed under the terms of the MIT license
*/
package org.barbon.acash;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ExpenseDatabase {
private static final int VERSION = 1;
private static final String DATABASE_NAME = "expenses";
private static final String ACCOUNTS_TABLE = "accounts";
private static final String EXPENSES_TABLE = "expenses";
public static final String GNUCASH_ACCOUNT_COLUMN = "gc_account";
public static final String ACCOUNT_DESCRIPTION_COLUMN =
"account_description";
public static final String FROM_ACCOUNT_COLUMN = "account_from";
public static final String TO_ACCOUNT_COLUMN = "account_to";
public static final String DATE_COLUMN = "transaction_date";
public static final String DATE_YEAR_COLUMN = "transaction_year";
public static final String DATE_MONTH_COLUMN = "transaction_month";
public static final String DATE_DAY_COLUMN = "transaction_day";
public static final String AMOUNT_COLUMN = "transaction_amount";
public static final String EXPENSE_DESCRIPTION_COLUMN =
"transaction_description";
private static ExpenseDatabase theInstance;
private static final SimpleDateFormat iso8601 =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private ExpenseOpenHelper openHelper;
private SQLiteDatabase database;
private ExpenseDatabase(Context context) {
openHelper = new ExpenseOpenHelper(context);
}
public static ExpenseDatabase getInstance(Context context) {
if (theInstance == null)
theInstance = new ExpenseDatabase(context);
return theInstance;
}
private SQLiteDatabase getDatabase() {
if (database == null)
database = openHelper.getWritableDatabase();
return database;
}
public Cursor getFromAccountList() {
SQLiteDatabase db = getDatabase();
return db.rawQuery(
"SELECT id AS _id, " + ACCOUNT_DESCRIPTION_COLUMN +
" FROM " + ACCOUNTS_TABLE +
" ORDER BY " + ACCOUNT_DESCRIPTION_COLUMN, null);
}
public Cursor getToAccountList() {
SQLiteDatabase db = getDatabase();
return db.rawQuery(
"SELECT id AS _id, " + ACCOUNT_DESCRIPTION_COLUMN +
" FROM " + ACCOUNTS_TABLE +
" ORDER BY " + ACCOUNT_DESCRIPTION_COLUMN, null);
}
public Cursor getAccountList() {
SQLiteDatabase db = getDatabase();
return db.rawQuery(
"SELECT id AS _id, " + ACCOUNT_DESCRIPTION_COLUMN +
" FROM " + ACCOUNTS_TABLE +
" ORDER BY " + ACCOUNT_DESCRIPTION_COLUMN, null);
}
public Cursor getExpenseList() {
SQLiteDatabase db = getDatabase();
return db.rawQuery(
"SELECT id AS _id, " + AMOUNT_COLUMN + ", " +
EXPENSE_DESCRIPTION_COLUMN +
" FROM " + EXPENSES_TABLE +
" ORDER BY " + DATE_COLUMN, null);
}
public boolean insertAccount(String description, String gnuCash) {
SQLiteDatabase db = getDatabase();
ContentValues vals = new ContentValues();
vals.put(ACCOUNT_DESCRIPTION_COLUMN, description);
vals.put(GNUCASH_ACCOUNT_COLUMN, gnuCash);
return db.insert(ACCOUNTS_TABLE, null, vals) == 1;
}
public boolean updateAccount(long id, String description, String gnuCash) {
SQLiteDatabase db = getDatabase();
ContentValues vals = new ContentValues();
vals.put(ACCOUNT_DESCRIPTION_COLUMN, description);
vals.put(GNUCASH_ACCOUNT_COLUMN, gnuCash);
return db.update(ACCOUNTS_TABLE, vals, "id = ?",
new String[] { Long.toString(id) }) == 1;
}
public boolean insertExpense(int from_account, int to_account,
double amount, Date date,
String description) {
SQLiteDatabase db = getDatabase();
ContentValues vals = new ContentValues();
vals.put(FROM_ACCOUNT_COLUMN, from_account);
vals.put(TO_ACCOUNT_COLUMN, to_account);
vals.put(DATE_COLUMN, iso8601.format(date));
vals.put(AMOUNT_COLUMN, amount);
vals.put(EXPENSE_DESCRIPTION_COLUMN, description);
return db.insert(EXPENSES_TABLE, null, vals) != -1;
}
public boolean updateExpense(long id,
int from_account, int to_account,
double amount, Date date,
String description) {
SQLiteDatabase db = getDatabase();
ContentValues vals = new ContentValues();
vals.put(FROM_ACCOUNT_COLUMN, from_account);
vals.put(TO_ACCOUNT_COLUMN, to_account);
vals.put(DATE_COLUMN, iso8601.format(date));
vals.put(AMOUNT_COLUMN, amount);
vals.put(EXPENSE_DESCRIPTION_COLUMN, description);
return db.update(EXPENSES_TABLE, vals, "id = ?",
new String[] { Long.toString(id) }) == 1;
}
public boolean deleteExpense(long id) {
SQLiteDatabase db = getDatabase();
return db.delete(EXPENSES_TABLE, "id = ?",
new String[] { Long.toString(id) }) == 1;
}
public ContentValues getAccount(long id) {
SQLiteDatabase db = getDatabase();
Cursor cursor = db.rawQuery(
"SELECT id AS _id, " + ACCOUNT_DESCRIPTION_COLUMN + ", " +
GNUCASH_ACCOUNT_COLUMN +
" FROM " + ACCOUNTS_TABLE +
" WHERE id = ?", new String[] { Long.toString(id) });
ContentValues vals = null;
if (cursor.moveToNext()) {
vals = new ContentValues();
vals.put(ACCOUNT_DESCRIPTION_COLUMN, cursor.getString(1));
vals.put(GNUCASH_ACCOUNT_COLUMN, cursor.getString(2));
}
cursor.close();
return vals;
}
public ContentValues getExpense(long id) {
SQLiteDatabase db = getDatabase();
Cursor cursor = db.rawQuery(
"SELECT id AS _id, " + AMOUNT_COLUMN + ", " +
EXPENSE_DESCRIPTION_COLUMN + ", " +
FROM_ACCOUNT_COLUMN + ", " +
TO_ACCOUNT_COLUMN + ", " +
" strftime('%Y', transaction_date)," +
" strftime('%m', transaction_date)," +
" strftime('%d', transaction_date)" +
" FROM " + EXPENSES_TABLE +
" WHERE id = ?", new String[] { Long.toString(id) });
ContentValues vals = null;
if (cursor.moveToNext()) {
vals = new ContentValues();
vals.put(AMOUNT_COLUMN, cursor.getDouble(1));
vals.put(EXPENSE_DESCRIPTION_COLUMN, cursor.getString(2));
vals.put(FROM_ACCOUNT_COLUMN, cursor.getInt(3));
vals.put(TO_ACCOUNT_COLUMN, cursor.getInt(4));
vals.put(DATE_YEAR_COLUMN, cursor.getInt(5));
vals.put(DATE_MONTH_COLUMN, cursor.getInt(6));
vals.put(DATE_DAY_COLUMN, cursor.getInt(7));
}
cursor.close();
return vals;
}
public boolean exportQif(File qifFile) {
PrintWriter qif = null;
try {
qif = new PrintWriter(new FileOutputStream(qifFile));
return exportQif(qif);
}
catch (FileNotFoundException e) {
return false;
}
finally {
if (qif != null)
qif.close();
}
}
public boolean exportQif(PrintWriter qif) {
SQLiteDatabase db = getDatabase();
Cursor expenses = db.rawQuery(
"SELECT af.gc_account, at.gc_account," +
" transaction_amount, transaction_description," +
" strftime('%Y', transaction_date)," +
" strftime('%m', transaction_date)," +
" strftime('%d', transaction_date)" +
" FROM " + EXPENSES_TABLE +
" INNER JOIN accounts AS af" +
" ON account_from = af.id" +
" INNER JOIN accounts AS at" +
" ON account_to = at.id" +
" ORDER BY af.id, transaction_date", null);
while (expenses.moveToNext()) {
// from account
qif.println("!Account");
qif.print('N');
qif.println(expenses.getString(0));
qif.println("^");
// start expense
qif.println("!Type:Cash");
// date
qif.print('D');
qif.print(expenses.getString(6));
qif.print('/');
qif.print(expenses.getString(5));
qif.print('/');
qif.println(expenses.getString(4));
// to account
qif.print('L');
qif.println(expenses.getString(1));
// amount
qif.print('T');
qif.println(expenses.getFloat(2));
// description
qif.print('M');
qif.println(expenses.getString(3));
// end of record
qif.println('^');
}
return true;
}
public boolean deleteExpenses() {
SQLiteDatabase db = getDatabase();
return db.delete(EXPENSES_TABLE, null, null) != -1;
}
private static class ExpenseOpenHelper extends SQLiteOpenHelper {
private static final String ACCOUNTS_TABLE_CREATE =
"CREATE TABLE " + ACCOUNTS_TABLE + " ( " +
"id INTEGER PRIMARY KEY," +
GNUCASH_ACCOUNT_COLUMN + " TEXT UNIQUE, " +
ACCOUNT_DESCRIPTION_COLUMN + " TEXT UNIQUE" +
")";
private static final String EXPENSES_TABLE_CREATE =
"CREATE TABLE " + EXPENSES_TABLE + " ( " +
"id INTEGER PRIMARY KEY," +
FROM_ACCOUNT_COLUMN + " INTEGER, " +
TO_ACCOUNT_COLUMN + " INTEGER, " +
EXPENSE_DESCRIPTION_COLUMN + " TEXT, " +
DATE_COLUMN + " DATETIME, " +
AMOUNT_COLUMN + " FLOAT," +
"FOREIGN KEY(" + FROM_ACCOUNT_COLUMN + ") REFERENCES " +
ACCOUNTS_TABLE + "(id)," +
"FOREIGN KEY(" + FROM_ACCOUNT_COLUMN + ") REFERENCES " +
ACCOUNTS_TABLE + "(id)" +
")";
public ExpenseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ACCOUNTS_TABLE_CREATE);
db.execSQL(EXPENSES_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int from, int to) {
throw new UnsupportedOperationException(
"Unable to upgrade database");
}
}
}
| Fixed amount sign for exported transactions.
| src/org/barbon/acash/ExpenseDatabase.java | Fixed amount sign for exported transactions. | <ide><path>rc/org/barbon/acash/ExpenseDatabase.java
<ide>
<ide> // amount
<ide> qif.print('T');
<del> qif.println(expenses.getFloat(2));
<add> qif.println(-expenses.getFloat(2));
<ide>
<ide> // description
<ide> qif.print('M'); |
|
Java | mit | b48f1742f4e1ff5147f31617b5c2fa09961df9cd | 0 | digibib/ls.ext,digibib/ls.ext,digibib/ls.ext,digibib/ls.ext | package no.deichman.services.resources;
import no.deichman.services.kohaadapter.KohaAdapterMock;
import no.deichman.services.repository.RepositoryInMemory;
import no.deichman.services.uridefaults.BaseURIMock;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class WorkResourceTest {
private WorkResource resource;
private BaseURIMock bum;
@Before
public void setUp() throws Exception {
resource = new WorkResource(new KohaAdapterMock(), new RepositoryInMemory(), new BaseURIMock());
bum = new BaseURIMock();
}
@Test
public void test_class_exists(){
assertNotNull(new WorkResource());
}
@Test
public void should_return_a_valid_json_work() {
String workId = "work_00001";
Response result = resource.getWorkJSON(workId);
assertNotNull(result);
assertEquals(200, result.getStatus());
assertTrue(isValidJSON(result.getEntity().toString()));
}
@Test(expected = NotFoundException.class)
public void should_throw_exception_when_work_is_not_found() {
String workId = "work_DOES_NOT_EXIST";
resource.getWorkJSON(workId);
}
@Test
public void should_return_201_when_work_created() throws URISyntaxException {
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_EXIST\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_EXIST\"}}";
Response result = resource.createWork(work);
assertNull(result.getEntity());
assertEquals(201, result.getStatus());
}
@Test
public void should_return_location_header_when_work_created() throws URISyntaxException {
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_EXIST\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_EXIST\"}}";
Response result = resource.createWork(work);
String workURI = bum.getWorkURI();
assertNull(result.getEntity());
assertTrue(Pattern.matches(workURI + "w\\d{12}", result.getHeaderString("Location")));
}
@Test
public void should_return_200_when_work_updated() {
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_EXIST\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_EXIST\"}}";
Response result = resource.updateWork(work);
assertNull(result.getEntity());
assertEquals(200, result.getStatus());
}
@Test
public void should_return_the_new_work() throws URISyntaxException{
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_EXIST\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_EXIST\"}}";
Response createResponse = resource.createWork(work);
String workId = createResponse.getHeaderString("Location").replaceAll("http://deichman.no/work/", "");
Response result = resource.getWorkJSON(workId);
assertNotNull(result);
assertEquals(201, createResponse.getStatus());
assertEquals(200, result.getStatus());
assertTrue(isValidJSON(result.getEntity().toString()));
}
@Test
public void should_return_list_of_items(){
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_EXIST\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_EXIST\",\"deichman:biblio\":\"1\"}}";
String workId = "work_SHOULD_EXIST";
Response createResponse = resource.updateWork(work);
Response result = resource.getWorkItems(workId);
assertEquals(200, createResponse.getStatus());
assertNotNull(result);
assertEquals(200, result.getStatus());
assertTrue(isValidJSON(result.getEntity().toString()));
}
@Test(expected=NotFoundException.class)
public void should_404_on_empty_items_list(){
Response result = resource.getWorkItems("DOES_NOT_EXIST");
assertEquals(result.getStatus(),404);
}
@Test
public void patch_should_return_status_400() throws Exception {
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_BE_PATCHABLE\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_BE_PATCHABLE\"}}";
Response result = resource.createWork(work);
String workId = result.getLocation().getPath().substring(6);
String patchData = "{}";
try {
resource.patchWork(workId,patchData);
fail("HTTP 400 Bad Request");
} catch (BadRequestException bre) {
assertEquals("HTTP 400 Bad Request", bre.getMessage());
}
}
@Test
public void patched_work_should_persist_changes() throws Exception {
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_BE_PATCHABLE\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_BE_PATCHABLE\"}}";
Response result = resource.createWork(work);
String workId = result.getLocation().getPath().substring(6);
String patchData = "{"
+ "\"op\": \"add\","
+ "\"s\": \"" + result.getLocation().toString() + "\","
+ "\"p\": \"http://deichman.no/ontology#color\","
+ "\"o\": {"
+ "\"value\": \"red\""
+ "}"
+ "}";
Response patchResponse = resource.patchWork(workId,patchData);
Model testModel = ModelFactory.createDefaultModel();
Model comparison = ModelFactory.createDefaultModel();
String response = patchResponse.getEntity().toString();
InputStream in = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));
RDFDataMgr.read(testModel, in, Lang.JSONLD);
String adaptedWork = work.replace("/work_SHOULD_BE_PATCHABLE", "/" + workId);
InputStream in2 = new ByteArrayInputStream(adaptedWork.getBytes(StandardCharsets.UTF_8));
RDFDataMgr.read(comparison,in2, Lang.JSONLD);
comparison.add(ResourceFactory.createStatement(
ResourceFactory.createResource(result.getLocation().toString()),
ResourceFactory.createProperty("http://deichman.no/ontology#color"),
ResourceFactory.createPlainLiteral("red")));
assertTrue(testModel.isIsomorphicWith(comparison));
}
@Test(expected = NotFoundException.class)
public void patching_a_non_existing_resource_should_return_404() throws Exception {
resource.patchWork("a_missing_work1234", "{}");
}
@Test
public void test_CORS_work_base(){
String reqHeader = "application/ld+json";
Response reponse = resource.corsWorkBase(reqHeader);
assertEquals(reponse.getHeaderString("Access-Control-Allow-Headers"),reqHeader);
assertEquals(reponse.getHeaderString("Access-Control-Allow-Origin"),"*");
assertEquals(reponse.getHeaderString("Access-Control-Allow-Methods"),"GET, POST, OPTIONS, PUT, PATCH");
}
@Test
public void test_CORS_work_base_empty_request_header(){
String reqHeader = "";
Response response = resource.corsWorkBase(reqHeader);
assert(response.getHeaderString("Access-Control-Allow-Headers") == null);
assertEquals(response.getHeaderString("Access-Control-Allow-Origin"),"*");
assertEquals(response.getHeaderString("Access-Control-Allow-Methods"),"GET, POST, OPTIONS, PUT, PATCH");
}
@Test(expected=NotFoundException.class)
public void test_delete_work_raises_not_found_exception(){
resource.deleteWork("work_DOES_NOT_EXIST_AND_FAILS");
}
@Test
public void test_delete_work() throws URISyntaxException{
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_BE_PATCHABLE\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_BE_PATCHABLE\"}}";
Response createResponse = resource.createWork(work);
String workId = createResponse.getHeaderString("Location").replaceAll("http://deichman.no/work/", "");
Response response = resource.deleteWork(workId);
assertEquals(response.getStatus(),204);
}
@Test
public void test_CORS_work_id(){
String reqHeader = "application/ld+json";
Response reponse = resource.corsWorkId(reqHeader);
assertEquals(reponse.getHeaderString("Access-Control-Allow-Headers"),reqHeader);
assertEquals(reponse.getHeaderString("Access-Control-Allow-Origin"),"*");
assertEquals(reponse.getHeaderString("Access-Control-Allow-Methods"),"GET, POST, OPTIONS, PUT, PATCH");
}
@Test
public void test_CORS_work_id_empty_request_header(){
String reqHeader = "";
Response response = resource.corsWorkId(reqHeader);
assert(response.getHeaderString("Access-Control-Allow-Headers") == null);
assertEquals(response.getHeaderString("Access-Control-Allow-Origin"),"*");
assertEquals(response.getHeaderString("Access-Control-Allow-Methods"),"GET, POST, OPTIONS, PUT, PATCH");
}
private boolean isValidJSON(final String json) {
boolean valid = false;
try {
final JsonParser parser = new ObjectMapper().getJsonFactory().createJsonParser(json);
while (parser.nextToken() != null) {
}
valid = true;
} catch (IOException ioe) {
ioe.printStackTrace();
}
return valid;
}
}
| redef/services/src/test/java/no/deichman/services/resources/WorkResourceTest.java | package no.deichman.services.resources;
import no.deichman.services.kohaadapter.KohaAdapterMock;
import no.deichman.services.repository.RepositoryInMemory;
import no.deichman.services.uridefaults.BaseURIMock;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFDataMgr;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class WorkResourceTest {
private WorkResource resource;
private BaseURIMock bum;
@Before
public void setUp() throws Exception {
resource = new WorkResource(new KohaAdapterMock(), new RepositoryInMemory(), new BaseURIMock());
bum = new BaseURIMock();
}
@Test
public void test_class_exists(){
assertNotNull(new WorkResource());
}
@Test
public void should_return_a_valid_json_work() {
String workId = "work_00001";
Response result = resource.getWorkJSON(workId);
assertNotNull(result);
assertEquals(200, result.getStatus());
assertTrue(isValidJSON(result.getEntity().toString()));
}
@Test(expected = NotFoundException.class)
public void should_throw_exception_when_work_is_not_found() {
String workId = "work_DOES_NOT_EXIST";
resource.getWorkJSON(workId);
}
@Test
public void should_return_201_when_work_created() throws URISyntaxException {
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_EXIST\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_EXIST\"}}";
Response result = resource.createWork(work);
assertNull(result.getEntity());
assertEquals(201, result.getStatus());
}
@Test
public void should_return_location_header_when_work_created() throws URISyntaxException {
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_EXIST\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_EXIST\"}}";
Response result = resource.createWork(work);
String workURI = bum.getWorkURI();
assertNull(result.getEntity());
assertTrue(Pattern.matches(workURI + "w\\d{12}", result.getHeaderString("Location")));
}
@Test
public void should_return_200_when_work_updated() {
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_EXIST\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_EXIST\"}}";
Response result = resource.updateWork(work);
assertNull(result.getEntity());
assertEquals(200, result.getStatus());
}
@Test
public void should_return_the_new_work() throws URISyntaxException{
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_EXIST\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_EXIST\"}}";
Response createResponse = resource.createWork(work);
String workId = createResponse.getHeaderString("Location").replaceAll("http://deichman.no/work/", "");
Response result = resource.getWorkJSON(workId);
assertNotNull(result);
assertEquals(201, createResponse.getStatus());
assertEquals(200, result.getStatus());
assertTrue(isValidJSON(result.getEntity().toString()));
}
@Test
public void should_return_list_of_items(){
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_EXIST\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_EXIST\",\"deichman:biblio\":\"1\"}}";
String workId = "work_SHOULD_EXIST";
Response createResponse = resource.updateWork(work);
Response result = resource.getWorkItems(workId);
assertEquals(200, createResponse.getStatus());
assertNotNull(result);
assertEquals(200, result.getStatus());
assertTrue(isValidJSON(result.getEntity().toString()));
}
@Test
public void patch_should_return_status_400() throws Exception {
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_BE_PATCHABLE\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_BE_PATCHABLE\"}}";
Response result = resource.createWork(work);
String workId = result.getLocation().getPath().substring(6);
String patchData = "{}";
try {
resource.patchWork(workId,patchData);
fail("HTTP 400 Bad Request");
} catch (BadRequestException bre) {
assertEquals("HTTP 400 Bad Request", bre.getMessage());
}
}
@Test
public void patched_work_should_persist_changes() throws Exception {
String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_BE_PATCHABLE\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_BE_PATCHABLE\"}}";
Response result = resource.createWork(work);
String workId = result.getLocation().getPath().substring(6);
String patchData = "{"
+ "\"op\": \"add\","
+ "\"s\": \"" + result.getLocation().toString() + "\","
+ "\"p\": \"http://deichman.no/ontology#color\","
+ "\"o\": {"
+ "\"value\": \"red\""
+ "}"
+ "}";
Response patchResponse = resource.patchWork(workId,patchData);
Model testModel = ModelFactory.createDefaultModel();
Model comparison = ModelFactory.createDefaultModel();
String response = patchResponse.getEntity().toString();
InputStream in = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));
RDFDataMgr.read(testModel, in, Lang.JSONLD);
String adaptedWork = work.replace("/work_SHOULD_BE_PATCHABLE", "/" + workId);
InputStream in2 = new ByteArrayInputStream(adaptedWork.getBytes(StandardCharsets.UTF_8));
RDFDataMgr.read(comparison,in2, Lang.JSONLD);
comparison.add(ResourceFactory.createStatement(
ResourceFactory.createResource(result.getLocation().toString()),
ResourceFactory.createProperty("http://deichman.no/ontology#color"),
ResourceFactory.createPlainLiteral("red")));
assertTrue(testModel.isIsomorphicWith(comparison));
}
@Test(expected = NotFoundException.class)
public void patching_a_non_existing_resource_should_return_404() throws Exception {
resource.patchWork("a_missing_work1234", "{}");
}
private boolean isValidJSON(final String json) {
boolean valid = false;
try {
final JsonParser parser = new ObjectMapper().getJsonFactory().createJsonParser(json);
while (parser.nextToken() != null) {
}
valid = true;
} catch (IOException ioe) {
ioe.printStackTrace();
}
return valid;
}
}
| Add test coverage for existing methods
| redef/services/src/test/java/no/deichman/services/resources/WorkResourceTest.java | Add test coverage for existing methods | <ide><path>edef/services/src/test/java/no/deichman/services/resources/WorkResourceTest.java
<ide> assertNotNull(result);
<ide> assertEquals(200, result.getStatus());
<ide> assertTrue(isValidJSON(result.getEntity().toString()));
<add> }
<add>
<add> @Test(expected=NotFoundException.class)
<add> public void should_404_on_empty_items_list(){
<add> Response result = resource.getWorkItems("DOES_NOT_EXIST");
<add> assertEquals(result.getStatus(),404);
<ide> }
<ide>
<ide> @Test
<ide> resource.patchWork("a_missing_work1234", "{}");
<ide> }
<ide>
<add> @Test
<add> public void test_CORS_work_base(){
<add> String reqHeader = "application/ld+json";
<add> Response reponse = resource.corsWorkBase(reqHeader);
<add> assertEquals(reponse.getHeaderString("Access-Control-Allow-Headers"),reqHeader);
<add> assertEquals(reponse.getHeaderString("Access-Control-Allow-Origin"),"*");
<add> assertEquals(reponse.getHeaderString("Access-Control-Allow-Methods"),"GET, POST, OPTIONS, PUT, PATCH");
<add> }
<add>
<add> @Test
<add> public void test_CORS_work_base_empty_request_header(){
<add> String reqHeader = "";
<add> Response response = resource.corsWorkBase(reqHeader);
<add> assert(response.getHeaderString("Access-Control-Allow-Headers") == null);
<add> assertEquals(response.getHeaderString("Access-Control-Allow-Origin"),"*");
<add> assertEquals(response.getHeaderString("Access-Control-Allow-Methods"),"GET, POST, OPTIONS, PUT, PATCH");
<add> }
<add>
<add> @Test(expected=NotFoundException.class)
<add> public void test_delete_work_raises_not_found_exception(){
<add> resource.deleteWork("work_DOES_NOT_EXIST_AND_FAILS");
<add> }
<add>
<add> @Test
<add> public void test_delete_work() throws URISyntaxException{
<add> String work = "{\"@context\": {\"dcterms\": \"http://purl.org/dc/terms/\",\"deichman\": \"http://deichman.no/ontology#\"},\"@graph\": {\"@id\": \"http://deichman.no/work/work_SHOULD_BE_PATCHABLE\",\"@type\": \"deichman:Work\",\"dcterms:identifier\":\"work_SHOULD_BE_PATCHABLE\"}}";
<add> Response createResponse = resource.createWork(work);
<add> String workId = createResponse.getHeaderString("Location").replaceAll("http://deichman.no/work/", "");
<add> Response response = resource.deleteWork(workId);
<add> assertEquals(response.getStatus(),204);
<add> }
<add>
<add> @Test
<add> public void test_CORS_work_id(){
<add> String reqHeader = "application/ld+json";
<add> Response reponse = resource.corsWorkId(reqHeader);
<add> assertEquals(reponse.getHeaderString("Access-Control-Allow-Headers"),reqHeader);
<add> assertEquals(reponse.getHeaderString("Access-Control-Allow-Origin"),"*");
<add> assertEquals(reponse.getHeaderString("Access-Control-Allow-Methods"),"GET, POST, OPTIONS, PUT, PATCH");
<add> }
<add>
<add> @Test
<add> public void test_CORS_work_id_empty_request_header(){
<add> String reqHeader = "";
<add> Response response = resource.corsWorkId(reqHeader);
<add> assert(response.getHeaderString("Access-Control-Allow-Headers") == null);
<add> assertEquals(response.getHeaderString("Access-Control-Allow-Origin"),"*");
<add> assertEquals(response.getHeaderString("Access-Control-Allow-Methods"),"GET, POST, OPTIONS, PUT, PATCH");
<add> }
<add>
<ide> private boolean isValidJSON(final String json) {
<ide> boolean valid = false;
<ide> try { |
|
Java | mit | error: pathspec 'Magic/src/main/java/com/elmakers/mine/bukkit/heroes/HeroesSpellSkill.java' did not match any file(s) known to git
| 84f60fe53bfe9f2562c5fc7a58e5def2327b6ff4 | 1 | elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin | package com.elmakers.mine.bukkit.heroes;
import com.elmakers.mine.bukkit.api.block.MaterialAndData;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.magic.MagicAPI;
import com.elmakers.mine.bukkit.api.spell.CastingCost;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellTemplate;
import com.herocraftonline.heroes.Heroes;
import com.herocraftonline.heroes.api.SkillResult;
import com.herocraftonline.heroes.characters.Hero;
import com.herocraftonline.heroes.characters.skill.ActiveSkill;
import com.herocraftonline.heroes.characters.skill.SkillSetting;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.plugin.Plugin;
import java.util.Collection;
import java.util.logging.Level;
public class HeroesSpellSkill extends ActiveSkill {
private SpellTemplate spellTemplate;
private MageController controller;
public HeroesSpellSkill(Heroes heroes, String spellKey) {
super(heroes, spellKey);
Plugin magicPlugin = heroes.getServer().getPluginManager().getPlugin("Magic");
if (magicPlugin == null || !(magicPlugin instanceof MagicAPI) && !magicPlugin.isEnabled()) {
heroes.getLogger().warning("MagicHeroes skills require the Magic plugin");
throw new RuntimeException("MagicHeroes skills require the Magic plugin");
}
try {
MagicAPI api = (MagicAPI) magicPlugin;
controller = api.getController();
spellTemplate = controller.getSpellTemplate(spellKey);
if (spellTemplate == null) {
heroes.getLogger().warning("Failed to load Magic skill spell: " + spellKey);
throw new RuntimeException("Failed to load Magic skill spell: " + spellKey);
}
this.setDescription(spellTemplate.getDescription());
this.setUsage("/skill " + spellKey);
this.setArgumentRange(0, 0);
this.setIdentifiers(new String[]{"skill " + spellKey});
} catch (Throwable ex) {
heroes.getLogger().log(Level.SEVERE, "Error loading Magic spell " + spellKey, ex);
throw new RuntimeException("Failed to load Magic skill spell: " + spellKey, ex);
}
}
@Override
public SkillResult use(Hero hero, String[] strings) {
Mage mage = controller.getMage(hero.getPlayer());
boolean success = false;
if (mage != null) {
Spell spell = mage.getSpell(spellTemplate.getKey());
if (spell != null) {
success = spell.cast();
}
}
return success ? SkillResult.NORMAL : SkillResult.FAIL;
}
public ConfigurationSection getDefaultConfig() {
ConfigurationSection node = super.getDefaultConfig();
node.set(SkillSetting.MAX_DISTANCE.node(), spellTemplate.getRange());
node.set("icon-url", spellTemplate.getIconURL());
MaterialAndData icon = spellTemplate.getIcon();
if (icon != null && icon.getMaterial() != Material.AIR) {
node.set("icon", icon.getKey());
}
MaterialAndData disabledIcon = spellTemplate.getDisabledIcon();
if (disabledIcon != null && disabledIcon.getMaterial() != Material.AIR) {
node.set("icon-disabled", disabledIcon.getKey());
}
node.set("icon-url", spellTemplate.getIconURL());
node.set("icon-disabled-url", spellTemplate.getDisabledIconURL());
node.set("cooldown", spellTemplate.getCooldown());
node.set("name", spellTemplate.getName());
Collection<CastingCost> costs = spellTemplate.getCosts();
for (CastingCost cost : costs) {
if (cost.getMana() > 0) {
node.set(SkillSetting.MANA.node(), cost.getMana());
}
// TODO: Reagent costs from item costs
}
return node;
}
@Override
public String getDescription(Hero hero) {
return this.getDescription();
}
}
| Magic/src/main/java/com/elmakers/mine/bukkit/heroes/HeroesSpellSkill.java | Move HeroesSpellSkill into Magic so it's esier to keep updated
| Magic/src/main/java/com/elmakers/mine/bukkit/heroes/HeroesSpellSkill.java | Move HeroesSpellSkill into Magic so it's esier to keep updated | <ide><path>agic/src/main/java/com/elmakers/mine/bukkit/heroes/HeroesSpellSkill.java
<add>package com.elmakers.mine.bukkit.heroes;
<add>
<add>import com.elmakers.mine.bukkit.api.block.MaterialAndData;
<add>import com.elmakers.mine.bukkit.api.magic.Mage;
<add>import com.elmakers.mine.bukkit.api.magic.MageController;
<add>import com.elmakers.mine.bukkit.api.magic.MagicAPI;
<add>import com.elmakers.mine.bukkit.api.spell.CastingCost;
<add>import com.elmakers.mine.bukkit.api.spell.Spell;
<add>import com.elmakers.mine.bukkit.api.spell.SpellTemplate;
<add>import com.herocraftonline.heroes.Heroes;
<add>import com.herocraftonline.heroes.api.SkillResult;
<add>import com.herocraftonline.heroes.characters.Hero;
<add>import com.herocraftonline.heroes.characters.skill.ActiveSkill;
<add>import com.herocraftonline.heroes.characters.skill.SkillSetting;
<add>import org.bukkit.Material;
<add>import org.bukkit.configuration.ConfigurationSection;
<add>import org.bukkit.plugin.Plugin;
<add>
<add>import java.util.Collection;
<add>import java.util.logging.Level;
<add>
<add>public class HeroesSpellSkill extends ActiveSkill {
<add> private SpellTemplate spellTemplate;
<add> private MageController controller;
<add>
<add> public HeroesSpellSkill(Heroes heroes, String spellKey) {
<add> super(heroes, spellKey);
<add> Plugin magicPlugin = heroes.getServer().getPluginManager().getPlugin("Magic");
<add> if (magicPlugin == null || !(magicPlugin instanceof MagicAPI) && !magicPlugin.isEnabled()) {
<add> heroes.getLogger().warning("MagicHeroes skills require the Magic plugin");
<add> throw new RuntimeException("MagicHeroes skills require the Magic plugin");
<add> }
<add> try {
<add> MagicAPI api = (MagicAPI) magicPlugin;
<add> controller = api.getController();
<add> spellTemplate = controller.getSpellTemplate(spellKey);
<add> if (spellTemplate == null) {
<add> heroes.getLogger().warning("Failed to load Magic skill spell: " + spellKey);
<add> throw new RuntimeException("Failed to load Magic skill spell: " + spellKey);
<add> }
<add>
<add> this.setDescription(spellTemplate.getDescription());
<add> this.setUsage("/skill " + spellKey);
<add> this.setArgumentRange(0, 0);
<add> this.setIdentifiers(new String[]{"skill " + spellKey});
<add> } catch (Throwable ex) {
<add> heroes.getLogger().log(Level.SEVERE, "Error loading Magic spell " + spellKey, ex);
<add> throw new RuntimeException("Failed to load Magic skill spell: " + spellKey, ex);
<add> }
<add> }
<add>
<add> @Override
<add> public SkillResult use(Hero hero, String[] strings) {
<add> Mage mage = controller.getMage(hero.getPlayer());
<add> boolean success = false;
<add> if (mage != null) {
<add> Spell spell = mage.getSpell(spellTemplate.getKey());
<add> if (spell != null) {
<add> success = spell.cast();
<add> }
<add> }
<add> return success ? SkillResult.NORMAL : SkillResult.FAIL;
<add> }
<add>
<add> public ConfigurationSection getDefaultConfig() {
<add> ConfigurationSection node = super.getDefaultConfig();
<add> node.set(SkillSetting.MAX_DISTANCE.node(), spellTemplate.getRange());
<add> node.set("icon-url", spellTemplate.getIconURL());
<add>
<add> MaterialAndData icon = spellTemplate.getIcon();
<add> if (icon != null && icon.getMaterial() != Material.AIR) {
<add> node.set("icon", icon.getKey());
<add> }
<add> MaterialAndData disabledIcon = spellTemplate.getDisabledIcon();
<add> if (disabledIcon != null && disabledIcon.getMaterial() != Material.AIR) {
<add> node.set("icon-disabled", disabledIcon.getKey());
<add> }
<add> node.set("icon-url", spellTemplate.getIconURL());
<add> node.set("icon-disabled-url", spellTemplate.getDisabledIconURL());
<add> node.set("cooldown", spellTemplate.getCooldown());
<add> node.set("name", spellTemplate.getName());
<add> Collection<CastingCost> costs = spellTemplate.getCosts();
<add> for (CastingCost cost : costs) {
<add> if (cost.getMana() > 0) {
<add> node.set(SkillSetting.MANA.node(), cost.getMana());
<add> }
<add> // TODO: Reagent costs from item costs
<add> }
<add> return node;
<add> }
<add>
<add> @Override
<add> public String getDescription(Hero hero) {
<add> return this.getDescription();
<add> }
<add>} |
|
Java | apache-2.0 | 5f9e7cb296289f95f8f26024ea2c0bf5b99cd112 | 0 | dimagi/javarosa,dimagi/javarosa,dimagi/javarosa | package org.javarosa.core.model;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.Externalizable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* @author ctsims
*/
public class Action implements Externalizable {
public static final String EVENT_XFORMS_READY = "xforms-ready";
public static final String EVENT_XFORMS_REVALIDATE = "xforms-revalidate";
public static final String EVENT_JR_INSERT = "jr-insert";
private String name;
public Action() {
}
public Action(String name) {
this.name = name;
}
/**
* Process actions that were triggered in the form.
*
* NOTE: Currently actions are only processed on nodes that are
* WITHIN the context provided, if one is provided. This will
* need to get changed possibly for future action types.
*/
public void processAction(FormDef model, TreeReference context) {
}
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
name = ExtUtil.readString(in);
}
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.writeString(out, name);
}
}
| core/src/main/java/org/javarosa/core/model/Action.java | package org.javarosa.core.model;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.Externalizable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* @author ctsims
*/
public abstract class Action implements Externalizable {
public static final String EVENT_XFORMS_READY = "xforms-ready";
public static final String EVENT_XFORMS_REVALIDATE = "xforms-revalidate";
public static final String EVENT_JR_INSERT = "jr-insert";
private String name;
public Action() {
}
public Action(String name) {
this.name = name;
}
/**
* Process actions that were triggered in the form.
*
* NOTE: Currently actions are only processed on nodes that are
* WITHIN the context provided, if one is provided. This will
* need to get changed possibly for future action types.
*/
public void processAction(FormDef model, TreeReference context) {
}
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
name = ExtUtil.readString(in);
}
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.writeString(out, name);
}
}
| Reverted Actions being abstract | core/src/main/java/org/javarosa/core/model/Action.java | Reverted Actions being abstract | <ide><path>ore/src/main/java/org/javarosa/core/model/Action.java
<ide> /**
<ide> * @author ctsims
<ide> */
<del>public abstract class Action implements Externalizable {
<add>public class Action implements Externalizable {
<ide> public static final String EVENT_XFORMS_READY = "xforms-ready";
<ide> public static final String EVENT_XFORMS_REVALIDATE = "xforms-revalidate";
<ide> public static final String EVENT_JR_INSERT = "jr-insert"; |
|
Java | apache-2.0 | b870bcd8e13c8fa45adef5056e9448a96519a050 | 0 | dodok1/cas,pmarasse/cas,doodelicious/cas,dodok1/cas,Unicon/cas,petracvv/cas,creamer/cas,petracvv/cas,GIP-RECIA/cas,William-Hill-Online/cas,dodok1/cas,Unicon/cas,creamer/cas,petracvv/cas,rrenomeron/cas,GIP-RECIA/cas,pmarasse/cas,prigaux/cas,tduehr/cas,William-Hill-Online/cas,rrenomeron/cas,tduehr/cas,robertoschwald/cas,GIP-RECIA/cas,GIP-RECIA/cas,rrenomeron/cas,pmarasse/cas,robertoschwald/cas,Unicon/cas,rrenomeron/cas,creamer/cas,frett/cas,robertoschwald/cas,prigaux/cas,William-Hill-Online/cas,frett/cas,Unicon/cas,prigaux/cas,doodelicious/cas,GIP-RECIA/cas,petracvv/cas,doodelicious/cas,frett/cas,frett/cas,tduehr/cas,William-Hill-Online/cas,prigaux/cas,robertoschwald/cas,pmarasse/cas,dodok1/cas,tduehr/cas,rrenomeron/cas,doodelicious/cas,Unicon/cas,creamer/cas | package org.apereo.cas.mgmt.config;
import com.google.common.base.Throwables;
import org.apereo.cas.CasProtocolConstants;
import org.apereo.cas.authentication.AuthenticationMetaDataPopulator;
import org.apereo.cas.authentication.principal.ServiceFactory;
import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.support.Beans;
import org.apereo.cas.mgmt.services.web.ManageRegisteredServicesMultiActionController;
import org.apereo.cas.mgmt.services.web.RegisteredServiceSimpleFormController;
import org.apereo.cas.mgmt.services.web.factory.AccessStrategyMapper;
import org.apereo.cas.mgmt.services.web.factory.AttributeFilterMapper;
import org.apereo.cas.mgmt.services.web.factory.AttributeFormDataPopulator;
import org.apereo.cas.mgmt.services.web.factory.AttributeReleasePolicyMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultAccessStrategyMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultAttributeFilterMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultAttributeReleasePolicyMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultPrincipalAttributesRepositoryMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultProxyPolicyMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultRegisteredServiceFactory;
import org.apereo.cas.mgmt.services.web.factory.DefaultRegisteredServiceMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultUsernameAttributeProviderMapper;
import org.apereo.cas.mgmt.services.web.factory.FormDataPopulator;
import org.apereo.cas.mgmt.services.web.factory.PrincipalAttributesRepositoryMapper;
import org.apereo.cas.mgmt.services.web.factory.ProxyPolicyMapper;
import org.apereo.cas.mgmt.services.web.factory.RegisteredServiceFactory;
import org.apereo.cas.mgmt.services.web.factory.RegisteredServiceMapper;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.ticket.UniqueTicketIdGenerator;
import org.apereo.services.persondir.IPersonAttributeDao;
import org.pac4j.cas.client.direct.DirectCasClient;
import org.pac4j.cas.config.CasConfiguration;
import org.pac4j.core.authorization.authorizer.Authorizer;
import org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer;
import org.pac4j.core.authorization.generator.AuthorizationGenerator;
import org.pac4j.core.authorization.generator.FromAttributesAuthorizationGenerator;
import org.pac4j.core.authorization.generator.SpringSecurityPropertiesAuthorizationGenerator;
import org.pac4j.core.client.Client;
import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.engine.DefaultSecurityLogic;
import org.pac4j.core.exception.HttpAction;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.springframework.web.SecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.ParameterizableViewController;
import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
import org.springframework.web.servlet.mvc.UrlFilenameViewController;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
/**
* This is {@link CasManagementWebAppConfiguration}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
@Configuration("casManagementWebAppConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class CasManagementWebAppConfiguration extends WebMvcConfigurerAdapter {
@Autowired(required = false)
@Qualifier("formDataPopulators")
private List formDataPopulators = new ArrayList<>();
@Autowired
private ServerProperties serverProperties;
@Autowired
private CasConfigurationProperties casProperties;
@Autowired
@Qualifier("webApplicationServiceFactory")
private ServiceFactory<WebApplicationService> webApplicationServiceFactory;
@Bean
public Filter characterEncodingFilter() {
return new CharacterEncodingFilter(StandardCharsets.UTF_8.name(), true);
}
@Bean
public Authorizer requireAnyRoleAuthorizer() {
return new RequireAnyRoleAuthorizer(casProperties.getMgmt().getAdminRoles());
}
@RefreshScope
@ConditionalOnMissingBean(name = "attributeRepository")
@Bean(name = {"stubAttributeRepository", "attributeRepository"})
public IPersonAttributeDao stubAttributeRepository() {
return Beans.newStubAttributeRepository(casProperties.getAuthn().getAttributeRepository());
}
@Bean
public Client casClient() {
final CasConfiguration cfg = new CasConfiguration(casProperties.getServer().getLoginUrl());
final DirectCasClient client = new DirectCasClient(cfg);
client.setAuthorizationGenerator(authorizationGenerator());
client.setName("CasClient");
return client;
}
@Bean
public Config config() {
final Config cfg = new Config(getDefaultServiceUrl(), casClient());
cfg.setAuthorizer(requireAnyRoleAuthorizer());
return cfg;
}
@Bean
protected Controller rootController() {
return new ParameterizableViewController() {
@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
final HttpServletResponse response)
throws Exception {
final String url = request.getContextPath() + "/manage.html";
return new ModelAndView(new RedirectView(response.encodeURL(url)));
}
};
}
@Bean
public SimpleUrlHandlerMapping handlerMappingC() {
final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(1);
mapping.setAlwaysUseFullPath(true);
mapping.setRootHandler(rootController());
final Properties properties = new Properties();
properties.put("/*.html", new UrlFilenameViewController());
mapping.setMappings(properties);
return mapping;
}
@Bean
public HandlerInterceptorAdapter casManagementSecurityInterceptor() {
return new CasManagementSecurityInterceptor();
}
@RefreshScope
@Bean
public Properties userProperties() {
try {
final Properties p = new Properties();
p.load(casProperties.getMgmt().getUserPropertiesFile().getInputStream());
return p;
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
@ConditionalOnMissingBean(name = "authorizationGenerator")
@Bean
@RefreshScope
public AuthorizationGenerator authorizationGenerator() {
final List<String> authzAttributes = casProperties.getMgmt().getAuthzAttributes();
if (!authzAttributes.isEmpty()) {
if ("*".equals(authzAttributes)) {
return new PermitAllAuthorizationGenerator();
}
return new FromAttributesAuthorizationGenerator(authzAttributes.toArray(new String[]{}), new String[]{});
}
return new SpringSecurityPropertiesAuthorizationGenerator(userProperties());
}
@Bean
public CookieLocaleResolver localeResolver() {
return new CookieLocaleResolver() {
@Override
protected Locale determineDefaultLocale(final HttpServletRequest request) {
final Locale locale = request.getLocale();
if (StringUtils.isEmpty(casProperties.getMgmt().getDefaultLocale())
|| !locale.getLanguage().equals(casProperties.getMgmt().getDefaultLocale())) {
return locale;
}
return new Locale(casProperties.getMgmt().getDefaultLocale());
}
};
}
@RefreshScope
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
final LocaleChangeInterceptor bean = new LocaleChangeInterceptor();
bean.setParamName(this.casProperties.getLocale().getParamName());
return bean;
}
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
registry.addInterceptor(casManagementSecurityInterceptor())
.addPathPatterns("/**").excludePathPatterns("/callback*", "/logout*", "/authorizationFailure");
}
@Bean
public SimpleControllerHandlerAdapter simpleControllerHandlerAdapter() {
return new SimpleControllerHandlerAdapter();
}
@Bean
public AccessStrategyMapper defaultAccessStrategyMapper() {
return new DefaultAccessStrategyMapper();
}
@Bean
public RegisteredServiceFactory registeredServiceFactory() {
this.formDataPopulators.add(attributeFormDataPopulator());
return new DefaultRegisteredServiceFactory(defaultAccessStrategyMapper(), defaultAttributeReleasePolicyMapper(), defaultProxyPolicyMapper(),
defaultRegisteredServiceMapper(), usernameAttributeProviderMapper(), formDataPopulators);
}
@Bean
public AttributeReleasePolicyMapper defaultAttributeReleasePolicyMapper() {
return new DefaultAttributeReleasePolicyMapper(defaultAttributeFilterMapper(), defaultPrincipalAttributesRepositoryMapper());
}
@Bean
public FormDataPopulator attributeFormDataPopulator() {
return new AttributeFormDataPopulator(stubAttributeRepository());
}
@Bean
public DefaultUsernameAttributeProviderMapper usernameAttributeProviderMapper() {
return new DefaultUsernameAttributeProviderMapper();
}
@Bean
public RegisteredServiceMapper defaultRegisteredServiceMapper() {
return new DefaultRegisteredServiceMapper();
}
@Bean
public ProxyPolicyMapper defaultProxyPolicyMapper() {
return new DefaultProxyPolicyMapper();
}
@Bean
public AttributeFilterMapper defaultAttributeFilterMapper() {
return new DefaultAttributeFilterMapper();
}
@Bean
public PrincipalAttributesRepositoryMapper defaultPrincipalAttributesRepositoryMapper() {
return new DefaultPrincipalAttributesRepositoryMapper();
}
@Bean
public ManageRegisteredServicesMultiActionController manageRegisteredServicesMultiActionController(
@Qualifier("servicesManager") final ServicesManager servicesManager) {
return new ManageRegisteredServicesMultiActionController(servicesManager, registeredServiceFactory(), webApplicationServiceFactory,
getDefaultServiceUrl());
}
@Bean
public RegisteredServiceSimpleFormController registeredServiceSimpleFormController(@Qualifier("servicesManager") final ServicesManager servicesManager) {
return new RegisteredServiceSimpleFormController(servicesManager, registeredServiceFactory());
}
private String getDefaultServiceUrl() {
return casProperties.getMgmt().getServerName().concat(serverProperties.getContextPath()).concat("/callback");
}
@Bean
public List serviceFactoryList() {
return new ArrayList();
}
@Bean
public Map<String, UniqueTicketIdGenerator> uniqueIdGeneratorsMap() {
return new HashMap<>();
}
@Bean
public List<AuthenticationMetaDataPopulator> authenticationMetadataPopulators() {
return new ArrayList<>();
}
/**
* The Cas management security interceptor.
*/
public class CasManagementSecurityInterceptor extends SecurityInterceptor {
public CasManagementSecurityInterceptor() {
super(config(), "CasClient", "securityHeaders,csrfToken,RequireAnyRoleAuthorizer");
final DefaultSecurityLogic logic = new DefaultSecurityLogic() {
@Override
protected HttpAction forbidden(final WebContext context, final List currentClients, final List list, final String authorizers) {
return HttpAction.redirect("Authorization failed", context, "authorizationFailure");
}
@Override
protected boolean loadProfilesFromSession(final WebContext context, final List currentClients) {
return true;
}
};
logic.setSaveProfileInSession(true);
setSecurityLogic(logic);
}
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response,
final Object handler, final ModelAndView modelAndView) throws Exception {
if (!StringUtils.isEmpty(request.getQueryString())
&& request.getQueryString().contains(CasProtocolConstants.PARAMETER_TICKET)) {
final RedirectView v = new RedirectView(request.getRequestURL().toString());
v.setExposeModelAttributes(false);
v.setExposePathVariables(false);
modelAndView.setView(v);
}
}
}
/**
* The Permit all authorization generator.
*/
public class PermitAllAuthorizationGenerator implements AuthorizationGenerator<CommonProfile> {
@Override
public CommonProfile generate(final WebContext webContext, final CommonProfile commonProfile) {
commonProfile.addRoles(casProperties.getMgmt().getAdminRoles());
return commonProfile;
}
}
}
| webapp-mgmt/cas-management-webapp-support/src/main/java/org/apereo/cas/mgmt/config/CasManagementWebAppConfiguration.java | package org.apereo.cas.mgmt.config;
import com.google.common.base.Throwables;
import org.apereo.cas.CasProtocolConstants;
import org.apereo.cas.authentication.AuthenticationMetaDataPopulator;
import org.apereo.cas.authentication.principal.ServiceFactory;
import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.support.Beans;
import org.apereo.cas.mgmt.services.web.ManageRegisteredServicesMultiActionController;
import org.apereo.cas.mgmt.services.web.RegisteredServiceSimpleFormController;
import org.apereo.cas.mgmt.services.web.factory.AccessStrategyMapper;
import org.apereo.cas.mgmt.services.web.factory.AttributeFilterMapper;
import org.apereo.cas.mgmt.services.web.factory.AttributeFormDataPopulator;
import org.apereo.cas.mgmt.services.web.factory.AttributeReleasePolicyMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultAccessStrategyMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultAttributeFilterMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultAttributeReleasePolicyMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultPrincipalAttributesRepositoryMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultProxyPolicyMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultRegisteredServiceFactory;
import org.apereo.cas.mgmt.services.web.factory.DefaultRegisteredServiceMapper;
import org.apereo.cas.mgmt.services.web.factory.DefaultUsernameAttributeProviderMapper;
import org.apereo.cas.mgmt.services.web.factory.FormDataPopulator;
import org.apereo.cas.mgmt.services.web.factory.PrincipalAttributesRepositoryMapper;
import org.apereo.cas.mgmt.services.web.factory.ProxyPolicyMapper;
import org.apereo.cas.mgmt.services.web.factory.RegisteredServiceFactory;
import org.apereo.cas.mgmt.services.web.factory.RegisteredServiceMapper;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.ticket.UniqueTicketIdGenerator;
import org.apereo.services.persondir.IPersonAttributeDao;
import org.pac4j.cas.client.direct.DirectCasClient;
import org.pac4j.cas.config.CasConfiguration;
import org.pac4j.core.authorization.authorizer.Authorizer;
import org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer;
import org.pac4j.core.authorization.generator.AuthorizationGenerator;
import org.pac4j.core.authorization.generator.FromAttributesAuthorizationGenerator;
import org.pac4j.core.authorization.generator.SpringSecurityPropertiesAuthorizationGenerator;
import org.pac4j.core.client.Client;
import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.engine.DefaultSecurityLogic;
import org.pac4j.core.exception.HttpAction;
import org.pac4j.springframework.web.SecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.ParameterizableViewController;
import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
import org.springframework.web.servlet.mvc.UrlFilenameViewController;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
/**
* This is {@link CasManagementWebAppConfiguration}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
@Configuration("casManagementWebAppConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class CasManagementWebAppConfiguration extends WebMvcConfigurerAdapter {
@Autowired(required = false)
@Qualifier("formDataPopulators")
private List formDataPopulators = new ArrayList<>();
@Autowired
private ServerProperties serverProperties;
@Autowired
private CasConfigurationProperties casProperties;
@Autowired
@Qualifier("webApplicationServiceFactory")
private ServiceFactory<WebApplicationService> webApplicationServiceFactory;
@Bean
public Filter characterEncodingFilter() {
return new CharacterEncodingFilter(StandardCharsets.UTF_8.name(), true);
}
@Bean
public Authorizer requireAnyRoleAuthorizer() {
return new RequireAnyRoleAuthorizer(casProperties.getMgmt().getAdminRoles());
}
@RefreshScope
@ConditionalOnMissingBean(name = "attributeRepository")
@Bean(name = {"stubAttributeRepository", "attributeRepository"})
public IPersonAttributeDao stubAttributeRepository() {
return Beans.newStubAttributeRepository(casProperties.getAuthn().getAttributeRepository());
}
@Bean
public Client casClient() {
final CasConfiguration cfg = new CasConfiguration(casProperties.getServer().getLoginUrl());
final DirectCasClient client = new DirectCasClient(cfg);
client.setAuthorizationGenerator(authorizationGenerator());
client.setName("CasClient");
return client;
}
@Bean
public Config config() {
final Config cfg = new Config(getDefaultServiceUrl(), casClient());
cfg.setAuthorizer(requireAnyRoleAuthorizer());
return cfg;
}
@Bean
protected Controller rootController() {
return new ParameterizableViewController() {
@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
final HttpServletResponse response)
throws Exception {
final String url = request.getContextPath() + "/manage.html";
return new ModelAndView(new RedirectView(response.encodeURL(url)));
}
};
}
@Bean
public SimpleUrlHandlerMapping handlerMappingC() {
final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(1);
mapping.setAlwaysUseFullPath(true);
mapping.setRootHandler(rootController());
final Properties properties = new Properties();
properties.put("/*.html", new UrlFilenameViewController());
mapping.setMappings(properties);
return mapping;
}
@Bean
public HandlerInterceptorAdapter casManagementSecurityInterceptor() {
return new CasManagementSecurityInterceptor();
}
@RefreshScope
@Bean
public Properties userProperties() {
try {
final Properties p = new Properties();
p.load(casProperties.getMgmt().getUserPropertiesFile().getInputStream());
return p;
} catch (final Exception e) {
throw Throwables.propagate(e);
}
}
@ConditionalOnMissingBean(name = "authorizationGenerator")
@Bean
@RefreshScope
public AuthorizationGenerator authorizationGenerator() {
final List<String> authzAttributes = casProperties.getMgmt().getAuthzAttributes();
if (!authzAttributes.isEmpty()) {
if ("*".equals(authzAttributes)) {
return (webContext, commonProfile) -> {
commonProfile.addRoles(casProperties.getMgmt().getAdminRoles());
return commonProfile;
};
}
return new FromAttributesAuthorizationGenerator(authzAttributes.toArray(new String[]{}), new String[]{});
}
return new SpringSecurityPropertiesAuthorizationGenerator(userProperties());
}
@Bean
public CookieLocaleResolver localeResolver() {
return new CookieLocaleResolver() {
@Override
protected Locale determineDefaultLocale(final HttpServletRequest request) {
final Locale locale = request.getLocale();
if (StringUtils.isEmpty(casProperties.getMgmt().getDefaultLocale())
|| !locale.getLanguage().equals(casProperties.getMgmt().getDefaultLocale())) {
return locale;
}
return new Locale(casProperties.getMgmt().getDefaultLocale());
}
};
}
@RefreshScope
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
final LocaleChangeInterceptor bean = new LocaleChangeInterceptor();
bean.setParamName(this.casProperties.getLocale().getParamName());
return bean;
}
@Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
registry.addInterceptor(casManagementSecurityInterceptor())
.addPathPatterns("/**").excludePathPatterns("/callback*", "/logout*", "/authorizationFailure");
}
@Bean
public SimpleControllerHandlerAdapter simpleControllerHandlerAdapter() {
return new SimpleControllerHandlerAdapter();
}
@Bean
public AccessStrategyMapper defaultAccessStrategyMapper() {
return new DefaultAccessStrategyMapper();
}
@Bean
public RegisteredServiceFactory registeredServiceFactory() {
this.formDataPopulators.add(attributeFormDataPopulator());
return new DefaultRegisteredServiceFactory(defaultAccessStrategyMapper(), defaultAttributeReleasePolicyMapper(), defaultProxyPolicyMapper(),
defaultRegisteredServiceMapper(), usernameAttributeProviderMapper(), formDataPopulators);
}
@Bean
public AttributeReleasePolicyMapper defaultAttributeReleasePolicyMapper() {
return new DefaultAttributeReleasePolicyMapper(defaultAttributeFilterMapper(), defaultPrincipalAttributesRepositoryMapper());
}
@Bean
public FormDataPopulator attributeFormDataPopulator() {
return new AttributeFormDataPopulator(stubAttributeRepository());
}
@Bean
public DefaultUsernameAttributeProviderMapper usernameAttributeProviderMapper() {
return new DefaultUsernameAttributeProviderMapper();
}
@Bean
public RegisteredServiceMapper defaultRegisteredServiceMapper() {
return new DefaultRegisteredServiceMapper();
}
@Bean
public ProxyPolicyMapper defaultProxyPolicyMapper() {
return new DefaultProxyPolicyMapper();
}
@Bean
public AttributeFilterMapper defaultAttributeFilterMapper() {
return new DefaultAttributeFilterMapper();
}
@Bean
public PrincipalAttributesRepositoryMapper defaultPrincipalAttributesRepositoryMapper() {
return new DefaultPrincipalAttributesRepositoryMapper();
}
@Bean
public ManageRegisteredServicesMultiActionController manageRegisteredServicesMultiActionController(
@Qualifier("servicesManager") final ServicesManager servicesManager) {
return new ManageRegisteredServicesMultiActionController(servicesManager, registeredServiceFactory(), webApplicationServiceFactory,
getDefaultServiceUrl());
}
@Bean
public RegisteredServiceSimpleFormController registeredServiceSimpleFormController(@Qualifier("servicesManager") final ServicesManager servicesManager) {
return new RegisteredServiceSimpleFormController(servicesManager, registeredServiceFactory());
}
private String getDefaultServiceUrl() {
return casProperties.getMgmt().getServerName().concat(serverProperties.getContextPath()).concat("/callback");
}
@Bean
public List serviceFactoryList() {
return new ArrayList();
}
@Bean
public Map<String, UniqueTicketIdGenerator> uniqueIdGeneratorsMap() {
return new HashMap<>();
}
@Bean
public List<AuthenticationMetaDataPopulator> authenticationMetadataPopulators() {
return new ArrayList<>();
}
/**
* The Cas management security interceptor.
*/
public class CasManagementSecurityInterceptor extends SecurityInterceptor {
public CasManagementSecurityInterceptor() {
super(config(), "CasClient", "securityHeaders,csrfToken,RequireAnyRoleAuthorizer");
final DefaultSecurityLogic logic = new DefaultSecurityLogic() {
@Override
protected HttpAction forbidden(final WebContext context, final List currentClients, final List list, final String authorizers) {
return HttpAction.redirect("Authorization failed", context, "authorizationFailure");
}
@Override
protected boolean loadProfilesFromSession(final WebContext context, final List currentClients) {
return true;
}
};
logic.setSaveProfileInSession(true);
setSecurityLogic(logic);
}
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response,
final Object handler, final ModelAndView modelAndView) throws Exception {
if (!StringUtils.isEmpty(request.getQueryString())
&& request.getQueryString().contains(CasProtocolConstants.PARAMETER_TICKET)) {
final RedirectView v = new RedirectView(request.getRequestURL().toString());
v.setExposeModelAttributes(false);
v.setExposePathVariables(false);
modelAndView.setView(v);
}
}
}
}
| Clean up pac4j API changes for authz
| webapp-mgmt/cas-management-webapp-support/src/main/java/org/apereo/cas/mgmt/config/CasManagementWebAppConfiguration.java | Clean up pac4j API changes for authz | <ide><path>ebapp-mgmt/cas-management-webapp-support/src/main/java/org/apereo/cas/mgmt/config/CasManagementWebAppConfiguration.java
<ide> import org.pac4j.core.context.WebContext;
<ide> import org.pac4j.core.engine.DefaultSecurityLogic;
<ide> import org.pac4j.core.exception.HttpAction;
<add>import org.pac4j.core.profile.CommonProfile;
<ide> import org.pac4j.springframework.web.SecurityInterceptor;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.beans.factory.annotation.Qualifier;
<ide> final List<String> authzAttributes = casProperties.getMgmt().getAuthzAttributes();
<ide> if (!authzAttributes.isEmpty()) {
<ide> if ("*".equals(authzAttributes)) {
<del> return (webContext, commonProfile) -> {
<del> commonProfile.addRoles(casProperties.getMgmt().getAdminRoles());
<del> return commonProfile;
<del> };
<add> return new PermitAllAuthorizationGenerator();
<ide> }
<ide> return new FromAttributesAuthorizationGenerator(authzAttributes.toArray(new String[]{}), new String[]{});
<ide> }
<ide> }
<ide> }
<ide> }
<add>
<add> /**
<add> * The Permit all authorization generator.
<add> */
<add> public class PermitAllAuthorizationGenerator implements AuthorizationGenerator<CommonProfile> {
<add> @Override
<add> public CommonProfile generate(final WebContext webContext, final CommonProfile commonProfile) {
<add> commonProfile.addRoles(casProperties.getMgmt().getAdminRoles());
<add> return commonProfile;
<add> }
<add> }
<ide> } |
|
Java | apache-2.0 | 991d8b4223a35a9c576e23eff715f6a05c9d096d | 0 | bigal91/CSAR_Repository,bigal91/CSAR_Repository,CloudCycle2/CSAR_Repository,CloudCycle2/CSAR_Repository | package org.opentosca.csarrepo.service;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opentosca.csarrepo.exception.PersistenceException;
import org.opentosca.csarrepo.filesystem.FileSystem;
import org.opentosca.csarrepo.model.Csar;
import org.opentosca.csarrepo.model.CsarFile;
import org.opentosca.csarrepo.model.HashedFile;
import org.opentosca.csarrepo.model.repository.CsarFileRepository;
import org.opentosca.csarrepo.model.repository.CsarRepository;
import org.opentosca.csarrepo.model.repository.FileSystemRepository;
import org.opentosca.csarrepo.util.Extractor;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* @author eiselems ([email protected]), Dennis Przytarski
*
*/
public class UploadCsarFileService extends AbstractService {
private static final String ENTRY_DEFINITION_PATTERN = "Entry-Definitions: ([\\S]+)\\n";
private static final String TOSCA_METADATA_FILEPATH = "TOSCA-Metadata/TOSCA.meta";
private static final String X_PATH_EXPRESSION = "//*[local-name()='ServiceTemplate']/@*[name()='id' or name()='targetNamespace']";
private static final Logger LOGGER = LogManager.getLogger(UploadCsarFileService.class);
private CsarFile csarFile;
/**
* @param userId
* @param file
* @throws IOException
*/
public UploadCsarFileService(long userId, long csarId, InputStream inputStream, String name) {
super(userId);
if (!checkExtension(name, "csar")) {
this.addError(String.format("Uploaded file %s does not contain required extension", name));
return;
}
storeFile(csarId, inputStream, name);
}
/**
* Checks, if the name contains the given extension.
*
* @param name
* @param extension
* @return true, if given name contains given extension
*/
private boolean checkExtension(String name, String extension) {
int index = name.lastIndexOf('.');
return 0 < index && name.substring(index + 1).equals(extension);
}
/**
* Moves the uploaded file to the filesystem and creates a csar file.
*
* @param csarId
* @param inputStream
* @param name
*/
private void storeFile(long csarId, InputStream inputStream, String name) {
CsarRepository csarRepository = new CsarRepository();
CsarFileRepository csarFileRepository = new CsarFileRepository();
FileSystemRepository fileSystemRepository = new FileSystemRepository();
try {
Csar csar = csarRepository.getbyId(csarId);
if (null == csar) {
String errorMsg = String.format("CSAR with ID: %d could not be found", csarId);
this.addError(errorMsg);
LOGGER.error(errorMsg);
return;
}
FileSystem fileSystem = new FileSystem();
File temporaryFile = fileSystem.saveTempFile(inputStream);
String entryDefinition = Extractor.match(Extractor.unzip(temporaryFile, TOSCA_METADATA_FILEPATH),
ENTRY_DEFINITION_PATTERN);
String xmlData = Extractor.unzip(temporaryFile, entryDefinition);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new ByteArrayInputStream(xmlData.getBytes()));
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xpath.compile(X_PATH_EXPRESSION);
NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
Map<String, String> nodeMap = new HashMap<>();
for (int i = 0; i < nodeList.getLength(); i++) {
nodeMap.put(nodeList.item(i).getNodeName(), nodeList.item(i).getNodeValue());
}
String serviceTemplateId = nodeMap.get("id");
String namespace = nodeMap.get("targetNamespace");
if (null == csar.getServiceTemplateId()) {
csar.setServiceTemplateId(serviceTemplateId);
csar.setNamespace(namespace);
LOGGER.info("csar: service template id ({}) and namespace ({}) set", serviceTemplateId, namespace);
} else if (!csar.getServiceTemplateId().equals(serviceTemplateId)
|| (null == csar.getNamespace() && null != namespace && !namespace.equals(null))
|| (null != csar.getNamespace() && !csar.getNamespace().equals(namespace))) {
throw new PersistenceException(String.format(
"File does not match csar service template id (%s: %s) or namespace (%s: %s).",
csar.getServiceTemplateId(), serviceTemplateId, csar.getNamespace(), namespace));
}
String hash = fileSystem.generateHash(temporaryFile);
HashedFile hashedFile;
if (!fileSystemRepository.containsHash(hash)) {
hashedFile = new HashedFile();
File newFile = fileSystem.saveToFileSystem(temporaryFile);
hashedFile.setFilename(UUID.fromString(newFile.getName()));
hashedFile.setHash(hash);
hashedFile.setSize(newFile.length());
fileSystemRepository.save(hashedFile);
} else {
hashedFile = fileSystemRepository.getByHash(hash);
}
this.csarFile = new CsarFile();
this.csarFile.setCsar(csar);
this.csarFile.setHashedFile(hashedFile);
this.csarFile.setName(name);
this.csarFile.setUploadDate(new Date());
this.csarFile.setVersion(1); // TODO: set correct version
csarFileRepository.save(csarFile);
csar.getCsarFiles().add(csarFile);
csarRepository.save(csar);
} catch (IllegalStateException | IOException | ParserConfigurationException | PersistenceException
| SAXException | XPathExpressionException e) {
this.addError(e.getMessage());
LOGGER.error(e.getMessage());
return;
}
}
public CsarFile getResult() {
super.logInvalidResultAccess("getResult");
return this.csarFile;
}
}
| src/main/java/org/opentosca/csarrepo/service/UploadCsarFileService.java | package org.opentosca.csarrepo.service;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opentosca.csarrepo.exception.PersistenceException;
import org.opentosca.csarrepo.filesystem.FileSystem;
import org.opentosca.csarrepo.model.Csar;
import org.opentosca.csarrepo.model.CsarFile;
import org.opentosca.csarrepo.model.HashedFile;
import org.opentosca.csarrepo.model.repository.CsarFileRepository;
import org.opentosca.csarrepo.model.repository.CsarRepository;
import org.opentosca.csarrepo.model.repository.FileSystemRepository;
import org.opentosca.csarrepo.util.Extractor;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* @author eiselems ([email protected]), Dennis Przytarski
*
*/
public class UploadCsarFileService extends AbstractService {
private static final String X_PATH_EXPRESSION = "//*[local-name()='ServiceTemplate']/@*[name()='id' or name()='targetNamespace']";
private static final String ENTRY_DEFINITION_PATTERN = "Entry-Definitions: ([\\S]+)\\n";
private static final String TOSCA_METADATA_FILEPATH = "TOSCA-Metadata/TOSCA.meta";
private static final Logger LOGGER = LogManager.getLogger(UploadCsarFileService.class);
private CsarFile csarFile;
/**
* @param userId
* @param file
* @throws IOException
*/
public UploadCsarFileService(long userId, long csarId, InputStream inputStream, String name) {
super(userId);
if (!checkExtension(name, "csar")) {
this.addError(String.format("Uploaded file %s does not contain required extension", name));
return;
}
storeFile(csarId, inputStream, name);
}
/**
* Checks, if the name contains the given extension.
*
* @param name
* @param extension
* @return true, if given name contains given extension
*/
private boolean checkExtension(String name, String extension) {
int index = name.lastIndexOf('.');
return 0 < index && name.substring(index + 1).equals(extension);
}
/**
* Moves the uploaded file to the filesystem and creates a csar file.
*
* @param csarId
* @param inputStream
* @param name
*/
private void storeFile(long csarId, InputStream inputStream, String name) {
CsarRepository csarRepository = new CsarRepository();
CsarFileRepository csarFileRepository = new CsarFileRepository();
FileSystemRepository fileSystemRepository = new FileSystemRepository();
try {
Csar csar = csarRepository.getbyId(csarId);
if (null == csar) {
String errorMsg = String.format("CSAR with ID: %d could not be found", csarId);
this.addError(errorMsg);
LOGGER.error(errorMsg);
return;
}
FileSystem fileSystem = new FileSystem();
File temporaryFile = fileSystem.saveTempFile(inputStream);
String entryDefinition = Extractor.match(Extractor.unzip(temporaryFile, TOSCA_METADATA_FILEPATH),
ENTRY_DEFINITION_PATTERN);
String xmlData = Extractor.unzip(temporaryFile, entryDefinition);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new ByteArrayInputStream(xmlData.getBytes()));
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xpath.compile(X_PATH_EXPRESSION);
NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
Map<String, String> nodeMap = new HashMap<>();
for (int i = 0; i < nodeList.getLength(); i++) {
nodeMap.put(nodeList.item(i).getNodeName(), nodeList.item(i).getNodeValue());
}
String serviceTemplateId = nodeMap.get("id");
String namespace = nodeMap.get("targetNamespace");
if (null == csar.getServiceTemplateId() && null == csar.getNamespace()) {
csar.setServiceTemplateId(serviceTemplateId);
csar.setNamespace(namespace);
} else if (!(csar.getServiceTemplateId().equals(serviceTemplateId) && csar.getNamespace().equals(namespace))) {
throw new PersistenceException(String.format("File does not match csar id (%s) or namespace (%s).",
serviceTemplateId, namespace));
}
String hash = fileSystem.generateHash(temporaryFile);
HashedFile hashedFile;
if (!fileSystemRepository.containsHash(hash)) {
hashedFile = new HashedFile();
File newFile = fileSystem.saveToFileSystem(temporaryFile);
hashedFile.setFilename(UUID.fromString(newFile.getName()));
hashedFile.setHash(hash);
hashedFile.setSize(newFile.length());
fileSystemRepository.save(hashedFile);
} else {
hashedFile = fileSystemRepository.getByHash(hash);
}
this.csarFile = new CsarFile();
this.csarFile.setCsar(csar);
this.csarFile.setHashedFile(hashedFile);
this.csarFile.setName(name);
this.csarFile.setUploadDate(new Date());
this.csarFile.setVersion(1); // TODO: set correct version
csarFileRepository.save(csarFile);
csar.getCsarFiles().add(csarFile);
csarRepository.save(csar);
} catch (IllegalStateException | IOException | ParserConfigurationException | PersistenceException
| SAXException | XPathExpressionException e) {
this.addError(e.getMessage());
LOGGER.error(e.getMessage());
return;
}
}
public CsarFile getResult() {
super.logInvalidResultAccess("getResult");
return this.csarFile;
}
}
| namespace is not mandatory
| src/main/java/org/opentosca/csarrepo/service/UploadCsarFileService.java | namespace is not mandatory | <ide><path>rc/main/java/org/opentosca/csarrepo/service/UploadCsarFileService.java
<ide> */
<ide> public class UploadCsarFileService extends AbstractService {
<ide>
<del> private static final String X_PATH_EXPRESSION = "//*[local-name()='ServiceTemplate']/@*[name()='id' or name()='targetNamespace']";
<ide> private static final String ENTRY_DEFINITION_PATTERN = "Entry-Definitions: ([\\S]+)\\n";
<ide> private static final String TOSCA_METADATA_FILEPATH = "TOSCA-Metadata/TOSCA.meta";
<add> private static final String X_PATH_EXPRESSION = "//*[local-name()='ServiceTemplate']/@*[name()='id' or name()='targetNamespace']";
<ide>
<ide> private static final Logger LOGGER = LogManager.getLogger(UploadCsarFileService.class);
<ide>
<ide> String serviceTemplateId = nodeMap.get("id");
<ide> String namespace = nodeMap.get("targetNamespace");
<ide>
<del> if (null == csar.getServiceTemplateId() && null == csar.getNamespace()) {
<add> if (null == csar.getServiceTemplateId()) {
<ide> csar.setServiceTemplateId(serviceTemplateId);
<ide> csar.setNamespace(namespace);
<del> } else if (!(csar.getServiceTemplateId().equals(serviceTemplateId) && csar.getNamespace().equals(namespace))) {
<del> throw new PersistenceException(String.format("File does not match csar id (%s) or namespace (%s).",
<del> serviceTemplateId, namespace));
<add> LOGGER.info("csar: service template id ({}) and namespace ({}) set", serviceTemplateId, namespace);
<add> } else if (!csar.getServiceTemplateId().equals(serviceTemplateId)
<add> || (null == csar.getNamespace() && null != namespace && !namespace.equals(null))
<add> || (null != csar.getNamespace() && !csar.getNamespace().equals(namespace))) {
<add> throw new PersistenceException(String.format(
<add> "File does not match csar service template id (%s: %s) or namespace (%s: %s).",
<add> csar.getServiceTemplateId(), serviceTemplateId, csar.getNamespace(), namespace));
<ide> }
<ide>
<ide> String hash = fileSystem.generateHash(temporaryFile); |
|
Java | mit | 4acd25113a1af223cfce8207ee209f0a74977950 | 0 | MateusAraujoBorges/motorola-ftestes-15,MateusAraujoBorges/motorola-ftestes-15 | package calculator;
import org.assertj.swing.edt.GuiActionRunner;
import org.assertj.swing.edt.GuiQuery;
import org.assertj.swing.fixture.FrameFixture;
import org.assertj.swing.image.ScreenshotTaker;
import org.assertj.swing.junit.testcase.AssertJSwingJUnitTestCase;
import org.junit.Test;
public class CalculatorGUITests extends AssertJSwingJUnitTestCase {
private FrameFixture window;
@Override
protected void onSetUp() {
Calculator frame = GuiActionRunner
.execute(new GuiQuery<Calculator>() {
protected Calculator executeInEDT() {
return new Calculator();
}
});
// IMPORTANT: note the call to 'robot()'
// we must use the Robot from AssertJSwingJUnitTestCase
window = new FrameFixture(robot(), frame);
window.show(); // shows the frame to test
}
@Test
public void testSum() {
window.button("2").click();
window.button("+").click();
window.button("2").click();
window.button("=").click();
window.textBox("lcd").requireText("4.0");
}
@Test
public void testSumWithSnapshot() {
window.button("3").click();
window.button("+").click();
window.button("3").click();
window.button("=").click();
try {
window.textBox("lcd").requireText("6");
} catch (Throwable e) {
ScreenshotTaker taker = new ScreenshotTaker();
taker.saveDesktopAsPng("test.png");
throw e;
}
}
}
| gui-testing/assertj-examples/src/calculator/CalculatorGUITests.java | package calculator;
import org.assertj.swing.edt.GuiActionRunner;
import org.assertj.swing.edt.GuiQuery;
import org.assertj.swing.fixture.FrameFixture;
import org.assertj.swing.image.ScreenshotTaker;
import org.assertj.swing.junit.testcase.AssertJSwingJUnitTestCase;
import org.junit.Test;
public class CalculatorGUITests extends AssertJSwingJUnitTestCase {
private FrameFixture window;
@Override
protected void onSetUp() {
Calculator frame = GuiActionRunner
.execute(new GuiQuery<Calculator>() {
protected Calculator executeInEDT() {
return new Calculator();
}
});
// IMPORTANT: note the call to 'robot()'
// we must use the Robot from AssertJSwingJUnitTestCase
window = new FrameFixture(robot(), frame);
window.show(); // shows the frame to test
}
@Test
public void testSum() {
window.button("2").click();
window.button("+").click();
window.button("2").click();
window.button("=").click();
window.textBox("lcd").requireText("4.0");
}
@Test
public void testSumWithSnapshot() {
window.button("3").click();
window.button("+").click();
window.button("3").click();
window.button("=").click();
try {
window.textBox("lcd").requireText("6");
} catch (Exception e) {
ScreenshotTaker taker = new ScreenshotTaker();
taker.saveDesktopAsPng("test.png");
throw e;
}
}
}
| fix issue with example
| gui-testing/assertj-examples/src/calculator/CalculatorGUITests.java | fix issue with example | <ide><path>ui-testing/assertj-examples/src/calculator/CalculatorGUITests.java
<ide>
<ide> try {
<ide> window.textBox("lcd").requireText("6");
<del> } catch (Exception e) {
<add> } catch (Throwable e) {
<ide> ScreenshotTaker taker = new ScreenshotTaker();
<ide> taker.saveDesktopAsPng("test.png");
<ide> throw e; |
|
Java | apache-2.0 | 98013a3b2a709b6d43aa7dedeb0186648e677b2c | 0 | benchdoos/WeblocOpener,benchdoos/WeblocOpener,benchdoos/WeblocOpener | /*
* (C) Copyright 2019. Eugene Zrazhevsky and others.
* 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.
* Contributors:
* Eugene Zrazhevsky <[email protected]>
*/
package com.github.benchdoos.weblocopener.nongui;
import com.github.benchdoos.weblocopener.core.Application;
import com.github.benchdoos.weblocopener.core.Translation;
import com.github.benchdoos.weblocopener.preferences.PreferencesManager;
import com.github.benchdoos.weblocopener.update.Updater;
import com.github.benchdoos.weblocopener.update.UpdaterManager;
import com.github.benchdoos.weblocopener.utils.Internal;
import com.github.benchdoos.weblocopener.utils.Logging;
import com.github.benchdoos.weblocopener.utils.UserUtils;
import com.github.benchdoos.weblocopener.utils.version.ApplicationVersion;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import static com.github.benchdoos.weblocopener.utils.system.SystemUtils.IS_WINDOWS_XP;
/**
* Created by Eugene Zrazhevsky on 04.11.2016.
*/
public class NonGuiUpdater {
public static final SystemTray tray = SystemTray.getSystemTray();
private static final Logger log = LogManager.getLogger(Logging.getCurrentClassName());
public static TrayIcon trayIcon;
private ApplicationVersion serverApplicationVersion = null;
public NonGuiUpdater() {
initGui();
Updater updater;
updater = UpdaterManager.getUpdaterForCurrentOperatingSystem();
final ApplicationVersion latestApplicationVersion = updater.getLatestAppVersion();
if (latestApplicationVersion != null) {
serverApplicationVersion = latestApplicationVersion;
compareVersions();
} else {
log.warn("Can not get server version");
if (Application.updateMode != Application.UPDATE_MODE.SILENT) {
Translation translation = new Translation("UpdaterBundle");
UserUtils.showErrorMessageToUser(null, translation.getTranslatedString("canNotUpdateTitle"),
translation.getTranslatedString("canNotUpdateMessage"));
}
}
}
private void compareVersions() {
if (!PreferencesManager.isDevMode()) {
switch (Internal.versionCompare(serverApplicationVersion)) {
case SERVER_VERSION_IS_NEWER:
onNewVersionAvailable();
break;
case CURRENT_VERSION_IS_NEWER:
log.info("Current version is newer");
break;
case VERSIONS_ARE_EQUAL:
log.info("There are no updates available");
break;
}
} else onNewVersionAvailable();
}
private void onNewVersionAvailable() {
if (serverApplicationVersion.getDownloadUrl() != null) {
//todo change to JOptionPane for unix, until trayIcon does not work
createTrayIcon();
trayIcon.displayMessage(Translation.getTranslatedString("UpdateDialogBundle", "windowTitle"),
Translation.getTranslatedString("UpdateDialogBundle",
"newVersionAvailableTrayNotification")
+ ": " + serverApplicationVersion.getVersion(),
TrayIcon.MessageType.INFO);
} else {
log.warn("Update is available, but there is no version for current system: {}", serverApplicationVersion);
}
}
private CheckboxMenuItem createCheckBoxItem() {
final CheckboxMenuItem autoUpdateCheckBox = new CheckboxMenuItem(
Translation.getTranslatedString("NonGuiUpdaterBundle", "autoUpdateCheckBox"));
log.debug(PreferencesManager.KEY_AUTO_UPDATE + ": " + PreferencesManager.isAutoUpdateActive());
autoUpdateCheckBox.setState(PreferencesManager.isAutoUpdateActive());
autoUpdateCheckBox.addItemListener(e -> {
log.debug(PreferencesManager.KEY_AUTO_UPDATE + ": " + autoUpdateCheckBox.getState());
PreferencesManager.setAutoUpdateActive(autoUpdateCheckBox.getState());
});
return autoUpdateCheckBox;
}
private MenuItem createExitItem() {
MenuItem exit = new MenuItem(
Translation.getTranslatedString("NonGuiUpdaterBundle", "exitButton"));
exit.addActionListener(e -> tray.remove(trayIcon));
return exit;
}
private MenuItem createSettingsItem() {
MenuItem settings = new MenuItem(
Translation.getTranslatedString("NonGuiUpdaterBundle", "settingsButton"));
settings.addActionListener(e -> {
Application.runSettingsDialog();
tray.remove(trayIcon);
});
return settings;
}
private void createTrayIcon() {
PopupMenu trayMenu = new PopupMenu();
MenuItem settings = createSettingsItem();
trayMenu.add(settings);
trayMenu.addSeparator();
final CheckboxMenuItem autoUpdateCheckBox = createCheckBoxItem();
trayMenu.add(autoUpdateCheckBox);
trayMenu.addSeparator();
MenuItem exit = createExitItem();
trayMenu.add(exit);
trayIcon.setImageAutoSize(true);
trayIcon.setPopupMenu(trayMenu);
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1) {
trayIcon.removeMouseListener(this);
Application.runUpdateDialog();
tray.remove(trayIcon);
}
super.mouseClicked(e);
}
});
trayIcon.setToolTip(Translation.getTranslatedString("UpdateDialogBundle", "windowTitle"));
try {
tray.add(trayIcon);
} catch (AWTException e) {
e.printStackTrace();
}
}
private void initGui() {
if (IS_WINDOWS_XP) {
trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(
NonGuiUpdater.class.getResource("/images/updateIconWhite256.png")));
} else {
trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(
NonGuiUpdater.class.getResource("/images/updateIconBlue256.png")));
}
}
}
| src/main/java/com/github/benchdoos/weblocopener/nongui/NonGuiUpdater.java | /*
* (C) Copyright 2019. Eugene Zrazhevsky and others.
* 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.
* Contributors:
* Eugene Zrazhevsky <[email protected]>
*/
package com.github.benchdoos.weblocopener.nongui;
import com.github.benchdoos.weblocopener.core.Application;
import com.github.benchdoos.weblocopener.core.Translation;
import com.github.benchdoos.weblocopener.preferences.PreferencesManager;
import com.github.benchdoos.weblocopener.update.Updater;
import com.github.benchdoos.weblocopener.update.UpdaterManager;
import com.github.benchdoos.weblocopener.utils.CoreUtils;
import com.github.benchdoos.weblocopener.utils.Internal;
import com.github.benchdoos.weblocopener.utils.Logging;
import com.github.benchdoos.weblocopener.utils.UserUtils;
import com.github.benchdoos.weblocopener.utils.version.ApplicationVersion;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import static com.github.benchdoos.weblocopener.utils.system.SystemUtils.IS_WINDOWS_XP;
/**
* Created by Eugene Zrazhevsky on 04.11.2016.
*/
public class NonGuiUpdater {
public static final SystemTray tray = SystemTray.getSystemTray();
private static final Logger log = LogManager.getLogger(Logging.getCurrentClassName());
public static TrayIcon trayIcon;
private ApplicationVersion serverApplicationVersion = null;
public NonGuiUpdater() {
initGui();
Updater updater;
updater = UpdaterManager.getUpdaterForCurrentOperatingSystem();
final ApplicationVersion latestApplicationVersion = updater.getLatestAppVersion();
if (latestApplicationVersion != null) {
serverApplicationVersion = latestApplicationVersion;
compareVersions();
} else {
log.warn("Can not get server version");
if (Application.updateMode != Application.UPDATE_MODE.SILENT) {
Translation translation = new Translation("UpdaterBundle");
UserUtils.showErrorMessageToUser(null, translation.getTranslatedString("canNotUpdateTitle"),
translation.getTranslatedString("canNotUpdateMessage"));
}
}
}
private void compareVersions() {
String str = PreferencesManager.isDevMode() ? "1.0.0.0" : CoreUtils.getApplicationVersionString();
if (Internal.versionCompare(str, serverApplicationVersion.getVersion()) < 0) {
//create tray icon and show pop-up
createTrayIcon();
trayIcon.displayMessage(Translation.getTranslatedString("UpdateDialogBundle", "windowTitle"),
Translation.getTranslatedString("UpdateDialogBundle",
"newVersionAvailableTrayNotification")
+ ": " + serverApplicationVersion.getVersion(),
TrayIcon.MessageType.INFO);
}
}
private CheckboxMenuItem createCheckBoxItem() {
final CheckboxMenuItem autoUpdateCheckBox = new CheckboxMenuItem(
Translation.getTranslatedString("NonGuiUpdaterBundle", "autoUpdateCheckBox"));
log.debug(PreferencesManager.KEY_AUTO_UPDATE + ": " + PreferencesManager.isAutoUpdateActive());
autoUpdateCheckBox.setState(PreferencesManager.isAutoUpdateActive());
autoUpdateCheckBox.addItemListener(e -> {
log.debug(PreferencesManager.KEY_AUTO_UPDATE + ": " + autoUpdateCheckBox.getState());
PreferencesManager.setAutoUpdateActive(autoUpdateCheckBox.getState());
});
return autoUpdateCheckBox;
}
private MenuItem createExitItem() {
MenuItem exit = new MenuItem(
Translation.getTranslatedString("NonGuiUpdaterBundle", "exitButton"));
exit.addActionListener(e -> tray.remove(trayIcon));
return exit;
}
private MenuItem createSettingsItem() {
MenuItem settings = new MenuItem(
Translation.getTranslatedString("NonGuiUpdaterBundle", "settingsButton"));
settings.addActionListener(e -> {
Application.runSettingsDialog();
tray.remove(trayIcon);
});
return settings;
}
private void createTrayIcon() {
PopupMenu trayMenu = new PopupMenu();
MenuItem settings = createSettingsItem();
trayMenu.add(settings);
trayMenu.addSeparator();
final CheckboxMenuItem autoUpdateCheckBox = createCheckBoxItem();
trayMenu.add(autoUpdateCheckBox);
trayMenu.addSeparator();
MenuItem exit = createExitItem();
trayMenu.add(exit);
trayIcon.setImageAutoSize(true);
trayIcon.setPopupMenu(trayMenu);
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == 1) {
trayIcon.removeMouseListener(this);
Application.runUpdateDialog();
tray.remove(trayIcon);
}
super.mouseClicked(e);
}
});
trayIcon.setToolTip(Translation.getTranslatedString("UpdateDialogBundle", "windowTitle"));
try {
tray.add(trayIcon);
} catch (AWTException e) {
e.printStackTrace();
}
}
private void initGui() {
if (IS_WINDOWS_XP) {
trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(
NonGuiUpdater.class.getResource("/images/updateIconWhite256.png")));
} else {
trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(
NonGuiUpdater.class.getResource("/images/updateIconBlue256.png")));
}
}
}
| Changed version comparing to new one
| src/main/java/com/github/benchdoos/weblocopener/nongui/NonGuiUpdater.java | Changed version comparing to new one | <ide><path>rc/main/java/com/github/benchdoos/weblocopener/nongui/NonGuiUpdater.java
<ide> import com.github.benchdoos.weblocopener.preferences.PreferencesManager;
<ide> import com.github.benchdoos.weblocopener.update.Updater;
<ide> import com.github.benchdoos.weblocopener.update.UpdaterManager;
<del>import com.github.benchdoos.weblocopener.utils.CoreUtils;
<ide> import com.github.benchdoos.weblocopener.utils.Internal;
<ide> import com.github.benchdoos.weblocopener.utils.Logging;
<ide> import com.github.benchdoos.weblocopener.utils.UserUtils;
<ide> }
<ide>
<ide> private void compareVersions() {
<del> String str = PreferencesManager.isDevMode() ? "1.0.0.0" : CoreUtils.getApplicationVersionString();
<del> if (Internal.versionCompare(str, serverApplicationVersion.getVersion()) < 0) {
<del> //create tray icon and show pop-up
<add>
<add> if (!PreferencesManager.isDevMode()) {
<add> switch (Internal.versionCompare(serverApplicationVersion)) {
<add> case SERVER_VERSION_IS_NEWER:
<add> onNewVersionAvailable();
<add> break;
<add> case CURRENT_VERSION_IS_NEWER:
<add> log.info("Current version is newer");
<add> break;
<add> case VERSIONS_ARE_EQUAL:
<add> log.info("There are no updates available");
<add> break;
<add> }
<add> } else onNewVersionAvailable();
<add> }
<add>
<add> private void onNewVersionAvailable() {
<add> if (serverApplicationVersion.getDownloadUrl() != null) {
<add> //todo change to JOptionPane for unix, until trayIcon does not work
<ide> createTrayIcon();
<ide>
<ide> trayIcon.displayMessage(Translation.getTranslatedString("UpdateDialogBundle", "windowTitle"),
<ide> "newVersionAvailableTrayNotification")
<ide> + ": " + serverApplicationVersion.getVersion(),
<ide> TrayIcon.MessageType.INFO);
<add> } else {
<add> log.warn("Update is available, but there is no version for current system: {}", serverApplicationVersion);
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | a3ddb0fe3cdafddf3bca951f17e92c0ac9ffb5c7 | 0 | dalnefre/tart-PEG | /*
test.js - test script
The MIT License (MIT)
Copyright (c) 2016 Dale Schumacher
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.
*/
"use strict";
var test = module.exports = {};
//var log = console.log;
var log = function () {};
var warn = console.log;
//var tart = require('tart-tracing');
var actor = require('../humus/hybrid.js');
test['actor model defines create and send'] = function (test) {
test.expect(2);
test.strictEqual(typeof actor.create, 'function');
test.strictEqual(typeof actor.send, 'function');
test.done();
};
var null_beh = function null_beh(msg) { // no-op actor behavior
return {
actors: [],
events: [],
behavior: undefined
};
};
test['behavior returns actors, events, and optional behavior'] = function (test) {
test.expect(4);
var m = 'Hello!';
var r = null_beh(m);
log('r:', r);
test.strictEqual(typeof r, 'object');
test.ok(Array.isArray(r.actors));
test.ok(Array.isArray(r.events));
test.ok((r.behavior === undefined) || ('function' === typeof r.behavior));
test.done();
};
test['create returns actor address'] = function (test) {
test.expect(1);
var a = actor.create(null_beh);
test.strictEqual(typeof a, 'function'); // address encoded as a function
test.done();
};
test['send returns message-event'] = function (test) {
test.expect(3);
var a = actor.create(null_beh);
var m = 'Hello!';
var e = actor.send(a, m);
test.strictEqual(typeof e, 'object');
test.strictEqual(e.target, a);
test.strictEqual(e.message, m);
test.done();
};
test['one shot actor should forward first message, then ignore everything'] = function (test) {
test.expect(4);
var null_beh = function null_beh(msg) {
log('null'+actor.self+':', msg);
test.strictEqual(++count, 2);
return {
actors: [],
events: [],
behavior: undefined
};
};
var one_shot = function one_shot(fwd) {
return function one_shot_beh(msg) {
log('one_shot'+actor.self+':', msg);
test.strictEqual(++count, 1);
return {
actors: [],
events: [
actor.send(fwd, msg)
],
behavior: null_beh
};
};
};
var done_beh = function done_beh(msg) {
log('done'+actor.self+':', msg);
test.done();
return {
actors: [],
events: [],
behavior: undefined
};
};
var count = 0;
var a = actor.create(function end_beh(msg) {
log('end'+actor.self+':', msg);
test.strictEqual(++count, 3);
var d = actor.create(done_beh);
return {
actors: [d],
events: [
actor.send(d, 'Z')
],
behavior: undefined
};
});
var b = actor.create(one_shot(a));
actor.apply({
actors: [a, b],
events: [
actor.send(b, 'X'),
actor.send(b, 'Y')
]
});
test.strictEqual(actor.self, undefined);
};
function Y(a, b) { // binary tree with left branch `a` and right branch `b`
this.a = a;
this.b = b;
}
// Y.prototype.toString = function toString() { return '<' + this.a + ', ' + this.b + '>' };
var aTree = new Y(1, new Y(new Y(2, 3), 4)); // <1, <<2, 3>, 4>>
var bTree = new Y(new Y(1, 2), new Y(3, 4)); // <<1, 2>, <3, 4>>
var cTree = new Y(new Y(new Y(1, 2), 3), new Y(5, 8)); // <<<1, 2>, 3>, <5, 8>>
test['<1, <<2, 3>, 4>> has fringe [1, 2, 3, 4]'] = function (test) {
test.expect(1);
var fringe = function fringe(tree) {
if (tree instanceof Y) {
let left = fringe(tree.a);
let right = fringe(tree.b);
return left.concat(right);
}
return [ tree ];
};
test.deepEqual(fringe(aTree), [ 1, 2, 3, 4 ]);
test.done();
};
test['fringe(<1, <<2, 3>, 4>>) = fringe(<<1, 2>, <3, 4>>)'] = function (test) {
test.expect(1);
var fringe = function fringe(tree) {
if (tree instanceof Y) {
return fringe(tree.a).concat(fringe(tree.b));
}
return [ tree ];
};
test.deepEqual(fringe(aTree), fringe(bTree));
test.done();
};
test['suspend calculations in generators'] = function (test) {
test.expect(1);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var fringe = [];
var gen = genFringe(aTree);
var leaf = gen.next();
while (leaf.value !== undefined) {
fringe.push(leaf.value);
leaf = gen.next();
};
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
};
test['suspend calculations in closures'] = function (test) {
test.expect(1);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => {
var right = genFringe(tree.b, next);
var left = genFringe(tree.a, right);
return left();
}
} else {
return () => ({ value: tree, next: next });
}
};
var fringe = [];
var leaf = (genFringe(aTree))();
while (leaf.value !== undefined) {
fringe.push(leaf.value);
leaf = leaf.next();
};
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
};
test['incrementally compare functional fringe'] = function (test) {
test.expect(5);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => (genFringe(tree.a, genFringe(tree.b, next)))();
} else {
return () => ({ value: tree, next: next });
}
};
var r0 = (genFringe(aTree))();
var r1 = (genFringe(bTree))();
while (true) {
test.strictEqual(r0.value, r1.value); // match stream contents
if ((r0.value === undefined) || (r1.value === undefined)) {
break; // stream end
}
r0 = r0.next();
r1 = r1.next();
};
test.done();
};
test['compare functional fringe to infinite series'] = function (test) {
test.expect(6);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => (genFringe(tree.a, genFringe(tree.b, next)))();
} else {
return () => ({ value: tree, next: next });
}
};
var genSeries = function genSeries(value, update) {
return () => ({ value: value, next: genSeries(update(value), update) });
};
var r0 = (genFringe(aTree))();
var r1 = (genSeries(1, n => n + 1))();
while ((r0.value !== undefined) && (r1.value !== undefined)) {
test.strictEqual(r0.value, r1.value); // match stream contents
r0 = r0.next();
r1 = r1.next();
};
test.strictEqual(r0.value, undefined); // fringe stream ended
test.strictEqual(r1.value, 5); // un-matched series value should be 5
test.done();
};
test['compare generator fringe to infinite series'] = function (test) {
test.expect(6);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var genSeries = function* genSeries(value, update) {
while (true) {
yield value;
value = update(value);
}
};
var gen0 = genFringe(aTree);
var r0 = gen0.next();
var gen1 = genSeries(1, n => n + 1);
var r1 = gen1.next();
while ((r0.value !== undefined) && (r1.value !== undefined)) {
test.strictEqual(r0.value, r1.value); // match stream contents
r0 = gen0.next();
r1 = gen1.next();
};
test.strictEqual(r0.value, undefined); // fringe stream ended
test.strictEqual(r1.value, 5); // un-matched series value should be 5
test.done();
};
test['compare generator fringe to infinite series using for..of'] = function (test) {
test.expect(6);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var genSeries = function* genSeries(value, update) {
while (true) {
yield value;
value = update(value);
}
};
var zip = function* zip(first, second) {
while (true) {
let f = first.next();
let s = second.next();
if (f.done || s.done) {
return;
}
yield [f.value, s.value];
}
};
let pair;
for (pair of zip(genFringe(aTree), genSeries(1, n => n + 1))) {
test.strictEqual(pair[0], pair[1]);
}
test.strictEqual(pair[0], 4); // finished at last fringe stream value
test.strictEqual(pair[1], 4); // finished at last series value
test.done();
};
test['compare generator fringe to infinite series using compare generator'] = function (test) {
test.expect(2);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var genSeries = function* genSeries(value, update) {
while (true) {
yield value;
value = update(value);
}
};
var compare = function* compare(first, second) {
while (true) {
let f = first.next();
let s = second.next();
if (f.value === s.value) {
if (f.value === undefined) {
return yield (f.done && s.done);
} else {
yield true;
}
} else {
return yield false;
}
}
};
let match;
let matched = 0;
for (match of compare(genFringe(aTree), genSeries(1, n => n + 1))) {
match ? matched++ : matched;
}
test.strictEqual(matched, 4); // only first four match
test.strictEqual(match, false); // the fringe doesn't match the series
test.done();
};
test['compare generator fringe to generator fringe using compare generator'] = function (test) {
test.expect(1);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var compare = function* compare(first, second) {
while (true) {
let f = first.next();
let s = second.next();
if (f.value === s.value) {
if (f.value === undefined) {
return yield (f.done && s.done);
} else {
yield true;
}
} else {
return yield false;
}
}
};
let match;
for (match of compare(genFringe(aTree), genFringe(aTree)))
;
test.strictEqual(match, true); // the fringe matches the fringe
test.done();
};
test['functional fringe comparisons'] = function (test) {
test.expect(6);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => (genFringe(tree.a, genFringe(tree.b, next)))();
} else {
return () => ({ value: tree, next: next });
}
};
var sameFringe = function sameFringe(s0, s1) {
let r0 = s0(); // get result from first sequence
let r1 = s1(); // get result from second sequence
while (r0.value === r1.value) {
if (r0.value === undefined) {
return true; // stream end
}
r0 = r0.next();
r1 = r1.next();
}
return false; // mismatch
};
test.strictEqual(sameFringe(genFringe(aTree), genFringe(bTree)), true);
test.strictEqual(sameFringe(genFringe(cTree), genFringe(bTree)), false);
var genSeries = function genSeries(value, update) {
return () => {
try {
let next = genSeries(update(value), update);
return { value: value, next: next };
} catch (e) {
return { error: e };
}
};
};
test.strictEqual(sameFringe(genFringe(cTree), genSeries(1, n => n + 1)), false);
var genRange = function genRange(lo, hi) {
if (lo < hi) {
return () => ({ value: lo, next: genRange(lo + 1, hi) });
} else {
return () => ({}); // stream end
}
};
test.strictEqual(sameFringe(genRange(0, 32), genRange(0, 32)), true);
test.strictEqual(sameFringe(genRange(0, 99999), genRange(0, 99999)), true);
test.strictEqual(sameFringe(genRange(42, 123456), genSeries(42, n => n + 1)), false);
test.done();
};
var tart = (f)=>{let c=(b)=>{let a=(m)=>{setImmediate(()=>{try{x.behavior(m)}catch(e){f&&f(e)}})},x={self:a,behavior:b,sponsor:c};return a};return c};
/*
var tart = (f) => {
let c = (b) => {
let a = (m) => {
setImmediate(() => {
try {
x.behavior(m)
} catch(e) {
f && f(e)
}
})
}, x = {
self: a,
behavior: b,
sponsor: c
};
return a
};
return c
};
var tart = function(){var c=function(b){var a=function(m){setImmediate(function(){x.behavior(m)})},x={self:a,behavior:b,sponsor:c};return a};return c}
var tart = function () {
var c = function (b) {
var a = function (m) {
setImmediate(function () {
x.behavior(m)
})
}, x = {
self: a,
behavior: b,
sponsor: c
};
return a
};
return c
}
*/
test['stateless actor-based fringe stream'] = function (test) {
test.expect(1);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
var right = this.sponsor(mkFringe(tree.b, next));
var left = this.sponsor(mkFringe(tree.a, right));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var collector = function collector(fringe) {
return function collectBeh(leaf) { // leaf = { value:, next: } | {}
log('leaf:', leaf);
if (leaf.value) {
this.behavior = collector(fringe.concat([ leaf.value ]));
leaf.next(this.self);
} else {
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
}
};
};
var stream = sponsor(mkFringe(aTree));
var reader = sponsor(collector([]));
stream(reader);
};
test['stateful actor-based fringe stream'] = function (test) {
test.expect(1);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
this.behavior = mkFringe(tree.b, next);
var left = this.sponsor(mkFringe(tree.a, this.self));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var collector = function collector(fringe) {
return function collectBeh(leaf) { // leaf = { value:, next: } | {}
log('leaf:', leaf);
if (leaf.value) {
this.behavior = collector(fringe.concat([ leaf.value ]));
leaf.next(this.self);
} else {
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
}
};
};
var stream = sponsor(mkFringe(aTree));
var reader = sponsor(collector([]));
stream(reader);
};
test['incrementally compare actor-based streams'] = function (test) {
test.expect(5);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
this.behavior = mkFringe(tree.b, next);
var left = this.sponsor(mkFringe(tree.a, this.self));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var comparator = function comparator(cust) {
var initBeh = function compareBeh(r0) { // r0 = { value:, next: } | {}
this.behavior = function compareBeh(r1) { // r1 = { value:, next: } | {}
this.behavior = initBeh;
log('r0:', r0, 'r1:', r1);
if (r0.value === r1.value) {
if (r0.value === undefined) {
cust(true); // stream end
} else {
test.strictEqual(r0.value, r1.value); // match stream contents
r0.next(this.self);
r1.next(this.self);
}
} else {
cust(false); // mismatch
}
};
};
return initBeh;
};
var finish = sponsor(function finishBeh(matched) {
test.ok(matched);
test.done();
});
var s0 = sponsor(mkFringe(aTree));
var s1 = sponsor(mkFringe(bTree));
var compare = sponsor(comparator(finish));
s0(compare);
s1(compare);
};
test['stream comparison stops early on mismatch'] = function (test) {
test.expect(5);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
this.behavior = mkFringe(tree.b, next);
var left = this.sponsor(mkFringe(tree.a, this.self));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var comparator = function comparator(cust) {
var initBeh = function compareBeh(r0) { // r0 = { value:, next: } | {}
this.behavior = function compareBeh(r1) { // r1 = { value:, next: } | {}
this.behavior = initBeh;
log('r0:', r0, 'r1:', r1);
if (r0.value === r1.value) {
if (r0.value === undefined) {
cust(true); // stream end
} else {
test.strictEqual(r0.value, r1.value); // match stream contents
r0.next(this.self);
r1.next(this.self);
}
} else {
// cust(false); // mismatch
cust(r1); // send mismatch to finish
}
};
};
return initBeh;
};
var finish = sponsor(function finishBeh(matched) {
log('matched:', matched);
test.strictEqual('object', typeof matched);
test.strictEqual(5, matched.value);
test.done();
});
var s0 = sponsor(mkFringe(aTree));
var s1 = sponsor(mkFringe(cTree));
var compare = sponsor(comparator(finish));
s0(compare);
s1(compare);
};
test['compare actor fringe to infinite series'] = function (test) {
test.expect(6);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
this.behavior = mkFringe(tree.b, next);
var left = this.sponsor(mkFringe(tree.a, this.self));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var mkSeries = function mkSeries(value, update) {
return function seriesBeh(cust) {
var next = this.sponsor(mkSeries(update(value), update));
cust({ value: value, next: next });
}
};
var comparator = function comparator(cust) {
var initBeh = function compareBeh(r0) { // r0 = { value:, next: } | {}
this.behavior = function compareBeh(r1) { // r1 = { value:, next: } | {}
this.behavior = initBeh;
log('r0:', r0, 'r1:', r1);
if (r0.value === r1.value) {
if (r0.value === undefined) {
cust(true); // stream end
} else {
test.strictEqual(r0.value, r1.value); // match stream contents
r0.next(this.self);
r1.next(this.self);
}
} else {
// cust(false); // mismatch
cust(r0); // send mismatch to finish
}
};
};
return initBeh;
};
var finish = sponsor(function finishBeh(matched) {
log('matched:', matched);
test.strictEqual('object', typeof matched);
test.strictEqual(5, matched.value);
test.done();
});
var s0 = sponsor(mkFringe(aTree));
var s1 = sponsor(mkSeries(1, (n => n + 1)));
var compare = sponsor(comparator(finish));
s0(compare);
s1(compare);
};
| test/hybrid.js | /*
test.js - test script
The MIT License (MIT)
Copyright (c) 2016 Dale Schumacher
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.
*/
"use strict";
var test = module.exports = {};
//var log = console.log;
var log = function () {};
var warn = console.log;
//var tart = require('tart-tracing');
var actor = require('../humus/hybrid.js');
test['actor model defines create and send'] = function (test) {
test.expect(2);
test.strictEqual(typeof actor.create, 'function');
test.strictEqual(typeof actor.send, 'function');
test.done();
};
var null_beh = function null_beh(msg) { // no-op actor behavior
return {
actors: [],
events: [],
behavior: undefined
};
};
test['behavior returns actors, events, and optional behavior'] = function (test) {
test.expect(4);
var m = 'Hello!';
var r = null_beh(m);
log('r:', r);
test.strictEqual(typeof r, 'object');
test.ok(Array.isArray(r.actors));
test.ok(Array.isArray(r.events));
test.ok((r.behavior === undefined) || ('function' === typeof r.behavior));
test.done();
};
test['create returns actor address'] = function (test) {
test.expect(1);
var a = actor.create(null_beh);
test.strictEqual(typeof a, 'function'); // address encoded as a function
test.done();
};
test['send returns message-event'] = function (test) {
test.expect(3);
var a = actor.create(null_beh);
var m = 'Hello!';
var e = actor.send(a, m);
test.strictEqual(typeof e, 'object');
test.strictEqual(e.target, a);
test.strictEqual(e.message, m);
test.done();
};
test['one shot actor should forward first message, then ignore everything'] = function (test) {
test.expect(4);
var null_beh = function null_beh(msg) {
log('null'+actor.self+':', msg);
test.strictEqual(++count, 2);
return {
actors: [],
events: [],
behavior: undefined
};
};
var one_shot = function one_shot(fwd) {
return function one_shot_beh(msg) {
log('one_shot'+actor.self+':', msg);
test.strictEqual(++count, 1);
return {
actors: [],
events: [
actor.send(fwd, msg)
],
behavior: null_beh
};
};
};
var done_beh = function done_beh(msg) {
log('done'+actor.self+':', msg);
test.done();
return {
actors: [],
events: [],
behavior: undefined
};
};
var count = 0;
var a = actor.create(function end_beh(msg) {
log('end'+actor.self+':', msg);
test.strictEqual(++count, 3);
var d = actor.create(done_beh);
return {
actors: [d],
events: [
actor.send(d, 'Z')
],
behavior: undefined
};
});
var b = actor.create(one_shot(a));
actor.apply({
actors: [a, b],
events: [
actor.send(b, 'X'),
actor.send(b, 'Y')
]
});
test.strictEqual(actor.self, undefined);
};
function Y(a, b) { // binary tree with left branch `a` and right branch `b`
this.a = a;
this.b = b;
}
// Y.prototype.toString = function toString() { return '<' + this.a + ', ' + this.b + '>' };
var aTree = new Y(1, new Y(new Y(2, 3), 4)); // <1, <<2, 3>, 4>>
var bTree = new Y(new Y(1, 2), new Y(3, 4)); // <<1, 2>, <3, 4>>
var cTree = new Y(new Y(new Y(1, 2), 3), new Y(5, 8)); // <<<1, 2>, 3>, <5, 8>>
test['<1, <<2, 3>, 4>> has fringe [1, 2, 3, 4]'] = function (test) {
test.expect(1);
var fringe = function fringe(tree) {
if (tree instanceof Y) {
let left = fringe(tree.a);
let right = fringe(tree.b);
return left.concat(right);
}
return [ tree ];
};
test.deepEqual(fringe(aTree), [ 1, 2, 3, 4 ]);
test.done();
};
test['fringe(<1, <<2, 3>, 4>>) = fringe(<<1, 2>, <3, 4>>)'] = function (test) {
test.expect(1);
var fringe = function fringe(tree) {
if (tree instanceof Y) {
return fringe(tree.a).concat(fringe(tree.b));
}
return [ tree ];
};
test.deepEqual(fringe(aTree), fringe(bTree));
test.done();
};
test['suspend calculations in generators'] = function (test) {
test.expect(1);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var fringe = [];
var gen = genFringe(aTree);
var leaf = gen.next();
while (leaf.value !== undefined) {
fringe.push(leaf.value);
leaf = gen.next();
};
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
};
test['suspend calculations in closures'] = function (test) {
test.expect(1);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => {
var right = genFringe(tree.b, next);
var left = genFringe(tree.a, right);
return left();
}
} else {
return () => ({ value: tree, next: next });
}
};
var fringe = [];
var leaf = (genFringe(aTree))();
while (leaf.value !== undefined) {
fringe.push(leaf.value);
leaf = leaf.next();
};
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
};
test['incrementally compare functional fringe'] = function (test) {
test.expect(5);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => (genFringe(tree.a, genFringe(tree.b, next)))();
} else {
return () => ({ value: tree, next: next });
}
};
var r0 = (genFringe(aTree))();
var r1 = (genFringe(bTree))();
while (true) {
test.strictEqual(r0.value, r1.value); // match stream contents
if ((r0.value === undefined) || (r1.value === undefined)) {
break; // stream end
}
r0 = r0.next();
r1 = r1.next();
};
test.done();
};
test['compare functional fringe to infinite series'] = function (test) {
test.expect(6);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => (genFringe(tree.a, genFringe(tree.b, next)))();
} else {
return () => ({ value: tree, next: next });
}
};
var genSeries = function genSeries(value, update) {
return () => ({ value: value, next: genSeries(update(value), update) });
};
var r0 = (genFringe(aTree))();
var r1 = (genSeries(1, n => n + 1))();
while ((r0.value !== undefined) && (r1.value !== undefined)) {
test.strictEqual(r0.value, r1.value); // match stream contents
r0 = r0.next();
r1 = r1.next();
};
test.strictEqual(r0.value, undefined); // fringe stream ended
test.strictEqual(r1.value, 5); // un-matched series value should be 5
test.done();
};
test['compare generator fringe to infinite series'] = function (test) {
test.expect(6);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var genSeries = function* genSeries(value, update) {
while (true) {
yield value;
value = update(value);
}
};
var gen0 = genFringe(aTree);
var r0 = gen0.next();
var gen1 = genSeries(1, n => n + 1);
var r1 = gen1.next();
while ((r0.value !== undefined) && (r1.value !== undefined)) {
test.strictEqual(r0.value, r1.value); // match stream contents
r0 = gen0.next();
r1 = gen1.next();
};
test.strictEqual(r0.value, undefined); // fringe stream ended
test.strictEqual(r1.value, 5); // un-matched series value should be 5
test.done();
};
test['compare generator fringe to infinite series using for..of'] = function (test) {
test.expect(6);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var genSeries = function* genSeries(value, update) {
while (true) {
yield value;
value = update(value);
}
};
var zip = function* zip(first, second) {
while (true) {
let f = first.next();
let s = second.next();
if (f.done || s.done) {
return;
}
yield [f.value, s.value];
}
};
let pair;
for (pair of zip(genFringe(aTree), genSeries(1, n => n + 1))) {
test.strictEqual(pair[0], pair[1]);
}
test.strictEqual(pair[0], 4); // finished at last fringe stream value
test.strictEqual(pair[1], 4); // finished at last series value
test.done();
};
test['compare generator fringe to infinite series using compare generator'] = function (test) {
test.expect(2);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var genSeries = function* genSeries(value, update) {
while (true) {
yield value;
value = update(value);
}
};
var compare = function* compare(first, second) {
while (true) {
let f = first.next();
let s = second.next();
if (f.value !== undefined && f.value == s.value) {
yield true;
} else if (f.value !== undefined && f.value != s.value) {
return yield false;
} else if (f.done && s.done) {
return yield true;
} else if (f.done || s.done) {
return yield false;
}
}
};
let match;
let matched = 0;
for (match of compare(genFringe(aTree), genSeries(1, n => n + 1))) {
match ? matched++ : matched;
}
test.strictEqual(matched, 4); // only first four match
test.strictEqual(match, false); // the fringe doesn't match the series
test.done();
};
test['compare generator fringe to generator fringe using compare generator'] = function (test) {
test.expect(1);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var compare = function* compare(first, second) {
while (true) {
let f = first.next();
let s = second.next();
if (f.value !== undefined && f.value == s.value) {
yield true;
} else if (f.value !== undefined && f.value != s.value) {
return yield false;
} else if (f.done && s.done) {
return yield true;
} else if (f.done || s.done) {
return yield false;
}
}
};
let match;
for (match of compare(genFringe(aTree), genFringe(aTree)))
;
test.strictEqual(match, true); // the fringe matches the fringe
test.done();
};
test['functional fringe comparisons'] = function (test) {
test.expect(6);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => (genFringe(tree.a, genFringe(tree.b, next)))();
} else {
return () => ({ value: tree, next: next });
}
};
var sameFringe = function sameFringe(s0, s1) {
let r0 = s0(); // get result from first sequence
let r1 = s1(); // get result from second sequence
while (r0.value === r1.value) {
if (r0.value === undefined) {
return true; // stream end
}
r0 = r0.next();
r1 = r1.next();
}
return false; // mismatch
};
test.strictEqual(sameFringe(genFringe(aTree), genFringe(bTree)), true);
test.strictEqual(sameFringe(genFringe(cTree), genFringe(bTree)), false);
var genSeries = function genSeries(value, update) {
return () => {
try {
let next = genSeries(update(value), update);
return { value: value, next: next };
} catch (e) {
return { error: e };
}
};
};
test.strictEqual(sameFringe(genFringe(cTree), genSeries(1, n => n + 1)), false);
var genRange = function genRange(lo, hi) {
if (lo < hi) {
return () => ({ value: lo, next: genRange(lo + 1, hi) });
} else {
return () => ({}); // stream end
}
};
test.strictEqual(sameFringe(genRange(0, 32), genRange(0, 32)), true);
test.strictEqual(sameFringe(genRange(0, 99999), genRange(0, 99999)), true);
test.strictEqual(sameFringe(genRange(42, 123456), genSeries(42, n => n + 1)), false);
test.done();
};
var tart = (f)=>{let c=(b)=>{let a=(m)=>{setImmediate(()=>{try{x.behavior(m)}catch(e){f&&f(e)}})},x={self:a,behavior:b,sponsor:c};return a};return c};
/*
var tart = (f) => {
let c = (b) => {
let a = (m) => {
setImmediate(() => {
try {
x.behavior(m)
} catch(e) {
f && f(e)
}
})
}, x = {
self: a,
behavior: b,
sponsor: c
};
return a
};
return c
};
var tart = function(){var c=function(b){var a=function(m){setImmediate(function(){x.behavior(m)})},x={self:a,behavior:b,sponsor:c};return a};return c}
var tart = function () {
var c = function (b) {
var a = function (m) {
setImmediate(function () {
x.behavior(m)
})
}, x = {
self: a,
behavior: b,
sponsor: c
};
return a
};
return c
}
*/
test['stateless actor-based fringe stream'] = function (test) {
test.expect(1);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
var right = this.sponsor(mkFringe(tree.b, next));
var left = this.sponsor(mkFringe(tree.a, right));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var collector = function collector(fringe) {
return function collectBeh(leaf) { // leaf = { value:, next: } | {}
log('leaf:', leaf);
if (leaf.value) {
this.behavior = collector(fringe.concat([ leaf.value ]));
leaf.next(this.self);
} else {
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
}
};
};
var stream = sponsor(mkFringe(aTree));
var reader = sponsor(collector([]));
stream(reader);
};
test['stateful actor-based fringe stream'] = function (test) {
test.expect(1);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
this.behavior = mkFringe(tree.b, next);
var left = this.sponsor(mkFringe(tree.a, this.self));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var collector = function collector(fringe) {
return function collectBeh(leaf) { // leaf = { value:, next: } | {}
log('leaf:', leaf);
if (leaf.value) {
this.behavior = collector(fringe.concat([ leaf.value ]));
leaf.next(this.self);
} else {
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
}
};
};
var stream = sponsor(mkFringe(aTree));
var reader = sponsor(collector([]));
stream(reader);
};
test['incrementally compare actor-based streams'] = function (test) {
test.expect(5);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
this.behavior = mkFringe(tree.b, next);
var left = this.sponsor(mkFringe(tree.a, this.self));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var comparator = function comparator(cust) {
var initBeh = function compareBeh(r0) { // r0 = { value:, next: } | {}
this.behavior = function compareBeh(r1) { // r1 = { value:, next: } | {}
this.behavior = initBeh;
log('r0:', r0, 'r1:', r1);
if (r0.value === r1.value) {
if (r0.value === undefined) {
cust(true); // stream end
} else {
test.strictEqual(r0.value, r1.value); // match stream contents
r0.next(this.self);
r1.next(this.self);
}
} else {
cust(false); // mismatch
}
};
};
return initBeh;
};
var finish = sponsor(function finishBeh(matched) {
test.ok(matched);
test.done();
});
var s0 = sponsor(mkFringe(aTree));
var s1 = sponsor(mkFringe(bTree));
var compare = sponsor(comparator(finish));
s0(compare);
s1(compare);
};
test['stream comparison stops early on mismatch'] = function (test) {
test.expect(5);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
this.behavior = mkFringe(tree.b, next);
var left = this.sponsor(mkFringe(tree.a, this.self));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var comparator = function comparator(cust) {
var initBeh = function compareBeh(r0) { // r0 = { value:, next: } | {}
this.behavior = function compareBeh(r1) { // r1 = { value:, next: } | {}
this.behavior = initBeh;
log('r0:', r0, 'r1:', r1);
if (r0.value === r1.value) {
if (r0.value === undefined) {
cust(true); // stream end
} else {
test.strictEqual(r0.value, r1.value); // match stream contents
r0.next(this.self);
r1.next(this.self);
}
} else {
// cust(false); // mismatch
cust(r1); // send mismatch to finish
}
};
};
return initBeh;
};
var finish = sponsor(function finishBeh(matched) {
log('matched:', matched);
test.strictEqual('object', typeof matched);
test.strictEqual(5, matched.value);
test.done();
});
var s0 = sponsor(mkFringe(aTree));
var s1 = sponsor(mkFringe(cTree));
var compare = sponsor(comparator(finish));
s0(compare);
s1(compare);
};
test['compare actor fringe to infinite series'] = function (test) {
test.expect(6);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
this.behavior = mkFringe(tree.b, next);
var left = this.sponsor(mkFringe(tree.a, this.self));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var mkSeries = function mkSeries(value, update) {
return function seriesBeh(cust) {
var next = this.sponsor(mkSeries(update(value), update));
cust({ value: value, next: next });
}
};
var comparator = function comparator(cust) {
var initBeh = function compareBeh(r0) { // r0 = { value:, next: } | {}
this.behavior = function compareBeh(r1) { // r1 = { value:, next: } | {}
this.behavior = initBeh;
log('r0:', r0, 'r1:', r1);
if (r0.value === r1.value) {
if (r0.value === undefined) {
cust(true); // stream end
} else {
test.strictEqual(r0.value, r1.value); // match stream contents
r0.next(this.self);
r1.next(this.self);
}
} else {
// cust(false); // mismatch
cust(r0); // send mismatch to finish
}
};
};
return initBeh;
};
var finish = sponsor(function finishBeh(matched) {
log('matched:', matched);
test.strictEqual('object', typeof matched);
test.strictEqual(5, matched.value);
test.done();
});
var s0 = sponsor(mkFringe(aTree));
var s1 = sponsor(mkSeries(1, (n => n + 1)));
var compare = sponsor(comparator(finish));
s0(compare);
s1(compare);
};
| Reduce comparisons and cases
| test/hybrid.js | Reduce comparisons and cases | <ide><path>est/hybrid.js
<ide> while (true) {
<ide> let f = first.next();
<ide> let s = second.next();
<del> if (f.value !== undefined && f.value == s.value) {
<del> yield true;
<del> } else if (f.value !== undefined && f.value != s.value) {
<del> return yield false;
<del> } else if (f.done && s.done) {
<del> return yield true;
<del> } else if (f.done || s.done) {
<add> if (f.value === s.value) {
<add> if (f.value === undefined) {
<add> return yield (f.done && s.done);
<add> } else {
<add> yield true;
<add> }
<add> } else {
<ide> return yield false;
<ide> }
<ide> }
<ide> while (true) {
<ide> let f = first.next();
<ide> let s = second.next();
<del> if (f.value !== undefined && f.value == s.value) {
<del> yield true;
<del> } else if (f.value !== undefined && f.value != s.value) {
<del> return yield false;
<del> } else if (f.done && s.done) {
<del> return yield true;
<del> } else if (f.done || s.done) {
<add> if (f.value === s.value) {
<add> if (f.value === undefined) {
<add> return yield (f.done && s.done);
<add> } else {
<add> yield true;
<add> }
<add> } else {
<ide> return yield false;
<ide> }
<ide> } |
|
Java | apache-2.0 | 700e116a053511467f38b920466ff2eb8003a093 | 0 | wschaeferB/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,wschaeferB/autopsy,APriestman/autopsy,rcordovano/autopsy,wschaeferB/autopsy,APriestman/autopsy,esaunders/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,APriestman/autopsy,esaunders/autopsy,APriestman/autopsy,rcordovano/autopsy,millmanorama/autopsy,APriestman/autopsy,millmanorama/autopsy,esaunders/autopsy,APriestman/autopsy,millmanorama/autopsy,APriestman/autopsy,millmanorama/autopsy,esaunders/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.commonfilesearch;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.corecomponents.DataResultTopComponent;
import org.sleuthkit.autopsy.corecomponents.TableFilterNode;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskCoreException;
/**
* Panel used for common files search configuration and configuration business
* logic. Nested within CommonFilesDialog.
*/
public final class CommonFilesPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(CommonFilesPanel.class.getName());
/**
* Creates new form CommonFilesPanel
*/
public CommonFilesPanel() {
initComponents();
customizeComponents();
}
private void customizeComponents() {
addListenerToAll(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
search();
}
});
}
void addListenerToAll(ActionListener l) {
this.searchButton.addActionListener(l);
}
private void search() {
String title = NbBundle.getMessage(this.getClass(), "CommonFilesPanel.search.results.title");
String pathText = NbBundle.getMessage(this.getClass(), "CommonFilesPanel.search.results.pathText");
new SwingWorker<Void, Void>() {
private int count = 0;
private TableFilterNode tfn = null;
@Override
@SuppressWarnings("FinallyDiscardsException")
protected Void doInBackground() throws Exception {
List<AbstractFile> contentList;
try {
Case currentCase = Case.getOpenCase();
SleuthkitCase tskDb = currentCase.getSleuthkitCase();
//TODO this is sort of a misues of the findAllFilesWhere function and seems brittle...
//...consider doing something else
//TODO verify that this works with postgres
contentList = tskDb.findAllFilesWhere("1 == 1 GROUP BY md5 HAVING COUNT(*) > 1;");
CommonFilesNode cfn = new CommonFilesNode(contentList);
tfn = new TableFilterNode(cfn, true, cfn.getName());
count = contentList.size();
} catch (TskCoreException | NoCurrentCaseException ex) {
LOGGER.log(Level.WARNING, "Error while trying to get common files.", ex);
contentList = Collections.<AbstractFile>emptyList();
CommonFilesNode cfn = new CommonFilesNode(contentList);
tfn = new TableFilterNode(cfn, true, cfn.getName());
} finally {
return null;
}
}
@Override
protected void done() {
try {
super.done();
get();
TopComponent component = DataResultTopComponent.createInstance(
title,
pathText,
tfn,
count);
component.requestActive(); // make it the active top component
} catch (InterruptedException | ExecutionException ex) {
JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
ex.getCause().getMessage(),
"Some went wrong finding common files.",
JOptionPane.ERROR_MESSAGE);
}
}
}.execute();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
searchButton = new javax.swing.JButton();
setPreferredSize(new java.awt.Dimension(300, 300));
org.openide.awt.Mnemonics.setLocalizedText(searchButton, org.openide.util.NbBundle.getMessage(CommonFilesPanel.class, "CommonFilesPanel.searchButton.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(325, Short.MAX_VALUE)
.addComponent(searchButton)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(266, Short.MAX_VALUE)
.addComponent(searchButton)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton searchButton;
// End of variables declaration//GEN-END:variables
}
| Core/src/org/sleuthkit/autopsy/commonfilesearch/CommonFilesPanel.java | /*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.commonfilesearch;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException;
import org.sleuthkit.autopsy.corecomponents.DataResultTopComponent;
import org.sleuthkit.autopsy.corecomponents.TableFilterNode;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskCoreException;
/**
* Panel used for common files search configuration and configuration business
* logic. Nested within CommonFilesDialog.
*/
public final class CommonFilesPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(CommonFilesPanel.class.getName());
/**
* Creates new form CommonFilesPanel
*/
public CommonFilesPanel() {
initComponents();
customizeComponents();
}
private void customizeComponents() {
addListenerToAll(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
search();
}
});
}
void addListenerToAll(ActionListener l) {
this.searchButton.addActionListener(l);
}
private void search() {
String title = NbBundle.getMessage(this.getClass(), "CommonFilesPanel.search.results.title");
String pathText = NbBundle.getMessage(this.getClass(), "CommonFilesPanel.search.results.pathText");
new SwingWorker<Void, Void>() {
private int count = 0;
private TableFilterNode tfn = null;
@Override
@SuppressWarnings("FinallyDiscardsException")
protected Void doInBackground() throws Exception {
List<AbstractFile> contentList;
try {
Case currentCase = Case.getOpenCase();
SleuthkitCase tskDb = currentCase.getSleuthkitCase();
//TODO this is sort of a misues of the findAllFilesWhere function and seems brittle...
//...consider doing something else
contentList = tskDb.findAllFilesWhere("1 == 1 GROUP BY md5 HAVING COUNT(*) > 1;");
CommonFilesNode cfn = new CommonFilesNode(contentList);
tfn = new TableFilterNode(cfn, true, cfn.getName());
count = contentList.size();
} catch (TskCoreException | NoCurrentCaseException ex) {
LOGGER.log(Level.WARNING, "Error while trying to get common files.", ex);
contentList = Collections.<AbstractFile>emptyList();
CommonFilesNode cfn = new CommonFilesNode(contentList);
tfn = new TableFilterNode(cfn, true, cfn.getName());
} finally {
return null;
}
}
@Override
protected void done() {
try {
super.done();
get();
TopComponent component = DataResultTopComponent.createInstance(
title,
pathText,
tfn,
count);
component.requestActive(); // make it the active top component
} catch (InterruptedException | ExecutionException ex) {
JOptionPane.showMessageDialog(WindowManager.getDefault().getMainWindow(),
ex.getCause().getMessage(),
"Some went wrong finding common files.",
JOptionPane.ERROR_MESSAGE);
}
}
}.execute();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
searchButton = new javax.swing.JButton();
setPreferredSize(new java.awt.Dimension(300, 300));
org.openide.awt.Mnemonics.setLocalizedText(searchButton, org.openide.util.NbBundle.getMessage(CommonFilesPanel.class, "CommonFilesPanel.searchButton.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(325, Short.MAX_VALUE)
.addComponent(searchButton)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(266, Short.MAX_VALUE)
.addComponent(searchButton)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton searchButton;
// End of variables declaration//GEN-END:variables
}
| comments
| Core/src/org/sleuthkit/autopsy/commonfilesearch/CommonFilesPanel.java | comments | <ide><path>ore/src/org/sleuthkit/autopsy/commonfilesearch/CommonFilesPanel.java
<ide>
<ide> //TODO this is sort of a misues of the findAllFilesWhere function and seems brittle...
<ide> //...consider doing something else
<add> //TODO verify that this works with postgres
<ide> contentList = tskDb.findAllFilesWhere("1 == 1 GROUP BY md5 HAVING COUNT(*) > 1;");
<ide>
<ide> CommonFilesNode cfn = new CommonFilesNode(contentList); |
|
Java | bsd-3-clause | a0e0aba97cd58041f37365c52921f71ecfd72f05 | 0 | littleyang/raven-java,reki2000/raven-java6,galmeida/raven-java,galmeida/raven-java,buckett/raven-java,littleyang/raven-java,buckett/raven-java,reki2000/raven-java6 | package net.kencochrane.raven;
import net.kencochrane.raven.exception.InvalidDsnException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.NoInitialContextException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Data Source name allowing a direct connection to a Sentry server.
*/
public class Dsn {
/**
* Name of the environment or system variable containing the DSN.
*/
public static final String DSN_VARIABLE = "SENTRY_DSN";
/**
* Option specific to raven-java, allowing to disable the compression of requests to the Sentry Server.
*/
public static final String NOCOMPRESSION_OPTION = "raven.nocompression";
/**
* Option specific to raven-java, allowing to set a timeout (in ms) for a request to the Sentry server.
*/
public static final String TIMEOUT_OPTION = "raven.timeout";
/**
* Option to send events asynchronously.
*/
public static final String ASYNC_OPTION = "raven.async";
/**
* Option to set the charset for strings sent to sentry.
*/
public static final String CHARSET_OPTION = "raven.charset";
/**
* Protocol setting to disable security checks over an SSL connection.
*/
public static final String NAIVE_PROTOCOL = "naive";
private static final Logger logger = Logger.getLogger(Raven.class.getCanonicalName());
private String secretKey;
private String publicKey;
private String projectId;
private String protocol;
private String host;
private int port;
private String path;
private Set<String> protocolSettings;
private Map<String, String> options;
private URI uri;
public Dsn() {
this(dsnLookup());
}
/**
* Creates a DS based on a String.
*
* @param dsn dsn in a string form.
*/
public Dsn(String dsn) {
if (dsn == null)
throw new InvalidDsnException("The sentry DSN must be provided and not be null");
options = new HashMap<String, String>();
protocolSettings = new HashSet<String>();
URI dsnUri = URI.create(dsn);
extractProtocolInfo(dsnUri);
extractUserKeys(dsnUri);
extractHostInfo(dsnUri);
extractPathInfo(dsnUri);
extractOptions(dsnUri);
makeOptionsImmutable();
validate();
try {
uri = new URI(protocol, null, host, port, path, null, null);
} catch (URISyntaxException e) {
throw new InvalidDsnException("Impossible to determine Sentry's URI from the DSN '" + dsn + "'", e);
}
}
public static String dsnLookup() {
String dsn = null;
// Try to obtain the DSN from JNDI
try {
Context c = new InitialContext();
dsn = (String) c.lookup("java:comp/env/sentry/dsn");
} catch (NoInitialContextException e) {
logger.log(Level.INFO, "JNDI not configured for sentry (NoInitialContextEx)");
} catch (NamingException e) {
logger.log(Level.INFO, "No /sentry/dsn in JNDI");
} catch (RuntimeException ex) {
logger.log(Level.INFO, "Odd RuntimeException while testing for JNDI: " + ex.getMessage());
}
// Try to obtain the DSN from a System Environment Variable
if (dsn == null)
dsn = System.getenv(Dsn.DSN_VARIABLE);
// Try to obtain the DSN from a Java System Property
if (dsn == null)
dsn = System.getProperty(Dsn.DSN_VARIABLE);
return dsn;
}
private void extractPathInfo(URI uri) {
String uriPath = uri.getPath();
if (uriPath == null)
return;
int projectIdStart = uriPath.lastIndexOf("/") + 1;
path = uriPath.substring(0, projectIdStart);
projectId = uriPath.substring(projectIdStart);
}
private void extractHostInfo(URI uri) {
host = uri.getHost();
port = uri.getPort();
}
private void extractProtocolInfo(URI uri) {
String scheme = uri.getScheme();
if (scheme == null)
return;
String[] schemeDetails = scheme.split("\\+");
protocolSettings.addAll(Arrays.asList(schemeDetails).subList(0, schemeDetails.length - 1));
protocol = schemeDetails[schemeDetails.length - 1];
}
private void extractUserKeys(URI uri) {
String userInfo = uri.getUserInfo();
if (userInfo == null)
return;
String[] userDetails = userInfo.split(":");
publicKey = userDetails[0];
if (userDetails.length > 1)
secretKey = userDetails[1];
}
private void extractOptions(URI uri) {
String query = uri.getQuery();
if (query == null)
return;
String[] optionPairs = query.split("&");
for (String optionPair : optionPairs) {
String[] pairDetails = optionPair.split("=");
options.put(pairDetails[0], (pairDetails.length > 1) ? pairDetails[1] : "");
}
}
private void makeOptionsImmutable() {
// Make the options immutable
options = Collections.unmodifiableMap(options);
protocolSettings = Collections.unmodifiableSet(protocolSettings);
}
private void validate() {
List<String> missingElements = new LinkedList<String>();
if (host == null)
missingElements.add("host");
if (publicKey == null)
missingElements.add("public key");
if (secretKey == null)
missingElements.add("secret key");
if (projectId == null || projectId.isEmpty())
missingElements.add("project ID");
if (!missingElements.isEmpty())
throw new InvalidDsnException("Invalid DSN, the following properties aren't set '" + missingElements + "'");
}
public String getSecretKey() {
return secretKey;
}
public String getPublicKey() {
return publicKey;
}
public String getProjectId() {
return projectId;
}
public String getProtocol() {
return protocol;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getPath() {
return path;
}
public Set<String> getProtocolSettings() {
return protocolSettings;
}
public Map<String, String> getOptions() {
return options;
}
/**
* Creates the URI of the sentry server.
*
* @return the URI of the sentry server.
*/
public URI getUri() {
return uri;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dsn dsn = (Dsn) o;
if (port != dsn.port) return false;
if (!host.equals(dsn.host)) return false;
if (!options.equals(dsn.options)) return false;
if (!path.equals(dsn.path)) return false;
if (!projectId.equals(dsn.projectId)) return false;
if (protocol != null ? !protocol.equals(dsn.protocol) : dsn.protocol != null) return false;
if (!protocolSettings.equals(dsn.protocolSettings)) return false;
if (!publicKey.equals(dsn.publicKey)) return false;
if (!secretKey.equals(dsn.secretKey)) return false;
return true;
}
@Override
public int hashCode() {
int result = publicKey.hashCode();
result = 31 * result + projectId.hashCode();
result = 31 * result + host.hashCode();
result = 31 * result + port;
result = 31 * result + path.hashCode();
return result;
}
@Override
public String toString() {
return getUri().toString();
}
}
| raven/src/main/java/net/kencochrane/raven/Dsn.java | package net.kencochrane.raven;
import net.kencochrane.raven.exception.InvalidDsnException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.NoInitialContextException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Data Source name allowing a direct connection to a Sentry server.
*/
public class Dsn {
/**
* Name of the environment or system variable containing the DSN.
*/
public static final String DSN_VARIABLE = "SENTRY_DSN";
/**
* Option specific to raven-java, allowing to disable the compression of requests to the Sentry Server.
*/
public static final String NOCOMPRESSION_OPTION = "raven.nocompression";
/**
* Option specific to raven-java, allowing to set a timeout (in ms) for a request to the Sentry server.
*/
public static final String TIMEOUT_OPTION = "raven.timeout";
/**
* Option to send events asynchronously.
*/
public static final String ASYNC_OPTION = "raven.async";
/**
* Option to set the charset for strings sent to sentry.
*/
public static final String CHARSET_OPTION = "raven.charset";
/**
* Protocol setting to disable security checks over an SSL connection.
*/
public static final String NAIVE_PROTOCOL = "naive";
private static final Logger logger = Logger.getLogger(Raven.class.getCanonicalName());
private String secretKey;
private String publicKey;
private String projectId;
private String protocol;
private String host;
private int port;
private String path;
private Set<String> protocolSettings;
private Map<String, String> options;
private URI uri;
public Dsn() {
this(dsnLookup());
}
/**
* Creates a DS based on a String.
*
* @param dsn dsn in a string form.
*/
public Dsn(String dsn) {
options = new HashMap<String, String>();
protocolSettings = new HashSet<String>();
URI dsnUri = URI.create(dsn);
extractProtocolInfo(dsnUri);
extractUserKeys(dsnUri);
extractHostInfo(dsnUri);
extractPathInfo(dsnUri);
extractOptions(dsnUri);
makeOptionsImmutable();
validate();
try {
uri = new URI(protocol, null, host, port, path, null, null);
} catch (URISyntaxException e) {
throw new InvalidDsnException("Impossible to determine Sentry's URI from the DSN '" + dsn + "'", e);
}
}
public static String dsnLookup() {
String dsn = null;
// Try to obtain the DSN from JNDI
try {
Context c = new InitialContext();
dsn = (String) c.lookup("java:comp/env/sentry/dsn");
} catch (NoInitialContextException e) {
logger.log(Level.INFO, "JNDI not configured for sentry (NoInitialContextEx)");
} catch (NamingException e) {
logger.log(Level.INFO, "No /sentry/dsn in JNDI");
} catch (RuntimeException ex) {
logger.log(Level.INFO, "Odd RuntimeException while testing for JNDI: " + ex.getMessage());
}
// Try to obtain the DSN from a System Environment Variable
if (dsn == null)
dsn = System.getenv(Dsn.DSN_VARIABLE);
// Try to obtain the DSN from a Java System Property
if (dsn == null)
dsn = System.getProperty(Dsn.DSN_VARIABLE);
if (dsn != null) {
return dsn;
} else {
throw new InvalidDsnException("Couldn't find a Sentry DSN in either the Java or System environment.");
}
}
private void extractPathInfo(URI uri) {
String uriPath = uri.getPath();
if (uriPath == null)
return;
int projectIdStart = uriPath.lastIndexOf("/") + 1;
path = uriPath.substring(0, projectIdStart);
projectId = uriPath.substring(projectIdStart);
}
private void extractHostInfo(URI uri) {
host = uri.getHost();
port = uri.getPort();
}
private void extractProtocolInfo(URI uri) {
String scheme = uri.getScheme();
if (scheme == null)
return;
String[] schemeDetails = scheme.split("\\+");
protocolSettings.addAll(Arrays.asList(schemeDetails).subList(0, schemeDetails.length - 1));
protocol = schemeDetails[schemeDetails.length - 1];
}
private void extractUserKeys(URI uri) {
String userInfo = uri.getUserInfo();
if (userInfo == null)
return;
String[] userDetails = userInfo.split(":");
publicKey = userDetails[0];
if (userDetails.length > 1)
secretKey = userDetails[1];
}
private void extractOptions(URI uri) {
String query = uri.getQuery();
if (query == null)
return;
String[] optionPairs = query.split("&");
for (String optionPair : optionPairs) {
String[] pairDetails = optionPair.split("=");
options.put(pairDetails[0], (pairDetails.length > 1) ? pairDetails[1] : "");
}
}
private void makeOptionsImmutable() {
// Make the options immutable
options = Collections.unmodifiableMap(options);
protocolSettings = Collections.unmodifiableSet(protocolSettings);
}
private void validate() {
List<String> missingElements = new LinkedList<String>();
if (host == null)
missingElements.add("host");
if (publicKey == null)
missingElements.add("public key");
if (secretKey == null)
missingElements.add("secret key");
if (projectId == null || projectId.isEmpty())
missingElements.add("project ID");
if (!missingElements.isEmpty())
throw new InvalidDsnException("Invalid DSN, the following properties aren't set '" + missingElements + "'");
}
public String getSecretKey() {
return secretKey;
}
public String getPublicKey() {
return publicKey;
}
public String getProjectId() {
return projectId;
}
public String getProtocol() {
return protocol;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public String getPath() {
return path;
}
public Set<String> getProtocolSettings() {
return protocolSettings;
}
public Map<String, String> getOptions() {
return options;
}
/**
* Creates the URI of the sentry server.
*
* @return the URI of the sentry server.
*/
public URI getUri() {
return uri;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dsn dsn = (Dsn) o;
if (port != dsn.port) return false;
if (!host.equals(dsn.host)) return false;
if (!options.equals(dsn.options)) return false;
if (!path.equals(dsn.path)) return false;
if (!projectId.equals(dsn.projectId)) return false;
if (protocol != null ? !protocol.equals(dsn.protocol) : dsn.protocol != null) return false;
if (!protocolSettings.equals(dsn.protocolSettings)) return false;
if (!publicKey.equals(dsn.publicKey)) return false;
if (!secretKey.equals(dsn.secretKey)) return false;
return true;
}
@Override
public int hashCode() {
int result = publicKey.hashCode();
result = 31 * result + projectId.hashCode();
result = 31 * result + host.hashCode();
result = 31 * result + port;
result = 31 * result + path.hashCode();
return result;
}
@Override
public String toString() {
return getUri().toString();
}
}
| Move the DSN nullcheck to Dsn(String)
| raven/src/main/java/net/kencochrane/raven/Dsn.java | Move the DSN nullcheck to Dsn(String) | <ide><path>aven/src/main/java/net/kencochrane/raven/Dsn.java
<ide> * @param dsn dsn in a string form.
<ide> */
<ide> public Dsn(String dsn) {
<add> if (dsn == null)
<add> throw new InvalidDsnException("The sentry DSN must be provided and not be null");
<add>
<ide> options = new HashMap<String, String>();
<ide> protocolSettings = new HashSet<String>();
<ide>
<ide> if (dsn == null)
<ide> dsn = System.getProperty(Dsn.DSN_VARIABLE);
<ide>
<del> if (dsn != null) {
<del> return dsn;
<del> } else {
<del> throw new InvalidDsnException("Couldn't find a Sentry DSN in either the Java or System environment.");
<del> }
<add> return dsn;
<ide> }
<ide>
<ide> private void extractPathInfo(URI uri) { |
|
Java | bsd-2-clause | 3e91c28bb7842df2d720ff2c728a08be2a36978b | 0 | JOMC/JOMC-Standalone | // SECTION-START[License Header]
// <editor-fold defaultstate="collapsed" desc=" Generated License ">
/*
* Copyright (C) Christian Schulte, 2005-206
* 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.
*
* THIS SOFTWARE IS PROVIDED "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 AUTHORS OR COPYRIGHT HOLDERS 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.
*
* $JOMC$
*
*/
// </editor-fold>
// SECTION-END
package org.jomc.standalone.model.modlet.test;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import org.jomc.model.ModelObject;
import org.jomc.model.Module;
import org.jomc.model.Modules;
import org.jomc.model.modlet.ModelHelper;
import org.jomc.modlet.Model;
import org.jomc.modlet.ModelContext;
import org.jomc.modlet.ModelContextFactory;
import org.jomc.modlet.ModelValidationReport;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
// SECTION-START[Documentation]
// <editor-fold defaultstate="collapsed" desc=" Generated Documentation ">
/**
* Test cases for class {@code org.jomc.standalone.model.modlet.StandaloneModelValidator}.
*
* <dl>
* <dt><b>Identifier:</b></dt><dd>org.jomc.standalone.model.modlet.test.StandaloneModelValidatorTest</dd>
* <dt><b>Name:</b></dt><dd>JOMC Standalone Model</dd>
* <dt><b>Abstract:</b></dt><dd>No</dd>
* <dt><b>Final:</b></dt><dd>No</dd>
* <dt><b>Stateless:</b></dt><dd>No</dd>
* </dl>
*
* @author <a href="mailto:[email protected]">Christian Schulte</a> 1.0
* @version 1.0-beta-3-SNAPSHOT
*/
// </editor-fold>
// SECTION-END
// SECTION-START[Annotations]
// <editor-fold defaultstate="collapsed" desc=" Generated Annotations ">
@javax.annotation.Generated( value = "org.jomc.tools.SourceFileProcessor 1.2-SNAPSHOT", comments = "See http://jomc.sourceforge.net/jomc/1.2/jomc-tools-1.2-SNAPSHOT" )
// </editor-fold>
// SECTION-END
public class StandaloneModelValidatorTest
{
// SECTION-START[StandaloneModelValidatorTest]
@Test public void testValidateModel() throws Exception
{
final ModelContext context = ModelContextFactory.newInstance().newModelContext();
final Unmarshaller u = context.createUnmarshaller( ModelObject.MODEL_PUBLIC_ID );
final Modules modules = new Modules();
final JAXBElement<Module> module =
(JAXBElement<Module>) u.unmarshal( this.getClass().getResourceAsStream( "testsuite.xml" ) );
modules.getModule().add( module.getValue() );
final Model model = new Model();
model.setIdentifier( ModelObject.MODEL_PUBLIC_ID );
ModelHelper.setModules( model, modules );
final ModelValidationReport report = context.validateModel( model );
assertFalse( report.isModelValid() );
for ( ModelValidationReport.Detail d : report.getDetails() )
{
System.out.println( d );
}
assertEquals( 1, report.getDetails( "IMPLEMENTATION_METHODS_DEFAULT_EXCEPTION_TARGET_CLASS_CONSTRAINT" ).size() );
assertEquals( 1, report.getDetails( "IMPLEMENTATION_METHOD_DEFAULT_EXCEPTION_TARGET_CLASS_CONSTRAINT" ).size() );
}
// SECTION-END
// SECTION-START[Constructors]
// <editor-fold defaultstate="collapsed" desc=" Generated Constructors ">
/** Creates a new {@code StandaloneModelValidatorTest} instance. */
@javax.annotation.Generated( value = "org.jomc.tools.SourceFileProcessor 1.2-SNAPSHOT", comments = "See http://jomc.sourceforge.net/jomc/1.2/jomc-tools-1.2-SNAPSHOT" )
public StandaloneModelValidatorTest()
{
// SECTION-START[Default Constructor]
super();
// SECTION-END
}
// </editor-fold>
// SECTION-END
// SECTION-START[Dependencies]
// SECTION-END
// SECTION-START[Properties]
// SECTION-END
// SECTION-START[Messages]
// SECTION-END
}
| jomc-standalone-model/src/test/java/org/jomc/standalone/model/modlet/test/StandaloneModelValidatorTest.java | // SECTION-START[License Header]
// <editor-fold defaultstate="collapsed" desc=" Generated License ">
/*
* Copyright (C) Christian Schulte, 2005-206
* 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.
*
* THIS SOFTWARE IS PROVIDED "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 AUTHORS OR COPYRIGHT HOLDERS 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.
*
* $JOMC$
*
*/
// </editor-fold>
// SECTION-END
package org.jomc.standalone.model.modlet.test;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import org.jomc.model.ModelObject;
import org.jomc.model.Module;
import org.jomc.model.Modules;
import org.jomc.model.modlet.ModelHelper;
import org.jomc.modlet.Model;
import org.jomc.modlet.ModelContext;
import org.jomc.modlet.ModelValidationReport;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
// SECTION-START[Documentation]
// <editor-fold defaultstate="collapsed" desc=" Generated Documentation ">
/**
* Test cases for class {@code org.jomc.standalone.model.modlet.StandaloneModelValidator}.
*
* <dl>
* <dt><b>Identifier:</b></dt><dd>org.jomc.standalone.model.modlet.test.StandaloneModelValidatorTest</dd>
* <dt><b>Name:</b></dt><dd>JOMC Standalone Model</dd>
* <dt><b>Abstract:</b></dt><dd>No</dd>
* <dt><b>Final:</b></dt><dd>No</dd>
* <dt><b>Stateless:</b></dt><dd>No</dd>
* </dl>
*
* @author <a href="mailto:[email protected]">Christian Schulte</a> 1.0
* @version 1.0-beta-3-SNAPSHOT
*/
// </editor-fold>
// SECTION-END
// SECTION-START[Annotations]
// <editor-fold defaultstate="collapsed" desc=" Generated Annotations ">
@javax.annotation.Generated( value = "org.jomc.tools.SourceFileProcessor 1.2-SNAPSHOT", comments = "See http://jomc.sourceforge.net/jomc/1.2/jomc-tools-1.2-SNAPSHOT" )
// </editor-fold>
// SECTION-END
public class StandaloneModelValidatorTest
{
// SECTION-START[StandaloneModelValidatorTest]
@Test public void testValidateModel() throws Exception
{
final ModelContext context = ModelContext.createModelContext( this.getClass().getClassLoader() );
final Unmarshaller u = context.createUnmarshaller( ModelObject.MODEL_PUBLIC_ID );
final Modules modules = new Modules();
final JAXBElement<Module> module =
(JAXBElement<Module>) u.unmarshal( this.getClass().getResourceAsStream( "testsuite.xml" ) );
modules.getModule().add( module.getValue() );
final Model model = new Model();
model.setIdentifier( ModelObject.MODEL_PUBLIC_ID );
ModelHelper.setModules( model, modules );
final ModelValidationReport report = context.validateModel( model );
assertFalse( report.isModelValid() );
for ( ModelValidationReport.Detail d : report.getDetails() )
{
System.out.println( d );
}
assertEquals( 1, report.getDetails( "IMPLEMENTATION_METHODS_DEFAULT_EXCEPTION_TARGET_CLASS_CONSTRAINT" ).size() );
assertEquals( 1, report.getDetails( "IMPLEMENTATION_METHOD_DEFAULT_EXCEPTION_TARGET_CLASS_CONSTRAINT" ).size() );
}
// SECTION-END
// SECTION-START[Constructors]
// <editor-fold defaultstate="collapsed" desc=" Generated Constructors ">
/** Creates a new {@code StandaloneModelValidatorTest} instance. */
@javax.annotation.Generated( value = "org.jomc.tools.SourceFileProcessor 1.2-SNAPSHOT", comments = "See http://jomc.sourceforge.net/jomc/1.2/jomc-tools-1.2-SNAPSHOT" )
public StandaloneModelValidatorTest()
{
// SECTION-START[Default Constructor]
super();
// SECTION-END
}
// </editor-fold>
// SECTION-END
// SECTION-START[Dependencies]
// SECTION-END
// SECTION-START[Properties]
// SECTION-END
// SECTION-START[Messages]
// SECTION-END
}
| o Updated to remove references to deprecated 'ModelContext.createModelContext' method.
git-svn-id: 985a8700d3d44944975dc3f8e40a21c4fe0a669c@4212 aee2edba-5628-49ba-b8b8-0e9d4ac63d57
| jomc-standalone-model/src/test/java/org/jomc/standalone/model/modlet/test/StandaloneModelValidatorTest.java | o Updated to remove references to deprecated 'ModelContext.createModelContext' method. | <ide><path>omc-standalone-model/src/test/java/org/jomc/standalone/model/modlet/test/StandaloneModelValidatorTest.java
<ide> import org.jomc.model.modlet.ModelHelper;
<ide> import org.jomc.modlet.Model;
<ide> import org.jomc.modlet.ModelContext;
<add>import org.jomc.modlet.ModelContextFactory;
<ide> import org.jomc.modlet.ModelValidationReport;
<ide> import org.junit.Test;
<ide> import static org.junit.Assert.assertEquals;
<ide>
<ide> @Test public void testValidateModel() throws Exception
<ide> {
<del> final ModelContext context = ModelContext.createModelContext( this.getClass().getClassLoader() );
<add> final ModelContext context = ModelContextFactory.newInstance().newModelContext();
<ide> final Unmarshaller u = context.createUnmarshaller( ModelObject.MODEL_PUBLIC_ID );
<ide>
<ide> final Modules modules = new Modules(); |
|
Java | epl-1.0 | b370320f24dbbdbcff65cb490042d6ebc56d3c50 | 0 | gnodet/wikitext | /*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.editors;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
import org.eclipse.mylyn.tasks.core.data.TaskDataModelEvent;
import org.eclipse.mylyn.tasks.core.data.TaskDataModelListener;
import org.eclipse.mylyn.tasks.ui.editors.AbstractAttributeEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
/**
* @author Steffen Pingel
*/
public class SingleSelectionAttributeEditor extends AbstractAttributeEditor {
private CCombo combo;
private boolean ignoreNotification;
private Text text;
private String[] values;
private final TaskDataModelListener modelListener = new TaskDataModelListener() {
@Override
public void attributeChanged(TaskDataModelEvent event) {
if (getTaskAttribute().equals(event.getTaskAttribute())) {
refresh();
}
}
};
public SingleSelectionAttributeEditor(TaskDataModel manager, TaskAttribute taskAttribute) {
super(manager, taskAttribute);
}
@Override
public void createControl(Composite parent, FormToolkit toolkit) {
if (isReadOnly()) {
text = new Text(parent, SWT.FLAT | SWT.READ_ONLY);
text.setFont(EditorUtil.TEXT_FONT);
toolkit.adapt(text, false, false);
text.setData(FormToolkit.KEY_DRAW_BORDER, Boolean.FALSE);
setControl(text);
} else {
combo = new CCombo(parent, SWT.FLAT | SWT.READ_ONLY);
combo.setVisibleItemCount(10);
toolkit.adapt(combo, false, false);
combo.setFont(EditorUtil.TEXT_FONT);
combo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
combo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (!ignoreNotification) {
int index = combo.getSelectionIndex();
if (index > -1) {
Assert.isNotNull(values);
Assert.isLegal(index >= 0 && index <= values.length - 1);
setValue(values[index]);
}
}
}
});
setControl(combo);
}
refresh();
getModel().addModelListener(modelListener);
}
public String getValue() {
return getAttributeMapper().getValue(getTaskAttribute());
}
public String getValueLabel() {
return getAttributeMapper().getValueLabel(getTaskAttribute());
}
@Override
public void refresh() {
try {
ignoreNotification = true;
if (text != null) {
String label = getValueLabel();
if ("".equals(label)) { //$NON-NLS-1$
// if set to the empty string the label will use 64px on GTK
text.setText(" "); //$NON-NLS-1$
} else {
text.setText(label);
}
} else if (combo != null) {
combo.removeAll();
Map<String, String> labelByValue = getAttributeMapper().getOptions(getTaskAttribute());
if (labelByValue != null) {
values = labelByValue.keySet().toArray(new String[0]);
for (String value : values) {
combo.add(labelByValue.get(value));
}
}
select(getValue(), getValueLabel());
combo.redraw();
}
} finally {
ignoreNotification = false;
}
}
private void select(String value, String label) {
if (values != null) {
for (int i = 0; i < values.length; i++) {
if (values[i].equals(value)) {
combo.select(i);
break;
}
}
} else {
combo.setText(label);
}
}
void selectDefaultValue() {
if (combo.getSelectionIndex() == -1 && values.length > 0) {
combo.select(0);
setValue(values[0]);
}
}
public void setValue(String value) {
String oldValue = getAttributeMapper().getValue(getTaskAttribute());
if (!oldValue.equals(value)) {
getAttributeMapper().setValue(getTaskAttribute(), value);
attributeChanged();
}
}
@Override
public void dispose() {
getModel().removeModelListener(modelListener);
super.dispose();
}
}
| org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/SingleSelectionAttributeEditor.java | /*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.editors;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
import org.eclipse.mylyn.tasks.core.data.TaskDataModelEvent;
import org.eclipse.mylyn.tasks.core.data.TaskDataModelListener;
import org.eclipse.mylyn.tasks.ui.editors.AbstractAttributeEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
/**
* @author Steffen Pingel
*/
public class SingleSelectionAttributeEditor extends AbstractAttributeEditor {
private CCombo combo;
private boolean ignoreNotification;
private Text text;
private String[] values;
public SingleSelectionAttributeEditor(TaskDataModel manager, TaskAttribute taskAttribute) {
super(manager, taskAttribute);
}
@Override
public void createControl(Composite parent, FormToolkit toolkit) {
if (isReadOnly()) {
text = new Text(parent, SWT.FLAT | SWT.READ_ONLY);
text.setFont(EditorUtil.TEXT_FONT);
toolkit.adapt(text, false, false);
text.setData(FormToolkit.KEY_DRAW_BORDER, Boolean.FALSE);
setControl(text);
} else {
combo = new CCombo(parent, SWT.FLAT | SWT.READ_ONLY);
combo.setVisibleItemCount(10);
toolkit.adapt(combo, false, false);
combo.setFont(EditorUtil.TEXT_FONT);
combo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
combo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
if (!ignoreNotification) {
int index = combo.getSelectionIndex();
if (index > -1) {
Assert.isNotNull(values);
Assert.isLegal(index >= 0 && index <= values.length - 1);
setValue(values[index]);
}
}
}
});
setControl(combo);
}
refresh();
getModel().addModelListener(new TaskDataModelListener() {
@Override
public void attributeChanged(TaskDataModelEvent event) {
if (getTaskAttribute().equals(event.getTaskAttribute())) {
refresh();
}
}
});
}
public String getValue() {
return getAttributeMapper().getValue(getTaskAttribute());
}
public String getValueLabel() {
return getAttributeMapper().getValueLabel(getTaskAttribute());
}
@Override
public void refresh() {
try {
ignoreNotification = true;
if (text != null) {
String label = getValueLabel();
if ("".equals(label)) { //$NON-NLS-1$
// if set to the empty string the label will use 64px on GTK
text.setText(" "); //$NON-NLS-1$
} else {
text.setText(label);
}
} else if (combo != null) {
combo.removeAll();
Map<String, String> labelByValue = getAttributeMapper().getOptions(getTaskAttribute());
if (labelByValue != null) {
values = labelByValue.keySet().toArray(new String[0]);
for (String value : values) {
combo.add(labelByValue.get(value));
}
}
select(getValue(), getValueLabel());
combo.redraw();
}
} finally {
ignoreNotification = false;
}
}
private void select(String value, String label) {
if (values != null) {
for (int i = 0; i < values.length; i++) {
if (values[i].equals(value)) {
combo.select(i);
break;
}
}
} else {
combo.setText(label);
}
}
void selectDefaultValue() {
if (combo.getSelectionIndex() == -1 && values.length > 0) {
combo.select(0);
setValue(values[0]);
}
}
public void setValue(String value) {
String oldValue = getAttributeMapper().getValue(getTaskAttribute());
if (!oldValue.equals(value)) {
getAttributeMapper().setValue(getTaskAttribute(), value);
attributeChanged();
}
}
}
| RESOLVED - bug 278256: error when submitting a task twice
https://bugs.eclipse.org/bugs/show_bug.cgi?id=278256
| org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/SingleSelectionAttributeEditor.java | RESOLVED - bug 278256: error when submitting a task twice https://bugs.eclipse.org/bugs/show_bug.cgi?id=278256 | <ide><path>rg.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/SingleSelectionAttributeEditor.java
<ide>
<ide> private String[] values;
<ide>
<add> private final TaskDataModelListener modelListener = new TaskDataModelListener() {
<add> @Override
<add> public void attributeChanged(TaskDataModelEvent event) {
<add> if (getTaskAttribute().equals(event.getTaskAttribute())) {
<add> refresh();
<add> }
<add> }
<add> };
<add>
<ide> public SingleSelectionAttributeEditor(TaskDataModel manager, TaskAttribute taskAttribute) {
<ide> super(manager, taskAttribute);
<ide> }
<ide> setControl(combo);
<ide> }
<ide> refresh();
<del> getModel().addModelListener(new TaskDataModelListener() {
<del> @Override
<del> public void attributeChanged(TaskDataModelEvent event) {
<del> if (getTaskAttribute().equals(event.getTaskAttribute())) {
<del> refresh();
<del> }
<del> }
<del> });
<add>
<add> getModel().addModelListener(modelListener);
<ide> }
<ide>
<ide> public String getValue() {
<ide> attributeChanged();
<ide> }
<ide> }
<add>
<add> @Override
<add> public void dispose() {
<add> getModel().removeModelListener(modelListener);
<add> super.dispose();
<add> }
<ide> } |
|
Java | apache-2.0 | d3c5837dbf23800fe3c886a7090b1fcb346e5cd4 | 0 | fitermay/intellij-community,adedayo/intellij-community,joewalnes/idea-community,slisson/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,ibinti/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,diorcety/intellij-community,jagguli/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,jagguli/intellij-community,vladmm/intellij-community,caot/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,da1z/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,xfournet/intellij-community,semonte/intellij-community,asedunov/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,semonte/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,holmes/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,fnouama/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,ernestp/consulo,joewalnes/idea-community,blademainer/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,slisson/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,kool79/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,clumsy/intellij-community,semonte/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,supersven/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,signed/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,signed/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,da1z/intellij-community,FHannes/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,clumsy/intellij-community,izonder/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,signed/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,caot/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,signed/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,izonder/intellij-community,slisson/intellij-community,FHannes/intellij-community,slisson/intellij-community,asedunov/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,dslomov/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,kdwink/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,apixandru/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,caot/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,signed/intellij-community,fnouama/intellij-community,slisson/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,apixandru/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,holmes/intellij-community,joewalnes/idea-community,blademainer/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,signed/intellij-community,holmes/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,vladmm/intellij-community,clumsy/intellij-community,petteyg/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,signed/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,dslomov/intellij-community,samthor/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,samthor/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,samthor/intellij-community,nicolargo/intellij-community,kool79/intellij-community,izonder/intellij-community,ernestp/consulo,ibinti/intellij-community,semonte/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,petteyg/intellij-community,ibinti/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,holmes/intellij-community,asedunov/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,caot/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,amith01994/intellij-community,amith01994/intellij-community,asedunov/intellij-community,kool79/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,signed/intellij-community,amith01994/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,TangHao1987/intellij-community,apixandru/intellij-community,caot/intellij-community,fitermay/intellij-community,diorcety/intellij-community,blademainer/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,asedunov/intellij-community,petteyg/intellij-community,vladmm/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,da1z/intellij-community,amith01994/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,holmes/intellij-community,diorcety/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,kool79/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,FHannes/intellij-community,robovm/robovm-studio,fnouama/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,fitermay/intellij-community,kdwink/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,izonder/intellij-community,suncycheng/intellij-community,kool79/intellij-community,xfournet/intellij-community,fitermay/intellij-community,consulo/consulo,alphafoobar/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,consulo/consulo,Distrotech/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,wreckJ/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,samthor/intellij-community,FHannes/intellij-community,fitermay/intellij-community,caot/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,fnouama/intellij-community,ibinti/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,diorcety/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,apixandru/intellij-community,joewalnes/idea-community,slisson/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,youdonghai/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,ryano144/intellij-community,allotria/intellij-community,izonder/intellij-community,jagguli/intellij-community,ernestp/consulo,dslomov/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,da1z/intellij-community,caot/intellij-community,kool79/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,fnouama/intellij-community,allotria/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,caot/intellij-community,diorcety/intellij-community,supersven/intellij-community,retomerz/intellij-community,joewalnes/idea-community,Lekanich/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,da1z/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,holmes/intellij-community,samthor/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,consulo/consulo,Distrotech/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,supersven/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,da1z/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,amith01994/intellij-community,adedayo/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,ibinti/intellij-community,FHannes/intellij-community,caot/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,retomerz/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,signed/intellij-community,adedayo/intellij-community,allotria/intellij-community,izonder/intellij-community,allotria/intellij-community,xfournet/intellij-community,consulo/consulo,fnouama/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,amith01994/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,holmes/intellij-community,ryano144/intellij-community,izonder/intellij-community,slisson/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,samthor/intellij-community,kdwink/intellij-community,retomerz/intellij-community,vladmm/intellij-community,kdwink/intellij-community,dslomov/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,supersven/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,signed/intellij-community,consulo/consulo,consulo/consulo,pwoodworth/intellij-community,fitermay/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,semonte/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,FHannes/intellij-community,asedunov/intellij-community,robovm/robovm-studio,FHannes/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,ernestp/consulo,jagguli/intellij-community,ryano144/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,caot/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,samthor/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,diorcety/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,ernestp/consulo,robovm/robovm-studio,asedunov/intellij-community,slisson/intellij-community,Lekanich/intellij-community,semonte/intellij-community,da1z/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,caot/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,holmes/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,kool79/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community | package com.intellij.tasks;
import com.intellij.codeInsight.completion.CompletionType;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.psi.PsiFile;
import com.intellij.tasks.impl.LocalTaskImpl;
import com.intellij.tasks.impl.TaskCompletionContributor;
import com.intellij.tasks.impl.TaskManagerImpl;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import java.util.Arrays;
/**
* @author Dmitry Avdeev
*/
public class TaskCompletionTest extends LightCodeInsightFixtureTestCase {
public void testTaskCompletion() throws Exception {
doTest("<caret>", "TEST-001: Test task<caret>");
}
public void testPrefix() throws Exception {
doTest("TEST-<caret>", "TEST-001: Test task<caret>");
}
public void testSecondWord() throws Exception {
doTest("my TEST-<caret>", "my TEST-001: Test task<caret>");
}
public void testNumberCompletion() throws Exception {
configureFile("TEST-0<caret>");
configureRepository(new LocalTaskImpl("TEST-001", "Test task"), new LocalTaskImpl("TEST-002", "Test task 2"));
LookupElement[] elements = myFixture.complete(CompletionType.BASIC);
assertNotNull(elements);
assertEquals(2, elements.length);
}
public void testSIOOBE() throws Exception {
doTest(" <caret> my ", " TEST-001: Test task my");
}
private void doTest(String text, String after) {
configureFile(text);
configureRepository(new LocalTaskImpl("TEST-001", "Test task"));
myFixture.completeBasic();
myFixture.checkResult(after);
}
private void configureFile(String text) {
PsiFile psiFile = myFixture.configureByText("test.txt", text);
TaskCompletionContributor.installCompletion(myFixture.getDocument(psiFile), getProject(), null, false);
}
private void configureRepository(LocalTaskImpl... tasks) {
TaskManagerImpl manager = (TaskManagerImpl)TaskManager.getManager(getProject());
manager.setRepositories(Arrays.asList(new TestRepository(tasks)));
manager.getState().updateEnabled = false;
}
}
| plugins/tasks/tasks-tests/test/com/intellij/tasks/TaskCompletionTest.java | package com.intellij.tasks;
import com.intellij.psi.PsiFile;
import com.intellij.tasks.impl.TaskCompletionContributor;
import com.intellij.tasks.impl.TaskManagerImpl;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import java.util.Arrays;
/**
* @author Dmitry Avdeev
*/
public class TaskCompletionTest extends LightCodeInsightFixtureTestCase {
public void testTaskCompletion() throws Exception {
doTest("<caret>", "TEST-001: Test task<caret>");
}
public void testPrefix() throws Exception {
doTest("TEST-<caret>", "TEST-001: Test task<caret>");
}
public void testSecondWord() throws Exception {
doTest("my TEST-<caret>", "my TEST-001: Test task<caret>");
}
public void testSIOOBE() throws Exception {
doTest(" <caret> my ", " TEST-001: Test task my");
}
private void doTest(String text, String after) {
PsiFile psiFile = myFixture.configureByText("test.txt", text);
TaskCompletionContributor.installCompletion(myFixture.getDocument(psiFile), getProject(), null, false);
TaskManagerImpl manager = (TaskManagerImpl)TaskManager.getManager(getProject());
manager.setRepositories(Arrays.asList(new TestRepository()));
manager.getState().updateEnabled = false;
myFixture.completeBasic();
myFixture.checkResult(after);
}
}
| another task completion test
| plugins/tasks/tasks-tests/test/com/intellij/tasks/TaskCompletionTest.java | another task completion test | <ide><path>lugins/tasks/tasks-tests/test/com/intellij/tasks/TaskCompletionTest.java
<ide> package com.intellij.tasks;
<ide>
<add>import com.intellij.codeInsight.completion.CompletionType;
<add>import com.intellij.codeInsight.lookup.LookupElement;
<ide> import com.intellij.psi.PsiFile;
<add>import com.intellij.tasks.impl.LocalTaskImpl;
<ide> import com.intellij.tasks.impl.TaskCompletionContributor;
<ide> import com.intellij.tasks.impl.TaskManagerImpl;
<ide> import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
<ide> doTest("my TEST-<caret>", "my TEST-001: Test task<caret>");
<ide> }
<ide>
<add> public void testNumberCompletion() throws Exception {
<add> configureFile("TEST-0<caret>");
<add> configureRepository(new LocalTaskImpl("TEST-001", "Test task"), new LocalTaskImpl("TEST-002", "Test task 2"));
<add> LookupElement[] elements = myFixture.complete(CompletionType.BASIC);
<add> assertNotNull(elements);
<add> assertEquals(2, elements.length);
<add> }
<add>
<ide> public void testSIOOBE() throws Exception {
<ide> doTest(" <caret> my ", " TEST-001: Test task my");
<ide> }
<ide>
<ide> private void doTest(String text, String after) {
<del> PsiFile psiFile = myFixture.configureByText("test.txt", text);
<del> TaskCompletionContributor.installCompletion(myFixture.getDocument(psiFile), getProject(), null, false);
<del> TaskManagerImpl manager = (TaskManagerImpl)TaskManager.getManager(getProject());
<del> manager.setRepositories(Arrays.asList(new TestRepository()));
<del> manager.getState().updateEnabled = false;
<add> configureFile(text);
<add> configureRepository(new LocalTaskImpl("TEST-001", "Test task"));
<ide> myFixture.completeBasic();
<ide> myFixture.checkResult(after);
<ide> }
<add>
<add> private void configureFile(String text) {
<add> PsiFile psiFile = myFixture.configureByText("test.txt", text);
<add> TaskCompletionContributor.installCompletion(myFixture.getDocument(psiFile), getProject(), null, false);
<add> }
<add>
<add> private void configureRepository(LocalTaskImpl... tasks) {
<add> TaskManagerImpl manager = (TaskManagerImpl)TaskManager.getManager(getProject());
<add> manager.setRepositories(Arrays.asList(new TestRepository(tasks)));
<add> manager.getState().updateEnabled = false;
<add> }
<ide> } |
|
Java | lgpl-2.1 | a55e45b9486ac1afe3c00ba5261e60da0dd823d5 | 0 | simoc/mapyrus,simoc/mapyrus,simoc/mapyrus | /*
* $Id$
*/
package au.id.chenery.mapyrus;
import java.awt.Color;
import java.io.IOException;
import java.io.Reader;
import java.text.DecimalFormat;
import java.util.Hashtable;
import java.util.ArrayList;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
/**
* Language interpreter. Parse and executes commands read from file, or
* typed by user.
*
* May be called repeatedly to interpret several files in the same context.
*/
public class Interpreter
{
/*
* Character starting a comment on a line.
* Character separating arguments to a statement.
* Tokens around definition of a procedure.
*/
private static final char COMMENT_CHAR = '#';
private static final char ARGUMENT_SEPARATOR = ',';
private static final char PARAM_SEPARATOR = ',';
private static final String BEGIN_KEYWORD = "begin";
private static final String END_KEYWORD = "end";
/*
* Keywords for if ... then ... else ... endif block.
*/
private static final String IF_KEYWORD = "if";
private static final String THEN_KEYWORD = "then";
private static final String ELSE_KEYWORD = "else";
private static final String ELSIF_KEYWORD = "elsif";
private static final String ENDIF_KEYWORD = "endif";
/*
* Keywords for while ... do ... done block.
*/
private static final String WHILE_KEYWORD = "while";
private static final String DO_KEYWORD = "do";
private static final String DONE_KEYWORD = "done";
/*
* States during parsing statements.
*/
private static final int AT_STATEMENT = 1; /* at start of a statement */
private static final int AT_ARG = 2; /* at argument to a statement */
private static final int AT_ARG_SEPARATOR = 3; /* at separator between arguments */
private static final int AT_PARAM = 4; /* at parameter to a procedure block */
private static final int AT_PARAM_SEPARATOR = 5; /* at separator between parameters */
private static final int AT_BLOCK_NAME = 6; /* expecting procedure block name */
private static final int AT_BLOCK_PARAM = 7;
private static final int AT_IF_TEST = 8; /* at expression to test in if ... then block */
private static final int AT_THEN_KEYWORD = 9; /* at "then" keyword in if ... then block */
private static final int AT_ELSE_KEYWORD = 10; /* at "else" keyword in if ... then block */
private static final int AT_ENDIF_KEYWORD = 11; /* at "endif" keyword in if ... then block */
private static final int AT_WHILE_TEST = 8; /* at expression to test in while loop block */
private static final int AT_DO_KEYWORD = 9; /* at "do" keyword in while loop block */
private static final int AT_DONE_KEYWORD = 10; /* at "done" keyword in while loop block */
private ContextStack mContext;
/*
* Blocks of statements for each procedure defined in
* this interpreter.
*/
private Hashtable mStatementBlocks;
/*
* Formats for printing numbers in statements.
*/
private DecimalFormat mDoubleformat, mExponentialFormat;
/*
* Static world coordinate system units lookup table.
*/
private static Hashtable mWorldUnitsLookup;
static
{
mWorldUnitsLookup = new Hashtable();
mWorldUnitsLookup.put("m", new Integer(Context.WORLD_UNITS_METRES));
mWorldUnitsLookup.put("metres", new Integer(Context.WORLD_UNITS_METRES));
mWorldUnitsLookup.put("meters", new Integer(Context.WORLD_UNITS_METRES));
mWorldUnitsLookup.put("feet", new Integer(Context.WORLD_UNITS_FEET));
mWorldUnitsLookup.put("foot", new Integer(Context.WORLD_UNITS_FEET));
mWorldUnitsLookup.put("ft", new Integer(Context.WORLD_UNITS_FEET));
}
/*
* Execute a single statement, changing the path, context or generating
* some output.
*/
private void execute(Statement st, ContextStack context)
throws MapyrusException, IOException
{
Expression []expr;
int nExpressions;
int type;
Argument []args = null;
double degrees;
double x1, y1, x2, y2;
int units;
expr = st.getExpressions();
nExpressions = expr.length;
/*
* Evaluate each of the expressions for this statement.
*/
if (nExpressions > 0)
{
args = new Argument[nExpressions];
for (int i = 0; i < nExpressions; i++)
{
args[i] = expr[i].evaluate(context);
}
}
type = st.getType();
switch (type)
{
case Statement.COLOR:
if (nExpressions == 1 && args[0].getType() == Argument.STRING)
{
/*
* Find named color in color name database.
*/
Color c = ColorDatabase.getColor(args[0].getStringValue());
if (c == null)
{
throw new MapyrusException("Color not found: " +
args[0].getStringValue());
}
context.setColor(c);
}
else if (nExpressions == 4 &&
args[0].getType() == Argument.STRING &&
args[1].getType() == Argument.NUMERIC &&
args[2].getType() == Argument.NUMERIC &&
args[3].getType() == Argument.NUMERIC)
{
String colorType = args[0].getStringValue();
float c1 = (float)args[1].getNumericValue();
float c2 = (float)args[2].getNumericValue();
float c3 = (float)args[3].getNumericValue();
if (colorType.equalsIgnoreCase("hsb"))
{
/*
* Set HSB color.
*/
int rgb = Color.HSBtoRGB(c1, c2, c3);
context.setColor(new Color(rgb));
}
else if (colorType.equalsIgnoreCase("rgb"))
{
/*
* Set RGB color.
*/
context.setColor(new Color(c1, c2, c3));
}
else
{
throw new MapyrusException("Unknown color type: " +
colorType);
}
}
else
{
throw new MapyrusException("Invalid color");
}
break;
case Statement.LINEWIDTH:
if (nExpressions == 1 && args[0].getType() == Argument.NUMERIC)
{
/*
* Set new line width.
*/
context.setLineWidth(args[0].getNumericValue());
}
else
{
throw new MapyrusException("Invalid line width");
}
break;
case Statement.MOVE:
case Statement.DRAW:
if (nExpressions > 0 && nExpressions % 2 == 0)
{
/*
* Check that all coordindate values are numbers.
*/
for (int i = 0; i < nExpressions; i++)
{
if (args[0].getType() != Argument.NUMERIC)
{
throw new MapyrusException("Invalid coordinate value");
}
}
for (int i = 0; i < nExpressions; i += 2)
{
/*
* Add point to path.
*/
if (type == Statement.MOVE)
{
context.moveTo(args[i].getNumericValue(),
args[i + 1].getNumericValue());
}
else
{
context.lineTo(args[i].getNumericValue(),
args[i + 1].getNumericValue());
}
}
}
else
{
throw new MapyrusException("Wrong number of coordinate values");
}
break;
case Statement.CLEARPATH:
if (nExpressions > 0)
{
throw new MapyrusException("Unexpected arguments");
}
context.clearPath();
break;
case Statement.SLICEPATH:
if (nExpressions == 2 && args[0].getType() == Argument.NUMERIC &&
args[1].getType() == Argument.NUMERIC)
{
context.slicePath(args[0].getNumericValue(), args[1].getNumericValue());
}
else
{
throw new MapyrusException("Invalid path slice values");
}
break;
case Statement.STRIPEPATH:
if (nExpressions == 2 && args[0].getType() == Argument.NUMERIC &&
args[1].getType() == Argument.NUMERIC)
{
degrees = args[1].getNumericValue();
context.stripePath(args[0].getNumericValue(), Math.toRadians(degrees));
}
else
{
throw new MapyrusException("Invalid path stripe values");
}
break;
case Statement.STROKE:
if (nExpressions > 0)
{
throw new MapyrusException("Unexpected arguments");
}
context.stroke();
break;
case Statement.FILL:
if (nExpressions > 0)
{
throw new MapyrusException("Unexpected arguments");
}
context.fill();
break;
case Statement.CLIP:
if (nExpressions > 0)
{
throw new MapyrusException("Unexpected arguments");
}
context.clip();
break;
case Statement.SCALE:
if (nExpressions == 2 &&
args[0].getType() == Argument.NUMERIC &&
args[1].getType() == Argument.NUMERIC)
{
context.setScaling(args[0].getNumericValue(),
args[1].getNumericValue());
}
else
{
throw new MapyrusException("Invalid scaling values");
}
break;
case Statement.ROTATE:
if (nExpressions == 1 && args[0].getType() == Argument.NUMERIC)
{
degrees = args[0].getNumericValue();
context.setRotation(Math.toRadians(degrees));
}
else
{
throw new MapyrusException("Invalid rotation value");
}
break;
case Statement.WORLDS:
if ((nExpressions == 4 || nExpressions == 5) &&
args[0].getType() == Argument.NUMERIC &&
args[1].getType() == Argument.NUMERIC &&
args[2].getType() == Argument.NUMERIC &&
args[3].getType() == Argument.NUMERIC)
{
x1 = args[0].getNumericValue();
y1 = args[1].getNumericValue();
x2 = args[2].getNumericValue();
y2 = args[3].getNumericValue();
if (nExpressions == 5)
{
Integer i;
if (args[4].getType() == Argument.STRING)
{
i = (Integer)mWorldUnitsLookup.get(args[4].getStringValue());
if (i == null)
{
throw new MapyrusException("Unknown world units value: " +
args[4].getStringValue());
}
units = i.intValue();
}
else
{
throw new MapyrusException("Invalid world units value");
}
}
else
{
units = Context.WORLD_UNITS_METRES;
}
if (x2 - x1 == 0.0 || y2 - y1 == 0.0)
{
throw new MapyrusException("Zero world coordinate range");
}
context.setWorlds(x1, y1, x2, y2, units);
}
else
{
throw new MapyrusException("Invalid worlds values");
}
break;
case Statement.PROJECT:
if (nExpressions == 2 && args[0].getType() == Argument.STRING &&
args[1].getType() == Argument.STRING)
{
context.setTransform(args[0].getStringValue(),
args[1].getStringValue());
}
else
{
throw new MapyrusException("Invalid transformation");
}
break;
case Statement.DATASET:
if (nExpressions >= 3)
{
/*
* All arguments are strings.
*/
for (int i = 0; i < nExpressions; i++)
{
if (args[i].getType() != Argument.STRING)
throw new MapyrusException("Invalid dataset");
}
/*
* Build array of geometry field names.
*/
String []geometryFieldNames = new String[nExpressions - 3];
for (int i = 0; i < geometryFieldNames.length; i++)
geometryFieldNames[i] = args[i + 3].getStringValue();
context.setDataset(args[0].getStringValue(),
args[1].getStringValue(), args[2].getStringValue(),
geometryFieldNames);
}
else
{
throw new MapyrusException("Invalid dataset");
}
break;
case Statement.IMPORT:
context.queryDataset();
break;
case Statement.FETCH:
/*
* Add next row from dataset to path.
*/
Row row = context.fetchRow();
int index = 0;
int []geometryFieldIndexes = context.getDatasetGeometryFieldIndexes();
String []fieldNames = context.getDatasetFieldNames();
double x = 0.0;
for (int i = 0; i < row.size(); i++)
{
Argument field = (Argument)row.get(i);
if (index < geometryFieldIndexes.length &&
i == geometryFieldIndexes[index])
{
if (field.getType() == Argument.GEOMETRY)
{
/*
* Define path from fetched geometry.
*/
double []coords = field.getGeometryValue();
int j = 1;
while (j < coords[0])
{
if (coords[j] == PathIterator.SEG_MOVETO)
context.moveTo(coords[j + 1], coords[j + 2]);
else
context.lineTo(coords[j + 1], coords[j + 2]);
j += 3;
}
}
else
{
/*
* First pair of geometry fields contain moveTo coordinates.
* Successive pairs define lineTo coordinates.
*/
if (index == 1)
context.moveTo(x, field.getNumericValue());
else if (index % 2 == 0)
x = field.getNumericValue();
else
context.lineTo(x, field.getNumericValue());
}
index++;
}
if (field.getType() != Argument.GEOMETRY)
{
/*
* Define attributes in non-geometry fields as variables.
*/
context.defineVariable(fieldNames[i], field);
}
}
break;
case Statement.NEWPAGE:
if (nExpressions == 4 &&
args[0].getType() == Argument.STRING &&
args[1].getType() == Argument.STRING &&
args[2].getType() == Argument.NUMERIC &&
args[3].getType() == Argument.NUMERIC)
{
context.setOutputFormat(args[0].getStringValue(),
args[1].getStringValue(),
(int)args[2].getNumericValue(),
(int)args[3].getNumericValue(), "extras");
}
else
{
throw new MapyrusException("Invalid page values");
}
break;
case Statement.PRINT:
/*
* Print to stdout each of the expressions passed.
*/
for (int i = 0; i <nExpressions; i++)
{
if (args[i].getType() == Argument.STRING)
{
System.out.print(args[i].getStringValue());
}
else
{
DecimalFormat format;
double d = args[i].getNumericValue();
double absoluteD = (d >= 0) ? d : -d;
/*
* Print large or small numbers in scientific notation
* to give more significant digits.
*/
if (absoluteD != 0 && (absoluteD < 0.01 || absoluteD > 10000000.0))
format = mExponentialFormat;
else
format = mDoubleformat;
System.out.print(format.format(d));
}
}
System.out.println("");
break;
case Statement.ASSIGN:
context.defineVariable(st.getAssignedVariable(), args[0]);
break;
}
}
/**
* Parse a statement name or variable name.
* @param c is first character of name.
* @param preprocessor is source to continue reading from.
* @return word parsed from preprocessor.
*/
private String parseWord(int c, Preprocessor preprocessor)
throws IOException, MapyrusException
{
StringBuffer word = new StringBuffer();
/*
* A statement or procedure name begins with a keyword
* which must begin with a letter.
*/
if (!Character.isLetter((char)c))
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Invalid keyword");
}
/*
* Read in whole word.
*/
do
{
word.append((char)c);
c = preprocessor.read();
}
while (Character.isLetterOrDigit((char)c) || c == '.' || c == '_');
/*
* Put back the character we read that is not part of the word.
*/
preprocessor.unread(c);
return(word.toString());
}
/*
* Are we currently reading a comment?
*/
private boolean mInComment = false;
/*
* Read next character, ignoring comments.
*/
private int readSkipComments(Preprocessor preprocessor)
throws IOException, MapyrusException
{
int c;
c = preprocessor.read();
while (mInComment == true || c == COMMENT_CHAR)
{
if (c == COMMENT_CHAR)
{
/*
* Start of comment, skip characters until the end of the line.
*/
mInComment = true;
c = preprocessor.read();
}
else if (c == '\n' || c == -1)
{
/*
* End of file or end of line is end of comment.
*/
mInComment = false;
}
else
{
/*
* Skip character in comment.
*/
c = preprocessor.read();
}
}
return(c);
}
/**
* Reads, parses and returns next statement.
* @param preprocessor is source to read statement from.
* @param keyword is first token that has already been read.
* @return next statement read from file, or null if EOF was reached
* before a statement could be read.
*/
private Statement parseSimpleStatement(String keyword, Preprocessor preprocessor)
throws MapyrusException, IOException
{
int state;
ArrayList expressions = new ArrayList();
Expression expr;
Statement retval = null;
boolean isAssignmentStatement = false;
boolean finishedStatement = false;
int c;
state = AT_STATEMENT;
c = readSkipComments(preprocessor);
finishedStatement = false;
while (!finishedStatement)
{
if (c == -1 || c == '\n')
{
/*
* End of line or end of file signifies end of statement.
*/
finishedStatement = true;
}
else if (Character.isWhitespace((char)c))
{
/*
* Ignore any whitespace.
*/
c = readSkipComments(preprocessor);
}
else if (state == AT_STATEMENT)
{
/*
* Is this an assignment statement of the form: var = value
*/
isAssignmentStatement = (c == '=');
if (isAssignmentStatement)
c = readSkipComments(preprocessor);
state = AT_ARG;
}
else if (state == AT_ARG_SEPARATOR)
{
/*
* Expect a ',' between arguments and parameters to
* procedure block.
*/
if (c != ARGUMENT_SEPARATOR)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expecting: " + ARGUMENT_SEPARATOR);
}
c = readSkipComments(preprocessor);
state = AT_ARG;
}
else if (state == AT_ARG)
{
/*
* Parse an expression.
*/
preprocessor.unread(c);
expr = new Expression(preprocessor);
expressions.add(expr);
state = AT_ARG_SEPARATOR;
c = preprocessor.read();
}
else
{
/*
* Parsing is lost. Don't know what is wrong.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Parsing error");
}
}
/*
* Build a statement structure for what we just parsed.
*/
if (c == -1 && state == AT_STATEMENT)
{
/*
* Could not parse anything before we got EOF.
*/
retval = null;
}
else if (isAssignmentStatement)
{
/*
* Exactly one expression is assigned in a statement.
*/
if (expressions.size() > 1)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Too many expressions in assignment");
}
else if (expressions.size() == 0)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": No expression in assignment");
}
retval = new Statement(keyword, (Expression)expressions.get(0));
retval.setFilenameAndLineNumber(preprocessor.getCurrentFilename(),
preprocessor.getCurrentLineNumber());
}
else
{
Expression []a = new Expression[expressions.size()];
for (int i = 0; i < a.length; i++)
{
a[i] = (Expression)expressions.get(i);
}
retval = new Statement(keyword, a);
retval.setFilenameAndLineNumber(preprocessor.getCurrentFilename(),
preprocessor.getCurrentLineNumber());
}
return(retval);
}
/**
* Parse paramters in a procedure block definition.
* Reads comma separated list of parameters
* @param preprocessor is source to read from.
* @return list of parameter names.
*/
private ArrayList parseParameters(Preprocessor preprocessor)
throws IOException, MapyrusException
{
int c;
ArrayList parameters = new ArrayList();
int state;
/*
* Read parameter names separated by ',' characters.
*/
state = AT_PARAM;
c = readSkipComments(preprocessor);
while (c != -1 && c != '\n')
{
if (Character.isWhitespace((char)c))
{
/*
* Ignore whitespace.
*/
c = readSkipComments(preprocessor);
}
else if (state == AT_PARAM)
{
/*
* Expect a parameter name.
*/
parameters.add(parseWord(c, preprocessor));
state = AT_PARAM_SEPARATOR;
c = readSkipComments(preprocessor);
}
else
{
/*
* Expect a ',' between parameter names.
*/
if (c != PARAM_SEPARATOR)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + PARAM_SEPARATOR);
}
state = AT_PARAM;
c = readSkipComments(preprocessor);
}
}
return(parameters);
}
/**
* Reads and parses a procedure block, several statements
* grouped together between "begin" and "end" keywords.
* @param preprocessor is source to read from.
* @retval parsed procedure block as single statement.
*/
private ParsedStatement parseProcedureBlock(Preprocessor preprocessor)
throws IOException, MapyrusException
{
String blockName;
ArrayList parameters;
ArrayList procedureStatements = new ArrayList();
ParsedStatement st;
Statement retval;
boolean parsedEndKeyword = false;
int c;
/*
* Skip whitespace between "begin" and block name.
*/
c = readSkipComments(preprocessor);
while (Character.isWhitespace((char)c))
c = readSkipComments(preprocessor);
blockName = parseWord(c, preprocessor);
parameters = parseParameters(preprocessor);
/*
* Keep reading statements until we get matching "end"
* keyword.
*/
do
{
st = parseStatementOrKeyword(preprocessor, true);
if (st == null)
{
/*
* Should not reach end of file inside a procedure block.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
if (st.isStatement())
{
/*
* Accumulate statements for this procedure block.
*/
procedureStatements.add(st.getStatement());
}
else if (st.getKeywordType() == ParsedStatement.PARSED_END)
{
/*
* Found matching "end" keyword for this procedure block.
*/
parsedEndKeyword = true;
}
else
{
/*
* Found some other sort of control-flow keyword
* that we did not expect.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + END_KEYWORD);
}
}
while(!parsedEndKeyword);
/*
* Return procedure block as a single statement.
*/
retval = new Statement(blockName, parameters, procedureStatements);
return(new ParsedStatement(retval));
}
/**
* Reads and parses while loop statement.
* Parses test expression, "do" keyword, some
* statements, and then "done" keyword.
* @param preprocessor is source to read from.
* @return parsed loop as single statement.
*/
private ParsedStatement parseWhileStatement(Preprocessor preprocessor,
boolean inProcedureDefn)
throws IOException, MapyrusException
{
ParsedStatement st;
Expression test;
ArrayList loopStatements = new ArrayList();
Statement statement;
test = new Expression(preprocessor);
/*
* Expect to parse "do" keyword.
*/
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside while loop.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
else if (st.isStatement() ||
st.getKeywordType() != ParsedStatement.PARSED_DO)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + DO_KEYWORD);
}
/*
* Now we want some statements to execute each time through the loop.
*/
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside loop.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
while (st.isStatement())
{
loopStatements.add(st.getStatement());
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside loop
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
}
/*
* Expect "done" after statements.
*/
if (st.getKeywordType() != ParsedStatement.PARSED_DONE)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + DONE_KEYWORD);
}
statement = new Statement(test, loopStatements);
return(new ParsedStatement(statement));
}
/**
* Reads and parses conditional statement.
* Parses test expression, "then" keyword, some
* statements, an "else" keyword, some statements and
* "endif" keyword.
* @param preprocessor is source to read from.
* @return parsed if block as single statement.
*/
private ParsedStatement parseIfStatement(Preprocessor preprocessor,
boolean inProcedureDefn)
throws IOException, MapyrusException
{
ParsedStatement st;
Expression test;
ArrayList thenStatements = new ArrayList();
ArrayList elseStatements = new ArrayList();
Statement statement;
boolean checkForEndif = true; /* do we need to check for "endif" keyword at end of statement? */
test = new Expression(preprocessor);
/*
* Expect to parse "then" keyword.
*/
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside if statement.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
else if (st.isStatement() ||
st.getKeywordType() != ParsedStatement.PARSED_THEN)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + THEN_KEYWORD);
}
/*
* Now we want some statements for when the expression is true.
*/
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside if statement.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
while (st.isStatement())
{
thenStatements.add(st.getStatement());
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside if statement.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
}
/*
* There may be an "else" part to the statement too.
*/
if (st.getKeywordType() == ParsedStatement.PARSED_ELSE)
{
/*
* Now get the statements for when the expression is false.
*/
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside if statement.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
while (st.isStatement())
{
elseStatements.add(st.getStatement());
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside if statement.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
}
}
else if (st.getKeywordType() == ParsedStatement.PARSED_ELSIF)
{
/*
* Parse "elsif" block as a single, separate "if" statement
* that is part of the "else" case.
*/
st = parseIfStatement(preprocessor, inProcedureDefn);
if (!st.isStatement())
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + ENDIF_KEYWORD);
}
elseStatements.add(st.getStatement());
checkForEndif = false;
}
/*
* Expect "endif" after statements.
*/
if (checkForEndif && st.getKeywordType() != ParsedStatement.PARSED_ENDIF)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + ENDIF_KEYWORD);
}
statement = new Statement(test, thenStatements, elseStatements);
return(new ParsedStatement(statement));
}
/*
* Static keyword lookup table for fast keyword lookup.
*/
private static Hashtable mKeywordLookup;
static
{
mKeywordLookup = new Hashtable();
mKeywordLookup.put(END_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_END));
mKeywordLookup.put(THEN_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_THEN));
mKeywordLookup.put(ELSE_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_ELSE));
mKeywordLookup.put(ELSIF_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_ELSIF));
mKeywordLookup.put(ENDIF_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_ENDIF));
mKeywordLookup.put(DO_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_DO));
mKeywordLookup.put(DONE_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_DONE));
}
/**
* Reads, parses and returns next statement, or block of statements.
* @param preprocessor source to read from.
* @param inProcedureDefn true if currently parsing inside an
* procedure block.
* @return next statement read from file, or null if EOF was reached
* before a statement could be read.
*/
private ParsedStatement parseStatementOrKeyword(Preprocessor preprocessor,
boolean inProcedureDefn)
throws MapyrusException, IOException
{
int c;
ParsedStatement retval = null;
Statement statement;
ArrayList procedureStatements = null;
int state;
boolean finishedStatement = false;
state = AT_STATEMENT;
c = readSkipComments(preprocessor);
finishedStatement = false;
while (!finishedStatement)
{
if (c == -1)
{
/*
* Reached EOF.
*/
finishedStatement = true;
break;
}
else if (Character.isWhitespace((char)c))
{
/*
* Skip whitespace
*/
c = readSkipComments(preprocessor);
}
else
{
String keyword = parseWord(c, preprocessor);
String lower = keyword.toLowerCase();
/*
* Is this the start or end of a procedure block definition?
*/
if (lower.equals(BEGIN_KEYWORD))
{
/*
* Nested procedure blocks not allowed.
*/
if (inProcedureDefn)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Procedure block definition inside procedure block");
}
retval = parseProcedureBlock(preprocessor);
}
else if (lower.equals(IF_KEYWORD))
{
retval = parseIfStatement(preprocessor, inProcedureDefn);
}
else if (lower.equals(WHILE_KEYWORD))
{
retval = parseWhileStatement(preprocessor, inProcedureDefn);
}
else
{
/*
* Does keyword match a control-flow keyword?
* like "then", or "else"?
*/
retval = (ParsedStatement)mKeywordLookup.get(lower);
if (retval == null)
{
/*
* It must be a regular type of statement if we
* can't match any special words.
*/
Statement st = parseSimpleStatement(keyword, preprocessor);
retval = new ParsedStatement(st);
}
}
finishedStatement = true;
}
}
return(retval);
}
/*
* Reads and parses a single statement.
* @param preprocessor is source to read statement from.
* @return next statement read and parsed.
*/
private Statement parseStatement(Preprocessor preprocessor)
throws IOException, MapyrusException
{
ParsedStatement st = parseStatementOrKeyword(preprocessor, false);
if (st == null)
{
return(null);
}
else if (!st.isStatement())
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Invalid keyword");
}
return(st.getStatement());
}
/**
* Reads and parses commands from file and executes them.
* @param f is open file or URL to read from.
* @param filename is name of file or URL (for use in error messages).
*/
public void interpret(Reader f, String filename)
throws IOException, MapyrusException
{
Statement st;
Preprocessor preprocessor = new Preprocessor(f, filename);
mInComment = false;
/*
* Keep parsing until we get EOF.
*/
while ((st = parseStatement(preprocessor)) != null)
{
executeStatement(st);
}
}
private void makeCall(Statement block, ArrayList parameters, Argument []args)
throws IOException, MapyrusException
{
Statement statement;
for (int i = 0; i < args.length; i++)
{
mContext.defineVariable((String)parameters.get(i), args[i]);
}
/*
* Execute each of the statements in the procedure block.
*/
ArrayList v = block.getStatementBlock();
for (int i = 0; i < v.size(); i++)
{
statement = (Statement)v.get(i);
executeStatement(statement);
}
}
/**
* Recursive function for executing statements.
* @param preprocessor is source to read statements from.
*/
private void executeStatement(Statement statement)
throws IOException, MapyrusException
{
Argument []args;
int statementType = statement.getType();
/*
* Store procedure blocks away for later execution,
* execute any other statements immediately.
*/
if (statementType == Statement.BLOCK)
{
mStatementBlocks.put(statement.getBlockName(), statement);
}
else if (statementType == Statement.CONDITIONAL)
{
/*
* Execute correct part of if statement depending on value of expression.
*/
Expression []expr = statement.getExpressions();
Argument test = expr[0].evaluate(mContext);
ArrayList v;
if (test.getType() != Argument.NUMERIC)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": Invalid expression");
}
if (test.getNumericValue() != 0.0)
v = statement.getThenStatements();
else
v = statement.getElseStatements();
if (v != null)
{
/*
* Execute each of the statements.
*/
for (int i = 0; i < v.size(); i++)
{
statement = (Statement)v.get(i);
executeStatement(statement);
}
}
}
else if (statementType == Statement.LOOP)
{
/*
* Find expression to test and loop statements to execute.
*/
Expression []expr = statement.getExpressions();
ArrayList v = statement.getLoopStatements();
Argument test = expr[0].evaluate(mContext);
if (test.getType() != Argument.NUMERIC)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": Invalid expression");
}
/*
* Execute loop while expression remains true (non-zero).
*/
while (test.getNumericValue() != 0.0)
{
/*
* Execute each of the statements.
*/
for (int i = 0; i < v.size(); i++)
{
statement = (Statement)v.get(i);
executeStatement(statement);
}
test = expr[0].evaluate(mContext);
if (test.getType() != Argument.NUMERIC)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": Invalid expression");
}
}
}
else if (statementType == Statement.CALL)
{
/*
* Find the statements for the procedure block we are calling.
*/
Statement block =
(Statement)mStatementBlocks.get(statement.getBlockName());
if (block == null)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": Procedure not defined: " + statement.getBlockName());
}
/*
* Check that correct number of parameters are being passed.
*/
ArrayList formalParameters = block.getBlockParameters();
Expression []actualParameters = statement.getExpressions();
if (actualParameters.length != formalParameters.size())
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": Wrong number of parameters in procedure call");
}
try
{
/*
* Save state and set parameters passed to the procedure.
*/
args = new Argument[actualParameters.length];
for (int i = 0; i < args.length; i++)
{
args[i] = actualParameters[i].evaluate(mContext);
}
}
catch (MapyrusException e)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": " + e.getMessage());
}
/*
* If one or more "move" points are defined without
* any lines then call the procedure block repeatedly
* with the origin transformed to each of move points
* in turn.
*/
int moveToCount = mContext.getMoveToCount();
int lineToCount = mContext.getLineToCount();
if (moveToCount > 0 && lineToCount == 0)
{
/*
* Step through path, setting origin and rotation for each
* point and then calling procedure block.
*/
ArrayList moveTos = mContext.getMoveTos();
ArrayList rotations = mContext.getMoveToRotations();
for (int i = 0; i < moveToCount; i++)
{
mContext.saveState();
Point2D.Float pt = (Point2D.Float)(moveTos.get(i));
mContext.setTranslation(pt.x, pt.y);
double rotation = ((Double)rotations.get(i)).doubleValue();
mContext.setRotation(rotation);
makeCall(block, formalParameters, args);
mContext.restoreState();
}
}
else
{
/*
* Execute statements in procedure block. Surround statments
* with a save/restore so nothing can be changed by accident.
*/
mContext.saveState();
makeCall(block, formalParameters, args);
mContext.restoreState();
}
}
else
{
/*
* Execute single statement. If error occurs then add filename and
* line number to message so user knows exactly where to look.
*/
try
{
execute(statement, mContext);
}
catch (MapyrusException e)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": " + e.getMessage());
}
catch (IOException e)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": " + e.getMessage());
}
}
}
/**
* Create new language interpreter.
* @param context is the context to use during interpretation.
* This may be in a changed state by the time interpretation
* is finished.
*/
public Interpreter(ContextStack context)
{
mContext = context;
mStatementBlocks = new Hashtable();
mDoubleformat = new DecimalFormat("#.################");
mExponentialFormat = new DecimalFormat("#.################E0");
}
}
| src/org/mapyrus/Interpreter.java | /*
* $Id$
*/
package au.id.chenery.mapyrus;
import java.awt.Color;
import java.io.IOException;
import java.io.Reader;
import java.text.DecimalFormat;
import java.util.Hashtable;
import java.util.ArrayList;
import java.awt.geom.PathIterator;
/**
* Language interpreter. Parse and executes commands read from file, or
* typed by user.
*
* May be called repeatedly to interpret several files in the same context.
*/
public class Interpreter
{
/*
* Character starting a comment on a line.
* Character separating arguments to a statement.
* Tokens around definition of a procedure.
*/
private static final char COMMENT_CHAR = '#';
private static final char ARGUMENT_SEPARATOR = ',';
private static final char PARAM_SEPARATOR = ',';
private static final String BEGIN_KEYWORD = "begin";
private static final String END_KEYWORD = "end";
/*
* Keywords for if ... then ... else ... endif block.
*/
private static final String IF_KEYWORD = "if";
private static final String THEN_KEYWORD = "then";
private static final String ELSE_KEYWORD = "else";
private static final String ELSIF_KEYWORD = "elsif";
private static final String ENDIF_KEYWORD = "endif";
/*
* Keywords for while ... do ... done block.
*/
private static final String WHILE_KEYWORD = "while";
private static final String DO_KEYWORD = "do";
private static final String DONE_KEYWORD = "done";
/*
* States during parsing statements.
*/
private static final int AT_STATEMENT = 1; /* at start of a statement */
private static final int AT_ARG = 2; /* at argument to a statement */
private static final int AT_ARG_SEPARATOR = 3; /* at separator between arguments */
private static final int AT_PARAM = 4; /* at parameter to a procedure block */
private static final int AT_PARAM_SEPARATOR = 5; /* at separator between parameters */
private static final int AT_BLOCK_NAME = 6; /* expecting procedure block name */
private static final int AT_BLOCK_PARAM = 7;
private static final int AT_IF_TEST = 8; /* at expression to test in if ... then block */
private static final int AT_THEN_KEYWORD = 9; /* at "then" keyword in if ... then block */
private static final int AT_ELSE_KEYWORD = 10; /* at "else" keyword in if ... then block */
private static final int AT_ENDIF_KEYWORD = 11; /* at "endif" keyword in if ... then block */
private static final int AT_WHILE_TEST = 8; /* at expression to test in while loop block */
private static final int AT_DO_KEYWORD = 9; /* at "do" keyword in while loop block */
private static final int AT_DONE_KEYWORD = 10; /* at "done" keyword in while loop block */
private ContextStack mContext;
/*
* Blocks of statements for each procedure defined in
* this interpreter.
*/
private Hashtable mStatementBlocks;
/*
* Static world coordinate system units lookup table.
*/
private static Hashtable mWorldUnitsLookup;
static
{
mWorldUnitsLookup = new Hashtable();
mWorldUnitsLookup.put("m", new Integer(Context.WORLD_UNITS_METRES));
mWorldUnitsLookup.put("metres", new Integer(Context.WORLD_UNITS_METRES));
mWorldUnitsLookup.put("meters", new Integer(Context.WORLD_UNITS_METRES));
mWorldUnitsLookup.put("feet", new Integer(Context.WORLD_UNITS_FEET));
mWorldUnitsLookup.put("foot", new Integer(Context.WORLD_UNITS_FEET));
mWorldUnitsLookup.put("ft", new Integer(Context.WORLD_UNITS_FEET));
}
/*
* Execute a single statement, changing the path, context or generating
* some output.
*/
private void execute(Statement st, ContextStack context)
throws MapyrusException, IOException
{
Expression []expr;
int nExpressions;
int type;
Argument []args = null;
double degrees;
double x1, y1, x2, y2;
int units;
expr = st.getExpressions();
nExpressions = expr.length;
/*
* Evaluate each of the expressions for this statement.
*/
if (nExpressions > 0)
{
args = new Argument[nExpressions];
for (int i = 0; i < nExpressions; i++)
{
args[i] = expr[i].evaluate(context);
}
}
type = st.getType();
switch (type)
{
case Statement.COLOR:
if (nExpressions == 1 && args[0].getType() == Argument.STRING)
{
/*
* Find named color in color name database.
*/
Color c = ColorDatabase.getColor(args[0].getStringValue());
if (c == null)
{
throw new MapyrusException("Color not found: " +
args[0].getStringValue());
}
context.setColor(c);
}
else if (nExpressions == 4 &&
args[0].getType() == Argument.STRING &&
args[1].getType() == Argument.NUMERIC &&
args[2].getType() == Argument.NUMERIC &&
args[3].getType() == Argument.NUMERIC)
{
String colorType = args[0].getStringValue();
float c1 = (float)args[1].getNumericValue();
float c2 = (float)args[2].getNumericValue();
float c3 = (float)args[3].getNumericValue();
if (colorType.equalsIgnoreCase("hsb"))
{
/*
* Set HSB color.
*/
int rgb = Color.HSBtoRGB(c1, c2, c3);
context.setColor(new Color(rgb));
}
else if (colorType.equalsIgnoreCase("rgb"))
{
/*
* Set RGB color.
*/
context.setColor(new Color(c1, c2, c3));
}
else
{
throw new MapyrusException("Unknown color type: " +
colorType);
}
}
else
{
throw new MapyrusException("Invalid color");
}
break;
case Statement.LINEWIDTH:
if (nExpressions == 1 && args[0].getType() == Argument.NUMERIC)
{
/*
* Set new line width.
*/
context.setLineWidth(args[0].getNumericValue());
}
else
{
throw new MapyrusException("Invalid line width");
}
break;
case Statement.MOVE:
case Statement.DRAW:
if (nExpressions > 0 && nExpressions % 2 == 0)
{
/*
* Check that all coordindate values are numbers.
*/
for (int i = 0; i < nExpressions; i++)
{
if (args[0].getType() != Argument.NUMERIC)
{
throw new MapyrusException("Invalid coordinate value");
}
}
for (int i = 0; i < nExpressions; i += 2)
{
/*
* Add point to path.
*/
if (type == Statement.MOVE)
{
context.moveTo(args[i].getNumericValue(),
args[i + 1].getNumericValue());
}
else
{
context.lineTo(args[i].getNumericValue(),
args[i + 1].getNumericValue());
}
}
}
else
{
throw new MapyrusException("Wrong number of coordinate values");
}
break;
case Statement.CLEARPATH:
if (nExpressions > 0)
{
throw new MapyrusException("Unexpected arguments");
}
context.clearPath();
break;
case Statement.SLICEPATH:
if (nExpressions == 2 && args[0].getType() == Argument.NUMERIC &&
args[1].getType() == Argument.NUMERIC)
{
context.slicePath(args[0].getNumericValue(), args[1].getNumericValue());
}
else
{
throw new MapyrusException("Invalid path slice values");
}
break;
case Statement.STRIPEPATH:
if (nExpressions == 2 && args[0].getType() == Argument.NUMERIC &&
args[1].getType() == Argument.NUMERIC)
{
degrees = args[1].getNumericValue();
context.stripePath(args[0].getNumericValue(), Math.toRadians(degrees));
}
else
{
throw new MapyrusException("Invalid path stripe values");
}
break;
case Statement.STROKE:
if (nExpressions > 0)
{
throw new MapyrusException("Unexpected arguments");
}
context.stroke();
break;
case Statement.FILL:
if (nExpressions > 0)
{
throw new MapyrusException("Unexpected arguments");
}
context.fill();
break;
case Statement.CLIP:
if (nExpressions > 0)
{
throw new MapyrusException("Unexpected arguments");
}
context.clip();
break;
case Statement.SCALE:
if (nExpressions == 2 &&
args[0].getType() == Argument.NUMERIC &&
args[1].getType() == Argument.NUMERIC)
{
context.setScaling(args[0].getNumericValue(),
args[1].getNumericValue());
}
else
{
throw new MapyrusException("Invalid scaling values");
}
break;
case Statement.ROTATE:
if (nExpressions == 1 && args[0].getType() == Argument.NUMERIC)
{
degrees = args[0].getNumericValue();
context.setRotation(Math.toRadians(degrees));
}
else
{
throw new MapyrusException("Invalid rotation value");
}
break;
case Statement.WORLDS:
if ((nExpressions == 4 || nExpressions == 5) &&
args[0].getType() == Argument.NUMERIC &&
args[1].getType() == Argument.NUMERIC &&
args[2].getType() == Argument.NUMERIC &&
args[3].getType() == Argument.NUMERIC)
{
x1 = args[0].getNumericValue();
y1 = args[1].getNumericValue();
x2 = args[2].getNumericValue();
y2 = args[3].getNumericValue();
if (nExpressions == 5)
{
Integer i;
if (args[4].getType() == Argument.STRING)
{
i = (Integer)mWorldUnitsLookup.get(args[4].getStringValue());
if (i == null)
{
throw new MapyrusException("Unknown world units value: " +
args[4].getStringValue());
}
units = i.intValue();
}
else
{
throw new MapyrusException("Invalid world units value");
}
}
else
{
units = Context.WORLD_UNITS_METRES;
}
if (x2 - x1 == 0.0 || y2 - y1 == 0.0)
{
throw new MapyrusException("Zero world coordinate range");
}
context.setWorlds(x1, y1, x2, y2, units);
}
else
{
throw new MapyrusException("Invalid worlds values");
}
break;
case Statement.PROJECT:
if (nExpressions == 2 && args[0].getType() == Argument.STRING &&
args[1].getType() == Argument.STRING)
{
context.setTransform(args[0].getStringValue(),
args[1].getStringValue());
}
else
{
throw new MapyrusException("Invalid transformation");
}
break;
case Statement.DATASET:
if (nExpressions >= 3)
{
/*
* All arguments are strings.
*/
for (int i = 0; i < nExpressions; i++)
{
if (args[i].getType() != Argument.STRING)
throw new MapyrusException("Invalid dataset");
}
/*
* Build array of geometry field names.
*/
String []geometryFieldNames = new String[nExpressions - 3];
for (int i = 0; i < geometryFieldNames.length; i++)
geometryFieldNames[i] = args[i + 3].getStringValue();
context.setDataset(args[0].getStringValue(),
args[1].getStringValue(), args[2].getStringValue(),
geometryFieldNames);
}
else
{
throw new MapyrusException("Invalid dataset");
}
break;
case Statement.IMPORT:
context.queryDataset();
break;
case Statement.FETCH:
/*
* Add next row from dataset to path.
*/
Row row = context.fetchRow();
int index = 0;
int []geometryFieldIndexes = context.getDatasetGeometryFieldIndexes();
String []fieldNames = context.getDatasetFieldNames();
double x = 0.0;
for (int i = 0; i < row.size(); i++)
{
Argument field = (Argument)row.get(i);
if (index < geometryFieldIndexes.length &&
i == geometryFieldIndexes[index])
{
if (field.getType() == Argument.GEOMETRY)
{
/*
* Define path from fetched geometry.
*/
double []coords = field.getGeometryValue();
int j = 1;
while (j < coords[0])
{
if (coords[j] == PathIterator.SEG_MOVETO)
context.moveTo(coords[j + 1], coords[j + 2]);
else
context.lineTo(coords[j + 1], coords[j + 2]);
j += 3;
}
}
else
{
/*
* First pair of geometry fields contain moveTo coordinates.
* Successive pairs define lineTo coordinates.
*/
if (index == 1)
context.moveTo(x, field.getNumericValue());
else if (index % 2 == 0)
x = field.getNumericValue();
else
context.lineTo(x, field.getNumericValue());
}
index++;
}
if (field.getType() != Argument.GEOMETRY)
{
/*
* Define attributes in non-geometry fields as variables.
*/
context.defineVariable(fieldNames[i], field);
}
}
break;
case Statement.NEWPAGE:
if (nExpressions == 4 &&
args[0].getType() == Argument.STRING &&
args[1].getType() == Argument.STRING &&
args[2].getType() == Argument.NUMERIC &&
args[3].getType() == Argument.NUMERIC)
{
context.setOutputFormat(args[0].getStringValue(),
args[1].getStringValue(),
(int)args[2].getNumericValue(),
(int)args[3].getNumericValue(), "extras");
}
else
{
throw new MapyrusException("Invalid page values");
}
break;
case Statement.PRINT:
/*
* Print to stdout each of the expressions passed.
*/
for (int i = 0; i <nExpressions; i++)
{
if (args[i].getType() == Argument.STRING)
{
System.out.print(args[i].getStringValue());
}
else
{
DecimalFormat format;
double d = args[i].getNumericValue();
double absoluteD = (d >= 0) ? d : -d;
/*
* Print large or small numbers in scientific notation
* to give more significant digits.
*/
if (absoluteD != 0 && (absoluteD < 0.01 || absoluteD > 10000000.0))
format = new DecimalFormat("#.################E0");
else
format = new DecimalFormat("#.################");
System.out.print(format.format(d));
}
}
System.out.println("");
break;
case Statement.ASSIGN:
context.defineVariable(st.getAssignedVariable(), args[0]);
break;
}
}
/**
* Parse a statement name or variable name.
* @param c is first character of name.
* @param preprocessor is source to continue reading from.
* @return word parsed from preprocessor.
*/
private String parseWord(int c, Preprocessor preprocessor)
throws IOException, MapyrusException
{
StringBuffer word = new StringBuffer();
/*
* A statement or procedure name begins with a keyword
* which must begin with a letter.
*/
if (!Character.isLetter((char)c))
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Invalid keyword");
}
/*
* Read in whole word.
*/
do
{
word.append((char)c);
c = preprocessor.read();
}
while (Character.isLetterOrDigit((char)c) || c == '.' || c == '_');
/*
* Put back the character we read that is not part of the word.
*/
preprocessor.unread(c);
return(word.toString());
}
/*
* Are we currently reading a comment?
*/
private boolean mInComment = false;
/*
* Read next character, ignoring comments.
*/
private int readSkipComments(Preprocessor preprocessor)
throws IOException, MapyrusException
{
int c;
c = preprocessor.read();
while (mInComment == true || c == COMMENT_CHAR)
{
if (c == COMMENT_CHAR)
{
/*
* Start of comment, skip characters until the end of the line.
*/
mInComment = true;
c = preprocessor.read();
}
else if (c == '\n' || c == -1)
{
/*
* End of file or end of line is end of comment.
*/
mInComment = false;
}
else
{
/*
* Skip character in comment.
*/
c = preprocessor.read();
}
}
return(c);
}
/**
* Reads, parses and returns next statement.
* @param preprocessor is source to read statement from.
* @param keyword is first token that has already been read.
* @return next statement read from file, or null if EOF was reached
* before a statement could be read.
*/
private Statement parseSimpleStatement(String keyword, Preprocessor preprocessor)
throws MapyrusException, IOException
{
int state;
ArrayList expressions = new ArrayList();
Expression expr;
Statement retval = null;
boolean isAssignmentStatement = false;
boolean finishedStatement = false;
int c;
state = AT_STATEMENT;
c = readSkipComments(preprocessor);
finishedStatement = false;
while (!finishedStatement)
{
if (c == -1 || c == '\n')
{
/*
* End of line or end of file signifies end of statement.
*/
finishedStatement = true;
}
else if (Character.isWhitespace((char)c))
{
/*
* Ignore any whitespace.
*/
c = readSkipComments(preprocessor);
}
else if (state == AT_STATEMENT)
{
/*
* Is this an assignment statement of the form: var = value
*/
isAssignmentStatement = (c == '=');
if (isAssignmentStatement)
c = readSkipComments(preprocessor);
state = AT_ARG;
}
else if (state == AT_ARG_SEPARATOR)
{
/*
* Expect a ',' between arguments and parameters to
* procedure block.
*/
if (c != ARGUMENT_SEPARATOR)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expecting: " + ARGUMENT_SEPARATOR);
}
c = readSkipComments(preprocessor);
state = AT_ARG;
}
else if (state == AT_ARG)
{
/*
* Parse an expression.
*/
preprocessor.unread(c);
expr = new Expression(preprocessor);
expressions.add(expr);
state = AT_ARG_SEPARATOR;
c = preprocessor.read();
}
else
{
/*
* Parsing is lost. Don't know what is wrong.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Parsing error");
}
}
/*
* Build a statement structure for what we just parsed.
*/
if (c == -1 && state == AT_STATEMENT)
{
/*
* Could not parse anything before we got EOF.
*/
retval = null;
}
else if (isAssignmentStatement)
{
/*
* Exactly one expression is assigned in a statement.
*/
if (expressions.size() > 1)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Too many expressions in assignment");
}
else if (expressions.size() == 0)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": No expression in assignment");
}
retval = new Statement(keyword, (Expression)expressions.get(0));
retval.setFilenameAndLineNumber(preprocessor.getCurrentFilename(),
preprocessor.getCurrentLineNumber());
}
else
{
Expression []a = new Expression[expressions.size()];
for (int i = 0; i < a.length; i++)
{
a[i] = (Expression)expressions.get(i);
}
retval = new Statement(keyword, a);
retval.setFilenameAndLineNumber(preprocessor.getCurrentFilename(),
preprocessor.getCurrentLineNumber());
}
return(retval);
}
/**
* Parse paramters in a procedure block definition.
* Reads comma separated list of parameters
* @param preprocessor is source to read from.
* @return list of parameter names.
*/
private ArrayList parseParameters(Preprocessor preprocessor)
throws IOException, MapyrusException
{
int c;
ArrayList parameters = new ArrayList();
int state;
/*
* Read parameter names separated by ',' characters.
*/
state = AT_PARAM;
c = readSkipComments(preprocessor);
while (c != -1 && c != '\n')
{
if (Character.isWhitespace((char)c))
{
/*
* Ignore whitespace.
*/
c = readSkipComments(preprocessor);
}
else if (state == AT_PARAM)
{
/*
* Expect a parameter name.
*/
parameters.add(parseWord(c, preprocessor));
state = AT_PARAM_SEPARATOR;
c = readSkipComments(preprocessor);
}
else
{
/*
* Expect a ',' between parameter names.
*/
if (c != PARAM_SEPARATOR)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + PARAM_SEPARATOR);
}
state = AT_PARAM;
c = readSkipComments(preprocessor);
}
}
return(parameters);
}
/**
* Reads and parses a procedure block, several statements
* grouped together between "begin" and "end" keywords.
* @param preprocessor is source to read from.
* @retval parsed procedure block as single statement.
*/
private ParsedStatement parseProcedureBlock(Preprocessor preprocessor)
throws IOException, MapyrusException
{
String blockName;
ArrayList parameters;
ArrayList procedureStatements = new ArrayList();
ParsedStatement st;
Statement retval;
boolean parsedEndKeyword = false;
int c;
/*
* Skip whitespace between "begin" and block name.
*/
c = readSkipComments(preprocessor);
while (Character.isWhitespace((char)c))
c = readSkipComments(preprocessor);
blockName = parseWord(c, preprocessor);
parameters = parseParameters(preprocessor);
/*
* Keep reading statements until we get matching "end"
* keyword.
*/
do
{
st = parseStatementOrKeyword(preprocessor, true);
if (st == null)
{
/*
* Should not reach end of file inside a procedure block.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
if (st.isStatement())
{
/*
* Accumulate statements for this procedure block.
*/
procedureStatements.add(st.getStatement());
}
else if (st.getKeywordType() == ParsedStatement.PARSED_END)
{
/*
* Found matching "end" keyword for this procedure block.
*/
parsedEndKeyword = true;
}
else
{
/*
* Found some other sort of control-flow keyword
* that we did not expect.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + END_KEYWORD);
}
}
while(!parsedEndKeyword);
/*
* Return procedure block as a single statement.
*/
retval = new Statement(blockName, parameters, procedureStatements);
return(new ParsedStatement(retval));
}
/**
* Reads and parses while loop statement.
* Parses test expression, "do" keyword, some
* statements, and then "done" keyword.
* @param preprocessor is source to read from.
* @return parsed loop as single statement.
*/
private ParsedStatement parseWhileStatement(Preprocessor preprocessor,
boolean inProcedureDefn)
throws IOException, MapyrusException
{
ParsedStatement st;
Expression test;
ArrayList loopStatements = new ArrayList();
Statement statement;
test = new Expression(preprocessor);
/*
* Expect to parse "do" keyword.
*/
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside while loop.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
else if (st.isStatement() ||
st.getKeywordType() != ParsedStatement.PARSED_DO)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + DO_KEYWORD);
}
/*
* Now we want some statements to execute each time through the loop.
*/
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside loop.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
while (st.isStatement())
{
loopStatements.add(st.getStatement());
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside loop
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
}
/*
* Expect "done" after statements.
*/
if (st.getKeywordType() != ParsedStatement.PARSED_DONE)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + DONE_KEYWORD);
}
statement = new Statement(test, loopStatements);
return(new ParsedStatement(statement));
}
/**
* Reads and parses conditional statement.
* Parses test expression, "then" keyword, some
* statements, an "else" keyword, some statements and
* "endif" keyword.
* @param preprocessor is source to read from.
* @return parsed if block as single statement.
*/
private ParsedStatement parseIfStatement(Preprocessor preprocessor,
boolean inProcedureDefn)
throws IOException, MapyrusException
{
ParsedStatement st;
Expression test;
ArrayList thenStatements = new ArrayList();
ArrayList elseStatements = new ArrayList();
Statement statement;
boolean checkForEndif = true; /* do we need to check for "endif" keyword at end of statement? */
test = new Expression(preprocessor);
/*
* Expect to parse "then" keyword.
*/
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside if statement.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
else if (st.isStatement() ||
st.getKeywordType() != ParsedStatement.PARSED_THEN)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + THEN_KEYWORD);
}
/*
* Now we want some statements for when the expression is true.
*/
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside if statement.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
while (st.isStatement())
{
thenStatements.add(st.getStatement());
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside if statement.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
}
/*
* There may be an "else" part to the statement too.
*/
if (st.getKeywordType() == ParsedStatement.PARSED_ELSE)
{
/*
* Now get the statements for when the expression is false.
*/
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside if statement.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
while (st.isStatement())
{
elseStatements.add(st.getStatement());
st = parseStatementOrKeyword(preprocessor, inProcedureDefn);
if (st == null)
{
/*
* Should not reach end of file inside if statement.
*/
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Unexpected end of file");
}
}
}
else if (st.getKeywordType() == ParsedStatement.PARSED_ELSIF)
{
/*
* Parse "elsif" block as a single, separate "if" statement
* that is part of the "else" case.
*/
st = parseIfStatement(preprocessor, inProcedureDefn);
if (!st.isStatement())
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + ENDIF_KEYWORD);
}
elseStatements.add(st.getStatement());
checkForEndif = false;
}
/*
* Expect "endif" after statements.
*/
if (checkForEndif && st.getKeywordType() != ParsedStatement.PARSED_ENDIF)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Expected: " + ENDIF_KEYWORD);
}
statement = new Statement(test, thenStatements, elseStatements);
return(new ParsedStatement(statement));
}
/*
* Static keyword lookup table for fast keyword lookup.
*/
private static Hashtable mKeywordLookup;
static
{
mKeywordLookup = new Hashtable();
mKeywordLookup.put(END_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_END));
mKeywordLookup.put(THEN_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_THEN));
mKeywordLookup.put(ELSE_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_ELSE));
mKeywordLookup.put(ELSIF_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_ELSIF));
mKeywordLookup.put(ENDIF_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_ENDIF));
mKeywordLookup.put(DO_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_DO));
mKeywordLookup.put(DONE_KEYWORD,
new ParsedStatement(ParsedStatement.PARSED_DONE));
}
/**
* Reads, parses and returns next statement, or block of statements.
* @param preprocessor source to read from.
* @param inProcedureDefn true if currently parsing inside an
* procedure block.
* @return next statement read from file, or null if EOF was reached
* before a statement could be read.
*/
private ParsedStatement parseStatementOrKeyword(Preprocessor preprocessor,
boolean inProcedureDefn)
throws MapyrusException, IOException
{
int c;
ParsedStatement retval = null;
Statement statement;
ArrayList procedureStatements = null;
int state;
boolean finishedStatement = false;
state = AT_STATEMENT;
c = readSkipComments(preprocessor);
finishedStatement = false;
while (!finishedStatement)
{
if (c == -1)
{
/*
* Reached EOF.
*/
finishedStatement = true;
break;
}
else if (Character.isWhitespace((char)c))
{
/*
* Skip whitespace
*/
c = readSkipComments(preprocessor);
}
else
{
String keyword = parseWord(c, preprocessor);
String lower = keyword.toLowerCase();
/*
* Is this the start or end of a procedure block definition?
*/
if (lower.equals(BEGIN_KEYWORD))
{
/*
* Nested procedure blocks not allowed.
*/
if (inProcedureDefn)
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Procedure block definition inside procedure block");
}
retval = parseProcedureBlock(preprocessor);
}
else if (lower.equals(IF_KEYWORD))
{
retval = parseIfStatement(preprocessor, inProcedureDefn);
}
else if (lower.equals(WHILE_KEYWORD))
{
retval = parseWhileStatement(preprocessor, inProcedureDefn);
}
else
{
/*
* Does keyword match a control-flow keyword?
* like "then", or "else"?
*/
retval = (ParsedStatement)mKeywordLookup.get(lower);
if (retval == null)
{
/*
* It must be a regular type of statement if we
* can't match any special words.
*/
Statement st = parseSimpleStatement(keyword, preprocessor);
retval = new ParsedStatement(st);
}
}
finishedStatement = true;
}
}
return(retval);
}
/*
* Reads and parses a single statement.
* @param preprocessor is source to read statement from.
* @return next statement read and parsed.
*/
private Statement parseStatement(Preprocessor preprocessor)
throws IOException, MapyrusException
{
ParsedStatement st = parseStatementOrKeyword(preprocessor, false);
if (st == null)
{
return(null);
}
else if (!st.isStatement())
{
throw new MapyrusException(preprocessor.getCurrentFilenameAndLineNumber() +
": Invalid keyword");
}
return(st.getStatement());
}
/**
* Reads and parses commands from file and executes them.
* @param f is open file or URL to read from.
* @param filename is name of file or URL (for use in error messages).
*/
public void interpret(Reader f, String filename)
throws IOException, MapyrusException
{
Statement st;
Preprocessor preprocessor = new Preprocessor(f, filename);
mInComment = false;
/*
* Keep parsing until we get EOF.
*/
while ((st = parseStatement(preprocessor)) != null)
{
executeStatement(st);
}
}
private void makeCall(Statement block, ArrayList parameters, Argument []args)
throws IOException, MapyrusException
{
Statement statement;
for (int i = 0; i < args.length; i++)
{
mContext.defineVariable((String)parameters.get(i), args[i]);
}
/*
* Execute each of the statements in the procedure block.
*/
ArrayList v = block.getStatementBlock();
for (int i = 0; i < v.size(); i++)
{
statement = (Statement)v.get(i);
executeStatement(statement);
}
}
/**
* Recursive function for executing statements.
* @param preprocessor is source to read statements from.
*/
private void executeStatement(Statement statement)
throws IOException, MapyrusException
{
Argument []args;
int statementType = statement.getType();
/*
* Store procedure blocks away for later execution,
* execute any other statements immediately.
*/
if (statementType == Statement.BLOCK)
{
mStatementBlocks.put(statement.getBlockName(), statement);
}
else if (statementType == Statement.CONDITIONAL)
{
/*
* Execute correct part of if statement depending on value of expression.
*/
Expression []expr = statement.getExpressions();
Argument test = expr[0].evaluate(mContext);
ArrayList v;
if (test.getType() != Argument.NUMERIC)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": Invalid expression");
}
if (test.getNumericValue() != 0.0)
v = statement.getThenStatements();
else
v = statement.getElseStatements();
if (v != null)
{
/*
* Execute each of the statements.
*/
for (int i = 0; i < v.size(); i++)
{
statement = (Statement)v.get(i);
executeStatement(statement);
}
}
}
else if (statementType == Statement.LOOP)
{
/*
* Find expression to test and loop statements to execute.
*/
Expression []expr = statement.getExpressions();
ArrayList v = statement.getLoopStatements();
Argument test = expr[0].evaluate(mContext);
if (test.getType() != Argument.NUMERIC)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": Invalid expression");
}
/*
* Execute loop while expression remains true (non-zero).
*/
while (test.getNumericValue() != 0.0)
{
/*
* Execute each of the statements.
*/
for (int i = 0; i < v.size(); i++)
{
statement = (Statement)v.get(i);
executeStatement(statement);
}
test = expr[0].evaluate(mContext);
if (test.getType() != Argument.NUMERIC)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": Invalid expression");
}
}
}
else if (statementType == Statement.CALL)
{
/*
* Find the statements for the procedure block we are calling.
*/
Statement block =
(Statement)mStatementBlocks.get(statement.getBlockName());
if (block == null)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": Procedure not defined: " + statement.getBlockName());
}
/*
* Check that correct number of parameters are being passed.
*/
ArrayList formalParameters = block.getBlockParameters();
Expression []actualParameters = statement.getExpressions();
if (actualParameters.length != formalParameters.size())
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": Wrong number of parameters in procedure call");
}
try
{
/*
* Save state and set parameters passed to the procedure.
*/
args = new Argument[actualParameters.length];
for (int i = 0; i < args.length; i++)
{
args[i] = actualParameters[i].evaluate(mContext);
}
}
catch (MapyrusException e)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": " + e.getMessage());
}
/*
* If one or more "move" points are defined without
* any lines then call the procedure block repeatedly
* with the origin transformed to each of move points
* in turn.
*/
int moveToCount = mContext.getMoveToCount();
int lineToCount = mContext.getLineToCount();
if (moveToCount > 0 && lineToCount == 0)
{
/*
* Step through path, setting origin and rotation for each
* point and then calling procedure block.
*/
float coords[];
ArrayList moveTos = mContext.getMoveTos();
for (int i = 0; i < moveToCount; i++)
{
mContext.saveState();
coords = (float [])moveTos.get(i);
mContext.setTranslation(coords[0], coords[1]);
mContext.setRotation(coords[2]);
makeCall(block, formalParameters, args);
mContext.restoreState();
}
}
else
{
/*
* Execute statements in procedure block. Surround statments
* with a save/restore so nothing can be changed by accident.
*/
mContext.saveState();
makeCall(block, formalParameters, args);
mContext.restoreState();
}
}
else
{
/*
* Execute single statement. If error occurs then add filename and
* line number to message so user knows exactly where to look.
*/
try
{
execute(statement, mContext);
}
catch (MapyrusException e)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": " + e.getMessage());
}
catch (IOException e)
{
throw new MapyrusException(statement.getFilenameAndLineNumber() +
": " + e.getMessage());
}
}
}
/**
* Create new language interpreter.
* @param context is the context to use during interpretation.
* This may be in a changed state by the time interpretation
* is finished.
*/
public Interpreter(ContextStack context)
{
mContext = context;
mStatementBlocks = new Hashtable();
}
}
| Methods getMoveTos(), getMoveToRotations() to get translation points
now return ArrayLists.
Allocate DecimalFormats one time and reuse them.
| src/org/mapyrus/Interpreter.java | Methods getMoveTos(), getMoveToRotations() to get translation points now return ArrayLists. Allocate DecimalFormats one time and reuse them. | <ide><path>rc/org/mapyrus/Interpreter.java
<ide> import java.util.Hashtable;
<ide> import java.util.ArrayList;
<ide> import java.awt.geom.PathIterator;
<add>import java.awt.geom.Point2D;
<ide>
<ide> /**
<ide> * Language interpreter. Parse and executes commands read from file, or
<ide> * this interpreter.
<ide> */
<ide> private Hashtable mStatementBlocks;
<add>
<add> /*
<add> * Formats for printing numbers in statements.
<add> */
<add> private DecimalFormat mDoubleformat, mExponentialFormat;
<ide>
<ide> /*
<ide> * Static world coordinate system units lookup table.
<ide> */
<ide> private static Hashtable mWorldUnitsLookup;
<del>
<add>
<ide> static
<ide> {
<ide> mWorldUnitsLookup = new Hashtable();
<ide> * to give more significant digits.
<ide> */
<ide> if (absoluteD != 0 && (absoluteD < 0.01 || absoluteD > 10000000.0))
<del> format = new DecimalFormat("#.################E0");
<add> format = mExponentialFormat;
<ide> else
<del> format = new DecimalFormat("#.################");
<add> format = mDoubleformat;
<add>
<ide> System.out.print(format.format(d));
<ide> }
<ide> }
<ide> * Step through path, setting origin and rotation for each
<ide> * point and then calling procedure block.
<ide> */
<del> float coords[];
<ide> ArrayList moveTos = mContext.getMoveTos();
<del>
<add> ArrayList rotations = mContext.getMoveToRotations();
<add>
<ide> for (int i = 0; i < moveToCount; i++)
<ide> {
<ide> mContext.saveState();
<del> coords = (float [])moveTos.get(i);
<del> mContext.setTranslation(coords[0], coords[1]);
<del> mContext.setRotation(coords[2]);
<add> Point2D.Float pt = (Point2D.Float)(moveTos.get(i));
<add> mContext.setTranslation(pt.x, pt.y);
<add> double rotation = ((Double)rotations.get(i)).doubleValue();
<add> mContext.setRotation(rotation);
<ide> makeCall(block, formalParameters, args);
<ide> mContext.restoreState();
<ide> }
<ide> {
<ide> mContext = context;
<ide> mStatementBlocks = new Hashtable();
<add>
<add> mDoubleformat = new DecimalFormat("#.################");
<add> mExponentialFormat = new DecimalFormat("#.################E0");
<ide> }
<ide> } |
|
Java | apache-2.0 | 15eaf7e05c18d241a97b5d0d71d0e7f8960e1d71 | 0 | IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl | /*
* Copyright 2011-2017 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.datastore.server.internal;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Sets.newHashSet;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.emf.cdo.common.branch.CDOBranch;
import org.eclipse.emf.cdo.common.branch.CDOBranchManager;
import org.eclipse.emf.cdo.common.commit.CDOCommitInfo;
import org.eclipse.emf.cdo.common.commit.CDOCommitInfoHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.collections.PrimitiveCollectionModule;
import com.b2international.commons.platform.Extensions;
import com.b2international.index.DefaultIndex;
import com.b2international.index.Index;
import com.b2international.index.IndexClient;
import com.b2international.index.IndexClientFactory;
import com.b2international.index.IndexWrite;
import com.b2international.index.Indexes;
import com.b2international.index.Writer;
import com.b2international.index.mapping.Mappings;
import com.b2international.index.query.slowlog.SlowLogConfig;
import com.b2international.index.revision.DefaultRevisionIndex;
import com.b2international.index.revision.RevisionBranch;
import com.b2international.index.revision.RevisionBranchProvider;
import com.b2international.index.revision.RevisionIndex;
import com.b2international.snowowl.core.ClassLoaderProvider;
import com.b2international.snowowl.core.Repository;
import com.b2international.snowowl.core.ServiceProvider;
import com.b2international.snowowl.core.api.IBranchPath;
import com.b2international.snowowl.core.branch.BranchManager;
import com.b2international.snowowl.core.config.SnowOwlConfiguration;
import com.b2international.snowowl.core.domain.DelegatingServiceProvider;
import com.b2international.snowowl.core.domain.RepositoryContext;
import com.b2international.snowowl.core.domain.RepositoryContextProvider;
import com.b2international.snowowl.core.events.RepositoryEvent;
import com.b2international.snowowl.core.events.util.ApiRequestHandler;
import com.b2international.snowowl.core.merge.MergeService;
import com.b2international.snowowl.core.setup.Environment;
import com.b2international.snowowl.datastore.BranchPathUtils;
import com.b2international.snowowl.datastore.CDOEditingContext;
import com.b2international.snowowl.datastore.CodeSystemEntry;
import com.b2international.snowowl.datastore.CodeSystemVersionEntry;
import com.b2international.snowowl.datastore.cdo.CDOCommitInfoUtils;
import com.b2international.snowowl.datastore.cdo.CDOCommitInfoUtils.CDOCommitInfoQuery;
import com.b2international.snowowl.datastore.cdo.CDOCommitInfoUtils.ConsumeAllCommitInfoHandler;
import com.b2international.snowowl.datastore.cdo.ICDOConnection;
import com.b2international.snowowl.datastore.cdo.ICDOConnectionManager;
import com.b2international.snowowl.datastore.cdo.ICDORepository;
import com.b2international.snowowl.datastore.cdo.ICDORepositoryManager;
import com.b2international.snowowl.datastore.commitinfo.CommitInfoDocument;
import com.b2international.snowowl.datastore.commitinfo.CommitInfos;
import com.b2international.snowowl.datastore.config.IndexConfiguration;
import com.b2international.snowowl.datastore.config.RepositoryConfiguration;
import com.b2international.snowowl.datastore.events.RepositoryCommitNotification;
import com.b2international.snowowl.datastore.index.MappingProvider;
import com.b2international.snowowl.datastore.replicate.BranchReplicator;
import com.b2international.snowowl.datastore.request.RepositoryRequests;
import com.b2international.snowowl.datastore.review.ConceptChanges;
import com.b2international.snowowl.datastore.review.MergeReview;
import com.b2international.snowowl.datastore.review.MergeReviewManager;
import com.b2international.snowowl.datastore.review.Review;
import com.b2international.snowowl.datastore.review.ReviewManager;
import com.b2international.snowowl.datastore.server.CDOServerUtils;
import com.b2international.snowowl.datastore.server.EditingContextFactory;
import com.b2international.snowowl.datastore.server.EditingContextFactoryProvider;
import com.b2international.snowowl.datastore.server.RepositoryClassLoaderProviderRegistry;
import com.b2international.snowowl.datastore.server.ReviewConfiguration;
import com.b2international.snowowl.datastore.server.cdo.CDOConflictProcessorBroker;
import com.b2international.snowowl.datastore.server.cdo.ICDOConflictProcessor;
import com.b2international.snowowl.datastore.server.internal.branch.CDOBranchImpl;
import com.b2international.snowowl.datastore.server.internal.branch.CDOBranchManagerImpl;
import com.b2international.snowowl.datastore.server.internal.branch.CDOMainBranchImpl;
import com.b2international.snowowl.datastore.server.internal.branch.InternalBranch;
import com.b2international.snowowl.datastore.server.internal.branch.InternalCDOBasedBranch;
import com.b2international.snowowl.datastore.server.internal.merge.MergeServiceImpl;
import com.b2international.snowowl.datastore.server.internal.review.ConceptChangesImpl;
import com.b2international.snowowl.datastore.server.internal.review.MergeReviewImpl;
import com.b2international.snowowl.datastore.server.internal.review.MergeReviewManagerImpl;
import com.b2international.snowowl.datastore.server.internal.review.ReviewImpl;
import com.b2international.snowowl.datastore.server.internal.review.ReviewManagerImpl;
import com.b2international.snowowl.eventbus.EventBusUtil;
import com.b2international.snowowl.eventbus.IEventBus;
import com.b2international.snowowl.eventbus.Pipe;
import com.b2international.snowowl.terminologymetadata.CodeSystem;
import com.b2international.snowowl.terminologymetadata.CodeSystemVersion;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Ordering;
import com.google.inject.Provider;
/**
* @since 4.1
*/
public final class CDOBasedRepository extends DelegatingServiceProvider implements InternalRepository, RepositoryContextProvider, CDOCommitInfoHandler {
private static final Logger LOG = LoggerFactory.getLogger(CDOBasedRepository.class);
private static final String REINDEX_KEY = "snowowl.reindex";
private final String toolingId;
private final String repositoryId;
private final IEventBus handlers;
private final Map<Long, RepositoryCommitNotification> commitNotifications = new MapMaker().makeMap();
CDOBasedRepository(String repositoryId, String toolingId, int numberOfWorkers, int mergeMaxResults, Environment env) {
super(env);
checkArgument(numberOfWorkers > 0, "At least one worker thread must be specified");
this.toolingId = toolingId;
this.repositoryId = repositoryId;
this.handlers = EventBusUtil.getWorkerBus(repositoryId, numberOfWorkers);
getCdoRepository().getRepository().addCommitInfoHandler(this);
final ObjectMapper mapper = JsonSupport.getDefaultObjectMapper();
mapper.registerModule(new PrimitiveCollectionModule());
initIndex(mapper);
initializeBranchingSupport(mergeMaxResults);
initializeRequestSupport(numberOfWorkers);
reindex();
bind(Repository.class, this);
bind(ObjectMapper.class, mapper);
}
@Override
public String id() {
return repositoryId;
}
@Override
public IEventBus events() {
return getDelegate().service(IEventBus.class);
}
@Override
public void sendNotification(RepositoryEvent event) {
if (event instanceof RepositoryCommitNotification) {
final RepositoryCommitNotification notification = (RepositoryCommitNotification) event;
// enqueue and wait until the actual CDO commit notification arrives
commitNotifications.put(notification.getCommitTimestamp(), notification);
} else {
event.publish(events());
}
}
@Override
public IEventBus handlers() {
return handlers;
}
private String address() {
return String.format("/%s", repositoryId);
}
private String address(String path) {
return String.format("%s%s", address(), path);
}
@Override
public ICDOConnection getConnection() {
return getDelegate().service(ICDOConnectionManager.class).getByUuid(repositoryId);
}
@Override
public CDOBranch getCdoMainBranch() {
return getConnection().getMainBranch();
}
@Override
public CDOBranchManager getCdoBranchManager() {
return getCdoMainBranch().getBranchManager();
}
@Override
public Index getIndex() {
return service(Index.class);
}
@Override
public RevisionIndex getRevisionIndex() {
return service(RevisionIndex.class);
}
@Override
public ICDORepository getCdoRepository() {
return getDelegate().service(ICDORepositoryManager.class).getByUuid(repositoryId);
}
@Override
public ICDOConflictProcessor getConflictProcessor() {
return CDOConflictProcessorBroker.INSTANCE.getProcessor(repositoryId);
}
@Override
public long getBaseTimestamp(CDOBranch branch) {
return branch.getBase().getTimeStamp();
}
@Override
public long getHeadTimestamp(CDOBranch branch) {
return Math.max(getBaseTimestamp(branch), CDOServerUtils.getLastCommitTime(branch));
}
private void initializeRequestSupport(int numberOfWorkers) {
final ClassLoaderProvider classLoaderProvider = getClassLoaderProvider();
for (int i = 0; i < numberOfWorkers; i++) {
handlers().registerHandler(address(), new ApiRequestHandler(this, classLoaderProvider));
}
// register number of cores event bridge/pipe between events and handlers
for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
events().registerHandler(address(), new Pipe(handlers(), address()));
}
// register RepositoryContextProvider
bind(RepositoryContextProvider.class, this);
}
private ClassLoaderProvider getClassLoaderProvider() {
return getDelegate().service(RepositoryClassLoaderProviderRegistry.class).get(repositoryId);
}
@Override
public RepositoryContext get(ServiceProvider context, String repositoryId) {
return new DefaultRepositoryContext(context, repositoryId);
}
private void initializeBranchingSupport(int mergeMaxResults) {
final CDOBranchManagerImpl branchManager = new CDOBranchManagerImpl(this);
bind(BranchManager.class, branchManager);
bind(BranchReplicator.class, branchManager);
final ReviewConfiguration reviewConfiguration = getDelegate().service(SnowOwlConfiguration.class).getModuleConfig(ReviewConfiguration.class);
final ReviewManagerImpl reviewManager = new ReviewManagerImpl(this, reviewConfiguration);
bind(ReviewManager.class, reviewManager);
final MergeReviewManager mergeReviewManager = new MergeReviewManagerImpl(this, reviewManager);
bind(MergeReviewManager.class, mergeReviewManager);
events().registerHandler(String.format(RepositoryEvent.ADDRESS_TEMPLATE, repositoryId), reviewManager.getStaleHandler());
final MergeServiceImpl mergeService = new MergeServiceImpl(this, mergeMaxResults);
bind(MergeService.class, mergeService);
}
private void initIndex(final ObjectMapper mapper) {
final Collection<Class<?>> types = newHashSet();
types.add(CDOMainBranchImpl.class);
types.add(CDOBranchImpl.class);
types.add(InternalBranch.class);
types.add(Review.class);
types.add(ReviewImpl.class);
types.add(MergeReview.class);
types.add(MergeReviewImpl.class);
types.add(ConceptChanges.class);
types.add(ConceptChangesImpl.class);
types.add(CodeSystemEntry.class);
types.add(CodeSystemVersionEntry.class);
types.addAll(getToolingTypes(toolingId));
types.add(CommitInfoDocument.class);
final Map<String, Object> settings = initIndexSettings();
final IndexClient indexClient = Indexes.createIndexClient(repositoryId, mapper, new Mappings(types), settings);
final Index index = new DefaultIndex(indexClient);
final Provider<BranchManager> branchManager = provider(BranchManager.class);
final RevisionIndex revisionIndex = new DefaultRevisionIndex(index, new RevisionBranchProvider() {
@Override
public RevisionBranch getBranch(String branchPath) {
final InternalCDOBasedBranch branch = (InternalCDOBasedBranch) branchManager.get().getBranch(branchPath);
final Set<Integer> segments = newHashSet();
segments.addAll(branch.segments());
segments.addAll(branch.parentSegments());
return new RevisionBranch(branchPath, branch.segmentId(), segments);
}
@Override
public RevisionBranch getParentBranch(String branchPath) {
final InternalCDOBasedBranch branch = (InternalCDOBasedBranch) branchManager.get().getBranch(branchPath);
return new RevisionBranch(branch.parent().path(), Ordering.natural().max(branch.parentSegments()), branch.parentSegments());
}
});
// register index and revision index access, the underlying index is the same
bind(Index.class, index);
bind(RevisionIndex.class, revisionIndex);
// initialize the index
index.admin().create();
}
private Map<String, Object> initIndexSettings() {
final ImmutableMap.Builder<String, Object> builder = ImmutableMap.<String, Object>builder();
builder.put(IndexClientFactory.DIRECTORY, getDelegate().getDataDirectory() + "/indexes");
final IndexConfiguration config = service(SnowOwlConfiguration.class)
.getModuleConfig(RepositoryConfiguration.class).getIndexConfiguration();
builder.put(IndexClientFactory.COMMIT_INTERVAL_KEY, config.getCommitInterval());
builder.put(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY, config.getTranslogSyncInterval());
final SlowLogConfig slowLog = createSlowLogConfig(config);
builder.put(IndexClientFactory.SLOW_LOG_KEY, slowLog);
return builder.build();
}
private SlowLogConfig createSlowLogConfig(final IndexConfiguration config) {
final ImmutableMap.Builder<String, Object> builder = ImmutableMap.<String, Object>builder();
builder.put(SlowLogConfig.FETCH_DEBUG_THRESHOLD, config.getFetchDebugThreshold());
builder.put(SlowLogConfig.FETCH_INFO_THRESHOLD, config.getFetchInfoThreshold());
builder.put(SlowLogConfig.FETCH_TRACE_THRESHOLD, config.getFetchTraceThreshold());
builder.put(SlowLogConfig.FETCH_WARN_THRESHOLD, config.getFetchWarnThreshold());
builder.put(SlowLogConfig.QUERY_DEBUG_THRESHOLD, config.getQueryDebugThreshold());
builder.put(SlowLogConfig.QUERY_INFO_THRESHOLD, config.getQueryInfoThreshold());
builder.put(SlowLogConfig.QUERY_TRACE_THRESHOLD, config.getQueryTraceThreshold());
builder.put(SlowLogConfig.QUERY_WARN_THRESHOLD, config.getQueryWarnThreshold());
return new SlowLogConfig(builder.build());
}
private Collection<Class<?>> getToolingTypes(String toolingId) {
final Collection<Class<?>> types = newHashSet();
final Collection<MappingProvider> providers = Extensions.getExtensions("com.b2international.snowowl.datastore.mappingProvider", MappingProvider.class);
for (MappingProvider provider : providers) {
if (provider.getToolingId().equals(toolingId)) {
types.addAll(provider.getMappings());
}
}
return types;
}
@Override
public void close() throws IOException {
getCdoRepository().getRepository().removeCommitInfoHandler(this);
getIndex().admin().close();
}
@Override
protected Environment getDelegate() {
return (Environment) super.getDelegate();
}
private void reindex() {
final boolean reindex = Boolean.parseBoolean(System.getProperty(REINDEX_KEY, "false"));
if (reindex) {
reindexCodeSystems();
}
}
// FIXME
private void reindexCodeSystems() {
final EditingContextFactoryProvider contextFactoryProvider = getDelegate().service(EditingContextFactoryProvider.class);
final EditingContextFactory contextFactory = contextFactoryProvider.get(repositoryId);
try (final CDOEditingContext editingContext = contextFactory.createEditingContext(BranchPathUtils.createMainPath())) {
final List<CodeSystem> codeSystems = editingContext.getCodeSystems();
getIndex().write(new IndexWrite<Void>() {
@Override
public Void execute(Writer index) throws IOException {
for (final CodeSystem codeSystem : codeSystems) {
final CodeSystemEntry entry = CodeSystemEntry.builder(codeSystem).build();
index.put(Long.toString(entry.getStorageKey()), entry);
for (final CodeSystemVersion codeSystemVersion : codeSystem.getCodeSystemVersions()) {
final CodeSystemVersionEntry versionEntry = CodeSystemVersionEntry.builder(codeSystemVersion).build();
index.put(Long.toString(versionEntry.getStorageKey()), versionEntry);
}
}
index.commit();
return null;
}
});
}
}
@Override
@SuppressWarnings("restriction")
public void handleCommitInfo(CDOCommitInfo commitInfo) {
if (!(commitInfo instanceof org.eclipse.emf.cdo.internal.common.commit.FailureCommitInfo)) {
final CDOBranch branch = commitInfo.getBranch();
final long commitTimestamp = commitInfo.getTimeStamp();
((CDOBranchManagerImpl) service(BranchManager.class)).handleCommit(branch.getID(), commitTimestamp);
// send out the currently enqueued commit notification, if there is any (import might skip sending commit notifications until a certain point)
RepositoryCommitNotification notification = commitNotifications.remove(commitTimestamp);
if (notification == null) {
// make sure we always send out commit notification
// required in case of manual commit notifications via CDO API
notification = new RepositoryCommitNotification(id(),
CDOCommitInfoUtils.getUuid(commitInfo),
branch.getPathName(),
commitInfo.getTimeStamp(),
commitInfo.getUserID(),
commitInfo.getComment(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList());
}
notification.publish(events());
}
}
@Override
public boolean isConsistent(IBranchPath branch) {
List<CDOCommitInfo> cdoCommitInfos = getCDOCommitInfos(branch);
CommitInfos indexCommitInfos = getIndexCommitInfos(branch);
boolean emptyDb = cdoCommitInfos.isEmpty();
boolean emptyIndex = indexCommitInfos.getItems().isEmpty();
if (emptyDb && emptyIndex) {
return true; // empty dataset
}
if (emptyDb ^ emptyIndex) {
LOG.error("{} is in inconsistent state. CDO {} but INDEX {}", getCdoRepository().getRepositoryName(), contentMessage(emptyDb), contentMessage(emptyIndex));
return false; // either CDO or index was deleted but not the other.
}
return !hasInvalidCDOTimeStamps(cdoCommitInfos, getLast(indexCommitInfos).getTimeStamp(), branch);
}
private boolean hasInvalidCDOTimeStamps(List<CDOCommitInfo> cdoCommitInfos, long lastIndexCommitTimestamp, IBranchPath branch) {
// expect all the commit infos to be invalid
List<CDOCommitInfo> problematicCommitInfos = Lists.newArrayList(cdoCommitInfos);
Iterator<CDOCommitInfo> cdoCommitInfosIterator = problematicCommitInfos.iterator();
while (cdoCommitInfosIterator.hasNext()) {
CDOCommitInfo cdoCommitInfo = cdoCommitInfosIterator.next();
if (cdoCommitInfo.getTimeStamp() <= lastIndexCommitTimestamp) {
//removing valid commits from the problematic list
cdoCommitInfosIterator.remove();
}
}
if (!problematicCommitInfos.isEmpty()) {
LOG.error("Index must be re-initialized for repository: {}. (The database is ahead of the index's timestamp: {} with CDO commit timestamp(s): {})", getCdoRepository().getRepositoryName(), lastIndexCommitTimestamp, transform(problematicCommitInfos, item -> item.getTimeStamp()));
return true;
} else if (getLast(cdoCommitInfos).getTimeStamp() < lastIndexCommitTimestamp) {
LOG.error("Database inconsistency for repository: {}. (The index head timestamp: {} is ahead of CDO's head timestamp : {})", getCdoRepository().getRepositoryName(), lastIndexCommitTimestamp, getLast(cdoCommitInfos).getTimeStamp());
return true;
} else {
LOG.info("{}'s {} branch's head CDO timestamp is: {} ", getCdoRepository().getRepositoryName(), branch.getPath(), Iterables.getLast(cdoCommitInfos).getTimeStamp());
LOG.info("{}'s {} branch's head INDEX timestamp is: {} ", getCdoRepository().getRepositoryName(), branch.getPath(), lastIndexCommitTimestamp);
return false;
}
}
private List<CDOCommitInfo> getCDOCommitInfos(IBranchPath branchPath) {
long baseTimestamp = getBaseTimestamp(getCdoMainBranch());
long headTimestamp = getHeadTimestamp(getCdoMainBranch());
Map<String, IBranchPath> branchPathMap = ImmutableMap.of(repositoryId, branchPath);
final CDOCommitInfoQuery query = new CDOCommitInfoQuery(branchPathMap)
.setStartTime(baseTimestamp)
.setEndTime(headTimestamp);
final ConsumeAllCommitInfoHandler handler = new ConsumeAllCommitInfoHandler();
CDOCommitInfoUtils.getCommitInfos(query, handler);
return handler.getInfos();
}
private CommitInfos getIndexCommitInfos(IBranchPath branch) {
return RepositoryRequests
.commitInfos()
.prepareSearchCommitInfo()
.filterByBranch(branch.getPath())
.all()
.build(repositoryId)
.execute(events())
.getSync();
}
private String contentMessage(boolean empty) {
return empty ? "IS EMPTY" : "HAS CONTENT";
}
}
| core/com.b2international.snowowl.datastore.server/src/com/b2international/snowowl/datastore/server/internal/CDOBasedRepository.java | /*
* Copyright 2011-2017 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.datastore.server.internal;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Sets.newHashSet;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.emf.cdo.common.branch.CDOBranch;
import org.eclipse.emf.cdo.common.branch.CDOBranchManager;
import org.eclipse.emf.cdo.common.commit.CDOCommitInfo;
import org.eclipse.emf.cdo.common.commit.CDOCommitInfoHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.collections.PrimitiveCollectionModule;
import com.b2international.commons.platform.Extensions;
import com.b2international.index.DefaultIndex;
import com.b2international.index.Index;
import com.b2international.index.IndexClient;
import com.b2international.index.IndexClientFactory;
import com.b2international.index.IndexWrite;
import com.b2international.index.Indexes;
import com.b2international.index.Searcher;
import com.b2international.index.Writer;
import com.b2international.index.mapping.Mappings;
import com.b2international.index.query.slowlog.SlowLogConfig;
import com.b2international.index.revision.DefaultRevisionIndex;
import com.b2international.index.revision.RevisionBranch;
import com.b2international.index.revision.RevisionBranchProvider;
import com.b2international.index.revision.RevisionIndex;
import com.b2international.snowowl.core.ClassLoaderProvider;
import com.b2international.snowowl.core.Repository;
import com.b2international.snowowl.core.ServiceProvider;
import com.b2international.snowowl.core.api.IBranchPath;
import com.b2international.snowowl.core.branch.BranchManager;
import com.b2international.snowowl.core.config.SnowOwlConfiguration;
import com.b2international.snowowl.core.domain.DelegatingServiceProvider;
import com.b2international.snowowl.core.domain.RepositoryContext;
import com.b2international.snowowl.core.domain.RepositoryContextProvider;
import com.b2international.snowowl.core.events.RepositoryEvent;
import com.b2international.snowowl.core.events.util.ApiRequestHandler;
import com.b2international.snowowl.core.merge.MergeService;
import com.b2international.snowowl.core.setup.Environment;
import com.b2international.snowowl.datastore.BranchPathUtils;
import com.b2international.snowowl.datastore.CDOEditingContext;
import com.b2international.snowowl.datastore.CodeSystemEntry;
import com.b2international.snowowl.datastore.CodeSystemVersionEntry;
import com.b2international.snowowl.datastore.cdo.CDOCommitInfoUtils;
import com.b2international.snowowl.datastore.cdo.CDOCommitInfoUtils.CDOCommitInfoQuery;
import com.b2international.snowowl.datastore.cdo.CDOCommitInfoUtils.ConsumeAllCommitInfoHandler;
import com.b2international.snowowl.datastore.cdo.ICDOConnection;
import com.b2international.snowowl.datastore.cdo.ICDOConnectionManager;
import com.b2international.snowowl.datastore.cdo.ICDORepository;
import com.b2international.snowowl.datastore.cdo.ICDORepositoryManager;
import com.b2international.snowowl.datastore.commitinfo.CommitInfoDocument;
import com.b2international.snowowl.datastore.commitinfo.CommitInfos;
import com.b2international.snowowl.datastore.config.IndexConfiguration;
import com.b2international.snowowl.datastore.config.RepositoryConfiguration;
import com.b2international.snowowl.datastore.events.RepositoryCommitNotification;
import com.b2international.snowowl.datastore.index.MappingProvider;
import com.b2international.snowowl.datastore.replicate.BranchReplicator;
import com.b2international.snowowl.datastore.request.RepositoryRequests;
import com.b2international.snowowl.datastore.review.ConceptChanges;
import com.b2international.snowowl.datastore.review.MergeReview;
import com.b2international.snowowl.datastore.review.MergeReviewManager;
import com.b2international.snowowl.datastore.review.Review;
import com.b2international.snowowl.datastore.review.ReviewManager;
import com.b2international.snowowl.datastore.server.CDOServerUtils;
import com.b2international.snowowl.datastore.server.EditingContextFactory;
import com.b2international.snowowl.datastore.server.EditingContextFactoryProvider;
import com.b2international.snowowl.datastore.server.RepositoryClassLoaderProviderRegistry;
import com.b2international.snowowl.datastore.server.ReviewConfiguration;
import com.b2international.snowowl.datastore.server.cdo.CDOConflictProcessorBroker;
import com.b2international.snowowl.datastore.server.cdo.ICDOConflictProcessor;
import com.b2international.snowowl.datastore.server.internal.branch.CDOBranchImpl;
import com.b2international.snowowl.datastore.server.internal.branch.CDOBranchManagerImpl;
import com.b2international.snowowl.datastore.server.internal.branch.CDOMainBranchImpl;
import com.b2international.snowowl.datastore.server.internal.branch.InternalBranch;
import com.b2international.snowowl.datastore.server.internal.branch.InternalCDOBasedBranch;
import com.b2international.snowowl.datastore.server.internal.merge.MergeServiceImpl;
import com.b2international.snowowl.datastore.server.internal.review.ConceptChangesImpl;
import com.b2international.snowowl.datastore.server.internal.review.MergeReviewImpl;
import com.b2international.snowowl.datastore.server.internal.review.MergeReviewManagerImpl;
import com.b2international.snowowl.datastore.server.internal.review.ReviewImpl;
import com.b2international.snowowl.datastore.server.internal.review.ReviewManagerImpl;
import com.b2international.snowowl.eventbus.EventBusUtil;
import com.b2international.snowowl.eventbus.IEventBus;
import com.b2international.snowowl.eventbus.Pipe;
import com.b2international.snowowl.terminologymetadata.CodeSystem;
import com.b2international.snowowl.terminologymetadata.CodeSystemVersion;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Ordering;
import com.google.inject.Provider;
/**
* @since 4.1
*/
public final class CDOBasedRepository extends DelegatingServiceProvider implements InternalRepository, RepositoryContextProvider, CDOCommitInfoHandler {
private static final Logger LOG = LoggerFactory.getLogger(CDOBasedRepository.class);
private static final String REINDEX_KEY = "snowowl.reindex";
private final String toolingId;
private final String repositoryId;
private final IEventBus handlers;
private final Map<Long, RepositoryCommitNotification> commitNotifications = new MapMaker().makeMap();
CDOBasedRepository(String repositoryId, String toolingId, int numberOfWorkers, int mergeMaxResults, Environment env) {
super(env);
checkArgument(numberOfWorkers > 0, "At least one worker thread must be specified");
this.toolingId = toolingId;
this.repositoryId = repositoryId;
this.handlers = EventBusUtil.getWorkerBus(repositoryId, numberOfWorkers);
getCdoRepository().getRepository().addCommitInfoHandler(this);
final ObjectMapper mapper = JsonSupport.getDefaultObjectMapper();
mapper.registerModule(new PrimitiveCollectionModule());
initIndex(mapper);
initializeBranchingSupport(mergeMaxResults);
initializeRequestSupport(numberOfWorkers);
reindex();
bind(Repository.class, this);
bind(ObjectMapper.class, mapper);
}
@Override
public String id() {
return repositoryId;
}
@Override
public IEventBus events() {
return getDelegate().service(IEventBus.class);
}
@Override
public void sendNotification(RepositoryEvent event) {
if (event instanceof RepositoryCommitNotification) {
final RepositoryCommitNotification notification = (RepositoryCommitNotification) event;
// enqueue and wait until the actual CDO commit notification arrives
commitNotifications.put(notification.getCommitTimestamp(), notification);
} else {
event.publish(events());
}
}
@Override
public IEventBus handlers() {
return handlers;
}
private String address() {
return String.format("/%s", repositoryId);
}
private String address(String path) {
return String.format("%s%s", address(), path);
}
@Override
public ICDOConnection getConnection() {
return getDelegate().service(ICDOConnectionManager.class).getByUuid(repositoryId);
}
@Override
public CDOBranch getCdoMainBranch() {
return getConnection().getMainBranch();
}
@Override
public CDOBranchManager getCdoBranchManager() {
return getCdoMainBranch().getBranchManager();
}
@Override
public Index getIndex() {
return service(Index.class);
}
@Override
public RevisionIndex getRevisionIndex() {
return service(RevisionIndex.class);
}
@Override
public ICDORepository getCdoRepository() {
return getDelegate().service(ICDORepositoryManager.class).getByUuid(repositoryId);
}
@Override
public ICDOConflictProcessor getConflictProcessor() {
return CDOConflictProcessorBroker.INSTANCE.getProcessor(repositoryId);
}
@Override
public long getBaseTimestamp(CDOBranch branch) {
return branch.getBase().getTimeStamp();
}
@Override
public long getHeadTimestamp(CDOBranch branch) {
return Math.max(getBaseTimestamp(branch), CDOServerUtils.getLastCommitTime(branch));
}
private void initializeRequestSupport(int numberOfWorkers) {
final ClassLoaderProvider classLoaderProvider = getClassLoaderProvider();
for (int i = 0; i < numberOfWorkers; i++) {
handlers().registerHandler(address(), new ApiRequestHandler(this, classLoaderProvider));
}
// register number of cores event bridge/pipe between events and handlers
for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
events().registerHandler(address(), new Pipe(handlers(), address()));
}
// register RepositoryContextProvider
bind(RepositoryContextProvider.class, this);
}
private ClassLoaderProvider getClassLoaderProvider() {
return getDelegate().service(RepositoryClassLoaderProviderRegistry.class).get(repositoryId);
}
@Override
public RepositoryContext get(ServiceProvider context, String repositoryId) {
return new DefaultRepositoryContext(context, repositoryId);
}
private void initializeBranchingSupport(int mergeMaxResults) {
final CDOBranchManagerImpl branchManager = new CDOBranchManagerImpl(this);
bind(BranchManager.class, branchManager);
bind(BranchReplicator.class, branchManager);
final ReviewConfiguration reviewConfiguration = getDelegate().service(SnowOwlConfiguration.class).getModuleConfig(ReviewConfiguration.class);
final ReviewManagerImpl reviewManager = new ReviewManagerImpl(this, reviewConfiguration);
bind(ReviewManager.class, reviewManager);
final MergeReviewManager mergeReviewManager = new MergeReviewManagerImpl(this, reviewManager);
bind(MergeReviewManager.class, mergeReviewManager);
events().registerHandler(String.format(RepositoryEvent.ADDRESS_TEMPLATE, repositoryId), reviewManager.getStaleHandler());
final MergeServiceImpl mergeService = new MergeServiceImpl(this, mergeMaxResults);
bind(MergeService.class, mergeService);
}
private void initIndex(final ObjectMapper mapper) {
final Collection<Class<?>> types = newHashSet();
types.add(CDOMainBranchImpl.class);
types.add(CDOBranchImpl.class);
types.add(InternalBranch.class);
types.add(Review.class);
types.add(ReviewImpl.class);
types.add(MergeReview.class);
types.add(MergeReviewImpl.class);
types.add(ConceptChanges.class);
types.add(ConceptChangesImpl.class);
types.add(CodeSystemEntry.class);
types.add(CodeSystemVersionEntry.class);
types.addAll(getToolingTypes(toolingId));
types.add(CommitInfoDocument.class);
final Map<String, Object> settings = initIndexSettings();
final IndexClient indexClient = Indexes.createIndexClient(repositoryId, mapper, new Mappings(types), settings);
final Index index = new DefaultIndex(indexClient);
final Provider<BranchManager> branchManager = provider(BranchManager.class);
final RevisionIndex revisionIndex = new DefaultRevisionIndex(index, new RevisionBranchProvider() {
@Override
public RevisionBranch getBranch(String branchPath) {
final InternalCDOBasedBranch branch = (InternalCDOBasedBranch) branchManager.get().getBranch(branchPath);
final Set<Integer> segments = newHashSet();
segments.addAll(branch.segments());
segments.addAll(branch.parentSegments());
return new RevisionBranch(branchPath, branch.segmentId(), segments);
}
@Override
public RevisionBranch getParentBranch(String branchPath) {
final InternalCDOBasedBranch branch = (InternalCDOBasedBranch) branchManager.get().getBranch(branchPath);
return new RevisionBranch(branch.parent().path(), Ordering.natural().max(branch.parentSegments()), branch.parentSegments());
}
});
// register index and revision index access, the underlying index is the same
bind(Index.class, index);
bind(RevisionIndex.class, revisionIndex);
// initialize the index
index.admin().create();
getDelegate().services().registerService(Searcher.class, indexClient.searcher());
}
private Map<String, Object> initIndexSettings() {
final ImmutableMap.Builder<String, Object> builder = ImmutableMap.<String, Object>builder();
builder.put(IndexClientFactory.DIRECTORY, getDelegate().getDataDirectory() + "/indexes");
final IndexConfiguration config = service(SnowOwlConfiguration.class)
.getModuleConfig(RepositoryConfiguration.class).getIndexConfiguration();
builder.put(IndexClientFactory.COMMIT_INTERVAL_KEY, config.getCommitInterval());
builder.put(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY, config.getTranslogSyncInterval());
final SlowLogConfig slowLog = createSlowLogConfig(config);
builder.put(IndexClientFactory.SLOW_LOG_KEY, slowLog);
return builder.build();
}
private SlowLogConfig createSlowLogConfig(final IndexConfiguration config) {
final ImmutableMap.Builder<String, Object> builder = ImmutableMap.<String, Object>builder();
builder.put(SlowLogConfig.FETCH_DEBUG_THRESHOLD, config.getFetchDebugThreshold());
builder.put(SlowLogConfig.FETCH_INFO_THRESHOLD, config.getFetchInfoThreshold());
builder.put(SlowLogConfig.FETCH_TRACE_THRESHOLD, config.getFetchTraceThreshold());
builder.put(SlowLogConfig.FETCH_WARN_THRESHOLD, config.getFetchWarnThreshold());
builder.put(SlowLogConfig.QUERY_DEBUG_THRESHOLD, config.getQueryDebugThreshold());
builder.put(SlowLogConfig.QUERY_INFO_THRESHOLD, config.getQueryInfoThreshold());
builder.put(SlowLogConfig.QUERY_TRACE_THRESHOLD, config.getQueryTraceThreshold());
builder.put(SlowLogConfig.QUERY_WARN_THRESHOLD, config.getQueryWarnThreshold());
return new SlowLogConfig(builder.build());
}
private Collection<Class<?>> getToolingTypes(String toolingId) {
final Collection<Class<?>> types = newHashSet();
final Collection<MappingProvider> providers = Extensions.getExtensions("com.b2international.snowowl.datastore.mappingProvider", MappingProvider.class);
for (MappingProvider provider : providers) {
if (provider.getToolingId().equals(toolingId)) {
types.addAll(provider.getMappings());
}
}
return types;
}
@Override
public void close() throws IOException {
getCdoRepository().getRepository().removeCommitInfoHandler(this);
getIndex().admin().close();
}
@Override
protected Environment getDelegate() {
return (Environment) super.getDelegate();
}
private void reindex() {
final boolean reindex = Boolean.parseBoolean(System.getProperty(REINDEX_KEY, "false"));
if (reindex) {
reindexCodeSystems();
}
}
// FIXME
private void reindexCodeSystems() {
final EditingContextFactoryProvider contextFactoryProvider = getDelegate().service(EditingContextFactoryProvider.class);
final EditingContextFactory contextFactory = contextFactoryProvider.get(repositoryId);
try (final CDOEditingContext editingContext = contextFactory.createEditingContext(BranchPathUtils.createMainPath())) {
final List<CodeSystem> codeSystems = editingContext.getCodeSystems();
getIndex().write(new IndexWrite<Void>() {
@Override
public Void execute(Writer index) throws IOException {
for (final CodeSystem codeSystem : codeSystems) {
final CodeSystemEntry entry = CodeSystemEntry.builder(codeSystem).build();
index.put(Long.toString(entry.getStorageKey()), entry);
for (final CodeSystemVersion codeSystemVersion : codeSystem.getCodeSystemVersions()) {
final CodeSystemVersionEntry versionEntry = CodeSystemVersionEntry.builder(codeSystemVersion).build();
index.put(Long.toString(versionEntry.getStorageKey()), versionEntry);
}
}
index.commit();
return null;
}
});
}
}
@Override
@SuppressWarnings("restriction")
public void handleCommitInfo(CDOCommitInfo commitInfo) {
if (!(commitInfo instanceof org.eclipse.emf.cdo.internal.common.commit.FailureCommitInfo)) {
final CDOBranch branch = commitInfo.getBranch();
final long commitTimestamp = commitInfo.getTimeStamp();
((CDOBranchManagerImpl) service(BranchManager.class)).handleCommit(branch.getID(), commitTimestamp);
// send out the currently enqueued commit notification, if there is any (import might skip sending commit notifications until a certain point)
RepositoryCommitNotification notification = commitNotifications.remove(commitTimestamp);
if (notification == null) {
// make sure we always send out commit notification
// required in case of manual commit notifications via CDO API
notification = new RepositoryCommitNotification(id(),
CDOCommitInfoUtils.getUuid(commitInfo),
branch.getPathName(),
commitInfo.getTimeStamp(),
commitInfo.getUserID(),
commitInfo.getComment(),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList());
}
notification.publish(events());
}
}
@Override
public boolean isConsistent(IBranchPath branch) {
List<CDOCommitInfo> cdoCommitInfos = getCDOCommitInfos(branch);
CommitInfos indexCommitInfos = getIndexCommitInfos(branch);
boolean emptyDb = cdoCommitInfos.isEmpty();
boolean emptyIndex = indexCommitInfos.getItems().isEmpty();
if (emptyDb && emptyIndex) {
return true; // empty dataset
}
if (emptyDb ^ emptyIndex) {
LOG.error("{} is in inconsistent state. CDO {} but INDEX {}", getCdoRepository().getRepositoryName(), contentMessage(emptyDb), contentMessage(emptyIndex));
return false; // either CDO or index was deleted but not the other.
}
return !hasInvalidCDOTimeStamps(cdoCommitInfos, getLast(indexCommitInfos).getTimeStamp(), branch);
}
private boolean hasInvalidCDOTimeStamps(List<CDOCommitInfo> cdoCommitInfos, long lastIndexCommitTimestamp, IBranchPath branch) {
// expect all the commit infos to be invalid
List<CDOCommitInfo> problematicCommitInfos = Lists.newArrayList(cdoCommitInfos);
Iterator<CDOCommitInfo> cdoCommitInfosIterator = problematicCommitInfos.iterator();
while (cdoCommitInfosIterator.hasNext()) {
CDOCommitInfo cdoCommitInfo = cdoCommitInfosIterator.next();
if (cdoCommitInfo.getTimeStamp() <= lastIndexCommitTimestamp) {
//removing valid commits from the problematic list
cdoCommitInfosIterator.remove();
}
}
if (!problematicCommitInfos.isEmpty()) {
LOG.error("Index must be re-initialized for repository: {}. (The database is ahead of the index's timestamp: {} with CDO commit timestamp(s): {})", getCdoRepository().getRepositoryName(), lastIndexCommitTimestamp, transform(problematicCommitInfos, item -> item.getTimeStamp()));
return true;
} else if (getLast(cdoCommitInfos).getTimeStamp() < lastIndexCommitTimestamp) {
LOG.error("Database inconsistency for repository: {}. (The index head timestamp: {} is ahead of CDO's head timestamp : {})", getCdoRepository().getRepositoryName(), lastIndexCommitTimestamp, getLast(cdoCommitInfos).getTimeStamp());
return true;
} else {
LOG.info("{}'s {} branch's head CDO timestamp is: {} ", getCdoRepository().getRepositoryName(), branch.getPath(), Iterables.getLast(cdoCommitInfos).getTimeStamp());
LOG.info("{}'s {} branch's head INDEX timestamp is: {} ", getCdoRepository().getRepositoryName(), branch.getPath(), lastIndexCommitTimestamp);
return false;
}
}
private List<CDOCommitInfo> getCDOCommitInfos(IBranchPath branchPath) {
long baseTimestamp = getBaseTimestamp(getCdoMainBranch());
long headTimestamp = getHeadTimestamp(getCdoMainBranch());
Map<String, IBranchPath> branchPathMap = ImmutableMap.of(repositoryId, branchPath);
final CDOCommitInfoQuery query = new CDOCommitInfoQuery(branchPathMap)
.setStartTime(baseTimestamp)
.setEndTime(headTimestamp);
final ConsumeAllCommitInfoHandler handler = new ConsumeAllCommitInfoHandler();
CDOCommitInfoUtils.getCommitInfos(query, handler);
return handler.getInfos();
}
private CommitInfos getIndexCommitInfos(IBranchPath branch) {
RepositoryContext context = get(this, repositoryId);
CommitInfos commitInfos = RepositoryRequests
.commitInfos()
.prepareSearchCommitInfo()
.filterByBranch(branch.getPath())
.all()
.build()
.execute(context);
return commitInfos;
}
private String contentMessage(boolean empty) {
return empty ? "IS EMPTY" : "HAS CONTENT";
}
}
| APDS-124 removed Searcher registration | core/com.b2international.snowowl.datastore.server/src/com/b2international/snowowl/datastore/server/internal/CDOBasedRepository.java | APDS-124 removed Searcher registration | <ide><path>ore/com.b2international.snowowl.datastore.server/src/com/b2international/snowowl/datastore/server/internal/CDOBasedRepository.java
<ide> import com.b2international.index.IndexClientFactory;
<ide> import com.b2international.index.IndexWrite;
<ide> import com.b2international.index.Indexes;
<del>import com.b2international.index.Searcher;
<ide> import com.b2international.index.Writer;
<ide> import com.b2international.index.mapping.Mappings;
<ide> import com.b2international.index.query.slowlog.SlowLogConfig;
<ide> bind(RevisionIndex.class, revisionIndex);
<ide> // initialize the index
<ide> index.admin().create();
<del> getDelegate().services().registerService(Searcher.class, indexClient.searcher());
<ide> }
<ide>
<ide> private Map<String, Object> initIndexSettings() {
<ide> }
<ide>
<ide> private CommitInfos getIndexCommitInfos(IBranchPath branch) {
<del> RepositoryContext context = get(this, repositoryId);
<del>
<del> CommitInfos commitInfos = RepositoryRequests
<add> return RepositoryRequests
<ide> .commitInfos()
<ide> .prepareSearchCommitInfo()
<ide> .filterByBranch(branch.getPath())
<ide> .all()
<del> .build()
<del> .execute(context);
<del>
<del> return commitInfos;
<add> .build(repositoryId)
<add> .execute(events())
<add> .getSync();
<ide> }
<ide>
<ide> private String contentMessage(boolean empty) { |
|
JavaScript | mit | 93037b5a2e4e10885b0be3a52aa3a868210c892b | 0 | Factlink/factlink-core,daukantas/factlink-core,Factlink/factlink-core,daukantas/factlink-core,daukantas/factlink-core,daukantas/factlink-core,Factlink/factlink-core,Factlink/factlink-core | //= require jquery
var // The iFrame
showFrame = document.getElementById("frame"),
xdm = window.easyXDM.noConflict("FACTLINK"),
// The global remote object
remote = new xdm.Rpc({}, {
remote: {
hide: {},
show: {},
highlightNewFactlink: {},
stopHighlightingFactlink: {},
createdNewFactlink: {}
},
local: {
showFactlink: function(id, successFn) {
var successCalled = 0;
var onLoadSuccess = function(){
if (! successCalled ){
successCalled++;
successFn();
}
}
showFrame.onload = onLoadSuccess;
// Somehow only lower case letters seem to work for those events --mark
$(document).bind("modalready", onLoadSuccess);
showFrame.src = "/facts/" + id + "?layout=client";
// Show the overlay
showFrame.className = "overlay";
},
prepareNewFactlink: function(text, siteUrl, siteTitle, successFn, errorFn) {
var successCalled = 0;
var onLoadSuccess = function() {
if (! successCalled ){
successCalled++;
if ( $.isFunction( successFn ) ) {
successFn();
}
}
};
showFrame.onload = onLoadSuccess;
// Somehow only lower case letters seem to work for those events --mark
$(document).bind("modalready", onLoadSuccess);
showFrame.src = "/facts/new" +
"?fact=" + encodeURIComponent(text) +
"&url=" + encodeURIComponent(siteUrl) +
"&title=" + encodeURIComponent(siteTitle) +
"&layout=client";
// Show the overlay
showFrame.className = "overlay";
var onFactlinkCreated = function(e, id) {
remote.highlightNewFactlink(text, id);
}
$(document).bind("factlinkCreated", onFactlinkCreated);
},
position: function(top, left) {
try {
showFrame.contentWindow.position(top, left);
} catch (e) { // Window not yet loaded
showFrame.onload = function() {
showFrame.contentWindow.position(top, left);
};
}
},
// easyXDM does not support passing functions wrapped in objects (such as options in this case)
// so therefore we need this workaround
ajax: function(path, options, successFn, errorFn) {
ajax(path, $.extend({
success: successFn,
error: errorFn
},options));
}
}
});
function ajax(path, options) {
$.ajax(path, $.extend({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
}, options));
}
| core/app/assets/javascripts/intermediate.js | //= require jquery
var // The iFrame
showFrame = document.getElementById("frame"),
xdm = window.easyXDM.noConflict("FACTLINK"),
// The global remote object
remote = new xdm.Rpc({}, {
remote: {
hide: {},
show: {},
highlightNewFactlink: {},
stopHighlightingFactlink: {},
createdNewFactlink: {}
},
local: {
showFactlink: function(id, successFn) {
var successCalled = 0;
var onLoadSuccess = function(){
if (! successCalled ){
successCalled++;
successFn();
}
}
showFrame.onload = onLoadSuccess;
// Somehow only lower case letters seem to work for those events --mark
$(document).bind("modalready", onLoadSuccess);
showFrame.src = "/facts/" + id + "?layout=client";
// Show the overlay
showFrame.className = "overlay";
},
prepareNewFactlink: function(text, siteUrl, siteTitle, successFn, errorFn) {
var successCalled = 0;
var onLoadSuccess = function() {
if (! successCalled ){
successCalled++;
if ( $.isFunction( successFn ) ) {
successFn();
}
}
};
showFrame.onload = onLoadSuccess;
// Somehow only lower case letters seem to work for those events --mark
$(document).bind("modalready", onLoadSuccess);
showFrame.src = "/facts/new" +
"?fact=" + text +
"&url=" + siteUrl +
"&title=" + siteTitle +
"&layout=client";
// Show the overlay
showFrame.className = "overlay";
var onFactlinkCreated = function(e, id) {
remote.highlightNewFactlink(text, id);
}
$(document).bind("factlinkCreated", onFactlinkCreated);
},
position: function(top, left) {
try {
showFrame.contentWindow.position(top, left);
} catch (e) { // Window not yet loaded
showFrame.onload = function() {
showFrame.contentWindow.position(top, left);
};
}
},
// easyXDM does not support passing functions wrapped in objects (such as options in this case)
// so therefore we need this workaround
ajax: function(path, options, successFn, errorFn) {
ajax(path, $.extend({
success: successFn,
error: errorFn
},options));
}
}
});
function ajax(path, options) {
$.ajax(path, $.extend({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
}, options));
}
| encodeURIComponent before using them in URL's
Had a site with a "#" in the title which borked up the layout completely
| core/app/assets/javascripts/intermediate.js | encodeURIComponent before using them in URL's | <ide><path>ore/app/assets/javascripts/intermediate.js
<ide> $(document).bind("modalready", onLoadSuccess);
<ide>
<ide> showFrame.src = "/facts/new" +
<del> "?fact=" + text +
<del> "&url=" + siteUrl +
<del> "&title=" + siteTitle +
<add> "?fact=" + encodeURIComponent(text) +
<add> "&url=" + encodeURIComponent(siteUrl) +
<add> "&title=" + encodeURIComponent(siteTitle) +
<ide> "&layout=client";
<ide> // Show the overlay
<ide> showFrame.className = "overlay"; |
|
JavaScript | mit | a141fbe078f0ab14bbef3faace2aa4effb89058f | 0 | panpawn/Pokemon-Showdown,Gold-Solox/Pokemon-Showdown,Tesarand/Pokemon-Showdown,panpawn/Gold-Server,BuzzyOG/Pokemon-Showdown,panpawn/Gold-Server,BuzzyOG/Pokemon-Showdown,Tesarand/Pokemon-Showdown,Git-Worm/City-PS,panpawn/Pokemon-Showdown,BuzzyOG/Pokemon-Showdown,Git-Worm/City-PS,Tesarand/Pokemon-Showdown,Gold-Solox/Pokemon-Showdown,panpawn/Gold-Server | /**
* Commands
* Pokemon Showdown - http://pokemonshowdown.com/
*
* These are commands. For instance, you can define the command 'whois'
* here, then use it by typing /whois into Pokemon Showdown.
*
* A command can be in the form:
* ip: 'whois',
* This is called an alias: it makes it so /ip does the same thing as
* /whois.
*
* But to actually define a command, it's a function:
* birkal: function(target, room, user) {
* this.sendReply("It's not funny anymore.");
* },
*
* Commands are actually passed five parameters:
* function(target, room, user, connection, cmd, message)
* Most of the time, you only need the first three, though.
*
* target = the part of the message after the command
* room = the room object the message was sent to
* The room name is room.id
* user = the user object that sent the message
* The user's name is user.name
* connection = the connection that the message was sent from
* cmd = the name of the command
* message = the entire message sent by the user
*
* If a user types in "/msg zarel, hello"
* target = "zarel, hello"
* cmd = "msg"
* message = "/msg zarel, hello"
*
* Commands return the message the user should say. If they don't
* return anything or return something falsy, the user won't say
* anything.
*
* Commands have access to the following functions:
*
* this.sendReply(message)
* Sends a message back to the room the user typed the command into.
*
* this.sendReplyBox(html)
* Same as sendReply, but shows it in a box, and you can put HTML in
* it.
*
* this.popupReply(message)
* Shows a popup in the window the user typed the command into.
*
* this.add(message)
* Adds a message to the room so that everyone can see it.
* This is like this.sendReply, except everyone in the room gets it,
* instead of just the user that typed the command.
*
* this.send(message)
* Sends a message to the room so that everyone can see it.
* This is like this.add, except it's not logged, and users who join
* the room later won't see it in the log, and if it's a battle, it
* won't show up in saved replays.
* You USUALLY want to use this.add instead.
*
* this.logEntry(message)
* Log a message to the room's log without sending it to anyone. This
* is like this.add, except no one will see it.
*
* this.addModCommand(message)
* Like this.add, but also logs the message to the moderator log
* which can be seen with /modlog.
*
* this.logModCommand(message)
* Like this.addModCommand, except users in the room won't see it.
*
* this.can(permission)
* this.can(permission, targetUser)
* Checks if the user has the permission to do something, or if a
* targetUser is passed, check if the user has permission to do
* it to that user. Will automatically give the user an "Access
* denied" message if the user doesn't have permission: use
* user.can() if you don't want that message.
*
* Should usually be near the top of the command, like:
* if (!this.can('potd')) return false;
*
* this.canBroadcast()
* Signifies that a message can be broadcast, as long as the user
* has permission to. This will check to see if the user used
* "!command" instead of "/command". If so, it will check to see
* if the user has permission to broadcast (by default, voice+ can),
* and return false if not. Otherwise, it will set it up so that
* this.sendReply and this.sendReplyBox will broadcast to the room
* instead of just the user that used the command.
*
* Should usually be near the top of the command, like:
* if (!this.canBroadcast()) return false;
*
* this.canTalk()
* Checks to see if the user can speak in the room. Returns false
* if the user can't speak (is muted, the room has modchat on, etc),
* or true otherwise.
*
* Should usually be near the top of the command, like:
* if (!this.canTalk()) return false;
*
* this.canTalk(message)
* Checks to see if the user can say the message. In addition to
* running the checks from this.canTalk(), it also checks to see if
* the message has any banned words or is too long. Returns the
* filtered message, or a falsy value if the user can't speak.
*
* Should usually be near the top of the command, like:
* target = this.canTalk(target);
* if (!target) return false;
*
* this.parse(message)
* Runs the message as if the user had typed it in.
*
* Mostly useful for giving help messages, like for commands that
* require a target:
* if (!target) return this.parse('/help msg');
*
* After 10 levels of recursion (calling this.parse from a command
* called by this.parse from a command called by this.parse etc)
* we will assume it's a bug in your command and error out.
*
* this.targetUserOrSelf(target)
* If target is blank, returns the user that sent the message.
* Otherwise, returns the user with the username in target, or
* a falsy value if no user with that username exists.
*
* this.splitTarget(target)
* Splits a target in the form "user, message" into its
* constituent parts. Returns message, and sets this.targetUser to
* the user, and this.targetUsername to the username.
*
* Remember to check if this.targetUser exists before going further.
*
* Unless otherwise specified, these functions will return undefined,
* so you can return this.sendReply or something to send a reply and
* stop the command there.
*
* @license MIT license
*/
var commands = exports.commands = {
ip: 'whois',
getip: 'whois',
rooms: 'whois',
altcheck: 'whois',
alt: 'whois',
alts: 'whois',
getalts: 'whois',
whois: function(target, room, user) {
var targetUser = this.targetUserOrSelf(target, user.group === ' ');
if (!targetUser) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
this.sendReply('User: '+targetUser.name);
if (user.can('alts', targetUser)) {
var alts = targetUser.getAlts();
var output = '';
for (var i in targetUser.prevNames) {
if (output) output += ", ";
output += targetUser.prevNames[i];
}
if (output) this.sendReply('Previous names: '+output);
for (var j=0; j<alts.length; j++) {
var targetAlt = Users.get(alts[j]);
if (!targetAlt.named && !targetAlt.connected) continue;
if (targetAlt.group === '~' && user.group !== '~') continue;
this.sendReply('Alt: '+targetAlt.name);
output = '';
for (var i in targetAlt.prevNames) {
if (output) output += ", ";
output += targetAlt.prevNames[i];
}
if (output) this.sendReply('Previous names: '+output);
}
}
if (config.groups[targetUser.group] && config.groups[targetUser.group].name) {
this.sendReply('Group: ' + config.groups[targetUser.group].name + ' (' + targetUser.group + ')');
}
if (targetUser.goldDev) {
this.sendReply('(Gold Development Staff)');
}
if (targetUser.vipUser) {
this.sendReply('(<font color="gold">VIP</font> User)');
}
if (targetUser.isSysop) {
this.sendReply('(Pok\xE9mon Showdown System Operator)');
}
if (!targetUser.authenticated) {
this.sendReply('(Unregistered)');
}
if (!this.broadcasting && (user.can('ip', targetUser) || user === targetUser)) {
var ips = Object.keys(targetUser.ips);
this.sendReply('IP' + ((ips.length > 1) ? 's' : '') + ': ' + ips.join(', '));
}
if (targetUser.canCustomSymbol || targetUser.canCustomAvatar || targetUser.canAnimatedAvatar || targetUser.canChatRoom || targetUser.canTrainerCard || targetUser.canFixItem || targetUser.canDecAdvertise || targetUser.canBadge || targetUser.canPOTD || targetUser.canForcerename || targetUser.canMusicBox) {
var i = '';
if (targetUser.canCustomSymbol) i += ' Custom Symbol';
if (targetUser.canCustomAvatar) i += ' Custom Avatar';
if (targetUser.canAnimatedAvatar) i += ' Animated Avatar';
if (targetUser.canChatRoom) i += ' Chat Room';
if (targetUser.canTrainerCard) i += ' Trainer Card';
if (targetUser.canFixItem) i += ' Alter card/avatar/music box';
if (targetUser.canDecAdvertise) i += ' Declare Advertise';
if (targetUser.canBadge) i += ' VIP Badge / Global Voice';
if (targetUser.canMusicBox) i += ' Music Box';
if (targetUser.canPOTD) i += ' POTD';
if (targetUser.canForcerename) i += ' Forcerename'
this.sendReply('Eligible for: ' + i);
}
if (targetUser.canVIP) {
var i = '';
if (targetUser.canVIP) i += '(VIP User)';
this.sendReply(i);
}
var output = 'In rooms: ';
var first = true;
for (var i in targetUser.roomCount) {
if (i === 'global' || Rooms.get(i).isPrivate) continue;
if (!first) output += ' | ';
first = false;
output += '<a href="/'+i+'" room="'+i+'">'+i+'</a>';
}
if (!targetUser.connected || targetUser.isAway) {
this.sendReply('|raw|This user is ' + ((!targetUser.connected) ? '<font color = "red">offline</font>.' : '<font color = "orange">away</font>.'));
}
this.sendReply('|raw|'+output);
},
fork: function(target, room, user) {
if (!this.canBroadcast()) return;
if (!this.canTalk()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/HrDUGmr.png" width=75 height= 100>');
this.add('|c|@fork| .3. ``**(fork\'d by '+user.name+')**``');
},
zarel: function (target, room, user, connection, cmd) {
if (!this.canTalk()) return;
this.add('|c|~Zarel| heh ``**(zarel\'d by '+user.name+')**``');
},
aip: 'inprivaterooms',
awhois: 'inprivaterooms',
allrooms: 'inprivaterooms',
prooms: 'inprivaterooms',
adminwhois: 'inprivaterooms',
inprivaterooms: function(target, room, user) {
if (!this.can('seeprivaterooms')) return false;
var targetUser = this.targetUserOrSelf(target);
if (!targetUser) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
this.sendReply('User: '+targetUser.name);
if (user.can('seeprivaterooms',targetUser)) {
var alts = targetUser.getAlts();
var output = '';
for (var i in targetUser.prevNames) {
if (output) output += ", ";
output += targetUser.prevNames[i];
}
if (output) this.sendReply('Previous names: '+output);
for (var j=0; j<alts.length; j++) {
var targetAlt = Users.get(alts[j]);
if (!targetAlt.named && !targetAlt.connected) continue;
this.sendReply('Alt: '+targetAlt.name);
output = '';
for (var i in targetAlt.prevNames) {
if (output) output += ", ";
output += targetAlt.prevNames[i];
}
if (output) this.sendReply('Previous names: '+output);
}
}
if (config.groups[targetUser.group] && config.groups[targetUser.group].name) {
this.sendReply('Group: ' + config.groups[targetUser.group].name + ' (' + targetUser.group + ')');
}
if (targetUser.isSysop) {
this.sendReply('(Pok\xE9mon Showdown System Operator)');
}
if (targetUser.goldDev) {
this.sendReply('(Gold Development Staff)');
}
if (!targetUser.authenticated) {
this.sendReply('(Unregistered)');
}
if (!this.broadcasting && (user.can('ip', targetUser) || user === targetUser)) {
var ips = Object.keys(targetUser.ips);
this.sendReply('IP' + ((ips.length > 1) ? 's' : '') + ': ' + ips.join(', '));
}
var output = 'In all rooms: ';
var first = false;
for (var i in targetUser.roomCount) {
if (i === 'global' || Rooms.get(i).isPublic) continue;
if (!first) output += ' | ';
first = false;
output += '<a href="/'+i+'" room="'+i+'">'+i+'</a>';
}
this.sendReply('|raw|'+output);
},
ipsearch: function(target, room, user) {
if (!this.can('rangeban')) return;
var atLeastOne = false;
this.sendReply("Users with IP "+target+":");
for (var userid in Users.users) {
var user = Users.users[userid];
if (user.latestIp === target) {
this.sendReply((user.connected?"+":"-")+" "+user.name);
atLeastOne = true;
}
}
if (!atLeastOne) this.sendReply("No results found.");
},
gdeclarered: 'gdeclare',
gdeclaregreen: 'gdeclare',
gdeclare: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help gdeclare');
if (!this.can('lockdown')) return false;
var roomName = (room.isPrivate)? 'a private room' : room.id;
if (cmd === 'gdeclare'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
if (cmd === 'gdeclarered'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
else if (cmd === 'gdeclaregreen'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
this.logEntry(user.name + ' used /gdeclare');
},
declaregreen: 'declarered',
declarered: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help declare');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
if (cmd === 'declarered'){
this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>');
}
else if (cmd === 'declaregreen'){
this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>');
}
this.logModCommand(user.name+' declared '+target);
},
declaregreen: 'declarered',
declarered: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help declare');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
if (cmd === 'declarered'){
this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>');
}
else if (cmd === 'declaregreen'){
this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>');
}
this.logModCommand(user.name+' declared '+target);
},
pdeclare: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help declare');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
if (cmd === 'pdeclare'){
this.add('|raw|<div class="broadcast-purple"><b>'+target+'</b></div>');
}
else if (cmd === 'pdeclare'){
this.add('|raw|<div class="broadcast-purple"><b>'+target+'</b></div>');
}
this.logModCommand(user.name+' declared '+target);
},
k: 'kick',
aura: 'kick',
kick: function(target, room, user){
if (!this.can('lock')) return false;
if (!target) return this.sendReply('/help kick');
if (!this.canTalk()) return false;
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
if (!this.can('lock', targetUser, room)) return false;
this.addModCommand(targetUser.name+' was kicked from the room by '+user.name+'.');
targetUser.popup('You were kicked from '+room.id+' by '+user.name+'.');
targetUser.leaveRoom(room.id);
},
dm: 'daymute',
daymute: function(target, room, user) {
if (!target) return this.parse('/help daymute');
if (!this.canTalk()) return false;
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
if (!this.can('mute', targetUser, room)) return false;
if (((targetUser.mutedRooms[room.id] && (targetUser.muteDuration[room.id]||0) >= 50*60*1000) || targetUser.locked) && !target) {
var problem = ' but was already '+(!targetUser.connected ? 'offline' : targetUser.locked ? 'locked' : 'muted');
return this.privateModCommand('('+targetUser.name+' would be muted by '+user.name+problem+'.)');
}
targetUser.popup(user.name+' has muted you for 24 hours. '+target);
this.addModCommand(''+targetUser.name+' was muted by '+user.name+' for 24 hours.' + (target ? " (" + target + ")" : ""));
var alts = targetUser.getAlts();
if (alts.length) this.addModCommand(""+targetUser.name+"'s alts were also muted: "+alts.join(", "));
targetUser.mute(room.id, 24*60*60*1000, true);
},
flogout: 'forcelogout',
forcelogout: function(target, room, user) {
if(!user.can('hotpatch')) return;
if (!this.canTalk()) return false;
if (!target) return this.sendReply('/forcelogout [username], [reason] OR /flogout [username], [reason] - You do not have to add a reason');
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
if (targetUser.can('hotpatch')) return this.sendReply('You cannot force logout another Admin - nice try. Chump.');
this.addModCommand(''+targetUser.name+' was forcibly logged out by '+user.name+'.' + (target ? " (" + target + ")" : ""));
targetUser.resetName();
},
declaregreen: 'declarered',
declarered: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help declare');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
if (cmd === 'declarered'){
this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>');
}
else if (cmd === 'declaregreen'){
this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>');
}
this.logModCommand(user.name+' declared '+target);
},
gdeclarered: 'gdeclare',
gdeclaregreen: 'gdeclare',
gdeclare: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help gdeclare');
if (!this.can('lockdown')) return false;
var roomName = (room.isPrivate)? 'a private room' : room.id;
if (cmd === 'gdeclare'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
if (cmd === 'gdeclarered'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
else if (cmd === 'gdeclaregreen'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
this.logModCommand(user.name+' globally declared '+target);
},
sd: 'declaremod',
staffdeclare: 'declaremod',
modmsg: 'declaremod',
moddeclare: 'declaremod',
declaremod: function(target, room, user) {
if (!target) return this.sendReply('/declaremod [message] - Also /moddeclare and /modmsg');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
this.privateModCommand('|raw|<div class="broadcast-red"><b><font size=1><i>Private Auth (Driver +) declare from '+user.name+'<br /></i></font size>'+target+'</b></div>');
this.logModCommand(user.name+' mod declared '+target);
},
/*********************************************************
* Shortcuts
*********************************************************/
invite: function(target, room, user) {
target = this.splitTarget(target);
if (!this.targetUser) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
var roomid = (target || room.id);
if (!Rooms.get(roomid)) {
return this.sendReply('Room '+roomid+' not found.');
}
return this.parse('/msg '+this.targetUsername+', /invite '+roomid);
},
/*********************************************************
* Informational commands
*********************************************************/
stats: 'data',
dex: 'data',
pokedex: 'data',
data: function(target, room, user) {
if (!this.canBroadcast()) return;
var data = '';
var targetId = toId(target);
var newTargets = Tools.dataSearch(target);
if (newTargets && newTargets.length) {
for (var i = 0; i < newTargets.length; i++) {
if (newTargets[i].id !== targetId && !Tools.data.Aliases[targetId] && !i) {
data = "No Pokemon, item, move or ability named '" + target + "' was found. Showing the data of '" + newTargets[0].name + "' instead.\n";
}
data += '|c|~|/data-' + newTargets[i].searchType + ' ' + newTargets[i].name + '\n';
}
} else {
data = "No Pokemon, item, move or ability named '" + target + "' was found. (Check your spelling?)";
}
this.sendReply(data);
},
ds: 'dexsearch',
dsearch: 'dexsearch',
dexsearch: function (target, room, user) {
if (!this.canBroadcast()) return;
if (!target) return this.parse('/help dexsearch');
var targets = target.split(',');
var searches = {};
var allTiers = {'uber':1,'ou':1,'uu':1,'lc':1,'cap':1,'bl':1};
var allColours = {'green':1,'red':1,'blue':1,'white':1,'brown':1,'yellow':1,'purple':1,'pink':1,'gray':1,'black':1};
var showAll = false;
var megaSearch = null;
var output = 10;
for (var i in targets) {
var isNotSearch = false;
target = targets[i].trim().toLowerCase();
if (target.slice(0,1) === '!') {
isNotSearch = true;
target = target.slice(1);
}
var targetAbility = Tools.getAbility(targets[i]);
if (targetAbility.exists) {
if (!searches['ability']) searches['ability'] = {};
if (Object.count(searches['ability'], true) === 1 && !isNotSearch) return this.sendReplyBox('Specify only one ability.');
if ((searches['ability'][targetAbility.name] && isNotSearch) || (searches['ability'][targetAbility.name] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include an ability.');
searches['ability'][targetAbility.name] = !isNotSearch;
continue;
}
if (target in allTiers) {
if (!searches['tier']) searches['tier'] = {};
if ((searches['tier'][target] && isNotSearch) || (searches['tier'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a tier.');
searches['tier'][target] = !isNotSearch;
continue;
}
if (target in allColours) {
if (!searches['color']) searches['color'] = {};
if ((searches['color'][target] && isNotSearch) || (searches['color'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a color.');
searches['color'][target] = !isNotSearch;
continue;
}
var targetInt = parseInt(target);
if (0 < targetInt && targetInt < 7) {
if (!searches['gen']) searches['gen'] = {};
if ((searches['gen'][target] && isNotSearch) || (searches['gen'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a generation.');
searches['gen'][target] = !isNotSearch;
continue;
}
if (target === 'all') {
if (this.broadcasting) {
return this.sendReplyBox('A search with the parameter "all" cannot be broadcast.');
}
showAll = true;
continue;
}
if (target === 'megas' || target === 'mega') {
if ((megaSearch && isNotSearch) || (megaSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include Mega Evolutions.');
megaSearch = !isNotSearch;
continue;
}
if (target.indexOf(' type') > -1) {
target = target.charAt(0).toUpperCase() + target.slice(1, target.indexOf(' type'));
if (target in Tools.data.TypeChart) {
if (!searches['types']) searches['types'] = {};
if (Object.count(searches['types'], true) === 2 && !isNotSearch) return this.sendReplyBox('Specify a maximum of two types.');
if ((searches['types'][target] && isNotSearch) || (searches['types'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a type.');
searches['types'][target] = !isNotSearch;
continue;
}
}
var targetMove = Tools.getMove(target);
if (targetMove.exists) {
if (!searches['moves']) searches['moves'] = {};
if (Object.count(searches['moves'], true) === 4 && !isNotSearch) return this.sendReplyBox('Specify a maximum of 4 moves.');
if ((searches['moves'][targetMove.name] && isNotSearch) || (searches['moves'][targetMove.name] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a move.');
searches['moves'][targetMove.name] = !isNotSearch;
continue;
} else {
return this.sendReplyBox('"' + sanitize(target, true) + '" could not be found in any of the search categories.');
}
}
if (showAll && Object.size(searches) === 0 && megaSearch === null) return this.sendReplyBox('No search parameters other than "all" were found.\nTry "/help dexsearch" for more information on this command.');
var dex = {};
for (var pokemon in Tools.data.Pokedex) {
var template = Tools.getTemplate(pokemon);
if (template.tier !== 'Unreleased' && template.tier !== 'Illegal' && (template.tier !== 'CAP' || (searches['tier'] && searches['tier']['cap'])) &&
(megaSearch === null || (megaSearch === true && template.isMega) || (megaSearch === false && !template.isMega))) {
dex[pokemon] = template;
}
}
for (var search in {'moves':1,'types':1,'ability':1,'tier':1,'gen':1,'color':1}) {
if (!searches[search]) continue;
switch (search) {
case 'types':
for (var mon in dex) {
if (Object.count(searches[search], true) === 2) {
if (!(searches[search][dex[mon].types[0]]) || !(searches[search][dex[mon].types[1]])) delete dex[mon];
} else {
if (searches[search][dex[mon].types[0]] === false || searches[search][dex[mon].types[1]] === false || (Object.count(searches[search], true) > 0 &&
(!(searches[search][dex[mon].types[0]]) && !(searches[search][dex[mon].types[1]])))) delete dex[mon];
}
}
break;
case 'tier':
for (var mon in dex) {
if ('lc' in searches[search]) {
// some LC legal Pokemon are stored in other tiers (Ferroseed/Murkrow etc)
// this checks for LC legality using the going criteria, instead of dex[mon].tier
var isLC = (dex[mon].evos && dex[mon].evos.length > 0) && !dex[mon].prevo && Tools.data.Formats['lc'].banlist.indexOf(dex[mon].species) === -1;
if ((searches[search]['lc'] && !isLC) || (!searches[search]['lc'] && isLC)) {
delete dex[mon];
continue;
}
}
if (searches[search][String(dex[mon][search]).toLowerCase()] === false) {
delete dex[mon];
} else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon];
}
break;
case 'gen':
case 'color':
for (var mon in dex) {
if (searches[search][String(dex[mon][search]).toLowerCase()] === false) {
delete dex[mon];
} else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; }
break;
case 'ability':
for (var mon in dex) {
for (var ability in searches[search]) {
var needsAbility = searches[search][ability];
var hasAbility = Object.count(dex[mon].abilities, ability) > 0;
if (hasAbility !== needsAbility) {
delete dex[mon];
break;
}
}
}
break;
case 'moves':
for (var mon in dex) {
var template = Tools.getTemplate(dex[mon].id);
if (!template.learnset) template = Tools.getTemplate(template.baseSpecies);
if (!template.learnset) continue;
for (var i in searches[search]) {
var move = Tools.getMove(i);
if (!move.exists) return this.sendReplyBox('"' + move + '" is not a known move.');
var prevoTemp = Tools.getTemplate(template.id);
while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[move.id])) {
prevoTemp = Tools.getTemplate(prevoTemp.prevo);
}
var canLearn = (prevoTemp.learnset.sketch && !(move.id in {'chatter':1,'struggle':1,'magikarpsrevenge':1})) || prevoTemp.learnset[move.id];
if ((!canLearn && searches[search][i]) || (searches[search][i] === false && canLearn)) delete dex[mon];
}
}
break;
default:
return this.sendReplyBox("Something broke! PM TalkTakesTime here or on the Smogon forums with the command you tried.");
}
}
var results = Object.keys(dex).map(function(speciesid) {return dex[speciesid].species;});
var resultsStr = '';
if (results.length > 0) {
if (showAll || results.length <= output) {
results.sort();
resultsStr = results.join(', ');
} else {
results.sort(function(a,b) {return Math.round(Math.random());});
resultsStr = results.slice(0, 10).join(', ') + ', and ' + string(results.length - output) + ' more. Redo the search with "all" as a search parameter to show all results.';
}
} else {
resultsStr = 'No Pokรฉmon found.';
}
return this.sendReplyBox(resultsStr);
},
learnset: 'learn',
learnall: 'learn',
learn5: 'learn',
g6learn: 'learn',
learn: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help learn');
if (!this.canBroadcast()) return;
var lsetData = {set:{}};
var targets = target.split(',');
var template = Tools.getTemplate(targets[0]);
var move = {};
var problem;
var all = (cmd === 'learnall');
if (cmd === 'learn5') lsetData.set.level = 5;
if (cmd === 'g6learn') lsetData.format = {noPokebank: true};
if (!template.exists) {
return this.sendReply('Pokemon "'+template.id+'" not found.');
}
if (targets.length < 2) {
return this.sendReply('You must specify at least one move.');
}
for (var i=1, len=targets.length; i<len; i++) {
move = Tools.getMove(targets[i]);
if (!move.exists) {
return this.sendReply('Move "'+move.id+'" not found.');
}
problem = TeamValidator.checkLearnsetSync(null, move, template, lsetData);
if (problem) break;
}
var buffer = ''+template.name+(problem?" <span class=\"message-learn-cannotlearn\">can't</span> learn ":" <span class=\"message-learn-canlearn\">can</span> learn ")+(targets.length>2?"these moves":move.name);
if (!problem) {
var sourceNames = {E:"egg",S:"event",D:"dream world"};
if (lsetData.sources || lsetData.sourcesBefore) buffer += " only when obtained from:<ul class=\"message-learn-list\">";
if (lsetData.sources) {
var sources = lsetData.sources.sort();
var prevSource;
var prevSourceType;
for (var i=0, len=sources.length; i<len; i++) {
var source = sources[i];
if (source.substr(0,2) === prevSourceType) {
if (prevSourceCount < 0) buffer += ": "+source.substr(2);
else if (all || prevSourceCount < 3) buffer += ', '+source.substr(2);
else if (prevSourceCount == 3) buffer += ', ...';
prevSourceCount++;
continue;
}
prevSourceType = source.substr(0,2);
prevSourceCount = source.substr(2)?0:-1;
buffer += "<li>gen "+source.substr(0,1)+" "+sourceNames[source.substr(1,1)];
if (prevSourceType === '5E' && template.maleOnlyHidden) buffer += " (cannot have hidden ability)";
if (source.substr(2)) buffer += ": "+source.substr(2);
}
}
if (lsetData.sourcesBefore) buffer += "<li>any generation before "+(lsetData.sourcesBefore+1);
buffer += "</ul>";
}
this.sendReplyBox(buffer);
},
weak: 'weakness',
weakness: function(target, room, user){
if (!this.canBroadcast()) return;
var targets = target.split(/[ ,\/]/);
var pokemon = Tools.getTemplate(target);
var type1 = Tools.getType(targets[0]);
var type2 = Tools.getType(targets[1]);
if (pokemon.exists) {
target = pokemon.species;
} else if (type1.exists && type2.exists) {
pokemon = {types: [type1.id, type2.id]};
target = type1.id + "/" + type2.id;
} else if (type1.exists) {
pokemon = {types: [type1.id]};
target = type1.id;
} else {
return this.sendReplyBox(sanitize(target) + " isn't a recognized type or pokemon.");
}
var weaknesses = [];
Object.keys(Tools.data.TypeChart).forEach(function (type) {
var notImmune = Tools.getImmunity(type, pokemon);
if (notImmune) {
var typeMod = Tools.getEffectiveness(type, pokemon);
if (typeMod == 1) weaknesses.push(type);
if (typeMod == 2) weaknesses.push("<b>" + type + "</b>");
}
});
if (!weaknesses.length) {
this.sendReplyBox(target + " has no weaknesses.");
} else {
this.sendReplyBox(target + " is weak to: " + weaknesses.join(', ') + " (not counting abilities).");
}
},
eff: 'effectiveness',
type: 'effectiveness',
matchup: 'effectiveness',
effectiveness: function(target, room, user) {
var targets = target.split(/[,/]/).slice(0, 2);
if (targets.length !== 2) return this.sendReply("Attacker and defender must be separated with a comma.");
var searchMethods = {'getType':1, 'getMove':1, 'getTemplate':1};
var sourceMethods = {'getType':1, 'getMove':1};
var targetMethods = {'getType':1, 'getTemplate':1};
var source;
var defender;
var foundData;
var atkName;
var defName;
for (var i=0; i<2; i++) {
for (var method in searchMethods) {
foundData = Tools[method](targets[i]);
if (foundData.exists) break;
}
if (!foundData.exists) return this.parse('/help effectiveness');
if (!source && method in sourceMethods) {
if (foundData.type) {
source = foundData;
atkName = foundData.name;
} else {
source = foundData.id;
atkName = foundData.id;
}
searchMethods = targetMethods;
} else if (!defender && method in targetMethods) {
if (foundData.types) {
defender = foundData;
defName = foundData.species+" (not counting abilities)";
} else {
defender = {types: [foundData.id]};
defName = foundData.id;
}
searchMethods = sourceMethods;
}
}
if (!this.canBroadcast()) return;
var factor = 0;
if (Tools.getImmunity(source.type || source, defender)) {
if (source.effectType !== 'Move' || source.basePower || source.basePowerCallback) {
factor = Math.pow(2, Tools.getEffectiveness(source, defender));
} else {
factor = 1;
}
}
this.sendReplyBox(atkName+" is "+factor+"x effective against "+defName+".");
},
uptime: (function(){
function formatUptime(uptime) {
if (uptime > 24*60*60) {
var uptimeText = "";
var uptimeDays = Math.floor(uptime/(24*60*60));
uptimeText = uptimeDays + " " + (uptimeDays == 1 ? "day" : "days");
var uptimeHours = Math.floor(uptime/(60*60)) - uptimeDays*24;
if (uptimeHours) uptimeText += ", " + uptimeHours + " " + (uptimeHours == 1 ? "hour" : "hours");
return uptimeText;
} else {
return uptime.seconds().duration();
}
}
return function(target, room, user) {
if (!this.canBroadcast()) return;
var uptime = process.uptime();
this.sendReplyBox("Uptime: <b>" + formatUptime(uptime) + "</b>" +
(global.uptimeRecord ? "<br /><font color=\"green\">Record: <b>" + formatUptime(global.uptimeRecord) + "</b></font>" : ""));
};
})(),
groups: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('+ <b>Voice</b> - They can use ! commands like !groups, and talk during moderated chat<br />' +
'% <b>Driver</b> - The above, and they can mute. Global % can also lock users and check for alts<br />' +
'@ <b>Moderator</b> - The above, and they can ban users<br />' +
'& <b>Leader</b> - The above, and they can promote to moderator and force ties<br />' +
'~ <b>Administrator</b> - They can do anything, like change what this message says<br />' +
'# <b>Room Owner</b> - They are administrators of the room and can almost totally control it');
},
//Trainer Cards.
pan: 'panpawn',
panpawn: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/BYTR6Fj.gif width="80" height="80">' +
'<img src="http://i.imgur.com/xzfPeaL.gif">' +
'<img src="http://i.imgur.com/qzflcXa.gif"><br />' +
'<b><font color="#4F86F7">Ace:</font></b> <font color="red">C<font color="orange">y<font color="red">n<font color="orange">d<font color="red">a<font color="orange">q<font color="red">u<font color="orange">i<font color="red">l</font><br />' +
'<font color="black">"Don\'t touch me when I\'m sleeping."</font></center>');
},
popcorn: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://www.allgeekthings.co.uk/wp-content/uploads/Popcorn.gif">');
},
destiny: 'itsdestiny',
itsdestiny: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="4" color="green"><b>It$de$tiny</b></font><br>' +
'<img src="http://www.icleiusa.org/blog/library/images-phase1-051308/landscape/blog-images-90.jpg" width="55%"> <img src="http://mindmillion.com/images/money/money-background-seamless-fill-bluesky.jpg" width="35%"><br>' +
'It ain\'t luck, it\'s destiny.');
},
miah: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="3" color="orange"><b>Miah<br>' +
'<img src="https://i.imgur.com/2RHOuPi.gif" width="50%"><img src="https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-frc1/t1.0-9/1511712_629640560439158_8415184400256062344_n.jpg" width="50%"><br></font></b>' +
'Ace: Gliscor<br>Catch phrase: Adding Euphemisms to Pokemon');
},
drag: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="5" color="red">Akely</font><br>' +
'<img src="http://gamesloveres.com/wp-content/uploads/2014/03/cute-pokemon-charmandercharmander-by-inversidom-riot-on-deviantart-llfutuct.png" width="25%"><br>' +
'Ace: Charizard<br>' +
'"Real mens can cry but real mens doesn\'t give up."');
},
kricketune: 'kriัketunะต',
kriัketunะต: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/VPcZ1rC.png"><br>' +
'<img src="http://i.imgur.com/NKGYqpn.png" width="50%"><br>' +
'Ace: Donnatello<br>' +
'"At day I own the streets, but at night I own the closet..."');
},
crowt: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><div class="infobox"><img src="http://i.imgur.com/BYTR6Fj.gif width="80" height="80" align="left">' +
' <img src="http://i.imgur.com/czMd1X5.gif" border="6" align="center">' +
' <img src="http://50.62.73.114:8000/avatars/crowt.png" align="right"><br clear="all" /></div>' +
'<blink><font color="red">~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</font></blink><br />' +
'<div class="infobox"><b><font color="#4F86F7" size="3">Ace:</font></b> <font color="blue" size="3">G</font><font color="black" size="3">r</font><font color="blue" size="3">e</font><font color="black" size="3">n</font><font color="blue" size="3">i</font><font color="black" size="3">n</font><font color="blue" size="3">j</font><font color="black" size="3">a</font></font><br />' +
'<font color="black">"It takes a great deal of <b>bravery</b> to <b>stand up to</b> our <b>enemies</b>, but just as much to stand up to our <b>friends</b>." - Dumbledore</font></center></div>');
},
ransu: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/kWaZd66.jpg" width="40%"><br>Develop a passion for learning. If you do, you will never cease to grow.');
},
panbox: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Panpawn\'s Music Box!</b><br>' +
'<center><img src="http://www.clipartbest.com/cliparts/ncE/eXz/ncEeXzpcA.svg" align="right" width="10%"></center><br>' +
'1. <a href="https://www.youtube.com/watch?v=EJR5A2dttp8"><button title="Let It Go - Connie Talbot cover">Let It Go - Connie Talbot cover</a></button><br>' +
'2. <a href="https://www.youtube.com/watch?v=Y2Ta0qCG8No"><button title="Crocodile Rock - Elton John">Crocodile Rock - Elton John</a></button><br>' +
'3. <a href="https://www.youtube.com/watch?v=ZA3vZwxnKnE"><button title="My Angel Gabriel - Lamb">My Angel Gabriel - Lamb</a></button><br>' +
'4. <a href="https://www.youtube.com/watch?v=y8AWFf7EAc4"><button title="Hallelujah - Jeff Buckley">Hallelujah - Jeff Buckley</a></button><br>' +
'5. <a href="https://www.youtube.com/watch?v=aFIApXs0_Nw"><button title="Better Off Dead - Elton John">Better Off Dead - Elton John</a></button><br>' +
'6. <a href="https://www.youtube.com/watch?v=eJLTGHEwaR8"><button title="Your Song - Carly Rose Sonenclar cover">Your Song - Carly Rose Sonenclar cover</a></button>');
},
lazerbox: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>lazerbeam\'s Music Box!</b><br>' +
'<center><img src="http://www.clipartbest.com/cliparts/ncE/eXz/ncEeXzpcA.svg" align="right" width="10%"></center><br>' +
'1. <a href="https://www.youtube.com/watch?v=fJ9rUzIMcZQ"><button title="Bohemian Rhapsody - Queen">Bohemian Rhapsody - Queen</a></button><br>' +
'2. <a href="https://www.youtube.com/watch?v=ZNaA7fVXB28"><button title="Against the Wind - Bob Seger">Against the Wind - Bob Seger</a></button><br>' +
'3. <a href="https://www.youtube.com/watch?v=TuCGiV-EVjA"><button title="Livin\' on the Edge - Aerosmith">Livin\' on the Edge - Aerosmith</a></button><br>' +
'4. <a href="https://www.youtube.com/watch?v=QZ_kYEDZVno"><button title="Rock and Roll Never Forgets - Bob Seger">Rock and Roll Never Forgets - Bob Seger</a></button><br>' +
'5. <a href="https://www.youtube.com/watch?v=GHjKEwV2-ZM"><button title="Jaded - Aerosmith">Jaded - Aerosmith</a></button>');
},
berry: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://blog.flamingtext.com/blog/2014/04/02/flamingtext_com_1396402375_186122138.png" width="50%"><br>' +
'<img src="http://50.62.73.114:8000/avatars/theberrymaster.gif"><br>' +
'Cherrim-Sunshine<br>' +
'I don\'t care what I end up being as long as I\'m a legend.');
},
moist: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://fc04.deviantart.net/fs70/i/2010/338/6/3/moister_by_arvalis-d347xgw.jpg" width="50%">');
},
spydreigon: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/57drGn3.jpg" width="75%"><br>' +
'<img src="http://fc00.deviantart.net/fs70/f/2013/102/8/3/hydreigon___draco_meteor_by_ishmam-d61irtz.png" width="75%"><br>' +
'You wish you were as badass as me');
},
mushy: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="3" color="purple">Mushy</font><br>' +
'<img src="http://i.imgur.com/yK6aCZH.png"><br>' +
'Life often causes us pain, so I try to fill it up with pleasure instead. Do you want a taste? ;)');
},
furgo: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/0qJzTgP.gif" width="25%"><br><font color="red">Ace:</font><br><img src="http://amethyst.xiaotai.org:2000/avatars/furgo.gif"><br>When I\'m sleeping, do not poke me. :I');
},
blazingflareon: 'bf',
bf: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/h3ZTk9u.gif"><br><img src="http://fc08.deviantart.net/fs71/i/2012/251/3/f/flareon_coloured_lineart_by_noel_tf-d5e166e.jpg" width="25%"><br><font size="3" color="red"><u><b><i>DARE TO DREAM');
},
mikado: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/oS2jnht.gif"><br><img src="http://i.imgur.com/oKEA0Om.png"');
},
dsg:'darkshinygiratina',
darkshinygiratina: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="4" color="blue" face="arial">DarkShinyGiratina</font><br><img src="http://i.imgur.com/sBIqMv8.gif"><br>I\'m gonna use Shadow Force on you!');
},
archbisharp: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/ibC46tQ.png"><br><img src="http://fc07.deviantart.net/fs70/f/2012/294/f/c/bisharp_by_xdarkblaze-d5ijnsf.gif" width="350" hieght="350"><br></font><b>Ruling you with an Iron Head.');
},
chimplup: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Chimplup</b> - The almighty ruler of chimchars and piplups alike, also likes pie.<br />');
},
shephard: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Shephard</b> - King Of Water and Ground types.<br />');
},
logic: 'psychological',
psychological: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/c4j9EdJ.png?1">' +
'<img src="http://i.imgur.com/tRRas7O.gif" width="200">' +
'<img src="http://i.imgur.com/TwpGsh3.png?1"><br />' +
'<img src="http://i.imgur.com/1MH0mJM.png" height="90">' +
'<img src="http://i.imgur.com/TSEXdOm.gif" width="300">' +
'<img src="http://i.imgur.com/4XlnMPZ.png" height="90"><br />' +
'If it isn\'t logical, it\'s probably Psychological.</center>');
},
seed: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Seed</b> - /me plant and water<br />');
},
auraburst: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="orange"><font size="2"><img src="http://i.imgur.com/9guvnD7.jpg"> <b>Aura Butt</b><font size="orange"><font size="2"> - Nick Cage. <img src="http://i.imgur.com/9guvnD7.jpg"><br />');
},
leo: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Leonardo DiCaprio</b> - Mirror mirror on the wall, who is the chillest of them all?<br />');
},
kupo: 'moogle',
moogle: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://50.62.73.114:8000/avatars/kupo.png"><br><b>Kupo</b> - abc!<br />');
},
starmaster: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Starmaster</b> - Well what were you expecting. Master of stars. Duh<br />');
},
ryun: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Ryun</b> - Will fuck your shit up with his army of Gloom, Chimecho, Duosion, Dunsparce, Plusle and Mr. Mime<br />');
},
miikasa: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://fc06.deviantart.net/fs70/f/2010/330/2/0/cirno_neutral_special_by_generalcirno-d33ndj0.gif"><br><font color="purple"><font size="2"><b>Miikasa</b><font color="purple"><font size="2"> - There are no buses in Gensokyo.<br />');
},
poliii: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/GsI3Y75.jpg"><br><font color="blue"><font size="2"><b>Poliii</b><font color="blue"><font size="2"> - Greninja is behind you.<br />');
},
frozengrace: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>FrozenGrace</b> - The gentle wind blows as the song birds sing of her vibrant radiance. The vibrant flowers and luscious petals dance in the serenading wind, welcoming her arrival for the epitome of all things beautiful. Bow down to her majesty for she is the Queen. Let her bestow upon you as she graces you with her elegance. FrozenGrace, eternal serenity.<br />');
},
awk: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Awk</b> - I have nothing to say to that!<br />');
},
screamingmilotic: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>ScreamingMilotic</b> - The shiny Milotic that wants to take over the world.<br />');
},
aikenkรก: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://fc05.deviantart.net/fs70/f/2010/004/3/4/Go_MAGIKARP_use_your_Splash_by_JoshR691.gif"><b><font size="2"><font color="blue">Aikenkรก</b><font size="2"><font color="blue"> - The Master of the imp.<img src="http://fc05.deviantart.net/fs70/f/2010/004/3/4/Go_MAGIKARP_use_your_Splash_by_JoshR691.gif"><br />');
},
ipad: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/miLUHTz.png"><br><b>iPood</b><br> - A total <font color="brown">pos</font> that panpawn will ban.<br><img src="http://i.imgur.com/miLUHTz.png"><br />');
},
rhan: 'rohansound',
rohansound: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="orange"><font size="2"><b>Rohansound</b><font size="orange"><font size="2"> - The master of the Snivy!<br />');
},
alittlepaw: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://fc00.deviantart.net/fs71/f/2013/025/5/d/wolf_dance_by_windwolf13-d5sq93d.gif"><br><font color="green"><font size="3"><b>ALittlePaw</b> - Fenrir would be proud.<br />');
},
smashbrosbrawl: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>SmashBrosBrawl</b> - Christian Bale<br />');
},
w00per: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/i3FYyoG.gif"><br><font size="2"><font color="brown"><b>W00per</b><font size="2"><font color="brown"> - "I CAME IN LIKE `EM WRECKIN` BALLZ!<br />');
},
empoleonxv: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/IHd5yRT.gif"><br><img src="http://i.imgur.com/sfQsRlH.gif"><br><b><font color="33FFFF"><big>Smiling and Waving can\'t make you more cute than me!');
},
foe: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://s21.postimg.org/durjqji4z/aaaaa.gif"><br><font size="2"><b>Foe</b><font size="2"> - Not a friend.<br />');
},
op: 'orangepoptarts',
orangepoptarts: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://www.jeboavatars.com/images/avatars/192809169066sunsetbeach.jpg"><br><b><font size="2">Orange Poptarts</b><font size="2"> - "Pop, who so you" ~ ALittlePaw<br />');
},
jack: 'jackzero',
jackzero: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="4" color="aqua">JackZero<br></font><img src="http://i.imgur.com/cE6LTKm.png"><br>I prefer the freedom of being hated to the shackles of expectaional love.<br>"Half as long, twice as bright.."');
},
wd: 'windoge',
windoge: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/qYTABJC.jpg" width="400">');
},
party: 'dance',
dance: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://collegecandy.files.wordpress.com/2013/05/tumblr_inline_mhv5qyiqvk1qz4rgp1.gif" width="400">');
},
kayo: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="2"><b>Kayo</b><br>By the Beard of Zeus that Ghost was Fat<br><img src="http://i.imgur.com/rPe9hBa.png">');
},
saburo: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font color="red" size="5"><b>Saburo</font></b><br><img src="http://i.imgur.com/pYUt8Hf.gif"><br>The god of dance.');
},
gara: 'garazan',
nub: 'garazan',
garazan: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="6" face="comic sans ms"><font color="red">G<font color="orange">a<font color="yellow">r<font color="tan">a<font color="violet">z<font color="purple">a<font color="blue">n<br></font><img src="http://www.quickmeme.com/img/3b/3b2ef0437a963f22d89b81bf7a8ef9d46f8770414ec98f3d25db4badbbe5f19c.jpg" width="150" height="150">');
},
//End Trainer Cards.
avatars: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Your avatar can be changed using the Options menu (it looks like a gear) in the upper right of Pokemon Showdown. Custom avatars are only obtainable by staff.');
},
git: 'opensource',
opensource: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Pokemon Showdown is open source:<br />- Language: JavaScript (Node.js)<br />'+
'- <a href="https://github.com/Zarel/Pokemon-Showdown" target="_blank">Pokemon Showdown Source Code / How to create a PS server</a><br />'+
'- <a href="https://github.com/Zarel/Pokemon-Showdown-Client" target="_blank">Client Source Code</a><br />'+
'- <a href="https://github.com/panpawn/Pokemon-Showdown">Gold Source Code</a>');
},
events: 'activities',
activities: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="3" face="comic sans ms">Gold Activities:</font></center></br>' +
'โ
<b>Tournaments</b> - Here on Gold, we have a tournaments script that allows users to partake in several different tiers. For a list of tour commands do /th. Ask in the lobby for a voice (+) or up to start one of these if you\'re interesrted!<br>' +
'โ
<b>Hangmans</b> - We have a hangans script that allows users to partake in a "hangmans" sort of a game. For a list of hangmans commands, do /hh. As a voice (+) or up in the lobby to start one of these if interested.<br>' +
'โ
<b>Scavengers</b> - We have a whole set of scavenger commands that can be done in the <button name="joinRoom" value="scavengers" target="_blank">Scavengers Room</button>.<br>' +
'โ
<b>Leagues</b> - If you click the "join room page" to the upper right (+), it will display a list of rooms we have. Several of these rooms are 3rd party leagues of Gold; join them to learn more about each one!<br>' +
'โ
<b>Battle</b> - By all means, invite your friends on here so that you can battle with each other! Here on Gold, we are always up to date on our formats, so we\'re a great place to battle on!<br>' +
'โ
<b>Chat</b> - Gold is full of great people in it\'s community and we\'d love to have you be apart of it!<br>' +
'โ
<b>Learn</b> - Are you new to Pokemon? If so, then feel FREE to ask the lobby any questions you might have!<br>' +
'โ
<b>Shop</b> - Do /shop to learn about where your Gold Bucks can go! <br>' +
'โ
<b>Plug.dj</b> - Come listen to music with us! Click <a href="http://plug.dj/gold-server/">here</a> to start!<br>' +
'<i>--PM staff (%, @, &, ~) any questions you might have!</i>');
},
introduction: 'intro',
intro: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('New to competitive pokemon?<br />' +
'- <a href="http://www.smogon.com/sim/ps_guide">Beginner\'s Guide to Pokรฉmon Showdown</a><br />' +
'- <a href="http://www.smogon.com/dp/articles/intro_comp_pokemon">An introduction to competitive Pokรฉmon</a><br />' +
'- <a href="http://www.smogon.com/bw/articles/bw_tiers">What do "OU", "UU", etc mean?</a><br />' +
'- <a href="http://www.smogon.com/xyhub/tiers">What are the rules for each format? What is "Sleep Clause"?</a>');
},
mentoring: 'smogintro',
smogonintro: 'smogintro',
smogintro: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Welcome to Smogon\'s Official Pokรฉmon Showdown server! The Mentoring room can be found ' +
'<a href="http://play.pokemonshowdown.com/communitymentoring">here</a> or by using /join communitymentoring.<br /><br />' +
'Here are some useful links to Smogon\'s Mentorship Program to help you get integrated into the community:<br />' +
'- <a href="http://www.smogon.com/mentorship/primer">Smogon Primer: A brief introduction to Smogon\'s subcommunities</a><br />' +
'- <a href="http://www.smogon.com/mentorship/introductions">Introduce yourself to Smogon!</a><br />' +
'- <a href="http://www.smogon.com/mentorship/profiles">Profiles of current Smogon Mentors</a><br />' +
'- <a href="http://mibbit.com/#[email protected]">#mentor: the Smogon Mentorship IRC channel</a><br />' +
'All of these links and more can be found at the <a href="http://www.smogon.com/mentorship/">Smogon Mentorship Program\'s hub</a>.');
},
calculator: 'calc',
calc: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Pokemon Showdown! damage calculator. (Courtesy of Honko)<br />' +
'- <a href="http://pokemonshowdown.com/damagecalc/">Damage Calculator</a>');
},
cap: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('An introduction to the Create-A-Pokemon project:<br />' +
'- <a href="http://www.smogon.com/cap/">CAP project website and description</a><br />' +
'- <a href="http://www.smogon.com/forums/showthread.php?t=48782">What Pokemon have been made?</a><br />' +
'- <a href="http://www.smogon.com/forums/showthread.php?t=3464513">Talk about the metagame here</a><br />' +
'- <a href="http://www.smogon.com/forums/showthread.php?t=3466826">Practice BW CAP teams</a>');
},
gennext: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('NEXT (also called Gen-NEXT) is a mod that makes changes to the game:<br />' +
'- <a href="https://github.com/Zarel/Pokemon-Showdown/blob/master/mods/gennext/README.md">README: overview of NEXT</a><br />' +
'Example replays:<br />' +
'- <a href="http://replay.pokemonshowdown.com/gennextou-37815908">roseyraid vs Zarel</a><br />' +
'- <a href="http://replay.pokemonshowdown.com/gennextou-37900768">QwietQwilfish vs pickdenis</a>');
},
om: 'othermetas',
othermetas: function(target, room, user) {
if (!this.canBroadcast()) return;
target = toId(target);
var buffer = '';
var matched = false;
if (!target || target === 'all') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/forums/206/">Information on the Other Metagames</a><br />';
}
if (target === 'all' || target === 'hackmons') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3475624/">Hackmons</a><br />';
}
if (target === 'all' || target === 'balancedhackmons' || target === 'bh') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3463764/">Balanced Hackmons</a><br />';
if (target !== 'all') {
buffer += '- <a href="http://www.smogon.com/forums/threads/3499973/">Balanced Hackmons Mentoring Program</a><br />';
}
}
if (target === 'all' || target === 'glitchmons') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3467120/">Glitchmons</a><br />';
}
if (target === 'all' || target === 'tiershift' || target === 'ts') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3479358/">Tier Shift</a><br />';
}
if (target === 'all' || target === 'stabmons') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3484106/">STABmons</a>';
}
if (target === 'all' || target === 'omotm' || target === 'omofthemonth' || target === 'month') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3481155/">OM of the Month</a>';
}
if (target === 'all' || target === 'skybattles') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3493601/">Sky Battles</a>';
}
if (target === 'all' || target === 'inversebattle' || target === 'inverse') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3492433/">Inverse Battle</a>';
}
if (target === 'all' || target === 'middlecup' || target === 'mc') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3494887/">Middle Cup</a>';
}
if (target === 'all' || target === 'outheorymon' || target === 'theorymon') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3499219/">OU Theorymon</a>';
}
if (target === 'all' || target === 'index') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/other-metagames-index.3472405/">OM Index</a><br />';
}
if (!matched) {
return this.sendReply('The Other Metas entry "'+target+'" was not found. Try /othermetas or /om for general help.');
}
this.sendReplyBox(buffer);
},
roomhelp: function(target, room, user) {
if (room.id === 'lobby') return this.sendReply('This command is too spammy for lobby.');
if (!this.canBroadcast()) return;
this.sendReplyBox('Room drivers (%) can use:<br />' +
'- /warn OR /k <em>username</em>: warn a user and show the Pokemon Showdown rules<br />' +
'- /mute OR /m <em>username</em>: 7 minute mute<br />' +
'- /hourmute OR /hm <em>username</em>: 60 minute mute<br />' +
'- /unmute <em>username</em>: unmute<br />' +
'- /announce OR /wall <em>message</em>: make an announcement<br />' +
'- /modlog <em>username</em>: search the moderator log of the room<br />' +
'<br />' +
'Room moderators (@) can also use:<br />' +
'- /roomban OR /rb <em>username</em>: bans user from the room<br />' +
'- /roomunban <em>username</em>: unbans user from the room<br />' +
'- /roomvoice <em>username</em>: appoint a room voice<br />' +
'- /roomdevoice <em>username</em>: remove a room voice<br />' +
'- /modchat <em>[off/autoconfirmed/+]</em>: set modchat level<br />' +
'<br />' +
'Room owners (#) can also use:<br />' +
'- /roomdesc <em>description</em>: set the room description on the room join page<br />' +
'- /rules <em>rules link</em>: set the room rules link seen when using /rules<br />' +
'- /roommod, /roomdriver <em>username</em>: appoint a room moderator/driver<br />' +
'- /roomdemod, /roomdedriver <em>username</em>: remove a room moderator/driver<br />' +
'- /modchat <em>[%/@/#]</em>: set modchat level<br />' +
'- /declare <em>message</em>: make a room declaration<br /><br>' +
'The room founder can also use:<br />' +
'- /roomowner <em>username</em><br />' +
'- /roomdeowner <em>username</em><br />' +
'</div>');
},
restarthelp: function(target, room, user) {
if (room.id === 'lobby' && !this.can('lockdown')) return false;
if (!this.canBroadcast()) return;
this.sendReplyBox('The server is restarting. Things to know:<br />' +
'- We wait a few minutes before restarting so people can finish up their battles<br />' +
'- The restart itself will take a few seconds<br />' +
'- Your ladder ranking and teams will not change<br />' +
'- We are restarting to update Gold to a newer version' +
'</div>');
},
tc: 'tourhelp',
th: 'tourhelp',
tourhelp: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b><font size="4"><font color="green">Tournament Commands List:</font></b><br>' +
'<b>/tpoll</b> - Starts a poll asking what tier users want. Requires: +, %, @, &, ~. <br>' +
'<b>/tour [tier], [number of people or xminutes]</b> Requires: +, %, @, &, ~.<br>' +
'<b>/endtour</b> - Ends the current tournement. Requires: +, %, @, &, ~.<br>' +
'<b>/replace [replacee], [replacement]</b> Requires: +, %, @, &, ~.<br>' +
'<b>/dq [username]</b> - Disqualifies a user from the tournement. Requires: +, %, @, &, ~.<br>' +
'<b>/fj [user]</b> - Forcibily joins a user into the tournement in the sign up phase. Requires: +, %, @, &, ~.<br>' +
'<b>/fl [username]</b> - Forcibily makes a user leave the tournement in the sign up phase. Requires: +, %, @, &, ~.<br>' +
'<b>/vr</b> - Views the current round in the tournement of whose won and whose lost and who hasn\'t started yet.<br>' +
'<b>/toursize [number]</b> - Changes the tour size if you started it with a number instead of a time limit during the sign up phase.<br>' +
'<b>/tourtime [xminutes]</b> - Changes the tour time if you started it with a time limit instead of a number during the sign up phase.<br>' +
'<b><font size="2"><font color="green">Polls Commands List:</b></font><br>' +
'<b>/poll [title], [option],[option], exc...</b> - Starts a poll. Requires: +, %, @, &, ~.<br>' +
'<b>/pr</b> - Reminds you of what the current poll is.<br>' +
'<b>/endpoll</b> - Ends the current poll. Requires: +, %, @, &, ~.<br>' +
'<b>/vote [opinion]</b> - votes for an option of the current poll.<br><br>' +
'<i>--Just ask in the lobby if you\'d like a voice or up to start a tourney!</i>');
},
rule: 'rules',
rules: function(target, room, user) {
if (!target) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Please follow the rules:<br />' +
(room.rulesLink ? '- <a href="' + sanitize(room.rulesLink) + '">' + sanitize(room.title) + ' room rules</a><br />' : '') +
'- <a href="http://goldserver.weebly.com/rules.html">'+(room.rulesLink?'Global rules':'Rules')+'</a><br />' +
'</div>');
return;
}
if (!this.can('roommod', null, room)) return;
if (target.length > 80) {
return this.sendReply('Error: Room rules link is too long (must be under 80 characters). You can use a URL shortener to shorten the link.');
}
room.rulesLink = target.trim();
this.sendReply('(The room rules link is now: '+target+')');
if (room.chatRoomData) {
room.chatRoomData.rulesLink = room.rulesLink;
Rooms.global.writeChatRoomData();
}
},
faq: function(target, room, user) {
if (!this.canBroadcast()) return;
target = target.toLowerCase();
var buffer = '';
var matched = false;
if (!target || target === 'all') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq">Frequently Asked Questions</a><br />';
}
if (target === 'all' || target === 'deviation') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#deviation">Why did this user gain or lose so many points?</a><br />';
}
if (target === 'all' || target === 'doubles' || target === 'triples' || target === 'rotation') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#doubles">Can I play doubles/triples/rotation battles here?</a><br />';
}
if (target === 'all' || target === 'randomcap') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#randomcap">What is this fakemon and what is it doing in my random battle?</a><br />';
}
if (target === 'all' || target === 'restarts') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#restarts">Why is the server restarting?</a><br />';
}
if (target === 'all' || target === 'staff') {
matched = true;
buffer += '<a href="http://goldserver.weebly.com/how-do-i-get-a-rank.html">Staff FAQ</a><br />';
}
if (target === 'all' || target === 'autoconfirmed' || target === 'ac') {
matched = true;
buffer += 'A user is autoconfirmed when they have won at least one rated battle and have been registered for a week or longer.<br />';
}
if (target === 'all' || target === 'customsymbol' || target === 'cs') {
matched = true;
buffer += 'A custom symbol will bring your name up to the top of the userlist with a custom symbol next to it. These reset after the server restarts.<br />';
}
if (target === 'all' || target === 'league') {
matched = true;
buffer += 'Welcome to Gold! So, you\'re interested in making or moving a league here? If so, read <a href="http://goldserver.weebly.com/making-a-league.html">this</a> and write down your answers on a <a href="http://pastebin.com">Pastebin</a> and PM it to an admin. Good luck!<br />';
}
if (!matched) {
return this.sendReply('The FAQ entry "'+target+'" was not found. Try /faq for general help.');
}
this.sendReplyBox(buffer);
},
banlists: 'tiers',
tier: 'tiers',
tiers: function(target, room, user) {
if (!this.canBroadcast()) return;
target = toId(target);
var buffer = '';
var matched = false;
if (!target || target === 'all') {
matched = true;
buffer += '- <a href="http://www.smogon.com/tiers/">Smogon Tiers</a><br />';
buffer += '- <a href="http://www.smogon.com/forums/threads/tiering-faq.3498332/">Tiering FAQ</a><br />';
buffer += '- <a href="http://www.smogon.com/xyhub/tiers">The banlists for each tier</a><br />';
}
if (target === 'all' || target === 'ubers' || target === 'uber') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/uber">Uber Pokemon</a><br />';
}
if (target === 'all' || target === 'overused' || target === 'ou') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/ou">Overused Pokemon</a><br />';
}
if (target === 'all' || target === 'underused' || target === 'uu') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/uu">Underused Pokemon</a><br />';
}
if (target === 'all' || target === 'rarelyused' || target === 'ru') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/ru">Rarelyused Pokemon</a><br />';
}
if (target === 'all' || target === 'neverused' || target === 'nu') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/nu">Neverused Pokemon</a><br />';
}
if (target === 'all' || target === 'littlecup' || target === 'lc') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/lc">Little Cup Pokemon</a><br />';
}
if (target === 'all' || target === 'doubles') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/metagames/doubles">Doubles</a><br />';
}
if (!matched) {
return this.sendReply('The Tiers entry "'+target+'" was not found. Try /tiers for general help.');
}
this.sendReplyBox(buffer);
},
analysis: 'smogdex',
strategy: 'smogdex',
smogdex: function(target, room, user) {
if (!this.canBroadcast()) return;
var targets = target.split(',');
if (toId(targets[0]) === 'previews') return this.sendReplyBox('<a href="http://www.smogon.com/forums/threads/sixth-generation-pokemon-analyses-index.3494918/">Generation 6 Analyses Index</a>, brought to you by <a href="http://www.smogon.com">Smogon University</a>');
var pokemon = Tools.getTemplate(targets[0]);
var item = Tools.getItem(targets[0]);
var move = Tools.getMove(targets[0]);
var ability = Tools.getAbility(targets[0]);
var atLeastOne = false;
var generation = (targets[1] || "bw").trim().toLowerCase();
var genNumber = 5;
var doublesFormats = {'vgc2012':1,'vgc2013':1,'doubles':1};
var doublesFormat = (!targets[2] && generation in doublesFormats)? generation : (targets[2] || '').trim().toLowerCase();
var doublesText = '';
if (generation === "bw" || generation === "bw2" || generation === "5" || generation === "five") {
generation = "bw";
} else if (generation === "dp" || generation === "dpp" || generation === "4" || generation === "four") {
generation = "dp";
genNumber = 4;
} else if (generation === "adv" || generation === "rse" || generation === "rs" || generation === "3" || generation === "three") {
generation = "rs";
genNumber = 3;
} else if (generation === "gsc" || generation === "gs" || generation === "2" || generation === "two") {
generation = "gs";
genNumber = 2;
} else if(generation === "rby" || generation === "rb" || generation === "1" || generation === "one") {
generation = "rb";
genNumber = 1;
} else {
generation = "bw";
}
if (doublesFormat !== '') {
// Smogon only has doubles formats analysis from gen 5 onwards.
if (!(generation in {'bw':1,'xy':1}) || !(doublesFormat in doublesFormats)) {
doublesFormat = '';
} else {
doublesText = {'vgc2012':'VGC 2012 ','vgc2013':'VGC 2013 ','doubles':'Doubles '}[doublesFormat];
doublesFormat = '/' + doublesFormat;
}
}
// Pokemon
if (pokemon.exists) {
atLeastOne = true;
if (genNumber < pokemon.gen) {
return this.sendReplyBox(pokemon.name+' did not exist in '+generation.toUpperCase()+'!');
}
if (pokemon.tier === 'G4CAP' || pokemon.tier === 'G5CAP') {
generation = "cap";
}
var poke = pokemon.name.toLowerCase();
if (poke === 'nidoranm') poke = 'nidoran-m';
if (poke === 'nidoranf') poke = 'nidoran-f';
if (poke === 'farfetch\'d') poke = 'farfetchd';
if (poke === 'mr. mime') poke = 'mr_mime';
if (poke === 'mime jr.') poke = 'mime_jr';
if (poke === 'deoxys-attack' || poke === 'deoxys-defense' || poke === 'deoxys-speed' || poke === 'kyurem-black' || poke === 'kyurem-white') poke = poke.substr(0,8);
if (poke === 'wormadam-trash') poke = 'wormadam-s';
if (poke === 'wormadam-sandy') poke = 'wormadam-g';
if (poke === 'rotom-wash' || poke === 'rotom-frost' || poke === 'rotom-heat') poke = poke.substr(0,7);
if (poke === 'rotom-mow') poke = 'rotom-c';
if (poke === 'rotom-fan') poke = 'rotom-s';
if (poke === 'giratina-origin' || poke === 'tornadus-therian' || poke === 'landorus-therian') poke = poke.substr(0,10);
if (poke === 'shaymin-sky') poke = 'shaymin-s';
if (poke === 'arceus') poke = 'arceus-normal';
if (poke === 'thundurus-therian') poke = 'thundurus-t';
this.sendReplyBox('<a href="http://www.smogon.com/'+generation+'/pokemon/'+poke+doublesFormat+'">'+generation.toUpperCase()+' '+doublesText+pokemon.name+' analysis</a>, brought to you by <a href="http://www.smogon.com">Smogon University</a>');
}
// Item
if (item.exists && genNumber > 1 && item.gen <= genNumber) {
atLeastOne = true;
var itemName = item.name.toLowerCase().replace(' ', '_');
this.sendReplyBox('<a href="http://www.smogon.com/'+generation+'/items/'+itemName+'">'+generation.toUpperCase()+' '+item.name+' item analysis</a>, brought to you by <a href="http://www.smogon.com">Smogon University</a>');
}
// Ability
if (ability.exists && genNumber > 2 && ability.gen <= genNumber) {
atLeastOne = true;
var abilityName = ability.name.toLowerCase().replace(' ', '_');
this.sendReplyBox('<a href="http://www.smogon.com/'+generation+'/abilities/'+abilityName+'">'+generation.toUpperCase()+' '+ability.name+' ability analysis</a>, brought to you by <a href="http://www.smogon.com">Smogon University</a>');
}
// Move
if (move.exists && move.gen <= genNumber) {
atLeastOne = true;
var moveName = move.name.toLowerCase().replace(' ', '_');
this.sendReplyBox('<a href="http://www.smogon.com/'+generation+'/moves/'+moveName+'">'+generation.toUpperCase()+' '+move.name+' move analysis</a>, brought to you by <a href="http://www.smogon.com">Smogon University</a>');
}
if (!atLeastOne) {
return this.sendReplyBox('Pokemon, item, move, or ability not found for generation ' + generation.toUpperCase() + '.');
}
},
forums: function(target, room, user) {
if (!this.canBroadcast()) return;
return this.sendReplyBox('Gold Forums can be found <a href="http://gold.lefora.com/" >here</a>.');
},
regdate: function(target, room, user, connection) {
if (!this.canBroadcast()) return;
if (!target || target == "." || target == "," || target == "'") return this.sendReply('/regdate - Please specify a valid username.'); //temp fix for symbols that break the command
var html = ['<img ','<a href','<font ','<marquee','<blink','<center', '<button'];
for (var x in html) {
if (target.indexOf(html[x]) > -1) return this.sendReply('HTML is not supported in this command.');
}
var username = target;
target = target.replace(/\s+/g, '');
var util = require("util"),
http = require("http");
var options = {
host: "www.pokemonshowdown.com",
port: 80,
path: "/forum/~"+target
};
var content = "";
var self = this;
var req = http.request(options, function(res) {
res.setEncoding("utf8");
res.on("data", function (chunk) {
content += chunk;
});
res.on("end", function () {
content = content.split("<em");
if (content[1]) {
content = content[1].split("</p>");
if (content[0]) {
content = content[0].split("</em>");
if (content[1]) {
regdate = content[1];
data = username+' was registered on'+regdate+'.';
}
}
}
else {
data = username+' is not registered.';
}
self.sendReplyBox(data);
});
});
req.end();
},
league: function(target, room, user) {
if (!this.canBroadcast()) return;
return this.sendReplyBox('<font size="2"><b><center>Goodra League</font></b></center>' +
'โ
The league consists of 3 Gym Leaders<br /> ' +
'โ
Currently the Champion position is empty.<br/>' +
'โ
Be the first to complete the league, and the spot is yours!<br />' +
'โ
The champion gets a FREE trainer card, custom avatar and global voice!<br />' +
'โ
The Goodra League information can be found <a href="http://goldserver.weebly.com/league.html" >here</a>.<br />' +
'โ
Click <button name=\"joinRoom\" value=\"goodraleague\">here</button> to enter our League\'s room!');
},
stafffaq: function (target, room, user) {
if (!this.canBroadcast()) return;
return this.sendReplyBox('Click <a href="http://goldserver.weebly.com/how-do-i-get-a-rank-on-gold.html">here</a> to find out about Gold\'s ranks and promotion system.');
},
/*********************************************************
* Miscellaneous commands
*********************************************************/
//kupo: function(target, room, user){
//if(!this.canBroadcast()|| !user.can('broadcast')) return this.sendReply('/kupo - Access Denied.');
//if(!target) return this.sendReply('Insufficent Parameters.');
//room.add('|c|~kupo|/me '+ target);
//this.logModCommand(user.name + ' used /kupo to say ' + target);
//},
birkal: function(target, room, user) {
this.sendReply("It's not funny anymore.");
},
potd: function(target, room, user) {
if (!this.can('potd')) return false;
config.potd = target;
Simulator.SimulatorProcess.eval('config.potd = \''+toId(target)+'\'');
if (target) {
if (Rooms.lobby) Rooms.lobby.addRaw('<div class="broadcast-blue"><b>The Pokemon of the Day is now '+target+'!</b><br />This Pokemon will be guaranteed to show up in random battles.</div>');
this.logModCommand('The Pokemon of the Day was changed to '+target+' by '+user.name+'.');
} else {
if (Rooms.lobby) Rooms.lobby.addRaw('<div class="broadcast-blue"><b>The Pokemon of the Day was removed!</b><br />No pokemon will be guaranteed in random battles.</div>');
this.logModCommand('The Pokemon of the Day was removed by '+user.name+'.');
}
},
//Artist of the Day Commands:
aotdhelp: function(target, room, user) {
if (!this.canBroadcast()) return;
//This command is room specific to prevent confusion.
if (room.id !== 'thestudio') return this.sendReply("This command can only be used in The Studio.");
//Explains artist of the day to users who are new or unfamiliar with it.
this.sendReplyBox('<b>Artist of the Day:</b><br />' +
'This is a room actity for The Studio where users nomiate artists for the title of "Artist of the Day". To find out more information about this activity, click <a href="http://thepsstudioroom.weebly.com/artist-of-the-day.html">here</a>.<br><br />' +
'Commands:<br />' +
'/naotd (artist) - This will nominate your artist of the day; only do this once, please. <br />' +
'/aotd - This allows you to see who the current Artist of the Day is.<br>' +
'/aotd (artist) - Sets an artist of the day. (requires %, @, #) <br />' +
'-- <i>For more information on Artist of the Day, click <a href="http://thepsstudioroom.weebly.com/artist-of-the-day.html">here</a>. <br />' +
'-- <i><a href="http://thepsstudioroom.weebly.com/rules.html">Room rules</a></i>.');
},
nominateartistoftheday: 'naotd',
naotd: function(target, room, user){
if (room.id !== 'thestudio') return this.sendReply("This command can only be used in The Studio.");
if (target.indexOf('<img ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<a href') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<font ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<marquee') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<blink') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<center') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if(!target) return this.sendReply('/naotd needs an artist.');
if (target.length > 25) {
return this.sendReply('This Artist\'s name is too long; it cannot exceed 25 characters.');
}
if (!this.canTalk()) return;
room.addRaw(''+user.name+'\'s nomination for Artist of the Day is: <b><i>' + target +'</i></b>');
},
artistoftheday: 'aotd',
aotd: function(target, room, user) {
if (room.id !== 'thestudio') return this.sendReply("This command can only be used in The Studio.");
if (target.indexOf('<img ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<a href') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<font ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<marquee') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<blink') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<center') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (!target) {
return this.sendReply('The current Artist of the Day is: '+room.aotd);
}
if (!this.canTalk()) return;
if (target.length > 25) {
return this.sendReply('This Artist\'s name is too long; it cannot exceed 25 characters.');
}
if (!this.can('mute', null, room)) return;
room.aotd = target;
if (target) {
room.addRaw('<div class="broadcast-green"><font size="2"><b>The Artist of the Day is now <font color="black">'+target+'</font color>!</font size></b><br>' +
'<font size="1">(Set by '+user.name+'.)<br />' +
'This Artist will be posted on our <a href="http://thepsstudioroom.weebly.com/artist-of-the-day.html">Artist of the Day page</a>.</div>');
this.logModCommand('The Artist of the Day was changed to '+target+' by '+user.name+'.');
} else {
room.addRaw('<div class="broadcast-green"><b>The Artist of the Day was removed!</b><br />There is no longer an Artist of the day today!</div>');
this.logModCommand('The Artist of the Day was removed by '+user.name+'.');
}
},
nstaffmemberoftheday: 'smotd',
nsmotd: function(target, room, user){
if (room.id !== 'lobby') return this.sendReply("This command can only be used in Lobby.");
//Users cannot do HTML tags with this command.
if (target.indexOf('<img ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<a href') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<font ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<marquee') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<blink') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<center') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if(!target) return this.sendReply('/nsmotd needs an Staff Member.');
//Users who are muted cannot use this command.
if (target.length > 25) {
return this.sendReply('This Staff Member\'s name is too long; it cannot exceed 25 characters.');
}
if (!this.canTalk()) return;
room.addRaw(''+user.name+'\'s nomination for Staff Member of the Day is: <b><i>' + target +'</i></b>');
},
staffmemberoftheday: 'smotd',
smotd: function(target, room, user) {
if (room.id !== 'lobby') return this.sendReply("This command can only be used in Lobby.");
//User use HTML with this command.
if (target.indexOf('<img ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<a href') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<font ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<marquee') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<blink') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<center') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (!target) {
//allows user to do /smotd to view who is the Staff Member of the day if people forget.
return this.sendReply('The current Staff Member of the Day is: '+room.smotd);
}
//Users who are muted cannot use this command.
if (!this.canTalk()) return;
//Only room drivers and up may use this command.
if (target.length > 25) {
return this.sendReply('This Staff Member\'s name is too long; it cannot exceed 25 characters.');
}
if (!this.can('mute', null, room)) return;
room.smotd = target;
if (target) {
//if a user does /smotd (Staff Member name here), then we will display the Staff Member of the Day.
room.addRaw('<div class="broadcast-red"><font size="2"><b>The Staff Member of the Day is now <font color="black">'+target+'!</font color></font size></b> <font size="1">(Set by '+user.name+'.)<br />This Staff Member is now the honorary Staff Member of the Day!</div>');
this.logModCommand('The Staff Member of the Day was changed to '+target+' by '+user.name+'.');
} else {
//If there is no target, then it will remove the Staff Member of the Day.
room.addRaw('<div class="broadcast-green"><b>The Staff Member of the Day was removed!</b><br />There is no longer an Staff Member of the day today!</div>');
this.logModCommand('The Staff Member of the Day was removed by '+user.name+'.');
}
},
roll: 'dice',
dice: function(target, room, user) {
if (!this.canBroadcast()) return;
var d = target.indexOf("d");
if (d != -1) {
var num = parseInt(target.substring(0,d));
faces = NaN;
if (target.length > d) var faces = parseInt(target.substring(d + 1));
if (isNaN(num)) num = 1;
if (isNaN(faces)) return this.sendReply("The number of faces must be a valid integer.");
if (faces < 1 || faces > 1000) return this.sendReply("The number of faces must be between 1 and 1000");
if (num < 1 || num > 20) return this.sendReply("The number of dice must be between 1 and 20");
var rolls = new Array();
var total = 0;
for (var i=0; i < num; i++) {
rolls[i] = (Math.floor(faces * Math.random()) + 1);
total += rolls[i];
}
return this.sendReplyBox('Random number ' + num + 'x(1 - ' + faces + '): ' + rolls.join(', ') + '<br />Total: ' + total);
}
if (target && isNaN(target) || target.length > 21) return this.sendReply('The max roll must be a number under 21 digits.');
var maxRoll = (target)? target : 6;
var rand = Math.floor(maxRoll * Math.random()) + 1;
return this.sendReplyBox('Random number (1 - ' + maxRoll + '): ' + rand);
},
rollgame: 'dicegame',
dicegame: function(target, room, user) {
if (!this.canBroadcast()) return;
if (Users.get(''+user.name+'').money < target) {
return this.sendReply('You cannot wager more than you have, nub.');
}
if(!target) return this.sendReply('/dicegame [amount of bucks agreed to wager].');
if (isNaN(target)) {
return this.sendReply('Very funny, now use a real number.');
}
if (String(target).indexOf('.') >= 0) {
return this.sendReply('You cannot wager numbers with decimals.');
}
if (target < 0) {
return this.sendReply('Number cannot be negative.');
}
if (target > 100) {
return this.sendReply('Error: You cannot wager over 100 bucks.');
}
if (target == 0) {
return this.sendReply('Number cannot be 0.');
}
var player1 = Math.floor(6 * Math.random()) + 1;
var player2 = Math.floor(6 * Math.random()) + 1;
var winner = '';
var loser= '';
if (player1 > player2) {
winner = 'The <b>winner</b> is <font color="green">'+user.name+'</font>!';
loser = 'Better luck next time, Opponent!';
}
if (player1 < player2) {
winner = 'The <b>winner</b> is <font color="green">Opponent</font>!';
loser = 'Better luck next time, '+user.name+'!';
}
if (player1 === player2) {
winner = 'It\'s a <b>tie</b>!';
loser = 'Try again!';
}
return this.sendReplyBox('<center><font size="4"><b><img border="5" title="Dice Game!"></b></font></center><br />' +
'<font color="red">This game is worth '+target+' buck(s).</font><br />' +
'Loser: Tranfer bucks to the winner using /tb [winner], '+target+' <br />' +
'<hr>' +
''+user.name+' roll (1-6): '+player1+'<br />' +
'Opponent roll (1-6): '+player2+'<br />' +
'<hr>' +
'Winner: '+winner+'<br />' +
''+loser+'');
},
coins: 'coingame',
coin: 'coingame',
coingame: function(target, room, user) {
if (!this.canBroadcast()) return;
var random = Math.floor(2 * Math.random()) + 1;
var results = '';
if (random == 1) {
results = '<img src="http://surviveourcollapse.com/wp-content/uploads/2013/01/zinc.png" width="15%" title="Heads!"><br>It\'s heads!';
}
if (random == 2) {
results = '<img src="http://upload.wikimedia.org/wikipedia/commons/e/e5/2005_Penny_Rev_Unc_D.png" width="15%" title="Tails!"><br>It\'s tails!';
}
return this.sendReplyBox('<center><font size="3"><b>Coin Game!</b></font><br>'+results+'');
},
register: function() {
if (!this.canBroadcast()) return;
this.sendReply("You must win a rated battle to register.");
},
br: 'banredirect',
banredirect: function(){
this.sendReply('/banredirect - This command is obsolete and has been removed.');
},
lobbychat: function(target, room, user, connection) {
if (!Rooms.lobby) return this.popupReply("This server doesn't have a lobby.");
target = toId(target);
if (target === 'off') {
user.leaveRoom(Rooms.lobby, connection.socket);
connection.send('|users|');
this.sendReply('You are now blocking lobby chat.');
} else {
user.joinRoom(Rooms.lobby, connection);
this.sendReply('You are now receiving lobby chat.');
}
},
a: function(target, room, user) {
if (!this.can('battlemessage')) return false;
// secret sysop command
room.add(target);
},
/*********************************************************
* Help commands
*********************************************************/
commands: 'help',
h: 'help',
'?': 'help',
help: function(target, room, user) {
target = target.toLowerCase();
var matched = false;
if (target === 'all' || target === 'msg' || target === 'pm' || target === 'whisper' || target === 'w') {
matched = true;
this.sendReply('/msg OR /whisper OR /w [username], [message] - Send a private message.');
}
if (target === 'all' || target === 'r' || target === 'reply') {
matched = true;
this.sendReply('/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to.');
}
if (target === 'all' || target === 'getip' || target === 'ip') {
matched = true;
this.sendReply('/ip - Get your own IP address.');
this.sendReply('/ip [username] - Get a user\'s IP address. Requires: @ & ~');
}
if (target === 'all' || target === 'rating' || target === 'ranking' || target === 'rank' || target === 'ladder') {
matched = true;
this.sendReply('/rating - Get your own rating.');
this.sendReply('/rating [username] - Get user\'s rating.');
}
if (target === 'all' || target === 'nick') {
matched = true;
this.sendReply('/nick [new username] - Change your username.');
}
if (target === 'all' || target === 'avatar') {
matched = true;
this.sendReply('/avatar [new avatar number] - Change your trainer sprite.');
}
if (target === 'all' || target === 'unlink') {
matched = true;
this.sendReply('/unlink [user] - Makes all prior links posted by this user unclickable. Requires: %, @, &, ~');
}
if (target === 'all' || target === 'rooms') {
matched = true;
this.sendReply('/rooms [username] - Show what rooms a user is in.');
}
if (target === 'all' || target === 'whois') {
matched = true;
this.sendReply('/whois [username] - Get details on a username: group, and rooms.');
}
if (target === 'all' || target === 'data') {
matched = true;
this.sendReply('/data [pokemon/item/move/ability] - Get details on this pokemon/item/move/ability.');
this.sendReply('!data [pokemon/item/move/ability] - Show everyone these details. Requires: + % @ & ~');
}
if (target === "all" || target === 'analysis') {
matched = true;
this.sendReply('/analysis [pokemon], [generation] - Links to the Smogon University analysis for this Pokemon in the given generation.');
this.sendReply('!analysis [pokemon], [generation] - Shows everyone this link. Requires: + % @ & ~');
}
if (target === 'all' || target === 'groups') {
matched = true;
this.sendReply('/groups - Explains what the + % @ & next to people\'s names mean.');
this.sendReply('!groups - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'opensource') {
matched = true;
this.sendReply('/opensource - Links to PS\'s source code repository.');
this.sendReply('!opensource - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'avatars') {
matched = true;
this.sendReply('/avatars - Explains how to change avatars.');
this.sendReply('!avatars - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'intro') {
matched = true;
this.sendReply('/intro - Provides an introduction to competitive pokemon.');
this.sendReply('!intro - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'cap') {
matched = true;
this.sendReply('/cap - Provides an introduction to the Create-A-Pokemon project.');
this.sendReply('!cap - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'om') {
matched = true;
this.sendReply('/om - Provides links to information on the Other Metagames.');
this.sendReply('!om - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'learn' || target === 'learnset' || target === 'learnall') {
matched = true;
this.sendReply('/learn [pokemon], [move, move, ...] - Displays how a Pokemon can learn the given moves, if it can at all.');
this.sendReply('!learn [pokemon], [move, move, ...] - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'calc' || target === 'caclulator') {
matched = true;
this.sendReply('/calc - Provides a link to a damage calculator');
this.sendReply('!calc - Shows everyone a link to a damage calculator. Requires: + % @ & ~');
}
if (target === 'all' || target === 'blockchallenges' || target === 'away' || target === 'idle') {
matched = true;
this.sendReply('/away - Blocks challenges so no one can challenge you. Deactivate it with /back.');
}
if (target === 'all' || target === 'allowchallenges' || target === 'back') {
matched = true;
this.sendReply('/back - Unlocks challenges so you can be challenged again. Deactivate it with /away.');
}
if (target === 'all' || target === 'faq') {
matched = true;
this.sendReply('/faq [theme] - Provides a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them.');
this.sendReply('!faq [theme] - Shows everyone a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them. Requires: + % @ & ~');
}
if (target === 'all' || target === 'highlight') {
matched = true;
this.sendReply('Set up highlights:');
this.sendReply('/highlight add, word - add a new word to the highlight list.');
this.sendReply('/highlight list - list all words that currently highlight you.');
this.sendReply('/highlight delete, word - delete a word from the highlight list.');
this.sendReply('/highlight delete - clear the highlight list');
}
if (target === 'all' || target === 'timestamps') {
matched = true;
this.sendReply('Set your timestamps preference:');
this.sendReply('/timestamps [all|lobby|pms], [minutes|seconds|off]');
this.sendReply('all - change all timestamps preferences, lobby - change only lobby chat preferences, pms - change only PM preferences');
this.sendReply('off - set timestamps off, minutes - show timestamps of the form [hh:mm], seconds - show timestamps of the form [hh:mm:ss]');
}
if (target === 'all' || target === 'effectiveness' || target === 'matchup' || target === 'eff' || target === 'type') {
matched = true;
this.sendReply('/effectiveness OR /matchup OR /eff OR /type [attack], [defender] - Provides the effectiveness of a move or type on another type or a Pokรฉmon.');
this.sendReply('!effectiveness OR /matchup OR !eff OR !type [attack], [defender] - Shows everyone the effectiveness of a move or type on another type or a Pokรฉmon.');
}
if (target === 'all' || target === 'pollson') {
matched = true;
this.sendReply('/pollson [none/room/all] - enables polls in the specified rooms. Requires @ & ~');
this.sendReply('/pollson - enables polls in the current room.');
this.sendReply('/pollson [room] - enables polls in the specified room.');
this.sendReply('/pollson all - enables polls in all rooms. Requires & ~');
}
if (target === 'all' || target === 'pollsoff') {
matched = true;
this.sendReply('/pollsoff [none/room/all] - disables polls in the specified rooms. Requires @ & ~');
this.sendReply('/pollsoff - disables polls in the current room.');
this.sendReply('/pollsoff [room] - disables polls in the specified room.');
this.sendReply('/pollsoff all - disables polls in all rooms. Requires & ~');
}
if (target === 'all' || target === 'dexsearch' || target === 'dsearch') {
matched = true;
this.sendReply('/dexsearch [type], [move], [move], ... - Searches for Pokemon that fulfill the selected criteria.');
this.sendReply('Search categories are: type, tier, color, moves, ability, gen.');
this.sendReply('Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black.');
this.sendReply('Valid tiers are: Uber/OU/BL/LC/CAP.');
this.sendReply('Types must be followed by " type", e.g., "dragon type".');
this.sendReply('Parameters can be excluded through the use of "!", e.g., "!water type" excludes all water types.');
this.sendReply('The parameter "mega" can be added to search for Mega Evolutions only.');
this.sendReply('The order of the parameters does not matter.');
}
if (target === 'all' || target === 'dice' || target === 'roll') {
matched = true;
this.sendReply('/dice [optional max number] - Randomly picks a number between 1 and 6, or between 1 and the number you choose.');
this.sendReply('/dice [number of dice]d[number of sides] - Simulates rolling a number of dice, e.g., /dice 2d4 simulates rolling two 4-sided dice.');
}
if (target === 'all' || target === 'join') {
matched = true;
this.sendReply('/join [roomname] - Attempts to join the room [roomname].');
}
if (target === 'all' || target === 'ignore') {
matched = true;
this.sendReply('/ignore [user] - Ignores all messages from the user [user].');
this.sendReply('Note that staff messages cannot be ignored.');
}
if (target === 'all' || target === 'invite') {
matched = true;
this.sendReply('/invite [username], [roomname] - Invites the player [username] to join the room [roomname].');
}
if (target === '%' || target === 'lock' || target === 'l') {
matched = true;
this.sendReply('/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: % @ & ~');
}
if (target === '%' || target === 'unlock') {
matched = true;
this.sendReply('/unlock [username] - Unlocks the user. Requires: % @ & ~');
}
if (target === '%' || target === 'redirect' || target === 'redir') {
matched = true;
this.sendReply('/redirect OR /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: % @ & ~');
}
if (target === '%' || target === 'modnote') {
matched = true;
this.sendReply('/modnote [note] - Adds a moderator note that can be read through modlog. Requires: % @ & ~');
}
if (target === '%' || target === 'altcheck' || target === 'alt' || target === 'alts' || target === 'getalts') {
matched = true;
this.sendReply('/alts OR /altcheck OR /alt OR /getalts [username] - Get a user\'s alts. Requires: % @ & ~');
}
if (target === '%' || target === 'forcerename' || target === 'fr') {
matched = true;
this.sendReply('/forcerename OR /fr [username], [reason] - Forcibly change a user\'s name and shows them the [reason]. Requires: % @ & ~');
}
if (target === '@' || target === 'roomban' || target === 'rb') {
matched = true;
this.sendReply('/roomban [username] - Bans the user from the room you are in. Requires: @ & ~');
}
if (target === '@' || target === 'roomunban') {
matched = true;
this.sendReply('/roomunban [username] - Unbans the user from the room you are in. Requires: @ & ~');
}
if (target === '@' || target === 'ban' || target === 'b') {
matched = true;
this.sendReply('/ban OR /b [username], [reason] - Kick user from all rooms and ban user\'s IP address with reason. Requires: @ & ~');
}
if (target === '&' || target === 'banip') {
matched = true;
this.sendReply('/banip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~');
}
if (target === '@' || target === 'unban') {
matched = true;
this.sendReply('/unban [username] - Unban a user. Requires: @ & ~');
}
if (target === '@' || target === 'unbanall') {
matched = true;
this.sendReply('/unbanall - Unban all IP addresses. Requires: @ & ~');
}
if (target === '%' || target === 'modlog') {
matched = true;
this.sendReply('/modlog [roomid|all], [n] - Roomid defaults to current room. If n is a number or omitted, display the last n lines of the moderator log. Defaults to 15. If n is not a number, search the moderator log for "n" on room\'s log [roomid]. If you set [all] as [roomid], searches for "n" on all rooms\'s logs. Requires: % @ & ~');
}
if (target === "%" || target === 'kickbattle ') {
matched = true;
this.sendReply('/kickbattle [username], [reason] - Kicks an user from a battle with reason. Requires: % @ & ~');
}
if (target === "%" || target === 'warn' || target === 'k') {
matched = true;
this.sendReply('/warn OR /k [username], [reason] - Warns a user showing them the Pokemon Showdown Rules and [reason] in an overlay. Requires: % @ & ~');
}
if (target === '%' || target === 'mute' || target === 'm') {
matched = true;
this.sendReply('/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: % @ & ~');
}
if (target === '%' || target === 'hourmute' || target === 'hm') {
matched = true;
this.sendReply('/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: % @ & ~');
}
if (target === '%' || target === 'unmute' || target === 'um') {
matched = true;
this.sendReply('/unmute [username] - Removes mute from user. Requires: % @ & ~');
}
if (target === '&' || target === 'promote') {
matched = true;
this.sendReply('/promote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: & ~');
}
if (target === '&' || target === 'demote') {
matched = true;
this.sendReply('/demote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: & ~');
}
if (target === '&' || target === 'forcetie') {
matched = true;
this.sendReply('/forcetie - Forces the current match to tie. Requires: & ~');
}
if (target === '&' || target === 'declare') {
matched = true;
this.sendReply('/declare [message] - Anonymously announces a message. Requires: & ~');
}
if (target === '~' || target === 'chatdeclare' || target === 'cdeclare') {
matched = true;
this.sendReply('/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: ~');
}
if (target === '~' || target === 'globaldeclare' || target === 'gdeclare') {
matched = true;
this.sendReply('/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: ~');
}
if (target === '%' || target === 'announce' || target === 'wall') {
matched = true;
this.sendReply('/announce OR /wall [message] - Makes an announcement. Requires: % @ & ~');
}
if (target === '@' || target === 'modchat') {
matched = true;
this.sendReply('/modchat [off/autoconfirmed/+/%/@/&/~] - Set the level of moderated chat. Requires: @ for off/autoconfirmed/+ options, & ~ for all the options');
}
if (target === '~' || target === 'hotpatch') {
matched = true;
this.sendReply('Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: ~');
this.sendReply('Hot-patching has greater memory requirements than restarting.');
this.sendReply('/hotpatch chat - reload chat-commands.js');
this.sendReply('/hotpatch battles - spawn new simulator processes');
this.sendReply('/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and also spawn new simulator processes');
}
if (target === '~' || target === 'lockdown') {
matched = true;
this.sendReply('/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: ~');
}
if (target === '~' || target === 'kill') {
matched = true;
this.sendReply('/kill - kills the server. Can\'t be done unless the server is in lockdown state. Requires: ~');
}
if (target === 'all' || target === 'kick' || target === '%') {
matched = true;
this.sendReply('/kick [user], [reason] - kicks the user from the current room. Requires %, @, &, or ~.');
this.sendReply('Requires & or ~ if used in a battle room.');
}
if (target === 'all' || target === 'dexsearch') {
matched = true;
this.sendReply('/dexsearch [type], [move], [move], ... - Searches for Pokemon that fulfill the selected criteria.');
this.sendReply('Search categories are: type, tier, color, moves, ability, gen.');
this.sendReply('Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black.');
this.sendReply('Valid tiers are: Uber/OU/BL/UU/BL2/RU/NU/NFE/LC/CAP/Illegal.');
this.sendReply('Types must be followed by " type", e.g., "dragon type".');
this.sendReply('The order of the parameters does not matter.');
}
if (target === 'all' || target === 'reminder' || target === 'reminders') {
matched = true;
this.sendReply('Set up and view reminders:');
this.sendReply('/reminder view - Show the reminders for the current room.');
this.sendReply('/reminder add, [message] - Adds a reminder to the current room. Most HTML is supported. Requires: # & ~');
this.sendReply('/reminder delete, [number/message] - Deletes a reminder from the current room. The number of the reminder or its message both work. Requires: # & ~');
this.sendReply('/reminder clear - Clears all reminders from the current room. Requires: # & ~');
}
if (target === 'all' || target === 'tell') {
matched = true;
this.sendReply('/tell [user], [message] - Leaves a message for the specified user that will be received when they next talk.');
}
if (target === 'all' || target === 'help' || target === 'h' || target === '?' || target === 'commands') {
matched = true;
this.sendReply('/help OR /h OR /? - Gives you help.');
}
if (!target) {
this.sendReply('COMMANDS: /msg, /reply, /ignore, /ip, /rating, /nick, /avatar, /rooms, /whois, /help, /away, /back, /timestamps, /highlight');
this.sendReply('INFORMATIONAL COMMANDS: /data, /dexsearch, /groups, /opensource, /avatars, /faq, /rules, /intro, /tiers, /othermetas, /learn, /analysis, /calc (replace / with ! to broadcast. (Requires: + % @ & ~))');
this.sendReply('For details on all room commands, use /roomhelp');
this.sendReply('For details on all commands, use /help all');
if (user.group !== config.groupsranking[0]) {
this.sendReply('DRIVER COMMANDS: /mute, /unmute, /announce, /modlog, /forcerename, /alts');
this.sendReply('MODERATOR COMMANDS: /ban, /unban, /unbanall, /ip, /redirect, /kick');
this.sendReply('LEADER COMMANDS: /promote, /demote, /forcewin, /forcetie, /declare');
this.sendReply('For details on all moderator commands, use /help @');
}
this.sendReply('For details of a specific command, use something like: /help data');
} else if (!matched) {
this.sendReply('The command "/'+target+'" was not found. Try /help for general help');
}
},
};
| config/commands.js | /**
* Commands
* Pokemon Showdown - http://pokemonshowdown.com/
*
* These are commands. For instance, you can define the command 'whois'
* here, then use it by typing /whois into Pokemon Showdown.
*
* A command can be in the form:
* ip: 'whois',
* This is called an alias: it makes it so /ip does the same thing as
* /whois.
*
* But to actually define a command, it's a function:
* birkal: function(target, room, user) {
* this.sendReply("It's not funny anymore.");
* },
*
* Commands are actually passed five parameters:
* function(target, room, user, connection, cmd, message)
* Most of the time, you only need the first three, though.
*
* target = the part of the message after the command
* room = the room object the message was sent to
* The room name is room.id
* user = the user object that sent the message
* The user's name is user.name
* connection = the connection that the message was sent from
* cmd = the name of the command
* message = the entire message sent by the user
*
* If a user types in "/msg zarel, hello"
* target = "zarel, hello"
* cmd = "msg"
* message = "/msg zarel, hello"
*
* Commands return the message the user should say. If they don't
* return anything or return something falsy, the user won't say
* anything.
*
* Commands have access to the following functions:
*
* this.sendReply(message)
* Sends a message back to the room the user typed the command into.
*
* this.sendReplyBox(html)
* Same as sendReply, but shows it in a box, and you can put HTML in
* it.
*
* this.popupReply(message)
* Shows a popup in the window the user typed the command into.
*
* this.add(message)
* Adds a message to the room so that everyone can see it.
* This is like this.sendReply, except everyone in the room gets it,
* instead of just the user that typed the command.
*
* this.send(message)
* Sends a message to the room so that everyone can see it.
* This is like this.add, except it's not logged, and users who join
* the room later won't see it in the log, and if it's a battle, it
* won't show up in saved replays.
* You USUALLY want to use this.add instead.
*
* this.logEntry(message)
* Log a message to the room's log without sending it to anyone. This
* is like this.add, except no one will see it.
*
* this.addModCommand(message)
* Like this.add, but also logs the message to the moderator log
* which can be seen with /modlog.
*
* this.logModCommand(message)
* Like this.addModCommand, except users in the room won't see it.
*
* this.can(permission)
* this.can(permission, targetUser)
* Checks if the user has the permission to do something, or if a
* targetUser is passed, check if the user has permission to do
* it to that user. Will automatically give the user an "Access
* denied" message if the user doesn't have permission: use
* user.can() if you don't want that message.
*
* Should usually be near the top of the command, like:
* if (!this.can('potd')) return false;
*
* this.canBroadcast()
* Signifies that a message can be broadcast, as long as the user
* has permission to. This will check to see if the user used
* "!command" instead of "/command". If so, it will check to see
* if the user has permission to broadcast (by default, voice+ can),
* and return false if not. Otherwise, it will set it up so that
* this.sendReply and this.sendReplyBox will broadcast to the room
* instead of just the user that used the command.
*
* Should usually be near the top of the command, like:
* if (!this.canBroadcast()) return false;
*
* this.canTalk()
* Checks to see if the user can speak in the room. Returns false
* if the user can't speak (is muted, the room has modchat on, etc),
* or true otherwise.
*
* Should usually be near the top of the command, like:
* if (!this.canTalk()) return false;
*
* this.canTalk(message)
* Checks to see if the user can say the message. In addition to
* running the checks from this.canTalk(), it also checks to see if
* the message has any banned words or is too long. Returns the
* filtered message, or a falsy value if the user can't speak.
*
* Should usually be near the top of the command, like:
* target = this.canTalk(target);
* if (!target) return false;
*
* this.parse(message)
* Runs the message as if the user had typed it in.
*
* Mostly useful for giving help messages, like for commands that
* require a target:
* if (!target) return this.parse('/help msg');
*
* After 10 levels of recursion (calling this.parse from a command
* called by this.parse from a command called by this.parse etc)
* we will assume it's a bug in your command and error out.
*
* this.targetUserOrSelf(target)
* If target is blank, returns the user that sent the message.
* Otherwise, returns the user with the username in target, or
* a falsy value if no user with that username exists.
*
* this.splitTarget(target)
* Splits a target in the form "user, message" into its
* constituent parts. Returns message, and sets this.targetUser to
* the user, and this.targetUsername to the username.
*
* Remember to check if this.targetUser exists before going further.
*
* Unless otherwise specified, these functions will return undefined,
* so you can return this.sendReply or something to send a reply and
* stop the command there.
*
* @license MIT license
*/
var commands = exports.commands = {
ip: 'whois',
getip: 'whois',
rooms: 'whois',
altcheck: 'whois',
alt: 'whois',
alts: 'whois',
getalts: 'whois',
whois: function(target, room, user) {
var targetUser = this.targetUserOrSelf(target, user.group === ' ');
if (!targetUser) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
this.sendReply('User: '+targetUser.name);
if (user.can('alts', targetUser)) {
var alts = targetUser.getAlts();
var output = '';
for (var i in targetUser.prevNames) {
if (output) output += ", ";
output += targetUser.prevNames[i];
}
if (output) this.sendReply('Previous names: '+output);
for (var j=0; j<alts.length; j++) {
var targetAlt = Users.get(alts[j]);
if (!targetAlt.named && !targetAlt.connected) continue;
if (targetAlt.group === '~' && user.group !== '~') continue;
this.sendReply('Alt: '+targetAlt.name);
output = '';
for (var i in targetAlt.prevNames) {
if (output) output += ", ";
output += targetAlt.prevNames[i];
}
if (output) this.sendReply('Previous names: '+output);
}
}
if (config.groups[targetUser.group] && config.groups[targetUser.group].name) {
this.sendReply('Group: ' + config.groups[targetUser.group].name + ' (' + targetUser.group + ')');
}
if (targetUser.goldDev) {
this.sendReply('(Gold Development Staff)');
}
if (targetUser.vipUser) {
this.sendReply('(<font color="gold">VIP</font> User)');
}
if (targetUser.isSysop) {
this.sendReply('(Pok\xE9mon Showdown System Operator)');
}
if (!targetUser.authenticated) {
this.sendReply('(Unregistered)');
}
if (!this.broadcasting && (user.can('ip', targetUser) || user === targetUser)) {
var ips = Object.keys(targetUser.ips);
this.sendReply('IP' + ((ips.length > 1) ? 's' : '') + ': ' + ips.join(', '));
}
if (targetUser.canCustomSymbol || targetUser.canCustomAvatar || targetUser.canAnimatedAvatar || targetUser.canChatRoom || targetUser.canTrainerCard || targetUser.canFixItem || targetUser.canDecAdvertise || targetUser.canBadge || targetUser.canPOTD || targetUser.canForcerename || targetUser.canMusicBox) {
var i = '';
if (targetUser.canCustomSymbol) i += ' Custom Symbol';
if (targetUser.canCustomAvatar) i += ' Custom Avatar';
if (targetUser.canAnimatedAvatar) i += ' Animated Avatar';
if (targetUser.canChatRoom) i += ' Chat Room';
if (targetUser.canTrainerCard) i += ' Trainer Card';
if (targetUser.canFixItem) i += ' Alter card/avatar/music box';
if (targetUser.canDecAdvertise) i += ' Declare Advertise';
if (targetUser.canBadge) i += ' VIP Badge / Global Voice';
if (targetUser.canMusicBox) i += ' Music Box';
if (targetUser.canPOTD) i += ' POTD';
if (targetUser.canForcerename) i += ' Forcerename'
this.sendReply('Eligible for: ' + i);
}
if (targetUser.canVIP) {
var i = '';
if (targetUser.canVIP) i += '(VIP User)';
this.sendReply(i);
}
var output = 'In rooms: ';
var first = true;
for (var i in targetUser.roomCount) {
if (i === 'global' || Rooms.get(i).isPrivate) continue;
if (!first) output += ' | ';
first = false;
output += '<a href="/'+i+'" room="'+i+'">'+i+'</a>';
}
if (!targetUser.connected || targetUser.isAway) {
this.sendReply('|raw|This user is ' + ((!targetUser.connected) ? '<font color = "red">offline</font>.' : '<font color = "orange">away</font>.'));
}
this.sendReply('|raw|'+output);
},
fork: function(target, room, user) {
if (!this.canBroadcast()) return;
if (!this.canTalk()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/HrDUGmr.png" width=75 height= 100>');
this.add('|c|@fork| .3. ``**(fork\'d by '+user.name+')**``');
},
zarel: function (target, room, user, connection, cmd) {
if (!this.canTalk()) return;
this.add('|c|~Zarel| heh ``**(zarel\'d by '+user.name+')**``');
},
aip: 'inprivaterooms',
awhois: 'inprivaterooms',
allrooms: 'inprivaterooms',
prooms: 'inprivaterooms',
adminwhois: 'inprivaterooms',
inprivaterooms: function(target, room, user) {
if (!this.can('seeprivaterooms')) return false;
var targetUser = this.targetUserOrSelf(target);
if (!targetUser) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
this.sendReply('User: '+targetUser.name);
if (user.can('seeprivaterooms',targetUser)) {
var alts = targetUser.getAlts();
var output = '';
for (var i in targetUser.prevNames) {
if (output) output += ", ";
output += targetUser.prevNames[i];
}
if (output) this.sendReply('Previous names: '+output);
for (var j=0; j<alts.length; j++) {
var targetAlt = Users.get(alts[j]);
if (!targetAlt.named && !targetAlt.connected) continue;
this.sendReply('Alt: '+targetAlt.name);
output = '';
for (var i in targetAlt.prevNames) {
if (output) output += ", ";
output += targetAlt.prevNames[i];
}
if (output) this.sendReply('Previous names: '+output);
}
}
if (config.groups[targetUser.group] && config.groups[targetUser.group].name) {
this.sendReply('Group: ' + config.groups[targetUser.group].name + ' (' + targetUser.group + ')');
}
if (targetUser.isSysop) {
this.sendReply('(Pok\xE9mon Showdown System Operator)');
}
if (targetUser.goldDev) {
this.sendReply('(Gold Development Staff)');
}
if (!targetUser.authenticated) {
this.sendReply('(Unregistered)');
}
if (!this.broadcasting && (user.can('ip', targetUser) || user === targetUser)) {
var ips = Object.keys(targetUser.ips);
this.sendReply('IP' + ((ips.length > 1) ? 's' : '') + ': ' + ips.join(', '));
}
var output = 'In all rooms: ';
var first = false;
for (var i in targetUser.roomCount) {
if (i === 'global' || Rooms.get(i).isPublic) continue;
if (!first) output += ' | ';
first = false;
output += '<a href="/'+i+'" room="'+i+'">'+i+'</a>';
}
this.sendReply('|raw|'+output);
},
ipsearch: function(target, room, user) {
if (!this.can('rangeban')) return;
var atLeastOne = false;
this.sendReply("Users with IP "+target+":");
for (var userid in Users.users) {
var user = Users.users[userid];
if (user.latestIp === target) {
this.sendReply((user.connected?"+":"-")+" "+user.name);
atLeastOne = true;
}
}
if (!atLeastOne) this.sendReply("No results found.");
},
gdeclarered: 'gdeclare',
gdeclaregreen: 'gdeclare',
gdeclare: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help gdeclare');
if (!this.can('lockdown')) return false;
var roomName = (room.isPrivate)? 'a private room' : room.id;
if (cmd === 'gdeclare'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
if (cmd === 'gdeclarered'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
else if (cmd === 'gdeclaregreen'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
this.logEntry(user.name + ' used /gdeclare');
},
declaregreen: 'declarered',
declarered: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help declare');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
if (cmd === 'declarered'){
this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>');
}
else if (cmd === 'declaregreen'){
this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>');
}
this.logModCommand(user.name+' declared '+target);
},
declaregreen: 'declarered',
declarered: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help declare');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
if (cmd === 'declarered'){
this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>');
}
else if (cmd === 'declaregreen'){
this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>');
}
this.logModCommand(user.name+' declared '+target);
},
pdeclare: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help declare');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
if (cmd === 'pdeclare'){
this.add('|raw|<div class="broadcast-purple"><b>'+target+'</b></div>');
}
else if (cmd === 'pdeclare'){
this.add('|raw|<div class="broadcast-purple"><b>'+target+'</b></div>');
}
this.logModCommand(user.name+' declared '+target);
},
k: 'kick',
aura: 'kick',
kick: function(target, room, user){
if (!this.can('lock')) return false;
if (!target) return this.sendReply('/help kick');
if (!this.canTalk()) return false;
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
if (!this.can('lock', targetUser, room)) return false;
this.addModCommand(targetUser.name+' was kicked from the room by '+user.name+'.');
targetUser.popup('You were kicked from '+room.id+' by '+user.name+'.');
targetUser.leaveRoom(room.id);
},
dm: 'daymute',
daymute: function(target, room, user) {
if (!target) return this.parse('/help daymute');
if (!this.canTalk()) return false;
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
if (!this.can('mute', targetUser, room)) return false;
if (((targetUser.mutedRooms[room.id] && (targetUser.muteDuration[room.id]||0) >= 50*60*1000) || targetUser.locked) && !target) {
var problem = ' but was already '+(!targetUser.connected ? 'offline' : targetUser.locked ? 'locked' : 'muted');
return this.privateModCommand('('+targetUser.name+' would be muted by '+user.name+problem+'.)');
}
targetUser.popup(user.name+' has muted you for 24 hours. '+target);
this.addModCommand(''+targetUser.name+' was muted by '+user.name+' for 24 hours.' + (target ? " (" + target + ")" : ""));
var alts = targetUser.getAlts();
if (alts.length) this.addModCommand(""+targetUser.name+"'s alts were also muted: "+alts.join(", "));
targetUser.mute(room.id, 24*60*60*1000, true);
},
flogout: 'forcelogout',
forcelogout: function(target, room, user) {
if(!user.can('hotpatch')) return;
if (!this.canTalk()) return false;
if (!target) return this.sendReply('/forcelogout [username], [reason] OR /flogout [username], [reason] - You do not have to add a reason');
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
if (targetUser.can('hotpatch')) return this.sendReply('You cannot force logout another Admin - nice try. Chump.');
this.addModCommand(''+targetUser.name+' was forcibly logged out by '+user.name+'.' + (target ? " (" + target + ")" : ""));
targetUser.resetName();
},
declaregreen: 'declarered',
declarered: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help declare');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
if (cmd === 'declarered'){
this.add('|raw|<div class="broadcast-red"><b>'+target+'</b></div>');
}
else if (cmd === 'declaregreen'){
this.add('|raw|<div class="broadcast-green"><b>'+target+'</b></div>');
}
this.logModCommand(user.name+' declared '+target);
},
gdeclarered: 'gdeclare',
gdeclaregreen: 'gdeclare',
gdeclare: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help gdeclare');
if (!this.can('lockdown')) return false;
var roomName = (room.isPrivate)? 'a private room' : room.id;
if (cmd === 'gdeclare'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
if (cmd === 'gdeclarered'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
else if (cmd === 'gdeclaregreen'){
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b><font size=1><i>Global declare from '+roomName+'<br /></i></font size>'+target+'</b></div>');
}
}
this.logModCommand(user.name+' globally declared '+target);
},
sd: 'declaremod',
staffdeclare: 'declaremod',
modmsg: 'declaremod',
moddeclare: 'declaremod',
declaremod: function(target, room, user) {
if (!target) return this.sendReply('/declaremod [message] - Also /moddeclare and /modmsg');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
this.privateModCommand('|raw|<div class="broadcast-red"><b><font size=1><i>Private Auth (Driver +) declare from '+user.name+'<br /></i></font size>'+target+'</b></div>');
this.logModCommand(user.name+' mod declared '+target);
},
/*********************************************************
* Shortcuts
*********************************************************/
invite: function(target, room, user) {
target = this.splitTarget(target);
if (!this.targetUser) {
return this.sendReply('User '+this.targetUsername+' not found.');
}
var roomid = (target || room.id);
if (!Rooms.get(roomid)) {
return this.sendReply('Room '+roomid+' not found.');
}
return this.parse('/msg '+this.targetUsername+', /invite '+roomid);
},
/*********************************************************
* Informational commands
*********************************************************/
stats: 'data',
dex: 'data',
pokedex: 'data',
data: function(target, room, user) {
if (!this.canBroadcast()) return;
var data = '';
var targetId = toId(target);
var newTargets = Tools.dataSearch(target);
if (newTargets && newTargets.length) {
for (var i = 0; i < newTargets.length; i++) {
if (newTargets[i].id !== targetId && !Tools.data.Aliases[targetId] && !i) {
data = "No Pokemon, item, move or ability named '" + target + "' was found. Showing the data of '" + newTargets[0].name + "' instead.\n";
}
data += '|c|~|/data-' + newTargets[i].searchType + ' ' + newTargets[i].name + '\n';
}
} else {
data = "No Pokemon, item, move or ability named '" + target + "' was found. (Check your spelling?)";
}
this.sendReply(data);
},
ds: 'dexsearch',
dsearch: 'dexsearch',
dexsearch: function (target, room, user) {
if (!this.canBroadcast()) return;
if (!target) return this.parse('/help dexsearch');
var targets = target.split(',');
var searches = {};
var allTiers = {'uber':1,'ou':1,'uu':1,'lc':1,'cap':1,'bl':1};
var allColours = {'green':1,'red':1,'blue':1,'white':1,'brown':1,'yellow':1,'purple':1,'pink':1,'gray':1,'black':1};
var showAll = false;
var megaSearch = null;
var output = 10;
for (var i in targets) {
var isNotSearch = false;
target = targets[i].trim().toLowerCase();
if (target.slice(0,1) === '!') {
isNotSearch = true;
target = target.slice(1);
}
var targetAbility = Tools.getAbility(targets[i]);
if (targetAbility.exists) {
if (!searches['ability']) searches['ability'] = {};
if (Object.count(searches['ability'], true) === 1 && !isNotSearch) return this.sendReplyBox('Specify only one ability.');
if ((searches['ability'][targetAbility.name] && isNotSearch) || (searches['ability'][targetAbility.name] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include an ability.');
searches['ability'][targetAbility.name] = !isNotSearch;
continue;
}
if (target in allTiers) {
if (!searches['tier']) searches['tier'] = {};
if ((searches['tier'][target] && isNotSearch) || (searches['tier'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a tier.');
searches['tier'][target] = !isNotSearch;
continue;
}
if (target in allColours) {
if (!searches['color']) searches['color'] = {};
if ((searches['color'][target] && isNotSearch) || (searches['color'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a color.');
searches['color'][target] = !isNotSearch;
continue;
}
var targetInt = parseInt(target);
if (0 < targetInt && targetInt < 7) {
if (!searches['gen']) searches['gen'] = {};
if ((searches['gen'][target] && isNotSearch) || (searches['gen'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a generation.');
searches['gen'][target] = !isNotSearch;
continue;
}
if (target === 'all') {
if (this.broadcasting) {
return this.sendReplyBox('A search with the parameter "all" cannot be broadcast.');
}
showAll = true;
continue;
}
if (target === 'megas' || target === 'mega') {
if ((megaSearch && isNotSearch) || (megaSearch === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include Mega Evolutions.');
megaSearch = !isNotSearch;
continue;
}
if (target.indexOf(' type') > -1) {
target = target.charAt(0).toUpperCase() + target.slice(1, target.indexOf(' type'));
if (target in Tools.data.TypeChart) {
if (!searches['types']) searches['types'] = {};
if (Object.count(searches['types'], true) === 2 && !isNotSearch) return this.sendReplyBox('Specify a maximum of two types.');
if ((searches['types'][target] && isNotSearch) || (searches['types'][target] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a type.');
searches['types'][target] = !isNotSearch;
continue;
}
}
var targetMove = Tools.getMove(target);
if (targetMove.exists) {
if (!searches['moves']) searches['moves'] = {};
if (Object.count(searches['moves'], true) === 4 && !isNotSearch) return this.sendReplyBox('Specify a maximum of 4 moves.');
if ((searches['moves'][targetMove.name] && isNotSearch) || (searches['moves'][targetMove.name] === false && !isNotSearch)) return this.sendReplyBox('A search cannot both exclude and include a move.');
searches['moves'][targetMove.name] = !isNotSearch;
continue;
} else {
return this.sendReplyBox('"' + sanitize(target, true) + '" could not be found in any of the search categories.');
}
}
if (showAll && Object.size(searches) === 0 && megaSearch === null) return this.sendReplyBox('No search parameters other than "all" were found.\nTry "/help dexsearch" for more information on this command.');
var dex = {};
for (var pokemon in Tools.data.Pokedex) {
var template = Tools.getTemplate(pokemon);
if (template.tier !== 'Unreleased' && template.tier !== 'Illegal' && (template.tier !== 'CAP' || (searches['tier'] && searches['tier']['cap'])) &&
(megaSearch === null || (megaSearch === true && template.isMega) || (megaSearch === false && !template.isMega))) {
dex[pokemon] = template;
}
}
for (var search in {'moves':1,'types':1,'ability':1,'tier':1,'gen':1,'color':1}) {
if (!searches[search]) continue;
switch (search) {
case 'types':
for (var mon in dex) {
if (Object.count(searches[search], true) === 2) {
if (!(searches[search][dex[mon].types[0]]) || !(searches[search][dex[mon].types[1]])) delete dex[mon];
} else {
if (searches[search][dex[mon].types[0]] === false || searches[search][dex[mon].types[1]] === false || (Object.count(searches[search], true) > 0 &&
(!(searches[search][dex[mon].types[0]]) && !(searches[search][dex[mon].types[1]])))) delete dex[mon];
}
}
break;
case 'tier':
for (var mon in dex) {
if ('lc' in searches[search]) {
// some LC legal Pokemon are stored in other tiers (Ferroseed/Murkrow etc)
// this checks for LC legality using the going criteria, instead of dex[mon].tier
var isLC = (dex[mon].evos && dex[mon].evos.length > 0) && !dex[mon].prevo && Tools.data.Formats['lc'].banlist.indexOf(dex[mon].species) === -1;
if ((searches[search]['lc'] && !isLC) || (!searches[search]['lc'] && isLC)) {
delete dex[mon];
continue;
}
}
if (searches[search][String(dex[mon][search]).toLowerCase()] === false) {
delete dex[mon];
} else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon];
}
break;
case 'gen':
case 'color':
for (var mon in dex) {
if (searches[search][String(dex[mon][search]).toLowerCase()] === false) {
delete dex[mon];
} else if (Object.count(searches[search], true) > 0 && !searches[search][String(dex[mon][search]).toLowerCase()]) delete dex[mon]; }
break;
case 'ability':
for (var mon in dex) {
for (var ability in searches[search]) {
var needsAbility = searches[search][ability];
var hasAbility = Object.count(dex[mon].abilities, ability) > 0;
if (hasAbility !== needsAbility) {
delete dex[mon];
break;
}
}
}
break;
case 'moves':
for (var mon in dex) {
var template = Tools.getTemplate(dex[mon].id);
if (!template.learnset) template = Tools.getTemplate(template.baseSpecies);
if (!template.learnset) continue;
for (var i in searches[search]) {
var move = Tools.getMove(i);
if (!move.exists) return this.sendReplyBox('"' + move + '" is not a known move.');
var prevoTemp = Tools.getTemplate(template.id);
while (prevoTemp.prevo && prevoTemp.learnset && !(prevoTemp.learnset[move.id])) {
prevoTemp = Tools.getTemplate(prevoTemp.prevo);
}
var canLearn = (prevoTemp.learnset.sketch && !(move.id in {'chatter':1,'struggle':1,'magikarpsrevenge':1})) || prevoTemp.learnset[move.id];
if ((!canLearn && searches[search][i]) || (searches[search][i] === false && canLearn)) delete dex[mon];
}
}
break;
default:
return this.sendReplyBox("Something broke! PM TalkTakesTime here or on the Smogon forums with the command you tried.");
}
}
var results = Object.keys(dex).map(function(speciesid) {return dex[speciesid].species;});
var resultsStr = '';
if (results.length > 0) {
if (showAll || results.length <= output) {
results.sort();
resultsStr = results.join(', ');
} else {
results.sort(function(a,b) {return Math.round(Math.random());});
resultsStr = results.slice(0, 10).join(', ') + ', and ' + string(results.length - output) + ' more. Redo the search with "all" as a search parameter to show all results.';
}
} else {
resultsStr = 'No Pokรฉmon found.';
}
return this.sendReplyBox(resultsStr);
},
learnset: 'learn',
learnall: 'learn',
learn5: 'learn',
g6learn: 'learn',
learn: function(target, room, user, connection, cmd) {
if (!target) return this.parse('/help learn');
if (!this.canBroadcast()) return;
var lsetData = {set:{}};
var targets = target.split(',');
var template = Tools.getTemplate(targets[0]);
var move = {};
var problem;
var all = (cmd === 'learnall');
if (cmd === 'learn5') lsetData.set.level = 5;
if (cmd === 'g6learn') lsetData.format = {noPokebank: true};
if (!template.exists) {
return this.sendReply('Pokemon "'+template.id+'" not found.');
}
if (targets.length < 2) {
return this.sendReply('You must specify at least one move.');
}
for (var i=1, len=targets.length; i<len; i++) {
move = Tools.getMove(targets[i]);
if (!move.exists) {
return this.sendReply('Move "'+move.id+'" not found.');
}
problem = TeamValidator.checkLearnsetSync(null, move, template, lsetData);
if (problem) break;
}
var buffer = ''+template.name+(problem?" <span class=\"message-learn-cannotlearn\">can't</span> learn ":" <span class=\"message-learn-canlearn\">can</span> learn ")+(targets.length>2?"these moves":move.name);
if (!problem) {
var sourceNames = {E:"egg",S:"event",D:"dream world"};
if (lsetData.sources || lsetData.sourcesBefore) buffer += " only when obtained from:<ul class=\"message-learn-list\">";
if (lsetData.sources) {
var sources = lsetData.sources.sort();
var prevSource;
var prevSourceType;
for (var i=0, len=sources.length; i<len; i++) {
var source = sources[i];
if (source.substr(0,2) === prevSourceType) {
if (prevSourceCount < 0) buffer += ": "+source.substr(2);
else if (all || prevSourceCount < 3) buffer += ', '+source.substr(2);
else if (prevSourceCount == 3) buffer += ', ...';
prevSourceCount++;
continue;
}
prevSourceType = source.substr(0,2);
prevSourceCount = source.substr(2)?0:-1;
buffer += "<li>gen "+source.substr(0,1)+" "+sourceNames[source.substr(1,1)];
if (prevSourceType === '5E' && template.maleOnlyHidden) buffer += " (cannot have hidden ability)";
if (source.substr(2)) buffer += ": "+source.substr(2);
}
}
if (lsetData.sourcesBefore) buffer += "<li>any generation before "+(lsetData.sourcesBefore+1);
buffer += "</ul>";
}
this.sendReplyBox(buffer);
},
weak: 'weakness',
weakness: function(target, room, user){
if (!this.canBroadcast()) return;
var targets = target.split(/[ ,\/]/);
var pokemon = Tools.getTemplate(target);
var type1 = Tools.getType(targets[0]);
var type2 = Tools.getType(targets[1]);
if (pokemon.exists) {
target = pokemon.species;
} else if (type1.exists && type2.exists) {
pokemon = {types: [type1.id, type2.id]};
target = type1.id + "/" + type2.id;
} else if (type1.exists) {
pokemon = {types: [type1.id]};
target = type1.id;
} else {
return this.sendReplyBox(sanitize(target) + " isn't a recognized type or pokemon.");
}
var weaknesses = [];
Object.keys(Tools.data.TypeChart).forEach(function (type) {
var notImmune = Tools.getImmunity(type, pokemon);
if (notImmune) {
var typeMod = Tools.getEffectiveness(type, pokemon);
if (typeMod == 1) weaknesses.push(type);
if (typeMod == 2) weaknesses.push("<b>" + type + "</b>");
}
});
if (!weaknesses.length) {
this.sendReplyBox(target + " has no weaknesses.");
} else {
this.sendReplyBox(target + " is weak to: " + weaknesses.join(', ') + " (not counting abilities).");
}
},
eff: 'effectiveness',
type: 'effectiveness',
matchup: 'effectiveness',
effectiveness: function(target, room, user) {
var targets = target.split(/[,/]/).slice(0, 2);
if (targets.length !== 2) return this.sendReply("Attacker and defender must be separated with a comma.");
var searchMethods = {'getType':1, 'getMove':1, 'getTemplate':1};
var sourceMethods = {'getType':1, 'getMove':1};
var targetMethods = {'getType':1, 'getTemplate':1};
var source;
var defender;
var foundData;
var atkName;
var defName;
for (var i=0; i<2; i++) {
for (var method in searchMethods) {
foundData = Tools[method](targets[i]);
if (foundData.exists) break;
}
if (!foundData.exists) return this.parse('/help effectiveness');
if (!source && method in sourceMethods) {
if (foundData.type) {
source = foundData;
atkName = foundData.name;
} else {
source = foundData.id;
atkName = foundData.id;
}
searchMethods = targetMethods;
} else if (!defender && method in targetMethods) {
if (foundData.types) {
defender = foundData;
defName = foundData.species+" (not counting abilities)";
} else {
defender = {types: [foundData.id]};
defName = foundData.id;
}
searchMethods = sourceMethods;
}
}
if (!this.canBroadcast()) return;
var factor = 0;
if (Tools.getImmunity(source.type || source, defender)) {
if (source.effectType !== 'Move' || source.basePower || source.basePowerCallback) {
factor = Math.pow(2, Tools.getEffectiveness(source, defender));
} else {
factor = 1;
}
}
this.sendReplyBox(atkName+" is "+factor+"x effective against "+defName+".");
},
uptime: (function(){
function formatUptime(uptime) {
if (uptime > 24*60*60) {
var uptimeText = "";
var uptimeDays = Math.floor(uptime/(24*60*60));
uptimeText = uptimeDays + " " + (uptimeDays == 1 ? "day" : "days");
var uptimeHours = Math.floor(uptime/(60*60)) - uptimeDays*24;
if (uptimeHours) uptimeText += ", " + uptimeHours + " " + (uptimeHours == 1 ? "hour" : "hours");
return uptimeText;
} else {
return uptime.seconds().duration();
}
}
return function(target, room, user) {
if (!this.canBroadcast()) return;
var uptime = process.uptime();
this.sendReplyBox("Uptime: <b>" + formatUptime(uptime) + "</b>" +
(global.uptimeRecord ? "<br /><font color=\"green\">Record: <b>" + formatUptime(global.uptimeRecord) + "</b></font>" : ""));
};
})(),
groups: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('+ <b>Voice</b> - They can use ! commands like !groups, and talk during moderated chat<br />' +
'% <b>Driver</b> - The above, and they can mute. Global % can also lock users and check for alts<br />' +
'@ <b>Moderator</b> - The above, and they can ban users<br />' +
'& <b>Leader</b> - The above, and they can promote to moderator and force ties<br />' +
'~ <b>Administrator</b> - They can do anything, like change what this message says<br />' +
'# <b>Room Owner</b> - They are administrators of the room and can almost totally control it');
},
//Trainer Cards.
pan: 'panpawn',
panpawn: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/BYTR6Fj.gif width="80" height="80">' +
'<img src="http://i.imgur.com/xzfPeaL.gif">' +
'<img src="http://i.imgur.com/qzflcXa.gif"><br />' +
'<b><font color="#4F86F7">Ace:</font></b> <font color="red">C<font color="orange">y<font color="red">n<font color="orange">d<font color="red">a<font color="orange">q<font color="red">u<font color="orange">i<font color="red">l</font><br />' +
'<font color="black">"Don\'t touch me when I\'m sleeping."</font></center>');
},
popcorn: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://www.allgeekthings.co.uk/wp-content/uploads/Popcorn.gif">');
},
destiny: 'itsdestiny',
itsdestiny: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="4" color="green"><b>It$de$tiny</b></font><br>' +
'<img src="http://www.icleiusa.org/blog/library/images-phase1-051308/landscape/blog-images-90.jpg" width="55%"> <img src="http://mindmillion.com/images/money/money-background-seamless-fill-bluesky.jpg" width="35%"><br>' +
'It ain\'t luck, it\'s destiny.');
},
miah: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="3" color="orange"><b>Miah<br>' +
'<img src="https://i.imgur.com/2RHOuPi.gif" width="50%"><img src="https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-frc1/t1.0-9/1511712_629640560439158_8415184400256062344_n.jpg" width="50%"><br></font></b>' +
'Ace: Gliscor<br>Catch phrase: Adding Euphemisms to Pokemon');
},
drag: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="5" color="red">Akely</font><br>' +
'<img src="http://gamesloveres.com/wp-content/uploads/2014/03/cute-pokemon-charmandercharmander-by-inversidom-riot-on-deviantart-llfutuct.png" width="25%"><br>' +
'Ace: Charizard<br>' +
'"Real mens can cry but real mens doesn\'t give up."');
},
kricketune: 'kriัketunะต',
kriัketunะต: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/VPcZ1rC.png"><br>' +
'<img src="http://i.imgur.com/NKGYqpn.png" width="50%"><br>' +
'Ace: Donnatello<br>' +
'"At day I own the streets, but at night I own the closet..."');
},
crowt: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><div class="infobox"><img src="http://i.imgur.com/BYTR6Fj.gif width="80" height="80" align="left">' +
' <img src="http://i.imgur.com/czMd1X5.gif" border="6" align="center">' +
' <img src="http://50.62.73.114:8000/avatars/crowt.png" align="right"><br clear="all" /></div>' +
'<blink><font color="red">~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</font></blink><br />' +
'<div class="infobox"><b><font color="#4F86F7" size="3">Ace:</font></b> <font color="blue" size="3">G</font><font color="black" size="3">r</font><font color="blue" size="3">e</font><font color="black" size="3">n</font><font color="blue" size="3">i</font><font color="black" size="3">n</font><font color="blue" size="3">j</font><font color="black" size="3">a</font></font><br />' +
'<font color="black">"It takes a great deal of <b>bravery</b> to <b>stand up to</b> our <b>enemies</b>, but just as much to stand up to our <b>friends</b>." - Dumbledore</font></center></div>');
},
ransu: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/kWaZd66.jpg" width="40%"><br>Develop a passion for learning. If you do, you will never cease to grow.');
},
panbox: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Panpawn\'s Music Box!</b><br>' +
'<center><img src="http://www.clipartbest.com/cliparts/ncE/eXz/ncEeXzpcA.svg" align="right" width="10%"></center><br>' +
'1. <a href="https://www.youtube.com/watch?v=EJR5A2dttp8"><button title="Let It Go - Connie Talbot cover">Let It Go - Connie Talbot cover</a></button><br>' +
'2. <a href="https://www.youtube.com/watch?v=Y2Ta0qCG8No"><button title="Crocodile Rock - Elton John">Crocodile Rock - Elton John</a></button><br>' +
'3. <a href="https://www.youtube.com/watch?v=ZA3vZwxnKnE"><button title="My Angel Gabriel - Lamb">My Angel Gabriel - Lamb</a></button><br>' +
'4. <a href="https://www.youtube.com/watch?v=y8AWFf7EAc4"><button title="Hallelujah - Jeff Buckley">Hallelujah - Jeff Buckley</a></button><br>' +
'5. <a href="https://www.youtube.com/watch?v=aFIApXs0_Nw"><button title="Better Off Dead - Elton John">Better Off Dead - Elton John</a></button><br>' +
'6. <a href="https://www.youtube.com/watch?v=eJLTGHEwaR8"><button title="Your Song - Carly Rose Sonenclar cover">Your Song - Carly Rose Sonenclar cover</a></button>');
},
lazerbox: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>lazerbeam\'s Music Box!</b><br>' +
'<center><img src="http://www.clipartbest.com/cliparts/ncE/eXz/ncEeXzpcA.svg" align="right" width="10%"></center><br>' +
'1. <a href="https://www.youtube.com/watch?v=fJ9rUzIMcZQ"><button title="Bohemian Rhapsody - Queen">Bohemian Rhapsody - Queen</a></button><br>' +
'2. <a href="https://www.youtube.com/watch?v=ZNaA7fVXB28"><button title="Against the Wind - Bob Seger">Against the Wind - Bob Seger</a></button><br>' +
'3. <a href="https://www.youtube.com/watch?v=TuCGiV-EVjA"><button title="Livin\' on the Edge - Aerosmith">Livin\' on the Edge - Aerosmith</a></button><br>' +
'4. <a href="https://www.youtube.com/watch?v=QZ_kYEDZVno"><button title="Rock and Roll Never Forgets - Bob Seger">Rock and Roll Never Forgets - Bob Seger</a></button><br>' +
'5. <a href="https://www.youtube.com/watch?v=GHjKEwV2-ZM"><button title="Jaded - Aerosmith">Jaded - Aerosmith</a></button>');
},
berry: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://blog.flamingtext.com/blog/2014/04/02/flamingtext_com_1396402375_186122138.png" width="50%"><br>' +
'<img src="http://50.62.73.114:8000/avatars/theberrymaster.gif"><br>' +
'Cherrim-Sunshine<br>' +
'I don\'t care what I end up being as long as I\'m a legend.');
},
moist: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://fc04.deviantart.net/fs70/i/2010/338/6/3/moister_by_arvalis-d347xgw.jpg" width="50%">');
},
spydreigon: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/57drGn3.jpg" width="75%"><br>' +
'<img src="http://fc00.deviantart.net/fs70/f/2013/102/8/3/hydreigon___draco_meteor_by_ishmam-d61irtz.png" width="75%"><br>' +
'You wish you were as badass as me');
},
mushy: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="3" color="purple">Mushy</font><br>' +
'<img src="http://i.imgur.com/yK6aCZH.png"><br>' +
'Life often causes us pain, so I try to fill it up with pleasure instead. Do you want a taste? ;)');
},
furgo: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/0qJzTgP.gif" width="25%"><br><font color="red">Ace:</font><br><img src="http://amethyst.xiaotai.org:2000/avatars/furgo.gif"><br>When I\'m sleeping, do not poke me. :I');
},
blazingflareon: 'bf',
bf: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/h3ZTk9u.gif"><br><img src="http://fc08.deviantart.net/fs71/i/2012/251/3/f/flareon_coloured_lineart_by_noel_tf-d5e166e.jpg" width="25%"><br><font size="3" color="red"><u><b><i>DARE TO DREAM');
},
mikado: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/oS2jnht.gif"><br><img src="http://i.imgur.com/oKEA0Om.png"');
},
dsg:'darkshinygiratina',
darkshinygiratina: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="4" color="blue" face="arial">DarkShinyGiratina</font><br><img src="http://i.imgur.com/sBIqMv8.gif"><br>I\'m gonna use Shadow Force on you!');
},
archbisharp: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/ibC46tQ.png"><br><img src="http://fc07.deviantart.net/fs70/f/2012/294/f/c/bisharp_by_xdarkblaze-d5ijnsf.gif" width="350" hieght="350"><br></font><b>Ruling you with an Iron Head.');
},
chimplup: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Chimplup</b> - The almighty ruler of chimchars and piplups alike, also likes pie.<br />');
},
shephard: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Shephard</b> - King Of Water and Ground types.<br />');
},
logic: 'psychological',
psychological: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/c4j9EdJ.png?1">' +
'<img src="http://i.imgur.com/tRRas7O.gif" width="200">' +
'<img src="http://i.imgur.com/TwpGsh3.png?1"><br />' +
'<img src="http://i.imgur.com/1MH0mJM.png" height="90">' +
'<img src="http://i.imgur.com/TSEXdOm.gif" width="300">' +
'<img src="http://i.imgur.com/4XlnMPZ.png" height="90"><br />' +
'If it isn\'t logical, it\'s probably Psychological.</center>');
},
seed: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Seed</b> - /me plant and water<br />');
},
auraburst: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="orange"><font size="2"><img src="http://i.imgur.com/9guvnD7.jpg"> <b>Aura Butt</b><font size="orange"><font size="2"> - Nick Cage. <img src="http://i.imgur.com/9guvnD7.jpg"><br />');
},
leo: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Leonardo DiCaprio</b> - Mirror mirror on the wall, who is the chillest of them all?<br />');
},
kupo: 'moogle',
moogle: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://50.62.73.114:8000/avatars/kupo.png"><br><b>Kupo</b> - abc!<br />');
},
starmaster: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Starmaster</b> - Well what were you expecting. Master of stars. Duh<br />');
},
ryun: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Ryun</b> - Will fuck your shit up with his army of Gloom, Chimecho, Duosion, Dunsparce, Plusle and Mr. Mime<br />');
},
miikasa: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://fc06.deviantart.net/fs70/f/2010/330/2/0/cirno_neutral_special_by_generalcirno-d33ndj0.gif"><br><font color="purple"><font size="2"><b>Miikasa</b><font color="purple"><font size="2"> - There are no buses in Gensokyo.<br />');
},
poliii: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/GsI3Y75.jpg"><br><font color="blue"><font size="2"><b>Poliii</b><font color="blue"><font size="2"> - Greninja is behind you.<br />');
},
frozengrace: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>FrozenGrace</b> - The gentle wind blows as the song birds sing of her vibrant radiance. The vibrant flowers and luscious petals dance in the serenading wind, welcoming her arrival for the epitome of all things beautiful. Bow down to her majesty for she is the Queen. Let her bestow upon you as she graces you with her elegance. FrozenGrace, eternal serenity.<br />');
},
awk: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>Awk</b> - I have nothing to say to that!<br />');
},
screamingmilotic: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>ScreamingMilotic</b> - The shiny Milotic that wants to take over the world.<br />');
},
aikenkรก: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://fc05.deviantart.net/fs70/f/2010/004/3/4/Go_MAGIKARP_use_your_Splash_by_JoshR691.gif"><b><font size="2"><font color="blue">Aikenkรก</b><font size="2"><font color="blue"> - The Master of the imp.<img src="http://fc05.deviantart.net/fs70/f/2010/004/3/4/Go_MAGIKARP_use_your_Splash_by_JoshR691.gif"><br />');
},
ipad: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/miLUHTz.png"><br><b>iPood</b><br> - A total <font color="brown">pos</font> that panpawn will ban.<br><img src="http://i.imgur.com/miLUHTz.png"><br />');
},
rhan: 'rohansound',
rohansound: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="orange"><font size="2"><b>Rohansound</b><font size="orange"><font size="2"> - The master of the Snivy!<br />');
},
alittlepaw: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://fc00.deviantart.net/fs71/f/2013/025/5/d/wolf_dance_by_windwolf13-d5sq93d.gif"><br><font color="green"><font size="3"><b>ALittlePaw</b> - Fenrir would be proud.<br />');
},
smashbrosbrawl: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b>SmashBrosBrawl</b> - Christian Bale<br />');
},
w00per: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/i3FYyoG.gif"><br><font size="2"><font color="brown"><b>W00per</b><font size="2"><font color="brown"> - "I CAME IN LIKE `EM WRECKIN` BALLZ!<br />');
},
empoleonxv: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/IHd5yRT.gif"><br><img src="http://i.imgur.com/sfQsRlH.gif"><br><b><font color="33FFFF"><big>Smiling and Waving can\'t make you more cute than me!');
},
foe: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://s21.postimg.org/durjqji4z/aaaaa.gif"><br><font size="2"><b>Foe</b><font size="2"> - Not a friend.<br />');
},
op: 'orangepoptarts',
orangepoptarts: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://www.jeboavatars.com/images/avatars/192809169066sunsetbeach.jpg"><br><b><font size="2">Orange Poptarts</b><font size="2"> - "Pop, who so you" ~ ALittlePaw<br />');
},
jack: 'jackzero',
jackzero: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="4" color="aqua">JackZero<br></font><img src="http://i.imgur.com/cE6LTKm.png"><br>I prefer the freedom of being hated to the shackles of expectaional love.<br>"Half as long, twice as bright.."');
},
wd: 'windoge',
windoge: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://i.imgur.com/qYTABJC.jpg" width="400">');
},
party: 'dance',
dance: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><img src="http://collegecandy.files.wordpress.com/2013/05/tumblr_inline_mhv5qyiqvk1qz4rgp1.gif" width="400">');
},
kayo: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="2"><b>Kayo</b><br>By the Beard of Zeus that Ghost was Fat<br><img src="http://i.imgur.com/rPe9hBa.png">');
},
saburo: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font color="red" size="5"><b>Saburo</font></b><br><img src="http://i.imgur.com/pYUt8Hf.gif"><br>The god of dance.');
},
gara: 'garazan',
nub: 'garazan',
garazan: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="6" face="comic sans ms"><font color="red">G<font color="orange">a<font color="yellow">r<font color="tan">a<font color="violet">z<font color="purple">a<font color="blue">n<br></font><img src="http://www.quickmeme.com/img/3b/3b2ef0437a963f22d89b81bf7a8ef9d46f8770414ec98f3d25db4badbbe5f19c.jpg" width="150" height="150">');
},
//End Trainer Cards.
avatars: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Your avatar can be changed using the Options menu (it looks like a gear) in the upper right of Pokemon Showdown. Custom avatars are only obtainable by staff.');
},
git: 'opensource',
opensource: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Pokemon Showdown is open source:<br />- Language: JavaScript (Node.js)<br />'+
'- <a href="https://github.com/Zarel/Pokemon-Showdown" target="_blank">Pokemon Showdown Source Code / How to create a PS server</a><br />'+
'- <a href="https://github.com/Zarel/Pokemon-Showdown-Client" target="_blank">Client Source Code</a><br />'+
'- <a href="https://github.com/panpawn/Pokemon-Showdown">Gold Source Code</a>');
},
events: 'activities',
activities: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<center><font size="3" face="comic sans ms">Gold Activities:</font></center></br>' +
'โ
<b>Tournaments</b> - Here on Gold, we have a tournaments script that allows users to partake in several different tiers. For a list of tour commands do /th. Ask in the lobby for a voice (+) or up to start one of these if you\'re interesrted!<br>' +
'โ
<b>Hangmans</b> - We have a hangans script that allows users to partake in a "hangmans" sort of a game. For a list of hangmans commands, do /hh. As a voice (+) or up in the lobby to start one of these if interested.<br>' +
'โ
<b>Scavengers</b> - We have a whole set of scavenger commands that can be done in the <button name="joinRoom" value="scavengers" target="_blank">Scavengers Room</button>.<br>' +
'โ
<b>Leagues</b> - If you click the "join room page" to the upper right (+), it will display a list of rooms we have. Several of these rooms are 3rd party leagues of Gold; join them to learn more about each one!<br>' +
'โ
<b>Battle</b> - By all means, invite your friends on here so that you can battle with each other! Here on Gold, we are always up to date on our formats, so we\'re a great place to battle on!<br>' +
'โ
<b>Chat</b> - Gold is full of great people in it\'s community and we\'d love to have you be apart of it!<br>' +
'โ
<b>Learn</b> - Are you new to Pokemon? If so, then feel FREE to ask the lobby any questions you might have!<br>' +
'โ
<b>Shop</b> - Do /shop to learn about where your Gold Bucks can go! <br>' +
'โ
<b>Plug.dj</b> - Come listen to music with us! Click <a href="http://plug.dj/gold-server/">here</a> to start!<br>' +
'<i>--PM staff (%, @, &, ~) any questions you might have!</i>');
},
introduction: 'intro',
intro: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('New to competitive pokemon?<br />' +
'- <a href="http://www.smogon.com/sim/ps_guide">Beginner\'s Guide to Pokรฉmon Showdown</a><br />' +
'- <a href="http://www.smogon.com/dp/articles/intro_comp_pokemon">An introduction to competitive Pokรฉmon</a><br />' +
'- <a href="http://www.smogon.com/bw/articles/bw_tiers">What do "OU", "UU", etc mean?</a><br />' +
'- <a href="http://www.smogon.com/xyhub/tiers">What are the rules for each format? What is "Sleep Clause"?</a>');
},
mentoring: 'smogintro',
smogonintro: 'smogintro',
smogintro: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Welcome to Smogon\'s Official Pokรฉmon Showdown server! The Mentoring room can be found ' +
'<a href="http://play.pokemonshowdown.com/communitymentoring">here</a> or by using /join communitymentoring.<br /><br />' +
'Here are some useful links to Smogon\'s Mentorship Program to help you get integrated into the community:<br />' +
'- <a href="http://www.smogon.com/mentorship/primer">Smogon Primer: A brief introduction to Smogon\'s subcommunities</a><br />' +
'- <a href="http://www.smogon.com/mentorship/introductions">Introduce yourself to Smogon!</a><br />' +
'- <a href="http://www.smogon.com/mentorship/profiles">Profiles of current Smogon Mentors</a><br />' +
'- <a href="http://mibbit.com/#[email protected]">#mentor: the Smogon Mentorship IRC channel</a><br />' +
'All of these links and more can be found at the <a href="http://www.smogon.com/mentorship/">Smogon Mentorship Program\'s hub</a>.');
},
calculator: 'calc',
calc: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Pokemon Showdown! damage calculator. (Courtesy of Honko)<br />' +
'- <a href="http://pokemonshowdown.com/damagecalc/">Damage Calculator</a>');
},
cap: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('An introduction to the Create-A-Pokemon project:<br />' +
'- <a href="http://www.smogon.com/cap/">CAP project website and description</a><br />' +
'- <a href="http://www.smogon.com/forums/showthread.php?t=48782">What Pokemon have been made?</a><br />' +
'- <a href="http://www.smogon.com/forums/showthread.php?t=3464513">Talk about the metagame here</a><br />' +
'- <a href="http://www.smogon.com/forums/showthread.php?t=3466826">Practice BW CAP teams</a>');
},
gennext: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('NEXT (also called Gen-NEXT) is a mod that makes changes to the game:<br />' +
'- <a href="https://github.com/Zarel/Pokemon-Showdown/blob/master/mods/gennext/README.md">README: overview of NEXT</a><br />' +
'Example replays:<br />' +
'- <a href="http://replay.pokemonshowdown.com/gennextou-37815908">roseyraid vs Zarel</a><br />' +
'- <a href="http://replay.pokemonshowdown.com/gennextou-37900768">QwietQwilfish vs pickdenis</a>');
},
om: 'othermetas',
othermetas: function(target, room, user) {
if (!this.canBroadcast()) return;
target = toId(target);
var buffer = '';
var matched = false;
if (!target || target === 'all') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/forums/206/">Information on the Other Metagames</a><br />';
}
if (target === 'all' || target === 'hackmons') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3475624/">Hackmons</a><br />';
}
if (target === 'all' || target === 'balancedhackmons' || target === 'bh') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3463764/">Balanced Hackmons</a><br />';
if (target !== 'all') {
buffer += '- <a href="http://www.smogon.com/forums/threads/3499973/">Balanced Hackmons Mentoring Program</a><br />';
}
}
if (target === 'all' || target === 'glitchmons') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3467120/">Glitchmons</a><br />';
}
if (target === 'all' || target === 'tiershift' || target === 'ts') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3479358/">Tier Shift</a><br />';
}
if (target === 'all' || target === 'stabmons') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3484106/">STABmons</a>';
}
if (target === 'all' || target === 'omotm' || target === 'omofthemonth' || target === 'month') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3481155/">OM of the Month</a>';
}
if (target === 'all' || target === 'skybattles') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3493601/">Sky Battles</a>';
}
if (target === 'all' || target === 'inversebattle' || target === 'inverse') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3492433/">Inverse Battle</a>';
}
if (target === 'all' || target === 'middlecup' || target === 'mc') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3494887/">Middle Cup</a>';
}
if (target === 'all' || target === 'outheorymon' || target === 'theorymon') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/3499219/">OU Theorymon</a>';
}
if (target === 'all' || target === 'index') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/threads/other-metagames-index.3472405/">OM Index</a><br />';
}
if (!matched) {
return this.sendReply('The Other Metas entry "'+target+'" was not found. Try /othermetas or /om for general help.');
}
this.sendReplyBox(buffer);
},
roomhelp: function(target, room, user) {
if (room.id === 'lobby') return this.sendReply('This command is too spammy for lobby.');
if (!this.canBroadcast()) return;
this.sendReplyBox('Room drivers (%) can use:<br />' +
'- /warn OR /k <em>username</em>: warn a user and show the Pokemon Showdown rules<br />' +
'- /mute OR /m <em>username</em>: 7 minute mute<br />' +
'- /hourmute OR /hm <em>username</em>: 60 minute mute<br />' +
'- /unmute <em>username</em>: unmute<br />' +
'- /announce OR /wall <em>message</em>: make an announcement<br />' +
'- /modlog <em>username</em>: search the moderator log of the room<br />' +
'<br />' +
'Room moderators (@) can also use:<br />' +
'- /roomban OR /rb <em>username</em>: bans user from the room<br />' +
'- /roomunban <em>username</em>: unbans user from the room<br />' +
'- /roomvoice <em>username</em>: appoint a room voice<br />' +
'- /roomdevoice <em>username</em>: remove a room voice<br />' +
'- /modchat <em>[off/autoconfirmed/+]</em>: set modchat level<br />' +
'<br />' +
'Room owners (#) can also use:<br />' +
'- /roomdesc <em>description</em>: set the room description on the room join page<br />' +
'- /rules <em>rules link</em>: set the room rules link seen when using /rules<br />' +
'- /roommod, /roomdriver <em>username</em>: appoint a room moderator/driver<br />' +
'- /roomdemod, /roomdedriver <em>username</em>: remove a room moderator/driver<br />' +
'- /modchat <em>[%/@/#]</em>: set modchat level<br />' +
'- /declare <em>message</em>: make a room declaration<br /><br>' +
'The room founder can also use:<br />' +
'- /roomowner <em>username</em><br />' +
'- /roomdeowner <em>username</em><br />' +
'</div>');
},
restarthelp: function(target, room, user) {
if (room.id === 'lobby' && !this.can('lockdown')) return false;
if (!this.canBroadcast()) return;
this.sendReplyBox('The server is restarting. Things to know:<br />' +
'- We wait a few minutes before restarting so people can finish up their battles<br />' +
'- The restart itself will take a few seconds<br />' +
'- Your ladder ranking and teams will not change<br />' +
'- We are restarting to update Gold to a newer version' +
'</div>');
},
tc: 'tourhelp',
th: 'tourhelp',
tourhelp: function(target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox('<b><font size="4"><font color="green">Tournament Commands List:</font></b><br>' +
'<b>/tpoll</b> - Starts a poll asking what tier users want. Requires: +, %, @, &, ~. <br>' +
'<b>/tour [tier], [number of people or xminutes]</b> Requires: +, %, @, &, ~.<br>' +
'<b>/endtour</b> - Ends the current tournement. Requires: +, %, @, &, ~.<br>' +
'<b>/replace [replacee], [replacement]</b> Requires: +, %, @, &, ~.<br>' +
'<b>/dq [username]</b> - Disqualifies a user from the tournement. Requires: +, %, @, &, ~.<br>' +
'<b>/fj [user]</b> - Forcibily joins a user into the tournement in the sign up phase. Requires: +, %, @, &, ~.<br>' +
'<b>/fl [username]</b> - Forcibily makes a user leave the tournement in the sign up phase. Requires: +, %, @, &, ~.<br>' +
'<b>/vr</b> - Views the current round in the tournement of whose won and whose lost and who hasn\'t started yet.<br>' +
'<b>/toursize [number]</b> - Changes the tour size if you started it with a number instead of a time limit during the sign up phase.<br>' +
'<b>/tourtime [xminutes]</b> - Changes the tour time if you started it with a time limit instead of a number during the sign up phase.<br>' +
'<b><font size="2"><font color="green">Polls Commands List:</b></font><br>' +
'<b>/poll [title], [option],[option], exc...</b> - Starts a poll. Requires: +, %, @, &, ~.<br>' +
'<b>/pr</b> - Reminds you of what the current poll is.<br>' +
'<b>/endpoll</b> - Ends the current poll. Requires: +, %, @, &, ~.<br>' +
'<b>/vote [opinion]</b> - votes for an option of the current poll.<br><br>' +
'<i>--Just ask in the lobby if you\'d like a voice or up to start a tourney!</i>');
},
rule: 'rules',
rules: function(target, room, user) {
if (!target) {
if (!this.canBroadcast()) return;
this.sendReplyBox('Please follow the rules:<br />' +
(room.rulesLink ? '- <a href="' + sanitize(room.rulesLink) + '">' + sanitize(room.title) + ' room rules</a><br />' : '') +
'- <a href="http://goldserver.weebly.com/rules.html">'+(room.rulesLink?'Global rules':'Rules')+'</a><br />' +
'</div>');
return;
}
if (!this.can('roommod', null, room)) return;
if (target.length > 80) {
return this.sendReply('Error: Room rules link is too long (must be under 80 characters). You can use a URL shortener to shorten the link.');
}
room.rulesLink = target.trim();
this.sendReply('(The room rules link is now: '+target+')');
if (room.chatRoomData) {
room.chatRoomData.rulesLink = room.rulesLink;
Rooms.global.writeChatRoomData();
}
},
faq: function(target, room, user) {
if (!this.canBroadcast()) return;
target = target.toLowerCase();
var buffer = '';
var matched = false;
if (!target || target === 'all') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq">Frequently Asked Questions</a><br />';
}
if (target === 'all' || target === 'deviation') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#deviation">Why did this user gain or lose so many points?</a><br />';
}
if (target === 'all' || target === 'doubles' || target === 'triples' || target === 'rotation') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#doubles">Can I play doubles/triples/rotation battles here?</a><br />';
}
if (target === 'all' || target === 'randomcap') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#randomcap">What is this fakemon and what is it doing in my random battle?</a><br />';
}
if (target === 'all' || target === 'restarts') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#restarts">Why is the server restarting?</a><br />';
}
if (target === 'all' || target === 'staff') {
matched = true;
buffer += '<a href="http://goldserver.weebly.com/how-do-i-get-a-rank.html">Staff FAQ</a><br />';
}
if (target === 'all' || target === 'autoconfirmed' || target === 'ac') {
matched = true;
buffer += 'A user is autoconfirmed when they have won at least one rated battle and have been registered for a week or longer.<br />';
}
if (target === 'all' || target === 'customsymbol' || target === 'cs') {
matched = true;
buffer += 'A custom symbol will bring your name up to the top of the userlist with a custom symbol next to it. These reset after the server restarts.<br />';
}
if (target === 'all' || target === 'league') {
matched = true;
buffer += 'Welcome to Gold! So, you\'re interested in making or moving a league here? If so, read <a href="http://goldserver.weebly.com/making-a-league.html">this</a> and write down your answers on a <a href="http://pastebin.com">Pastebin</a> and PM it to an admin. Good luck!<br />';
}
if (!matched) {
return this.sendReply('The FAQ entry "'+target+'" was not found. Try /faq for general help.');
}
this.sendReplyBox(buffer);
},
banlists: 'tiers',
tier: 'tiers',
tiers: function(target, room, user) {
if (!this.canBroadcast()) return;
target = toId(target);
var buffer = '';
var matched = false;
if (!target || target === 'all') {
matched = true;
buffer += '- <a href="http://www.smogon.com/tiers/">Smogon Tiers</a><br />';
buffer += '- <a href="http://www.smogon.com/forums/threads/tiering-faq.3498332/">Tiering FAQ</a><br />';
buffer += '- <a href="http://www.smogon.com/xyhub/tiers">The banlists for each tier</a><br />';
}
if (target === 'all' || target === 'ubers' || target === 'uber') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/uber">Uber Pokemon</a><br />';
}
if (target === 'all' || target === 'overused' || target === 'ou') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/ou">Overused Pokemon</a><br />';
}
if (target === 'all' || target === 'underused' || target === 'uu') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/uu">Underused Pokemon</a><br />';
}
if (target === 'all' || target === 'rarelyused' || target === 'ru') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/ru">Rarelyused Pokemon</a><br />';
}
if (target === 'all' || target === 'neverused' || target === 'nu') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/nu">Neverused Pokemon</a><br />';
}
if (target === 'all' || target === 'littlecup' || target === 'lc') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/lc">Little Cup Pokemon</a><br />';
}
if (target === 'all' || target === 'doubles') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/metagames/doubles">Doubles</a><br />';
}
if (!matched) {
return this.sendReply('The Tiers entry "'+target+'" was not found. Try /tiers for general help.');
}
this.sendReplyBox(buffer);
},
analysis: 'smogdex',
strategy: 'smogdex',
smogdex: function(target, room, user) {
if (!this.canBroadcast()) return;
var targets = target.split(',');
if (toId(targets[0]) === 'previews') return this.sendReplyBox('<a href="http://www.smogon.com/forums/threads/sixth-generation-pokemon-analyses-index.3494918/">Generation 6 Analyses Index</a>, brought to you by <a href="http://www.smogon.com">Smogon University</a>');
var pokemon = Tools.getTemplate(targets[0]);
var item = Tools.getItem(targets[0]);
var move = Tools.getMove(targets[0]);
var ability = Tools.getAbility(targets[0]);
var atLeastOne = false;
var generation = (targets[1] || "bw").trim().toLowerCase();
var genNumber = 5;
var doublesFormats = {'vgc2012':1,'vgc2013':1,'doubles':1};
var doublesFormat = (!targets[2] && generation in doublesFormats)? generation : (targets[2] || '').trim().toLowerCase();
var doublesText = '';
if (generation === "bw" || generation === "bw2" || generation === "5" || generation === "five") {
generation = "bw";
} else if (generation === "dp" || generation === "dpp" || generation === "4" || generation === "four") {
generation = "dp";
genNumber = 4;
} else if (generation === "adv" || generation === "rse" || generation === "rs" || generation === "3" || generation === "three") {
generation = "rs";
genNumber = 3;
} else if (generation === "gsc" || generation === "gs" || generation === "2" || generation === "two") {
generation = "gs";
genNumber = 2;
} else if(generation === "rby" || generation === "rb" || generation === "1" || generation === "one") {
generation = "rb";
genNumber = 1;
} else {
generation = "bw";
}
if (doublesFormat !== '') {
// Smogon only has doubles formats analysis from gen 5 onwards.
if (!(generation in {'bw':1,'xy':1}) || !(doublesFormat in doublesFormats)) {
doublesFormat = '';
} else {
doublesText = {'vgc2012':'VGC 2012 ','vgc2013':'VGC 2013 ','doubles':'Doubles '}[doublesFormat];
doublesFormat = '/' + doublesFormat;
}
}
// Pokemon
if (pokemon.exists) {
atLeastOne = true;
if (genNumber < pokemon.gen) {
return this.sendReplyBox(pokemon.name+' did not exist in '+generation.toUpperCase()+'!');
}
if (pokemon.tier === 'G4CAP' || pokemon.tier === 'G5CAP') {
generation = "cap";
}
var poke = pokemon.name.toLowerCase();
if (poke === 'nidoranm') poke = 'nidoran-m';
if (poke === 'nidoranf') poke = 'nidoran-f';
if (poke === 'farfetch\'d') poke = 'farfetchd';
if (poke === 'mr. mime') poke = 'mr_mime';
if (poke === 'mime jr.') poke = 'mime_jr';
if (poke === 'deoxys-attack' || poke === 'deoxys-defense' || poke === 'deoxys-speed' || poke === 'kyurem-black' || poke === 'kyurem-white') poke = poke.substr(0,8);
if (poke === 'wormadam-trash') poke = 'wormadam-s';
if (poke === 'wormadam-sandy') poke = 'wormadam-g';
if (poke === 'rotom-wash' || poke === 'rotom-frost' || poke === 'rotom-heat') poke = poke.substr(0,7);
if (poke === 'rotom-mow') poke = 'rotom-c';
if (poke === 'rotom-fan') poke = 'rotom-s';
if (poke === 'giratina-origin' || poke === 'tornadus-therian' || poke === 'landorus-therian') poke = poke.substr(0,10);
if (poke === 'shaymin-sky') poke = 'shaymin-s';
if (poke === 'arceus') poke = 'arceus-normal';
if (poke === 'thundurus-therian') poke = 'thundurus-t';
this.sendReplyBox('<a href="http://www.smogon.com/'+generation+'/pokemon/'+poke+doublesFormat+'">'+generation.toUpperCase()+' '+doublesText+pokemon.name+' analysis</a>, brought to you by <a href="http://www.smogon.com">Smogon University</a>');
}
// Item
if (item.exists && genNumber > 1 && item.gen <= genNumber) {
atLeastOne = true;
var itemName = item.name.toLowerCase().replace(' ', '_');
this.sendReplyBox('<a href="http://www.smogon.com/'+generation+'/items/'+itemName+'">'+generation.toUpperCase()+' '+item.name+' item analysis</a>, brought to you by <a href="http://www.smogon.com">Smogon University</a>');
}
// Ability
if (ability.exists && genNumber > 2 && ability.gen <= genNumber) {
atLeastOne = true;
var abilityName = ability.name.toLowerCase().replace(' ', '_');
this.sendReplyBox('<a href="http://www.smogon.com/'+generation+'/abilities/'+abilityName+'">'+generation.toUpperCase()+' '+ability.name+' ability analysis</a>, brought to you by <a href="http://www.smogon.com">Smogon University</a>');
}
// Move
if (move.exists && move.gen <= genNumber) {
atLeastOne = true;
var moveName = move.name.toLowerCase().replace(' ', '_');
this.sendReplyBox('<a href="http://www.smogon.com/'+generation+'/moves/'+moveName+'">'+generation.toUpperCase()+' '+move.name+' move analysis</a>, brought to you by <a href="http://www.smogon.com">Smogon University</a>');
}
if (!atLeastOne) {
return this.sendReplyBox('Pokemon, item, move, or ability not found for generation ' + generation.toUpperCase() + '.');
}
},
forums: function(target, room, user) {
if (!this.canBroadcast()) return;
return this.sendReplyBox('Gold Forums can be found <a href="http://gold.lefora.com/" >here</a>.');
},
regdate: function(target, room, user, connection) {
if (!this.canBroadcast()) return;
if (!target || target == "." || target == "," || target == "'") return this.sendReply('/regdate - Please specify a valid username.'); //temp fix for symbols that break the command
var html = ['<img ','<a href','<font ','<marquee','<blink','<center', '<button'];
for (var x in html) {
if (target.indexOf(html[x]) > -1) return this.sendReply('HTML is not supported in this command.');
}
var username = target;
target = target.replace(/\s+/g, '');
var util = require("util"),
http = require("http");
var options = {
host: "www.pokemonshowdown.com",
port: 80,
path: "/forum/~"+target
};
var content = "";
var self = this;
var req = http.request(options, function(res) {
res.setEncoding("utf8");
res.on("data", function (chunk) {
content += chunk;
});
res.on("end", function () {
content = content.split("<em");
if (content[1]) {
content = content[1].split("</p>");
if (content[0]) {
content = content[0].split("</em>");
if (content[1]) {
regdate = content[1];
data = username+' was registered on'+regdate+'.';
}
}
}
else {
data = username+' is not registered.';
}
self.sendReplyBox(data);
});
});
req.end();
},
league: function(target, room, user) {
if (!this.canBroadcast()) return;
return this.sendReplyBox('<font size="2"><b><center>Goodra League</font></b></center>' +
'โ
The league consists of 3 Gym Leaders<br /> ' +
'โ
Currently the Champion position is empty.<br/>' +
'โ
Be the first to complete the league, and the spot is yours!<br />' +
'โ
The champion gets a FREE trainer card, custom avatar and global voice!<br />' +
'โ
The Goodra League information can be found <a href="http://goldserver.weebly.com/league.html" >here</a>.<br />' +
'โ
Click <button name=\"joinRoom\" value=\"goodraleague\">here</button> to enter our League\'s room!');
},
stafffaq: function (target, room, user) {
if (!this.canBroadcast()) return;
return this.sendReplyBox('Click <a href="http://goldserver.weebly.com/how-do-i-get-a-rank-on-gold.html">here</a> to find out about Gold\'s ranks and promotion system.');
},
/*********************************************************
* Miscellaneous commands
*********************************************************/
//kupo: function(target, room, user){
//if(!this.canBroadcast()|| !user.can('broadcast')) return this.sendReply('/kupo - Access Denied.');
//if(!target) return this.sendReply('Insufficent Parameters.');
//room.add('|c|~kupo|/me '+ target);
//this.logModCommand(user.name + ' used /kupo to say ' + target);
//},
birkal: function(target, room, user) {
this.sendReply("It's not funny anymore.");
},
potd: function(target, room, user) {
if (!this.can('potd')) return false;
config.potd = target;
Simulator.SimulatorProcess.eval('config.potd = \''+toId(target)+'\'');
if (target) {
if (Rooms.lobby) Rooms.lobby.addRaw('<div class="broadcast-blue"><b>The Pokemon of the Day is now '+target+'!</b><br />This Pokemon will be guaranteed to show up in random battles.</div>');
this.logModCommand('The Pokemon of the Day was changed to '+target+' by '+user.name+'.');
} else {
if (Rooms.lobby) Rooms.lobby.addRaw('<div class="broadcast-blue"><b>The Pokemon of the Day was removed!</b><br />No pokemon will be guaranteed in random battles.</div>');
this.logModCommand('The Pokemon of the Day was removed by '+user.name+'.');
}
},
//Artist of the Day Commands:
aotdhelp: function(target, room, user) {
if (!this.canBroadcast()) return;
//This command is room specific to prevent confusion.
if (room.id !== 'thestudio') return this.sendReply("This command can only be used in The Studio.");
//Explains artist of the day to users who are new or unfamiliar with it.
this.sendReplyBox('<b>Artist of the Day:</b><br />' +
'This is a room actity for The Studio where users nomiate artists for the title of "Artist of the Day". To find out more information about this activity, click <a href="http://thepsstudioroom.weebly.com/artist-of-the-day.html">here</a>.<br><br />' +
'Commands:<br />' +
'/naotd (artist) - This will nominate your artist of the day; only do this once, please. <br />' +
'/aotd - This allows you to see who the current Artist of the Day is.<br>' +
'/aotd (artist) - Sets an artist of the day. (requires %, @, #) <br />' +
'-- <i>For more information on Artist of the Day, click <a href="http://thepsstudioroom.weebly.com/artist-of-the-day.html">here</a>. <br />' +
'-- <i><a href="http://thepsstudioroom.weebly.com/rules.html">Room rules</a></i>.');
},
nominateartistoftheday: 'naotd',
naotd: function(target, room, user){
if (room.id !== 'thestudio') return this.sendReply("This command can only be used in The Studio.");
if (target.indexOf('<img ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<a href') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<font ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<marquee') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<blink') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<center') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if(!target) return this.sendReply('/naotd needs an artist.');
if (target.length > 25) {
return this.sendReply('This Artist\'s name is too long; it cannot exceed 25 characters.');
}
if (!this.canTalk()) return;
room.addRaw(''+user.name+'\'s nomination for Artist of the Day is: <b><i>' + target +'</i></b>');
},
artistoftheday: 'aotd',
aotd: function(target, room, user) {
if (room.id !== 'thestudio') return this.sendReply("This command can only be used in The Studio.");
if (target.indexOf('<img ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<a href') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<font ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<marquee') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<blink') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<center') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (!target) {
return this.sendReply('The current Artist of the Day is: '+room.aotd);
}
if (!this.canTalk()) return;
if (target.length > 25) {
return this.sendReply('This Artist\'s name is too long; it cannot exceed 25 characters.');
}
if (!this.can('mute', null, room)) return;
room.aotd = target;
if (target) {
room.addRaw('<div class="broadcast-green"><font size="2"><b>The Artist of the Day is now <font color="black">'+target+'</font color>!</font size></b><br>' +
'<font size="1">(Set by '+user.name+'.)<br />' +
'This Artist will be posted on our <a href="http://thepsstudioroom.weebly.com/artist-of-the-day.html">Artist of the Day page</a>.</div>');
this.logModCommand('The Artist of the Day was changed to '+target+' by '+user.name+'.');
} else {
room.addRaw('<div class="broadcast-green"><b>The Artist of the Day was removed!</b><br />There is no longer an Artist of the day today!</div>');
this.logModCommand('The Artist of the Day was removed by '+user.name+'.');
}
},
nstaffmemberoftheday: 'smotd',
nsmotd: function(target, room, user){
if (room.id !== 'lobby') return this.sendReply("This command can only be used in Lobby.");
//Users cannot do HTML tags with this command.
if (target.indexOf('<img ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<a href') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<font ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<marquee') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<blink') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<center') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if(!target) return this.sendReply('/nsmotd needs an Staff Member.');
//Users who are muted cannot use this command.
if (target.length > 25) {
return this.sendReply('This Staff Member\'s name is too long; it cannot exceed 25 characters.');
}
if (!this.canTalk()) return;
room.addRaw(''+user.name+'\'s nomination for Staff Member of the Day is: <b><i>' + target +'</i></b>');
},
staffmemberoftheday: 'smotd',
smotd: function(target, room, user) {
if (room.id !== 'lobby') return this.sendReply("This command can only be used in Lobby.");
//User use HTML with this command.
if (target.indexOf('<img ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<a href') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<font ') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<marquee') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<blink') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (target.indexOf('<center') > -1) {
return this.sendReply('HTML is not supported in this command.')
}
if (!target) {
//allows user to do /smotd to view who is the Staff Member of the day if people forget.
return this.sendReply('The current Staff Member of the Day is: '+room.smotd);
}
//Users who are muted cannot use this command.
if (!this.canTalk()) return;
//Only room drivers and up may use this command.
if (target.length > 25) {
return this.sendReply('This Staff Member\'s name is too long; it cannot exceed 25 characters.');
}
if (!this.can('mute', null, room)) return;
room.smotd = target;
if (target) {
//if a user does /smotd (Staff Member name here), then we will display the Staff Member of the Day.
room.addRaw('<div class="broadcast-red"><font size="2"><b>The Staff Member of the Day is now <font color="black">'+target+'!</font color></font size></b> <font size="1">(Set by '+user.name+'.)<br />This Staff Member is now the honorary Staff Member of the Day!</div>');
this.logModCommand('The Staff Member of the Day was changed to '+target+' by '+user.name+'.');
} else {
//If there is no target, then it will remove the Staff Member of the Day.
room.addRaw('<div class="broadcast-green"><b>The Staff Member of the Day was removed!</b><br />There is no longer an Staff Member of the day today!</div>');
this.logModCommand('The Staff Member of the Day was removed by '+user.name+'.');
}
},
roll: 'dice',
dice: function(target, room, user) {
if (!this.canBroadcast()) return;
var d = target.indexOf("d");
if (d != -1) {
var num = parseInt(target.substring(0,d));
faces = NaN;
if (target.length > d) var faces = parseInt(target.substring(d + 1));
if (isNaN(num)) num = 1;
if (isNaN(faces)) return this.sendReply("The number of faces must be a valid integer.");
if (faces < 1 || faces > 1000) return this.sendReply("The number of faces must be between 1 and 1000");
if (num < 1 || num > 20) return this.sendReply("The number of dice must be between 1 and 20");
var rolls = new Array();
var total = 0;
for (var i=0; i < num; i++) {
rolls[i] = (Math.floor(faces * Math.random()) + 1);
total += rolls[i];
}
return this.sendReplyBox('Random number ' + num + 'x(1 - ' + faces + '): ' + rolls.join(', ') + '<br />Total: ' + total);
}
if (target && isNaN(target) || target.length > 21) return this.sendReply('The max roll must be a number under 21 digits.');
var maxRoll = (target)? target : 6;
var rand = Math.floor(maxRoll * Math.random()) + 1;
return this.sendReplyBox('Random number (1 - ' + maxRoll + '): ' + rand);
},
rollgame: 'dicegame',
dicegame: function(target, room, user) {
if (!this.canBroadcast()) return;
if (Users.get(''+user.name+'').money < target) {
return this.sendReply('You cannot wager more than you have, nub.');
}
if(!target) return this.sendReply('/dicegame [amount of bucks agreed to wager].');
if (isNaN(target)) {
return this.sendReply('Very funny, now use a real number.');
}
if (String(target).indexOf('.') >= 0) {
return this.sendReply('You cannot wager numbers with decimals.');
}
if (target < 0) {
return this.sendReply('Number cannot be negative.');
}
if (target > 100) {
return this.sendReply('Error: You cannot wager over 100 bucks.');
}
if (target == 0) {
return this.sendReply('Number cannot be 0.');
}
var player1 = Math.floor(6 * Math.random()) + 1;
var player2 = Math.floor(6 * Math.random()) + 1;
var winner = '';
var loser= '';
if (player1 > player2) {
winner = 'The <b>winner</b> is <font color="green">'+user.name+'</font>!';
loser = 'Better luck next time, Opponent!';
}
if (player1 < player2) {
winner = 'The <b>winner</b> is <font color="green">Opponent</font>!';
loser = 'Better luck next time, '+user.name+'!';
}
if (player1 === player2) {
winner = 'It\'s a <b>tie</b>!';
loser = 'Try again!';
}
return this.sendReplyBox('<center><font size="4"><b><img border="5" title="Dice Game!"></b></font></center><br />' +
'<font color="red">This game is worth '+target+' buck(s).</font><br />' +
'Loser: Tranfer bucks to the winner using /tb [winner], '+target+' <br />' +
'<hr>' +
''+user.name+' roll (1-6): '+player1+'<br />' +
'Opponent roll (1-6): '+player2+'<br />' +
'<hr>' +
'Winner: '+winner+'<br />' +
''+loser+'');
},
coins: 'coingame',
coin: 'coingame',
coingame: function(target, room, user) {
if (!this.canBroadcast()) return;
var random = Math.floor(1000000 * Math.random()) + 1;
var results = '';
if (random > 500000) {
results = '<img src="http://surviveourcollapse.com/wp-content/uploads/2013/01/zinc.png" width="15%" title="Heads!"><br>It\'s heads!';
}
if (random <= 500000) {
results = '<img src="http://upload.wikimedia.org/wikipedia/commons/e/e5/2005_Penny_Rev_Unc_D.png" width="15%" title="Tails!"><br>It\'s tails!';
}
return this.sendReplyBox('<center><font size="3"><b>Coin Game!</b></font><br>'+results+'');
},
register: function() {
if (!this.canBroadcast()) return;
this.sendReply("You must win a rated battle to register.");
},
br: 'banredirect',
banredirect: function(){
this.sendReply('/banredirect - This command is obsolete and has been removed.');
},
lobbychat: function(target, room, user, connection) {
if (!Rooms.lobby) return this.popupReply("This server doesn't have a lobby.");
target = toId(target);
if (target === 'off') {
user.leaveRoom(Rooms.lobby, connection.socket);
connection.send('|users|');
this.sendReply('You are now blocking lobby chat.');
} else {
user.joinRoom(Rooms.lobby, connection);
this.sendReply('You are now receiving lobby chat.');
}
},
a: function(target, room, user) {
if (!this.can('battlemessage')) return false;
// secret sysop command
room.add(target);
},
/*********************************************************
* Help commands
*********************************************************/
commands: 'help',
h: 'help',
'?': 'help',
help: function(target, room, user) {
target = target.toLowerCase();
var matched = false;
if (target === 'all' || target === 'msg' || target === 'pm' || target === 'whisper' || target === 'w') {
matched = true;
this.sendReply('/msg OR /whisper OR /w [username], [message] - Send a private message.');
}
if (target === 'all' || target === 'r' || target === 'reply') {
matched = true;
this.sendReply('/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to.');
}
if (target === 'all' || target === 'getip' || target === 'ip') {
matched = true;
this.sendReply('/ip - Get your own IP address.');
this.sendReply('/ip [username] - Get a user\'s IP address. Requires: @ & ~');
}
if (target === 'all' || target === 'rating' || target === 'ranking' || target === 'rank' || target === 'ladder') {
matched = true;
this.sendReply('/rating - Get your own rating.');
this.sendReply('/rating [username] - Get user\'s rating.');
}
if (target === 'all' || target === 'nick') {
matched = true;
this.sendReply('/nick [new username] - Change your username.');
}
if (target === 'all' || target === 'avatar') {
matched = true;
this.sendReply('/avatar [new avatar number] - Change your trainer sprite.');
}
if (target === 'all' || target === 'unlink') {
matched = true;
this.sendReply('/unlink [user] - Makes all prior links posted by this user unclickable. Requires: %, @, &, ~');
}
if (target === 'all' || target === 'rooms') {
matched = true;
this.sendReply('/rooms [username] - Show what rooms a user is in.');
}
if (target === 'all' || target === 'whois') {
matched = true;
this.sendReply('/whois [username] - Get details on a username: group, and rooms.');
}
if (target === 'all' || target === 'data') {
matched = true;
this.sendReply('/data [pokemon/item/move/ability] - Get details on this pokemon/item/move/ability.');
this.sendReply('!data [pokemon/item/move/ability] - Show everyone these details. Requires: + % @ & ~');
}
if (target === "all" || target === 'analysis') {
matched = true;
this.sendReply('/analysis [pokemon], [generation] - Links to the Smogon University analysis for this Pokemon in the given generation.');
this.sendReply('!analysis [pokemon], [generation] - Shows everyone this link. Requires: + % @ & ~');
}
if (target === 'all' || target === 'groups') {
matched = true;
this.sendReply('/groups - Explains what the + % @ & next to people\'s names mean.');
this.sendReply('!groups - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'opensource') {
matched = true;
this.sendReply('/opensource - Links to PS\'s source code repository.');
this.sendReply('!opensource - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'avatars') {
matched = true;
this.sendReply('/avatars - Explains how to change avatars.');
this.sendReply('!avatars - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'intro') {
matched = true;
this.sendReply('/intro - Provides an introduction to competitive pokemon.');
this.sendReply('!intro - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'cap') {
matched = true;
this.sendReply('/cap - Provides an introduction to the Create-A-Pokemon project.');
this.sendReply('!cap - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'om') {
matched = true;
this.sendReply('/om - Provides links to information on the Other Metagames.');
this.sendReply('!om - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'learn' || target === 'learnset' || target === 'learnall') {
matched = true;
this.sendReply('/learn [pokemon], [move, move, ...] - Displays how a Pokemon can learn the given moves, if it can at all.');
this.sendReply('!learn [pokemon], [move, move, ...] - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'calc' || target === 'caclulator') {
matched = true;
this.sendReply('/calc - Provides a link to a damage calculator');
this.sendReply('!calc - Shows everyone a link to a damage calculator. Requires: + % @ & ~');
}
if (target === 'all' || target === 'blockchallenges' || target === 'away' || target === 'idle') {
matched = true;
this.sendReply('/away - Blocks challenges so no one can challenge you. Deactivate it with /back.');
}
if (target === 'all' || target === 'allowchallenges' || target === 'back') {
matched = true;
this.sendReply('/back - Unlocks challenges so you can be challenged again. Deactivate it with /away.');
}
if (target === 'all' || target === 'faq') {
matched = true;
this.sendReply('/faq [theme] - Provides a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them.');
this.sendReply('!faq [theme] - Shows everyone a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them. Requires: + % @ & ~');
}
if (target === 'all' || target === 'highlight') {
matched = true;
this.sendReply('Set up highlights:');
this.sendReply('/highlight add, word - add a new word to the highlight list.');
this.sendReply('/highlight list - list all words that currently highlight you.');
this.sendReply('/highlight delete, word - delete a word from the highlight list.');
this.sendReply('/highlight delete - clear the highlight list');
}
if (target === 'all' || target === 'timestamps') {
matched = true;
this.sendReply('Set your timestamps preference:');
this.sendReply('/timestamps [all|lobby|pms], [minutes|seconds|off]');
this.sendReply('all - change all timestamps preferences, lobby - change only lobby chat preferences, pms - change only PM preferences');
this.sendReply('off - set timestamps off, minutes - show timestamps of the form [hh:mm], seconds - show timestamps of the form [hh:mm:ss]');
}
if (target === 'all' || target === 'effectiveness' || target === 'matchup' || target === 'eff' || target === 'type') {
matched = true;
this.sendReply('/effectiveness OR /matchup OR /eff OR /type [attack], [defender] - Provides the effectiveness of a move or type on another type or a Pokรฉmon.');
this.sendReply('!effectiveness OR /matchup OR !eff OR !type [attack], [defender] - Shows everyone the effectiveness of a move or type on another type or a Pokรฉmon.');
}
if (target === 'all' || target === 'pollson') {
matched = true;
this.sendReply('/pollson [none/room/all] - enables polls in the specified rooms. Requires @ & ~');
this.sendReply('/pollson - enables polls in the current room.');
this.sendReply('/pollson [room] - enables polls in the specified room.');
this.sendReply('/pollson all - enables polls in all rooms. Requires & ~');
}
if (target === 'all' || target === 'pollsoff') {
matched = true;
this.sendReply('/pollsoff [none/room/all] - disables polls in the specified rooms. Requires @ & ~');
this.sendReply('/pollsoff - disables polls in the current room.');
this.sendReply('/pollsoff [room] - disables polls in the specified room.');
this.sendReply('/pollsoff all - disables polls in all rooms. Requires & ~');
}
if (target === 'all' || target === 'dexsearch' || target === 'dsearch') {
matched = true;
this.sendReply('/dexsearch [type], [move], [move], ... - Searches for Pokemon that fulfill the selected criteria.');
this.sendReply('Search categories are: type, tier, color, moves, ability, gen.');
this.sendReply('Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black.');
this.sendReply('Valid tiers are: Uber/OU/BL/LC/CAP.');
this.sendReply('Types must be followed by " type", e.g., "dragon type".');
this.sendReply('Parameters can be excluded through the use of "!", e.g., "!water type" excludes all water types.');
this.sendReply('The parameter "mega" can be added to search for Mega Evolutions only.');
this.sendReply('The order of the parameters does not matter.');
}
if (target === 'all' || target === 'dice' || target === 'roll') {
matched = true;
this.sendReply('/dice [optional max number] - Randomly picks a number between 1 and 6, or between 1 and the number you choose.');
this.sendReply('/dice [number of dice]d[number of sides] - Simulates rolling a number of dice, e.g., /dice 2d4 simulates rolling two 4-sided dice.');
}
if (target === 'all' || target === 'join') {
matched = true;
this.sendReply('/join [roomname] - Attempts to join the room [roomname].');
}
if (target === 'all' || target === 'ignore') {
matched = true;
this.sendReply('/ignore [user] - Ignores all messages from the user [user].');
this.sendReply('Note that staff messages cannot be ignored.');
}
if (target === 'all' || target === 'invite') {
matched = true;
this.sendReply('/invite [username], [roomname] - Invites the player [username] to join the room [roomname].');
}
if (target === '%' || target === 'lock' || target === 'l') {
matched = true;
this.sendReply('/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: % @ & ~');
}
if (target === '%' || target === 'unlock') {
matched = true;
this.sendReply('/unlock [username] - Unlocks the user. Requires: % @ & ~');
}
if (target === '%' || target === 'redirect' || target === 'redir') {
matched = true;
this.sendReply('/redirect OR /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: % @ & ~');
}
if (target === '%' || target === 'modnote') {
matched = true;
this.sendReply('/modnote [note] - Adds a moderator note that can be read through modlog. Requires: % @ & ~');
}
if (target === '%' || target === 'altcheck' || target === 'alt' || target === 'alts' || target === 'getalts') {
matched = true;
this.sendReply('/alts OR /altcheck OR /alt OR /getalts [username] - Get a user\'s alts. Requires: % @ & ~');
}
if (target === '%' || target === 'forcerename' || target === 'fr') {
matched = true;
this.sendReply('/forcerename OR /fr [username], [reason] - Forcibly change a user\'s name and shows them the [reason]. Requires: % @ & ~');
}
if (target === '@' || target === 'roomban' || target === 'rb') {
matched = true;
this.sendReply('/roomban [username] - Bans the user from the room you are in. Requires: @ & ~');
}
if (target === '@' || target === 'roomunban') {
matched = true;
this.sendReply('/roomunban [username] - Unbans the user from the room you are in. Requires: @ & ~');
}
if (target === '@' || target === 'ban' || target === 'b') {
matched = true;
this.sendReply('/ban OR /b [username], [reason] - Kick user from all rooms and ban user\'s IP address with reason. Requires: @ & ~');
}
if (target === '&' || target === 'banip') {
matched = true;
this.sendReply('/banip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~');
}
if (target === '@' || target === 'unban') {
matched = true;
this.sendReply('/unban [username] - Unban a user. Requires: @ & ~');
}
if (target === '@' || target === 'unbanall') {
matched = true;
this.sendReply('/unbanall - Unban all IP addresses. Requires: @ & ~');
}
if (target === '%' || target === 'modlog') {
matched = true;
this.sendReply('/modlog [roomid|all], [n] - Roomid defaults to current room. If n is a number or omitted, display the last n lines of the moderator log. Defaults to 15. If n is not a number, search the moderator log for "n" on room\'s log [roomid]. If you set [all] as [roomid], searches for "n" on all rooms\'s logs. Requires: % @ & ~');
}
if (target === "%" || target === 'kickbattle ') {
matched = true;
this.sendReply('/kickbattle [username], [reason] - Kicks an user from a battle with reason. Requires: % @ & ~');
}
if (target === "%" || target === 'warn' || target === 'k') {
matched = true;
this.sendReply('/warn OR /k [username], [reason] - Warns a user showing them the Pokemon Showdown Rules and [reason] in an overlay. Requires: % @ & ~');
}
if (target === '%' || target === 'mute' || target === 'm') {
matched = true;
this.sendReply('/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: % @ & ~');
}
if (target === '%' || target === 'hourmute' || target === 'hm') {
matched = true;
this.sendReply('/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: % @ & ~');
}
if (target === '%' || target === 'unmute' || target === 'um') {
matched = true;
this.sendReply('/unmute [username] - Removes mute from user. Requires: % @ & ~');
}
if (target === '&' || target === 'promote') {
matched = true;
this.sendReply('/promote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: & ~');
}
if (target === '&' || target === 'demote') {
matched = true;
this.sendReply('/demote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: & ~');
}
if (target === '&' || target === 'forcetie') {
matched = true;
this.sendReply('/forcetie - Forces the current match to tie. Requires: & ~');
}
if (target === '&' || target === 'declare') {
matched = true;
this.sendReply('/declare [message] - Anonymously announces a message. Requires: & ~');
}
if (target === '~' || target === 'chatdeclare' || target === 'cdeclare') {
matched = true;
this.sendReply('/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: ~');
}
if (target === '~' || target === 'globaldeclare' || target === 'gdeclare') {
matched = true;
this.sendReply('/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: ~');
}
if (target === '%' || target === 'announce' || target === 'wall') {
matched = true;
this.sendReply('/announce OR /wall [message] - Makes an announcement. Requires: % @ & ~');
}
if (target === '@' || target === 'modchat') {
matched = true;
this.sendReply('/modchat [off/autoconfirmed/+/%/@/&/~] - Set the level of moderated chat. Requires: @ for off/autoconfirmed/+ options, & ~ for all the options');
}
if (target === '~' || target === 'hotpatch') {
matched = true;
this.sendReply('Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: ~');
this.sendReply('Hot-patching has greater memory requirements than restarting.');
this.sendReply('/hotpatch chat - reload chat-commands.js');
this.sendReply('/hotpatch battles - spawn new simulator processes');
this.sendReply('/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and also spawn new simulator processes');
}
if (target === '~' || target === 'lockdown') {
matched = true;
this.sendReply('/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: ~');
}
if (target === '~' || target === 'kill') {
matched = true;
this.sendReply('/kill - kills the server. Can\'t be done unless the server is in lockdown state. Requires: ~');
}
if (target === 'all' || target === 'kick' || target === '%') {
matched = true;
this.sendReply('/kick [user], [reason] - kicks the user from the current room. Requires %, @, &, or ~.');
this.sendReply('Requires & or ~ if used in a battle room.');
}
if (target === 'all' || target === 'dexsearch') {
matched = true;
this.sendReply('/dexsearch [type], [move], [move], ... - Searches for Pokemon that fulfill the selected criteria.');
this.sendReply('Search categories are: type, tier, color, moves, ability, gen.');
this.sendReply('Valid colors are: green, red, blue, white, brown, yellow, purple, pink, gray and black.');
this.sendReply('Valid tiers are: Uber/OU/BL/UU/BL2/RU/NU/NFE/LC/CAP/Illegal.');
this.sendReply('Types must be followed by " type", e.g., "dragon type".');
this.sendReply('The order of the parameters does not matter.');
}
if (target === 'all' || target === 'reminder' || target === 'reminders') {
matched = true;
this.sendReply('Set up and view reminders:');
this.sendReply('/reminder view - Show the reminders for the current room.');
this.sendReply('/reminder add, [message] - Adds a reminder to the current room. Most HTML is supported. Requires: # & ~');
this.sendReply('/reminder delete, [number/message] - Deletes a reminder from the current room. The number of the reminder or its message both work. Requires: # & ~');
this.sendReply('/reminder clear - Clears all reminders from the current room. Requires: # & ~');
}
if (target === 'all' || target === 'tell') {
matched = true;
this.sendReply('/tell [user], [message] - Leaves a message for the specified user that will be received when they next talk.');
}
if (target === 'all' || target === 'help' || target === 'h' || target === '?' || target === 'commands') {
matched = true;
this.sendReply('/help OR /h OR /? - Gives you help.');
}
if (!target) {
this.sendReply('COMMANDS: /msg, /reply, /ignore, /ip, /rating, /nick, /avatar, /rooms, /whois, /help, /away, /back, /timestamps, /highlight');
this.sendReply('INFORMATIONAL COMMANDS: /data, /dexsearch, /groups, /opensource, /avatars, /faq, /rules, /intro, /tiers, /othermetas, /learn, /analysis, /calc (replace / with ! to broadcast. (Requires: + % @ & ~))');
this.sendReply('For details on all room commands, use /roomhelp');
this.sendReply('For details on all commands, use /help all');
if (user.group !== config.groupsranking[0]) {
this.sendReply('DRIVER COMMANDS: /mute, /unmute, /announce, /modlog, /forcerename, /alts');
this.sendReply('MODERATOR COMMANDS: /ban, /unban, /unbanall, /ip, /redirect, /kick');
this.sendReply('LEADER COMMANDS: /promote, /demote, /forcewin, /forcetie, /declare');
this.sendReply('For details on all moderator commands, use /help @');
}
this.sendReply('For details of a specific command, use something like: /help data');
} else if (!matched) {
this.sendReply('The command "/'+target+'" was not found. Try /help for general help');
}
},
};
| Update commands.js | config/commands.js | Update commands.js | <ide><path>onfig/commands.js
<ide> coin: 'coingame',
<ide> coingame: function(target, room, user) {
<ide> if (!this.canBroadcast()) return;
<del> var random = Math.floor(1000000 * Math.random()) + 1;
<add> var random = Math.floor(2 * Math.random()) + 1;
<ide> var results = '';
<del> if (random > 500000) {
<add> if (random == 1) {
<ide> results = '<img src="http://surviveourcollapse.com/wp-content/uploads/2013/01/zinc.png" width="15%" title="Heads!"><br>It\'s heads!';
<ide> }
<del> if (random <= 500000) {
<add> if (random == 2) {
<ide> results = '<img src="http://upload.wikimedia.org/wikipedia/commons/e/e5/2005_Penny_Rev_Unc_D.png" width="15%" title="Tails!"><br>It\'s tails!';
<ide> }
<ide> return this.sendReplyBox('<center><font size="3"><b>Coin Game!</b></font><br>'+results+''); |
|
JavaScript | mit | 69fdcde608753d2853de32ddd0ac2463054c7623 | 0 | HexChronicle/Fwibble,HexChronicle/Fwibble | var React = require('react');
var Link = require('react-router').Link;
var $ = require('../../../jquery.min.js');
module.exports = React.createClass({
getInitialState: function() {
return {
username: '',
password: '',
loginErr: null
}
},
handleUsername: function (e) {
this.setState({username: e.target.value})
},
handlePassword: function (e) {
this.setState({password: e.target.value})
},
handleClick: function (e) {
e.preventDefault()
var postData = JSON.stringify({
"username": this.state.username,
"password": this.state.password
})
console.log('data:',postData)
$.ajax({
type: 'POST',
url: '/user/signup',
data: postData,
contentType: 'application/json',
success: function(data) {
console.log("success data:", data)
// display error if username unavailable else create user and login
if (data.error) {
this.setState({loginError: (<div className="alert alert-danger"><strong>{data.error}</strong></div>)})
} else {
this.setState({loginError: (<div className="alert alert-success"><strong>Login Successful</strong></div>)})
// var setUserClosure = this.props.setUser;
this.props.setUser({username: data.activeUser, active_game: data.activeGame});
// setTimeout(function(){setUserClosure(data.activeUser)}, 1000);
console.log("this is firing when you think it does", data.sessToken)
localStorage.fwibbleToken = data.sessToken;
}
}.bind(this),
error: function(data) {
console.error("error data:", data)
}.bind(this)
});
this.setState({password: ""})
},
render: function() {
return (
<div className="container">
<div className="text-center">
<div className="row">
<div className="col-md-6 col-md-offset-3">
<div className="jumbotron">
<h1 className="display-3">Fwibble</h1>
<div className="signUpForm">
<form>
<input type="text" placeholder="username" value={this.state.username} onChange={this.handleUsername} />
<br/>
<input type="password" placeholder="password" value={this.state.password} onChange={this.handlePassword} />
<br/>
<input type="submit" name="signUpSubmit" onClick={this.handleClick} />
{this.state.loginError}
</form>
<div className="row">
<a href="/signup">Already have an account? Sign in!</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}) | app/components/signup/signup.js | var React = require('react');
var Link = require('react-router').Link;
var $ = require('../../../jquery.min.js');
module.exports = React.createClass({
getInitialState: function() {
return {
username: '',
password: '',
loginErr: null
}
},
handleUsername: function (e) {
this.setState({username: e.target.value})
},
handlePassword: function (e) {
this.setState({password: e.target.value})
},
handleClick: function (e) {
e.preventDefault()
var postData = JSON.stringify({
"username": this.state.username,
"password": this.state.password
})
console.log('data:',postData)
$.ajax({
type: 'POST',
url: '/user/signup',
data: postData,
contentType: 'application/json',
success: function(data) {
console.log("success data:", data)
// display error if username unavailable else create user and login
if (data.error) {
this.setState({loginError: (<div className="alert alert-danger"><strong>{data.error}</strong></div>)})
} else {
this.setState({loginError: (<div className="alert alert-success"><strong>Login Successful</strong></div>)})
// var setUserClosure = this.props.setUser;
this.props.setUser({username: data.activeUser, active_game: data.activeGame});
// setTimeout(function(){setUserClosure(data.activeUser)}, 1000);
console.log("this is firing when you think it does", data.sessToken)
localStorage.fwibbleToken = data.sessToken;
}
}.bind(this),
error: function(data) {
console.error("error data:", data)
}.bind(this)
});
this.setState({password: ""})
},
render: function() {
return (
<div className="container">
<h2>Signup Page</h2>
<div><Link to="/">Home</Link></div>
<br />
<div className="signUpForm">
<form>
<input type="text" placeholder="username" value={this.state.username} onChange={this.handleUsername} />
<br/>
<input type="password" placeholder="password" value={this.state.password} onChange={this.handlePassword} />
<br/>
<input type="submit" name="signUpSubmit" onClick={this.handleClick} />
{this.state.loginError}
</form>
</div>
</div>
)
}
}) | sign up pge styled to match sign in page
| app/components/signup/signup.js | sign up pge styled to match sign in page | <ide><path>pp/components/signup/signup.js
<ide>
<ide> return (
<ide> <div className="container">
<del> <h2>Signup Page</h2>
<del> <div><Link to="/">Home</Link></div>
<del> <br />
<del> <div className="signUpForm">
<del> <form>
<del> <input type="text" placeholder="username" value={this.state.username} onChange={this.handleUsername} />
<del> <br/>
<del> <input type="password" placeholder="password" value={this.state.password} onChange={this.handlePassword} />
<del> <br/>
<del> <input type="submit" name="signUpSubmit" onClick={this.handleClick} />
<del> {this.state.loginError}
<del> </form>
<del> </div>
<add> <div className="text-center">
<add> <div className="row">
<add> <div className="col-md-6 col-md-offset-3">
<add> <div className="jumbotron">
<add> <h1 className="display-3">Fwibble</h1>
<add> <div className="signUpForm">
<add> <form>
<add> <input type="text" placeholder="username" value={this.state.username} onChange={this.handleUsername} />
<add> <br/>
<add> <input type="password" placeholder="password" value={this.state.password} onChange={this.handlePassword} />
<add> <br/>
<add> <input type="submit" name="signUpSubmit" onClick={this.handleClick} />
<add> {this.state.loginError}
<add> </form>
<add> <div className="row">
<add> <a href="/signup">Already have an account? Sign in!</a>
<add> </div>
<add> </div>
<add> </div>
<add> </div>
<add> </div>
<add> </div>
<ide> </div>
<ide> )
<ide> } |
|
Java | bsd-3-clause | 41de3ad14e85efd26cf5a9268978d64a82258387 | 0 | NCIP/cananolab,NCIP/cananolab,NCIP/cananolab | package gov.nih.nci.cananolab.util;
import java.util.HashMap;
import java.util.Map;
public class Constants {
public static final String DOMAIN_MODEL_NAME = "caNanoLab";
public static final String SDK_BEAN_JAR = "caNanoLabSDK-beans.jar";
public static final String CSM_APP_NAME = "caNanoLab";
public static final String DATE_FORMAT = "MM/dd/yyyy";
public static final String ACCEPT_DATE_FORMAT = "MM/dd/yy";
// File upload
public static final String FILEUPLOAD_PROPERTY = "caNanoLab.properties";
public static final String UNCOMPRESSED_FILE_DIRECTORY = "decompressedFiles";
public static final String EMPTY = "N/A";
// caNanoLab property file
public static final String CANANOLAB_PROPERTY = "caNanoLab.properties";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES,
BOOLEAN_NO };
public static final String DEFAULT_SAMPLE_PREFIX = "NANO-";
public static final String DEFAULT_APP_OWNER = "NCICB";
public static final String APP_OWNER;
public static final String VIEW_COL_DELIMITER = "~~~";
public static final String VIEW_CLASSNAME_DELIMITER = "!!!";
static {
String appOwner = PropertyUtils.getProperty(CANANOLAB_PROPERTY,
"applicationOwner").trim();
if (appOwner == null || appOwner.length() == 0)
appOwner = DEFAULT_APP_OWNER;
APP_OWNER = appOwner;
}
public static final String SAMPLE_PREFIX;
static {
String samplePrefix = PropertyUtils.getProperty(CANANOLAB_PROPERTY,
"samplePrefix");
if (samplePrefix == null || samplePrefix.length() == 0)
samplePrefix = DEFAULT_SAMPLE_PREFIX;
SAMPLE_PREFIX = samplePrefix;
}
public static final String GRID_INDEX_SERVICE_URL;
static {
String gridIndexServiceURL = PropertyUtils.getProperty(
CANANOLAB_PROPERTY, "gridIndexServiceURL").trim();
GRID_INDEX_SERVICE_URL = gridIndexServiceURL;
}
/*
* The following Strings are nano specific
*
*/
public static final String[] DEFAULT_CHARACTERIZATION_SOURCES = new String[] { APP_OWNER };
public static final String ASSOCIATED_FILE = "Other Associated File";
public static final String PROTOCOL_FILE = "Protocol File";
public static final String FOLDER_PARTICLE = "particles";
// public static final String FOLDER_REPORT = "reports";
public static final String FOLDER_PUBLICATION = "publications";
public static final String FOLDER_PROTOCOL = "protocols";
public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] {
"Free Radicals", "Peroxide" };
public static final String CHARACTERIZATION_FILE = "characterizationFile";
public static final int MAX_VIEW_TITLE_LENGTH = 23;
public static final String CSM_DATA_CURATOR = APP_OWNER + "_DataCurator";
public static final String CSM_RESEARCHER = APP_OWNER + "_Researcher";
public static final String CSM_ADMIN = APP_OWNER + "_Administrator";
public static final String CSM_PUBLIC_GROUP = "Public";
public static final String[] VISIBLE_GROUPS = new String[] {
CSM_DATA_CURATOR, CSM_RESEARCHER };
public static final String AUTO_COPY_ANNOTATION_PREFIX = "COPY";
public static final String AUTO_COPY_ANNNOTATION_VIEW_COLOR = "red";
public static final String CSM_READ_ROLE = "R";
public static final String CSM_DELETE_ROLE = "D";
public static final String CSM_EXECUTE_ROLE = "E";
public static final String CSM_CURD_ROLE = "CURD";
public static final String CSM_CUR_ROLE = "CUR";
public static final String CSM_READ_PRIVILEGE = "READ";
public static final String CSM_EXECUTE_PRIVILEGE = "EXECUTE";
public static final String CSM_DELETE_PRIVILEGE = "DELETE";
public static final String CSM_CREATE_PRIVILEGE = "CREATE";
public static final String CSM_PG_PROTOCOL = "protocol";
public static final String CSM_PG_PARTICLE = "nanoparticle";
public static final String CSM_PG_PUBLICATION = "publication";
public static final String PHYSICAL_CHARACTERIZATION_CLASS_NAME = "Physical Characterization";
public static final String IN_VITRO_CHARACTERIZATION_CLASS_NAME = "In Vitro Characterization";
public static final short CHARACTERIZATION_ROOT_DISPLAY_ORDER = 0;
// This is a hack to querying based on .class to work in case of multi-level
// inheritance with joined-subclass
// TODO check the order generated in the hibernate mapping file for each
// release
public static final Map<String, Integer> FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP = new HashMap<String, Integer>();
static {
FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String(
"OtherFunctionalizingEntity"), new Integer(0));
FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String("Biopolymer"),
new Integer(1));
FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String("Antibody"),
new Integer(2));
FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String(
"SmallMolecule"), new Integer(3));
}
/* image file name extension */
public static final String[] IMAGE_FILE_EXTENSIONS = { "AVS", "BMP", "CIN",
"DCX", "DIB", "DPX", "FITS", "GIF", "ICO", "JFIF", "JIF", "JPE",
"JPEG", "JPG", "MIFF", "OTB", "P7", "PALM", "PAM", "PBM", "PCD",
"PCDS", "PCL", "PCX", "PGM", "PICT", "PNG", "PNM", "PPM", "PSD",
"RAS", "SGI", "SUN", "TGA", "TIF", "TIFF", "WMF", "XBM", "XPM",
"YUV", "CGM", "DXF", "EMF", "EPS", "MET", "MVG", "ODG", "OTG",
"STD", "SVG", "SXD", "WMF" };
public static final String[] PRIVATE_DISPATCHES = { "create", "delete",
"setupNew", "setupUpdate", "summaryEdit", "add", "remove", "save" };
public static final String PHYSICOCHEMICAL_ASSAY_PROTOCOL = "physico-chemical assay";
public static final String INVITRO_ASSAY_PROTOCOL = "in vitro assay";
public static final String NODE_UNAVAILABLE = "Unable to connect to the grid location that you selected";
// default discovery internal for grid index server
public static final int DEFAULT_GRID_DISCOVERY_INTERVAL_IN_MINS = 20;
public static final String DOMAIN_MODEL_VERSION = "1.4";
public static final String GRID_SERVICE_PATH = "wsrf-canano/services/cagrid/CaNanoLabService";
// Default date format for exported file name.
public static final String EXPORT_FILE_DATE_FORMAT = "yyyyMMdd_HH-mm-ss-SSS";
// String for local search.
public static final String LOCAL_SITE = APP_OWNER;
// String for file repository entry in property file.
public static final String FILE_REPOSITORY_DIR = "fileRepositoryDir";
// String for site name entry in property file.
public static final String SITE_NAME = "siteName";
// String for site logo entry in property file.
public static final String SITE_LOGO = "siteLogo";
// File name of site logo.
public static final String SITE_LOGO_FILENAME = "siteLogo.gif";
// Maximum file size of site logo.
public static final int MAX_LOGO_SIZE = 65536;
// LOCATION
public static final String LOCATION = "location";
public static final int DISPLAY_TAG_TABLE_SIZE=25;
}
| src/gov/nih/nci/cananolab/util/Constants.java | package gov.nih.nci.cananolab.util;
import java.util.HashMap;
import java.util.Map;
public class Constants {
public static final String DOMAIN_MODEL_NAME = "caNanoLab";
public static final String SDK_BEAN_JAR = "caNanoLabSDK-beans.jar";
public static final String CSM_APP_NAME = "caNanoLab";
public static final String DATE_FORMAT = "MM/dd/yyyy";
public static final String ACCEPT_DATE_FORMAT = "MM/dd/yy";
// File upload
public static final String FILEUPLOAD_PROPERTY = "caNanoLab.properties";
public static final String UNCOMPRESSED_FILE_DIRECTORY = "decompressedFiles";
public static final String EMPTY = "N/A";
// caNanoLab property file
public static final String CANANOLAB_PROPERTY = "caNanoLab.properties";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES,
BOOLEAN_NO };
public static final String DEFAULT_SAMPLE_PREFIX = "NANO-";
public static final String DEFAULT_APP_OWNER = "NCICB";
public static final String APP_OWNER;
public static final String VIEW_COL_DELIMITER = "~~~";
public static final String VIEW_CLASSNAME_DELIMITER = "!!!";
static {
String appOwner = PropertyUtils.getProperty(CANANOLAB_PROPERTY,
"applicationOwner").trim();
if (appOwner == null || appOwner.length() == 0)
appOwner = DEFAULT_APP_OWNER;
APP_OWNER = appOwner;
}
public static final String SAMPLE_PREFIX;
static {
String samplePrefix = PropertyUtils.getProperty(CANANOLAB_PROPERTY,
"samplePrefix");
if (samplePrefix == null || samplePrefix.length() == 0)
samplePrefix = DEFAULT_SAMPLE_PREFIX;
SAMPLE_PREFIX = samplePrefix;
}
public static final String GRID_INDEX_SERVICE_URL;
static {
String gridIndexServiceURL = PropertyUtils.getProperty(
CANANOLAB_PROPERTY, "gridIndexServiceURL").trim();
GRID_INDEX_SERVICE_URL = gridIndexServiceURL;
}
/*
* The following Strings are nano specific
*
*/
public static final String[] DEFAULT_CHARACTERIZATION_SOURCES = new String[] { APP_OWNER };
public static final String ASSOCIATED_FILE = "Other Associated File";
public static final String PROTOCOL_FILE = "Protocol File";
public static final String FOLDER_PARTICLE = "particles";
// public static final String FOLDER_REPORT = "reports";
public static final String FOLDER_PUBLICATION = "publications";
public static final String FOLDER_PROTOCOL = "protocols";
public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] {
"Free Radicals", "Peroxide" };
public static final String CHARACTERIZATION_FILE = "characterizationFile";
public static final int MAX_VIEW_TITLE_LENGTH = 23;
public static final String CSM_DATA_CURATOR = APP_OWNER + "_DataCurator";
public static final String CSM_RESEARCHER = APP_OWNER + "_Researcher";
public static final String CSM_ADMIN = APP_OWNER + "_Administrator";
public static final String CSM_PUBLIC_GROUP = "Public";
public static final String[] VISIBLE_GROUPS = new String[] {
CSM_DATA_CURATOR, CSM_RESEARCHER };
public static final String AUTO_COPY_ANNOTATION_PREFIX = "COPY";
public static final String AUTO_COPY_ANNNOTATION_VIEW_COLOR = "red";
public static final String CSM_READ_ROLE = "R";
public static final String CSM_DELETE_ROLE = "D";
public static final String CSM_EXECUTE_ROLE = "E";
public static final String CSM_CURD_ROLE = "CURD";
public static final String CSM_CUR_ROLE = "CUR";
public static final String CSM_READ_PRIVILEGE = "READ";
public static final String CSM_EXECUTE_PRIVILEGE = "EXECUTE";
public static final String CSM_DELETE_PRIVILEGE = "DELETE";
public static final String CSM_CREATE_PRIVILEGE = "CREATE";
public static final String CSM_PG_PROTOCOL = "protocol";
public static final String CSM_PG_PARTICLE = "nanoparticle";
public static final String CSM_PG_PUBLICATION = "publication";
public static final String PHYSICAL_CHARACTERIZATION_CLASS_NAME = "Physical Characterization";
public static final String IN_VITRO_CHARACTERIZATION_CLASS_NAME = "In Vitro Characterization";
public static final short CHARACTERIZATION_ROOT_DISPLAY_ORDER = 0;
// This is a hack to querying based on .class to work in case of multi-level
// inheritance with joined-subclass
// TODO check the order generated in the hibernate mapping file for each
// release
public static final Map<String, Integer> FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP = new HashMap<String, Integer>();
static {
FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String(
"OtherFunctionalizingEntity"), new Integer(0));
FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String("Biopolymer"),
new Integer(1));
FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String("Antibody"),
new Integer(2));
FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP.put(new String(
"SmallMolecule"), new Integer(3));
}
/* image file name extension */
public static final String[] IMAGE_FILE_EXTENSIONS = { "AVS", "BMP", "CIN",
"DCX", "DIB", "DPX", "FITS", "GIF", "ICO", "JFIF", "JIF", "JPE",
"JPEG", "JPG", "MIFF", "OTB", "P7", "PALM", "PAM", "PBM", "PCD",
"PCDS", "PCL", "PCX", "PGM", "PICT", "PNG", "PNM", "PPM", "PSD",
"RAS", "SGI", "SUN", "TGA", "TIF", "TIFF", "WMF", "XBM", "XPM",
"YUV", "CGM", "DXF", "EMF", "EPS", "MET", "MVG", "ODG", "OTG",
"STD", "SVG", "SXD", "WMF" };
public static final String[] PRIVATE_DISPATCHES = { "create", "delete",
"setupNew", "setupUpdate", "summaryEdit", "add", "remove", "save" };
public static final String PHYSICOCHEMICAL_ASSAY_PROTOCOL = "physico-chemical assay";
public static final String INVITRO_ASSAY_PROTOCOL = "in vitro assay";
public static final String NODE_UNAVAILABLE = "Unable to connect to the grid location that you selected";
// default discovery internal for grid index server
public static final int DEFAULT_GRID_DISCOVERY_INTERVAL_IN_MINS = 20;
public static final String DOMAIN_MODEL_VERSION = "1.4";
public static final String GRID_SERVICE_PATH = "wsrf-canano/services/cagrid/CaNanoLabService";
// Default date format for exported file name.
public static final String EXPORT_FILE_DATE_FORMAT = "yyyyMMdd_HH-mm-ss-SSS";
// String for local search.
public static final String LOCAL_SITE = APP_OWNER;
// String for file repository entry in property file.
public static final String FILE_REPOSITORY_DIR = "fileRepositoryDir";
// String for site name entry in property file.
public static final String SITE_NAME = "siteName";
// String for site logo entry in property file.
public static final String SITE_LOGO = "siteLogo";
// File name of site logo.
public static final String SITE_LOGO_FILENAME = "siteLogo.gif";
// Maximum file size of site logo.
public static final int MAX_LOGO_SIZE = 65536;
// LOCATION
public static final String LOCATION = "location";
}
| added DISPLAY_TAG_TABLE_SIZE
SVN-Revision: 16098
| src/gov/nih/nci/cananolab/util/Constants.java | added DISPLAY_TAG_TABLE_SIZE | <ide><path>rc/gov/nih/nci/cananolab/util/Constants.java
<ide> // LOCATION
<ide> public static final String LOCATION = "location";
<ide>
<add> public static final int DISPLAY_TAG_TABLE_SIZE=25;
<ide> } |
|
Java | apache-2.0 | acc33911d9d2aff517976c1c8e0fea7f4f050bac | 0 | kamilrogowski/ZZPJ-2016-Breathalyser | package zzpj.breathalyser.service;
import org.junit.Assert;
import org.junit.Test;
import zzpj.breathalyser.model.Score;
import static org.junit.Assert.*;
/**
* Created by Krzychu on 07.09.2016.
*/
public class ScoreServiceTest {
@Test
public void addScore() throws Exception {
ScoreService scoreService = new ScoreService();
Score score = new Score();
scoreService.addScore(score);
int actual = scoreService.getScores().size();
int expected = 1;
Assert.assertEquals(expected, actual);
}
@Test
public void getScores() throws Exception {
ScoreService scoreService = new ScoreService();
Score score = new Score();
scoreService.addScore(score);
int actual = scoreService.getScores().size();
int expected = 1;
Assert.assertEquals(expected, actual);
}
@Test
public void removeScore() throws Exception {
ScoreService scoreService = new ScoreService();
Score score = new Score();
scoreService.addScore(score);
scoreService.removeScore(score);
int actual = scoreService.getScores().size();
int expected = 0;
Assert.assertEquals(expected, actual);
}
} | src/test/java/zzpj/breathalyser/service/ScoreServiceTest.java | package zzpj.breathalyser.service;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by Krzychu on 07.09.2016.
*/
public class ScoreServiceTest {
@Test
public void addScore() throws Exception {
}
@Test
public void getScores() throws Exception {
}
@Test
public void removeScore() throws Exception {
}
} | Added tests for ScoreService.
| src/test/java/zzpj/breathalyser/service/ScoreServiceTest.java | Added tests for ScoreService. | <ide><path>rc/test/java/zzpj/breathalyser/service/ScoreServiceTest.java
<ide> package zzpj.breathalyser.service;
<ide>
<add>import org.junit.Assert;
<ide> import org.junit.Test;
<add>import zzpj.breathalyser.model.Score;
<ide>
<ide> import static org.junit.Assert.*;
<ide>
<ide> public class ScoreServiceTest {
<ide> @Test
<ide> public void addScore() throws Exception {
<del>
<add> ScoreService scoreService = new ScoreService();
<add> Score score = new Score();
<add> scoreService.addScore(score);
<add> int actual = scoreService.getScores().size();
<add> int expected = 1;
<add> Assert.assertEquals(expected, actual);
<ide> }
<ide>
<ide> @Test
<ide> public void getScores() throws Exception {
<del>
<add> ScoreService scoreService = new ScoreService();
<add> Score score = new Score();
<add> scoreService.addScore(score);
<add> int actual = scoreService.getScores().size();
<add> int expected = 1;
<add> Assert.assertEquals(expected, actual);
<ide> }
<ide>
<ide> @Test
<ide> public void removeScore() throws Exception {
<del>
<add> ScoreService scoreService = new ScoreService();
<add> Score score = new Score();
<add> scoreService.addScore(score);
<add> scoreService.removeScore(score);
<add> int actual = scoreService.getScores().size();
<add> int expected = 0;
<add> Assert.assertEquals(expected, actual);
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | ee297d28bdbb23eb32e4818b8fe0d6d9d6ead3f1 | 0 | etirelli/jbpm-form-modeler,droolsjbpm/jbpm-form-modeler,porcelli-forks/jbpm-form-modeler,baldimir/jbpm-form-modeler,etirelli/jbpm-form-modeler,etirelli/jbpm-form-modeler,baldimir/jbpm-form-modeler,mbiarnes/jbpm-form-modeler,porcelli-forks/jbpm-form-modeler,droolsjbpm/jbpm-form-modeler,baldimir/jbpm-form-modeler,droolsjbpm/jbpm-form-modeler,mbiarnes/jbpm-form-modeler,mbiarnes/jbpm-form-modeler,porcelli-forks/jbpm-form-modeler | /**
* Copyright (C) 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.formModeler.api.config.builders;
import org.jbpm.formModeler.api.model.FieldType;
import java.util.ArrayList;
import java.util.List;
public class SimpleFieldTypeBuilder implements FieldTypeBuilder<FieldType> {
@Override
public List<FieldType> buildList() {
List<FieldType> result = new ArrayList<FieldType>();
FieldType ft = new FieldType();
ft.setCode("InputText");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setMaxlength(new Long(4000));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextArea");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.TextAreaFieldHandler");
ft.setMaxlength(new Long(4000));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextDouble");
ft.setFieldClass("java.lang.Double");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler");
ft.setMaxlength(new Long(100));
ft.setSize("25");
ft.setPattern("#.##");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextInteger");
ft.setFieldClass("java.lang.Integer");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler");
ft.setMaxlength(new Long(100));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextLong");
ft.setFieldClass("java.lang.Long");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler");
ft.setMaxlength(new Long(100));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextEmail");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setPattern("[a-z0-9\\!\\#$%&'*+/\\=?^_`{|}~-]+(?\\:\\\\.[a-z0-9\\!\\#$%&'*+/\\=?^_`{|}~-]+)*@(?\\:[a-z0-9](?\\:[a-z0-9-]*[a-z0-9])?\\\\.)+[a-z0-9](?\\:[a-z0-9-]*[a-z0-9])?");
ft.setMaxlength(new Long(4000));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextCP");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setPattern("[0-9]{5}");
ft.setMaxlength(new Long(5));
ft.setSize("5");
result.add(ft);
ft = new FieldType();
ft.setCode("CheckBox");
ft.setFieldClass("java.lang.Boolean");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.CheckBoxFieldHandler");
result.add(ft);
ft = new FieldType();
ft.setCode("HTMLEditor");
ft.setFieldClass("org.jbpm.formModeler.core.wrappers.HTMLString");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.HTMLTextAreaFieldHandler");
ft.setHeight("30");
ft.setSize("50");
result.add(ft);
ft = new FieldType();
ft.setCode("I18nHTMLText");
ft.setFieldClass("org.jbpm.formModeler.core.wrappers.HTMLi18n");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.HTMLi18nFieldHandler");
ft.setHeight("30");
ft.setSize("50");
result.add(ft);
ft = new FieldType();
ft.setCode("I18nText");
ft.setFieldClass("org.jbpm.formModeler.api.model.i18n.I18nSet");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.I18nSetFieldHandler");
ft.setMaxlength(new Long(4000));
ft.setSize("16");
result.add(ft);
ft = new FieldType();
ft.setCode("I18nTextArea");
ft.setFieldClass("org.jbpm.formModeler.api.model.i18n.I18nSet");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.I18nTextAreaFieldHandler");
ft.setHeight("5");
ft.setMaxlength(new Long(4000));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputDate");
ft.setFieldClass("java.util.Date");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.DateFieldHandler");
ft.setMaxlength(new Long(25));
ft.setSize("25");
ft.setPattern("MM-dd-yyyy HH:mm:ss");
result.add(ft);
ft = new FieldType();
ft.setCode("InputShortDate");
ft.setFieldClass("java.util.Date");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.ShortDateFieldHandler");
ft.setMaxlength(new Long(25));
ft.setSize("25");
ft.setPattern("MM-dd-yyyy");
result.add(ft);
ft = new FieldType();
ft.setCode("Link");
ft.setFieldClass("org.jbpm.formModeler.core.wrappers.Link");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.LinkFieldHandler");
ft.setMaxlength(new Long(4000));
ft.setSize("30");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextCCC");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setFormula("=Functions.String.upperCase({$this}.trim())");
ft.setPattern("=Functions.checkCCC({$this})");
ft.setMaxlength(new Long(20));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextIBAN");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setFormula("=Functions.String.upperCase({$this}.trim())");
ft.setPattern("=Functions.checkIBAN({$this})");
ft.setMaxlength(new Long(24));
ft.setSize("24");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextPhone");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setPattern("[0-9]{9}");
ft.setMaxlength(new Long(9));
ft.setSize("13");
result.add(ft);
return result;
}
}
| jbpm-form-modeler-core/jbpm-form-modeler-api/src/main/java/org/jbpm/formModeler/api/config/builders/SimpleFieldTypeBuilder.java | /**
* Copyright (C) 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.formModeler.api.config.builders;
import org.jbpm.formModeler.api.model.FieldType;
import java.util.ArrayList;
import java.util.List;
public class SimpleFieldTypeBuilder implements FieldTypeBuilder<FieldType> {
@Override
public List<FieldType> buildList() {
List<FieldType> result = new ArrayList<FieldType>();
FieldType ft = new FieldType();
ft.setCode("InputText");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setMaxlength(new Long(4000));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextArea");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.TextAreaFieldHandler");
ft.setMaxlength(new Long(4000));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextDouble");
ft.setFieldClass("java.lang.Double");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler");
ft.setMaxlength(new Long(100));
ft.setSize("25");
ft.setPattern("#.##");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextInteger");
ft.setFieldClass("java.lang.Integer");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler");
ft.setMaxlength(new Long(100));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextLong");
ft.setFieldClass("java.lang.Long");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler");
ft.setMaxlength(new Long(100));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextEmail");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setPattern("[a-z0-9\\!\\#$%&'*+/\\=?^_`{|}~-]+(?\\:\\\\.[a-z0-9\\!\\#$%&'*+/\\=?^_`{|}~-]+)*@(?\\:[a-z0-9](?\\:[a-z0-9-]*[a-z0-9])?\\\\.)+[a-z0-9](?\\:[a-z0-9-]*[a-z0-9])?");
ft.setMaxlength(new Long(4000));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextCP");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setPattern("[0-9]{5}");
ft.setMaxlength(new Long(5));
ft.setSize("5");
result.add(ft);
ft = new FieldType();
ft.setCode("CheckBox");
ft.setFieldClass("java.lang.Boolean");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.CheckBoxFieldHandler");
result.add(ft);
ft = new FieldType();
ft.setCode("HTMLEditor");
ft.setFieldClass("org.jbpm.formModeler.core.wrappers.HTMLString");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.HTMLTextAreaFieldHandler");
ft.setHeight("170");
ft.setSize("310");
result.add(ft);
ft = new FieldType();
ft.setCode("I18nHTMLText");
ft.setFieldClass("org.jbpm.formModeler.core.wrappers.HTMLi18n");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.HTMLi18nFieldHandler");
ft.setHeight("170");
ft.setSize("310");
result.add(ft);
ft = new FieldType();
ft.setCode("I18nText");
ft.setFieldClass("org.jbpm.formModeler.api.model.i18n.I18nSet");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.I18nSetFieldHandler");
ft.setMaxlength(new Long(4000));
ft.setSize("16");
result.add(ft);
ft = new FieldType();
ft.setCode("I18nTextArea");
ft.setFieldClass("org.jbpm.formModeler.api.model.i18n.I18nSet");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.I18nTextAreaFieldHandler");
ft.setHeight("5");
ft.setMaxlength(new Long(4000));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputDate");
ft.setFieldClass("java.util.Date");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.DateFieldHandler");
ft.setMaxlength(new Long(25));
ft.setSize("25");
ft.setPattern("MM-dd-yyyy HH:mm:ss");
result.add(ft);
ft = new FieldType();
ft.setCode("InputShortDate");
ft.setFieldClass("java.util.Date");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.ShortDateFieldHandler");
ft.setMaxlength(new Long(25));
ft.setSize("25");
ft.setPattern("MM-dd-yyyy");
result.add(ft);
ft = new FieldType();
ft.setCode("Link");
ft.setFieldClass("org.jbpm.formModeler.core.wrappers.Link");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.LinkFieldHandler");
ft.setMaxlength(new Long(4000));
ft.setSize("30");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextCCC");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setFormula("=Functions.String.upperCase({$this}.trim())");
ft.setPattern("=Functions.checkCCC({$this})");
ft.setMaxlength(new Long(20));
ft.setSize("25");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextIBAN");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setFormula("=Functions.String.upperCase({$this}.trim())");
ft.setPattern("=Functions.checkIBAN({$this})");
ft.setMaxlength(new Long(24));
ft.setSize("24");
result.add(ft);
ft = new FieldType();
ft.setCode("InputTextPhone");
ft.setFieldClass("java.lang.String");
ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.InputTextFieldHandler");
ft.setPattern("[0-9]{9}");
ft.setMaxlength(new Long(9));
ft.setSize("13");
result.add(ft);
return result;
}
}
| textarea default size changed
| jbpm-form-modeler-core/jbpm-form-modeler-api/src/main/java/org/jbpm/formModeler/api/config/builders/SimpleFieldTypeBuilder.java | textarea default size changed | <ide><path>bpm-form-modeler-core/jbpm-form-modeler-api/src/main/java/org/jbpm/formModeler/api/config/builders/SimpleFieldTypeBuilder.java
<ide> ft.setCode("HTMLEditor");
<ide> ft.setFieldClass("org.jbpm.formModeler.core.wrappers.HTMLString");
<ide> ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.HTMLTextAreaFieldHandler");
<del> ft.setHeight("170");
<del> ft.setSize("310");
<add> ft.setHeight("30");
<add> ft.setSize("50");
<ide> result.add(ft);
<ide>
<ide> ft = new FieldType();
<ide> ft.setCode("I18nHTMLText");
<ide> ft.setFieldClass("org.jbpm.formModeler.core.wrappers.HTMLi18n");
<ide> ft.setManagerClass("org.jbpm.formModeler.core.processing.fieldHandlers.HTMLi18nFieldHandler");
<del> ft.setHeight("170");
<del> ft.setSize("310");
<add> ft.setHeight("30");
<add> ft.setSize("50");
<ide> result.add(ft);
<ide>
<ide> ft = new FieldType(); |
|
Java | apache-2.0 | 79529ff124cd664eeb061ba5d88fa52d1dd81787 | 0 | facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho | /*
* Copyright (c) Meta Platforms, Inc. and 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 com.facebook.litho;
import static androidx.core.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.ComponentHostUtils.maybeSetDrawableState;
import static com.facebook.litho.FrameworkLogEvents.EVENT_MOUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_HAD_PREVIOUS_CT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_IS_DIRTY;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_EXTRAS;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOVED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_NO_OP_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNCHANGED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLERS_TOTAL_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER_TIME;
import static com.facebook.litho.LayoutOutput.getLayoutOutput;
import static com.facebook.litho.LithoMountData.getMountData;
import static com.facebook.litho.LithoMountData.isViewClickable;
import static com.facebook.litho.LithoMountData.isViewEnabled;
import static com.facebook.litho.LithoMountData.isViewFocusable;
import static com.facebook.litho.LithoMountData.isViewLongClickable;
import static com.facebook.litho.LithoMountData.isViewSelected;
import static com.facebook.litho.LithoRenderUnit.getComponentContext;
import static com.facebook.litho.LithoRenderUnit.isMountableView;
import static com.facebook.litho.ThreadUtils.assertMainThread;
import static com.facebook.rendercore.MountState.ROOT_HOST_ID;
import android.animation.AnimatorInflater;
import android.animation.StateListAnimator;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.collection.LongSparseArray;
import androidx.core.util.Preconditions;
import androidx.core.view.ViewCompat;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.stats.LithoStats;
import com.facebook.rendercore.ErrorReporter;
import com.facebook.rendercore.Host;
import com.facebook.rendercore.LogLevel;
import com.facebook.rendercore.MountDelegate;
import com.facebook.rendercore.MountDelegateTarget;
import com.facebook.rendercore.MountItem;
import com.facebook.rendercore.MountItemsPool;
import com.facebook.rendercore.RenderCoreExtensionHost;
import com.facebook.rendercore.RenderCoreSystrace;
import com.facebook.rendercore.RenderTree;
import com.facebook.rendercore.RenderTreeNode;
import com.facebook.rendercore.RenderUnit;
import com.facebook.rendercore.UnmountDelegateExtension;
import com.facebook.rendercore.extensions.ExtensionState;
import com.facebook.rendercore.extensions.MountExtension;
import com.facebook.rendercore.incrementalmount.IncrementalMountOutput;
import com.facebook.rendercore.utils.BoundsUtils;
import com.facebook.rendercore.visibility.VisibilityItem;
import com.facebook.rendercore.visibility.VisibilityMountExtension;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Encapsulates the mounted state of a {@link Component}. Provides APIs to update state by recycling
* existing UI elements e.g. {@link Drawable}s.
*
* @see #mount(LayoutState, Rect, boolean)
* @see LithoView
* @see LayoutState
*/
@ThreadConfined(ThreadConfined.UI)
class MountState implements MountDelegateTarget {
private static final String INVALID_REENTRANT_MOUNTS = "MountState:InvalidReentrantMounts";
private static final double NS_IN_MS = 1000000.0;
private static final Rect sTempRect = new Rect();
// Holds the current list of mounted items.
// Should always be used within a draw lock.
private final LongSparseArray<MountItem> mIndexToItemMap;
// Holds a list of MountItems that are currently mounted which can mount incrementally.
private final LongSparseArray<MountItem> mCanMountIncrementallyMountItems;
// A map from test key to a list of one or more `TestItem`s which is only allocated
// and populated during test runs.
private final Map<String, Deque<TestItem>> mTestItemMap;
// Both these arrays are updated in prepareMount(), thus during mounting they hold the information
// about the LayoutState that is being mounted, not mLastMountedLayoutState
@Nullable private long[] mLayoutOutputsIds;
// True if we are receiving a new LayoutState and we need to completely
// refresh the content of the HostComponent. Always set from the main thread.
private boolean mIsDirty;
// True if MountState is currently performing mount.
private boolean mIsMounting;
// See #needsRemount()
private boolean mNeedsRemount;
// Holds the list of known component hosts during a mount pass.
private final LongSparseArray<ComponentHost> mHostsByMarker = new LongSparseArray<>();
private final ComponentContext mContext;
private final LithoView mLithoView;
private final Rect mPreviousLocalVisibleRect = new Rect();
private final PrepareMountStats mPrepareMountStats = new PrepareMountStats();
private final MountStats mMountStats = new MountStats();
private int mPreviousTopsIndex;
private int mPreviousBottomsIndex;
private int mLastMountedComponentTreeId = ComponentTree.INVALID_ID;
private @Nullable LayoutState mLayoutState;
private @Nullable LayoutState mLastMountedLayoutState;
private int mLastDisappearRangeStart = -1;
private int mLastDisappearRangeEnd = -1;
private final MountItem mRootHostMountItem;
private final @Nullable VisibilityMountExtension mVisibilityExtension;
private final @Nullable ExtensionState mVisibilityExtensionState;
private final Set<Long> mComponentIdsMountedInThisFrame = new HashSet<>();
private final DynamicPropsManager mDynamicPropsManager = new DynamicPropsManager();
private @Nullable MountDelegate mMountDelegate;
private @Nullable UnmountDelegateExtension mUnmountDelegateExtension;
private @Nullable TransitionsExtension mTransitionsExtension;
private @Nullable ExtensionState mTransitionsExtensionState;
private @Nullable HostMountContentPool mHostMountContentPool;
public final boolean mShouldUsePositionInParent =
ComponentsConfiguration.shouldUsePositionInParentForMounting;
public MountState(LithoView view) {
mIndexToItemMap = new LongSparseArray<>();
mCanMountIncrementallyMountItems = new LongSparseArray<>();
mContext = view.getComponentContext();
mLithoView = view;
mIsDirty = true;
mTestItemMap =
ComponentsConfiguration.isEndToEndTestRun ? new HashMap<String, Deque<TestItem>>() : null;
// The mount item representing the top-level root host (LithoView) which
// is always automatically mounted.
mRootHostMountItem = LithoMountData.createRootHostMountItem(mLithoView);
mMountDelegate = new MountDelegate(this);
if (ComponentsConfiguration.enableVisibilityExtension) {
mVisibilityExtension = VisibilityMountExtension.getInstance();
mVisibilityExtensionState = mMountDelegate.registerMountExtension(mVisibilityExtension);
VisibilityMountExtension.setRootHost(mVisibilityExtensionState, mLithoView);
} else {
mVisibilityExtension = null;
mVisibilityExtensionState = null;
}
// Using Incremental Mount Extension and the Transition Extension here is not allowed.
if (ComponentsConfiguration.enableTransitionsExtension) {
mTransitionsExtension =
TransitionsExtension.getInstance((AnimationsDebug.ENABLED ? AnimationsDebug.TAG : null));
mTransitionsExtensionState = mMountDelegate.registerMountExtension(mTransitionsExtension);
} else {
mTransitionsExtension = null;
mTransitionsExtensionState = null;
}
}
@Deprecated
@Override
public ExtensionState registerMountExtension(MountExtension mountExtensions) {
throw new UnsupportedOperationException("Must not be invoked when use this Litho's MountState");
}
/** @deprecated Only used for Litho's integration. Marked for removal. */
@Deprecated
@Override
public void unregisterAllExtensions() {
throw new UnsupportedOperationException("Must not be invoked when use this Litho's MountState");
}
/**
* To be called whenever the components needs to start the mount process from scratch e.g. when
* the component's props or layout change or when the components gets attached to a host.
*/
void setDirty() {
assertMainThread();
mIsDirty = true;
mPreviousLocalVisibleRect.setEmpty();
}
boolean isDirty() {
assertMainThread();
return mIsDirty;
}
/**
* True if we have manually unmounted content (e.g. via unmountAllItems) which means that while we
* may not have a new LayoutState, the mounted content does not match what the viewport for the
* LithoView may be.
*/
@Override
public boolean needsRemount() {
assertMainThread();
return mNeedsRemount;
}
/**
* Mount the layoutState on the pre-set HostView.
*
* @param layoutState a new {@link LayoutState} to mount
* @param localVisibleRect If this variable is null, then mount everything, since incremental
* mount is not enabled. Otherwise mount only what the rect (in local coordinates) contains
* @param processVisibilityOutputs whether to process visibility outputs as part of the mount
*/
void mount(
LayoutState layoutState, @Nullable Rect localVisibleRect, boolean processVisibilityOutputs) {
final ComponentTree componentTree = mLithoView.getComponentTree();
final boolean isIncrementalMountEnabled = componentTree.isIncrementalMountEnabled();
final boolean isVisibilityProcessingEnabled =
componentTree.isVisibilityProcessingEnabled() && processVisibilityOutputs;
assertMainThread();
if (layoutState == null) {
throw new IllegalStateException("Trying to mount a null layoutState");
}
final boolean shouldIncrementallyMount =
isIncrementalMountEnabled
&& localVisibleRect != null
&& !mPreviousLocalVisibleRect.isEmpty()
&& localVisibleRect.left == mPreviousLocalVisibleRect.left
&& localVisibleRect.right == mPreviousLocalVisibleRect.right;
if (mVisibilityExtension != null && mIsDirty) {
mVisibilityExtension.beforeMount(mVisibilityExtensionState, layoutState, localVisibleRect);
}
if (mTransitionsExtension != null && mIsDirty) {
mTransitionsExtension.beforeMount(mTransitionsExtensionState, layoutState, localVisibleRect);
}
mLayoutState = layoutState;
if (mIsMounting) {
ComponentsReporter.emitMessage(
ComponentsReporter.LogLevel.FATAL,
INVALID_REENTRANT_MOUNTS,
"Trying to mount while already mounting! "
+ getMountItemDebugMessage(mRootHostMountItem));
}
mIsMounting = true;
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
if (mIsDirty && !shouldIncrementallyMount) {
// Equivalent to RCMS MountState.mount
RenderCoreSystrace.beginSection("MountState.mount");
} else {
// Trace special to LMS
RenderCoreSystrace.beginSection(
"LMS."
+ (shouldIncrementallyMount ? "incrementalMount" : "mount")
+ (mIsDirty ? "Dirty" : ""));
}
ComponentsSystrace.beginSectionWithArgs("MountState.mount: " + componentTree.getSimpleName())
.arg("treeId", layoutState.getComponentTreeId())
.arg("component", componentTree.getSimpleName())
.arg("logTag", componentTree.getContext().getLogTag())
.flush();
}
final ComponentsLogger logger = componentTree.getContext().getLogger();
final int componentTreeId = layoutState.getComponentTreeId();
if (componentTreeId != mLastMountedComponentTreeId) {
// If we're mounting a new ComponentTree, don't keep around and use the previous LayoutState
// since things like transition animations aren't relevant.
clearLastMountedLayoutState();
}
final PerfEvent mountPerfEvent =
logger == null
? null
: LogTreePopulator.populatePerfEventFromLogger(
componentTree.getContext(),
logger,
logger.newPerformanceEvent(componentTree.getContext(), EVENT_MOUNT));
if (mIsDirty) {
// Prepare the data structure for the new LayoutState and removes mountItems
// that are not present anymore if isUpdateMountInPlace is enabled.
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_START");
}
prepareMount(layoutState, mountPerfEvent);
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_END");
}
}
mMountStats.reset();
if (mountPerfEvent != null && logger.isTracing(mountPerfEvent)) {
mMountStats.enableLogging();
}
if (shouldIncrementallyMount) {
performIncrementalMount(layoutState, localVisibleRect, processVisibilityOutputs);
} else {
final MountItem rootMountItem = mIndexToItemMap.get(ROOT_HOST_ID);
final Rect absoluteBounds = new Rect();
for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) {
final RenderTreeNode node = layoutState.getMountableOutputAt(i);
final LayoutOutput layoutOutput = getLayoutOutput(node);
final Component component = layoutOutput.getComponent();
final MountItem currentMountItem = getItemAt(i);
final boolean isMounted = currentMountItem != null;
final boolean isRoot = currentMountItem != null && currentMountItem == rootMountItem;
final boolean isMountable =
!isIncrementalMountEnabled
|| isMountedHostWithChildContent(currentMountItem)
|| Rect.intersects(localVisibleRect, node.getAbsoluteBounds(absoluteBounds))
|| isAnimationLocked(node)
|| isRoot;
if (isMountable && !isMounted) {
mountLayoutOutput(i, node, layoutOutput, layoutState);
if (isIncrementalMountEnabled) {
applyMountBinders(layoutOutput, getItemAt(i), i);
}
} else if (!isMountable && isMounted) {
unmountItem(i, mHostsByMarker);
} else if (isMounted) {
if (mIsDirty || (isRoot && mNeedsRemount)) {
final boolean useUpdateValueFromLayoutOutput =
mLastMountedLayoutState != null
&& mLastMountedLayoutState.getId() == layoutState.getPreviousLayoutStateId();
final long startTime = System.nanoTime();
final boolean itemUpdated =
updateMountItemIfNeeded(
node, currentMountItem, useUpdateValueFromLayoutOutput, componentTreeId, i);
if (mMountStats.isLoggingEnabled) {
if (itemUpdated) {
mMountStats.updatedNames.add(component.getSimpleName());
mMountStats.updatedTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.updatedCount++;
} else {
mMountStats.noOpCount++;
}
}
}
if (isIncrementalMountEnabled
&& component.hasChildLithoViews()
&& !mLithoView.skipNotifyVisibleBoundsChangedCalls()) {
mountItemIncrementally(currentMountItem, processVisibilityOutputs);
}
}
}
if (isIncrementalMountEnabled) {
setupPreviousMountableOutputData(layoutState, localVisibleRect);
}
}
if (isTracing) {
RenderCoreSystrace.endSection();
ComponentsSystrace.endSection(); // beginSectionWithArgs
RenderCoreSystrace.beginSection("RenderCoreExtension.afterMount");
}
afterMountMaybeUpdateAnimations();
if (isVisibilityProcessingEnabled) {
if (isTracing) {
RenderCoreSystrace.beginSection("LMS.processVisibilityOutputs");
}
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("EVENT_PROCESS_VISIBILITY_OUTPUTS_START");
}
processVisibilityOutputs(
layoutState, localVisibleRect, mPreviousLocalVisibleRect, mIsDirty, mountPerfEvent);
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("EVENT_PROCESS_VISIBILITY_OUTPUTS_END");
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
final boolean wasDirty = mIsDirty;
final boolean hadPreviousComponentTree =
(mLastMountedComponentTreeId != ComponentTree.INVALID_ID);
mIsDirty = false;
mNeedsRemount = false;
if (localVisibleRect != null) {
mPreviousLocalVisibleRect.set(localVisibleRect);
}
clearLastMountedLayoutState();
mLastMountedComponentTreeId = componentTreeId;
mLastMountedLayoutState = layoutState;
processTestOutputs(layoutState);
if (mountPerfEvent != null) {
logMountPerfEvent(logger, mountPerfEvent, wasDirty, hadPreviousComponentTree);
}
LithoStats.incrementComponentMountCount();
mIsMounting = false;
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
private void clearLastMountedLayoutState() {
mLastMountedLayoutState = null;
}
private void afterMountMaybeUpdateAnimations() {
if (mTransitionsExtension != null && mIsDirty) {
mTransitionsExtension.afterMount(mTransitionsExtensionState);
}
}
@Override
public void mount(RenderTree renderTree) {
final LayoutState layoutState = (LayoutState) renderTree.getRenderTreeData();
mount(layoutState);
}
/**
* Mount only. Similar shape to RenderCore's mount. For extras such as incremental mount,
* visibility outputs etc register an extension. To do: extract transitions logic from here.
*/
void mount(LayoutState layoutState) {
assertMainThread();
if (layoutState == null) {
throw new IllegalStateException("Trying to mount a null layoutState");
}
mLayoutState = layoutState;
if (mIsMounting) {
ComponentsReporter.emitMessage(
ComponentsReporter.LogLevel.FATAL,
INVALID_REENTRANT_MOUNTS,
"Trying to mount while already mounting! "
+ getMountItemDebugMessage(mRootHostMountItem));
}
mIsMounting = true;
final ComponentTree componentTree = mLithoView.getComponentTree();
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
ComponentsSystrace.beginSectionWithArgs("mount")
.arg("treeId", layoutState.getComponentTreeId())
.arg("component", componentTree.getSimpleName())
.arg("logTag", componentTree.getContext().getLogTag())
.flush();
}
final ComponentsLogger logger = componentTree.getContext().getLogger();
final int componentTreeId = layoutState.getComponentTreeId();
if (componentTreeId != mLastMountedComponentTreeId) {
// If we're mounting a new ComponentTree, don't keep around and use the previous LayoutState
// since things like transition animations aren't relevant.
clearLastMountedLayoutState();
}
final PerfEvent mountPerfEvent =
logger == null
? null
: LogTreePopulator.populatePerfEventFromLogger(
componentTree.getContext(),
logger,
logger.newPerformanceEvent(componentTree.getContext(), EVENT_MOUNT));
// Prepare the data structure for the new LayoutState and removes mountItems
// that are not present anymore if isUpdateMountInPlace is enabled.
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_START");
}
prepareMount(layoutState, mountPerfEvent);
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_END");
}
mMountStats.reset();
if (mountPerfEvent != null && logger.isTracing(mountPerfEvent)) {
mMountStats.enableLogging();
}
for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) {
final RenderTreeNode renderTreeNode = layoutState.getMountableOutputAt(i);
final LayoutOutput layoutOutput = getLayoutOutput(renderTreeNode);
final Component component = layoutOutput.getComponent();
if (isTracing) {
RenderCoreSystrace.beginSection(component.getSimpleName());
}
final MountItem currentMountItem = getItemAt(i);
final boolean isMounted = currentMountItem != null;
final boolean isMountable = isMountable(renderTreeNode, i);
if (!isMountable) {
if (isMounted) {
unmountItem(i, mHostsByMarker);
}
} else if (!isMounted) {
mountLayoutOutput(i, renderTreeNode, layoutOutput, layoutState);
applyMountBinders(layoutOutput, getItemAt(i), i);
} else {
final boolean useUpdateValueFromLayoutOutput =
mLastMountedLayoutState != null
&& mLastMountedLayoutState.getId() == layoutState.getPreviousLayoutStateId();
final long startTime = System.nanoTime();
final boolean itemUpdated =
updateMountItemIfNeeded(
renderTreeNode,
currentMountItem,
useUpdateValueFromLayoutOutput,
componentTreeId,
i);
if (mMountStats.isLoggingEnabled) {
if (itemUpdated) {
mMountStats.updatedNames.add(component.getSimpleName());
mMountStats.updatedTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.updatedCount++;
} else {
mMountStats.noOpCount++;
}
}
applyBindBinders(currentMountItem);
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
final boolean wasDirty = mIsDirty;
final boolean hadPreviousComponentTree =
(mLastMountedComponentTreeId != ComponentTree.INVALID_ID);
mIsDirty = false;
mNeedsRemount = false;
clearLastMountedLayoutState();
mLastMountedComponentTreeId = componentTreeId;
mLastMountedLayoutState = layoutState;
if (mountPerfEvent != null) {
logMountPerfEvent(logger, mountPerfEvent, wasDirty, hadPreviousComponentTree);
}
if (isTracing) {
ComponentsSystrace.endSection(); // beginSectionWithArgs
}
LithoStats.incrementComponentMountCount();
mIsMounting = false;
}
private void applyMountBinders(LayoutOutput layoutOutput, MountItem mountItem, int position) {
if (mTransitionsExtension != null) {
mTransitionsExtension.onBoundsAppliedToItem(
mTransitionsExtensionState,
mountItem.getRenderTreeNode().getRenderUnit(),
mountItem.getContent(),
mountItem.getRenderTreeNode().getLayoutData());
} else if (mMountDelegate != null) {
mMountDelegate.onMountItem(
mountItem.getRenderTreeNode().getRenderUnit(),
mountItem.getContent(),
mountItem.getRenderTreeNode().getLayoutData());
}
}
private void applyBindBinders(MountItem mountItem) {
if (mMountDelegate == null) {
return;
}
}
private void applyUnbindBinders(LayoutOutput output, MountItem mountItem) {
if (mTransitionsExtension != null) {
mTransitionsExtension.onUnbindItem(
mTransitionsExtensionState,
mountItem.getRenderTreeNode().getRenderUnit(),
output,
mountItem.getRenderTreeNode().getLayoutData());
} else if (mMountDelegate != null) {
mMountDelegate.onUnmountItem(
mountItem.getRenderTreeNode().getRenderUnit(), output, mountItem.getContent());
}
}
private boolean isMountable(RenderTreeNode renderTreeNode, int position) {
if (mMountDelegate == null) {
return true;
}
final boolean isLockedForMount = mMountDelegate.maybeLockForMount(renderTreeNode, position);
return isLockedForMount;
}
@Override
public void notifyMount(long id) {
if (mLayoutState == null) {
return;
}
final int position = mLayoutState.getPositionForId(id);
if (position < 0 || getItemAt(position) != null) {
return;
}
final RenderTreeNode node = mLayoutState.getMountableOutputAt(position);
mountLayoutOutput(position, node, getLayoutOutput(node), mLayoutState);
}
@Override
public void notifyUnmount(long id) {
final MountItem item = mIndexToItemMap.get(id);
if (item == null || mLayoutState == null) {
return;
}
final int position = mLayoutState.getPositionForId(id);
if (position >= 0) {
unmountItem(position, mHostsByMarker);
}
}
private void logMountPerfEvent(
ComponentsLogger logger,
PerfEvent mountPerfEvent,
boolean isDirty,
boolean hadPreviousComponentTree) {
if (!mMountStats.isLoggingEnabled) {
logger.cancelPerfEvent(mountPerfEvent);
return;
}
// MOUNT events that don't mount any content are not valuable enough to log at the moment.
// We will likely enable them again in the future. T31729233
if (mMountStats.mountedCount == 0 || mMountStats.mountedNames.isEmpty()) {
logger.cancelPerfEvent(mountPerfEvent);
return;
}
mountPerfEvent.markerAnnotate(PARAM_MOUNTED_COUNT, mMountStats.mountedCount);
mountPerfEvent.markerAnnotate(
PARAM_MOUNTED_CONTENT, mMountStats.mountedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_MOUNTED_TIME, mMountStats.mountTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, mMountStats.unmountedCount);
mountPerfEvent.markerAnnotate(
PARAM_UNMOUNTED_CONTENT, mMountStats.unmountedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_UNMOUNTED_TIME, mMountStats.unmountedTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_MOUNTED_EXTRAS, mMountStats.extras.toArray(new String[0]));
mountPerfEvent.markerAnnotate(PARAM_UPDATED_COUNT, mMountStats.updatedCount);
mountPerfEvent.markerAnnotate(
PARAM_UPDATED_CONTENT, mMountStats.updatedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_UPDATED_TIME, mMountStats.updatedTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLERS_TOTAL_TIME, mMountStats.visibilityHandlersTotalTime);
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLER, mMountStats.visibilityHandlerNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLER_TIME, mMountStats.visibilityHandlerTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_NO_OP_COUNT, mMountStats.noOpCount);
mountPerfEvent.markerAnnotate(PARAM_IS_DIRTY, isDirty);
mountPerfEvent.markerAnnotate(PARAM_HAD_PREVIOUS_CT, hadPreviousComponentTree);
logger.logPerfEvent(mountPerfEvent);
}
void processVisibilityOutputs(
LayoutState layoutState,
@Nullable Rect localVisibleRect,
Rect previousLocalVisibleRect,
boolean isDirty,
@Nullable PerfEvent mountPerfEvent) {
if (mVisibilityExtension == null) {
return;
}
if (isDirty) {
mVisibilityExtension.afterMount(mVisibilityExtensionState);
} else {
mVisibilityExtension.onVisibleBoundsChanged(mVisibilityExtensionState, localVisibleRect);
}
}
@VisibleForTesting
Map<String, VisibilityItem> getVisibilityIdToItemMap() {
return VisibilityMountExtension.getVisibilityIdToItemMap(mVisibilityExtensionState);
}
@VisibleForTesting
@Override
public ArrayList<Host> getHosts() {
final ArrayList<Host> hosts = new ArrayList<>();
for (int i = 0, size = mHostsByMarker.size(); i < size; i++) {
hosts.add(mHostsByMarker.valueAt(i));
}
return hosts;
}
@Override
public int getMountItemCount() {
return mIndexToItemMap.size();
}
@Override
public int getRenderUnitCount() {
assertMainThread();
return mLayoutOutputsIds == null ? 0 : mLayoutOutputsIds.length;
}
@Override
public @Nullable MountItem getMountItemAt(int position) {
return getItemAt(position);
}
@Override
public void setUnmountDelegateExtension(UnmountDelegateExtension unmountDelegateExtension) {
mUnmountDelegateExtension = unmountDelegateExtension;
}
@Override
public void removeUnmountDelegateExtension() {
mUnmountDelegateExtension = null;
}
@Nullable
@Override
public MountDelegate getMountDelegate() {
return mMountDelegate;
}
/** Clears and re-populates the test item map if we are in e2e test mode. */
private void processTestOutputs(LayoutState layoutState) {
if (mTestItemMap == null) {
return;
}
mTestItemMap.clear();
for (int i = 0, size = layoutState.getTestOutputCount(); i < size; i++) {
final TestOutput testOutput = layoutState.getTestOutputAt(i);
final long hostMarker = testOutput.getHostMarker();
final long layoutOutputId = testOutput.getLayoutOutputId();
final MountItem mountItem = layoutOutputId == -1 ? null : mIndexToItemMap.get(layoutOutputId);
final TestItem testItem = new TestItem();
testItem.setHost(hostMarker == -1 ? null : mHostsByMarker.get(hostMarker));
testItem.setBounds(testOutput.getBounds());
testItem.setTestKey(testOutput.getTestKey());
testItem.setContent(mountItem == null ? null : mountItem.getContent());
final Deque<TestItem> items = mTestItemMap.get(testOutput.getTestKey());
final Deque<TestItem> updatedItems = items == null ? new LinkedList<TestItem>() : items;
updatedItems.add(testItem);
mTestItemMap.put(testOutput.getTestKey(), updatedItems);
}
}
private static boolean isMountedHostWithChildContent(@Nullable MountItem mountItem) {
if (mountItem == null) {
return false;
}
final Object content = mountItem.getContent();
if (!(content instanceof ComponentHost)) {
return false;
}
final ComponentHost host = (ComponentHost) content;
return host.getMountItemCount() > 0;
}
private void setupPreviousMountableOutputData(LayoutState layoutState, Rect localVisibleRect) {
if (localVisibleRect.isEmpty()) {
return;
}
final ArrayList<IncrementalMountOutput> layoutOutputTops =
layoutState.getOutputsOrderedByTopBounds();
final ArrayList<IncrementalMountOutput> layoutOutputBottoms =
layoutState.getOutputsOrderedByBottomBounds();
final int mountableOutputCount = layoutState.getMountableOutputCount();
mPreviousTopsIndex = layoutState.getMountableOutputCount();
for (int i = 0; i < mountableOutputCount; i++) {
if (localVisibleRect.bottom <= layoutOutputTops.get(i).getBounds().top) {
mPreviousTopsIndex = i;
break;
}
}
mPreviousBottomsIndex = layoutState.getMountableOutputCount();
for (int i = 0; i < mountableOutputCount; i++) {
if (localVisibleRect.top < layoutOutputBottoms.get(i).getBounds().bottom) {
mPreviousBottomsIndex = i;
break;
}
}
}
List<LithoView> getChildLithoViewsFromCurrentlyMountedItems() {
final ArrayList<LithoView> childLithoViews = new ArrayList<>();
for (int i = 0; i < mIndexToItemMap.size(); i++) {
final long layoutOutputId = mIndexToItemMap.keyAt(i);
final MountItem mountItem = mIndexToItemMap.get(layoutOutputId);
if (mountItem != null && mountItem.getContent() instanceof HasLithoViewChildren) {
((HasLithoViewChildren) mountItem.getContent()).obtainLithoViewChildren(childLithoViews);
}
}
return childLithoViews;
}
void clearVisibilityItems() {
if (mVisibilityExtension != null) {
VisibilityMountExtension.clearVisibilityItems(mVisibilityExtensionState);
}
}
private void registerHost(long id, ComponentHost host) {
mHostsByMarker.put(id, host);
}
private static int computeRectArea(Rect rect) {
return rect.isEmpty() ? 0 : (rect.width() * rect.height());
}
private boolean updateMountItemIfNeeded(
RenderTreeNode node,
MountItem currentMountItem,
boolean useUpdateValueFromLayoutOutput,
int componentTreeId,
int index) {
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("updateMountItemIfNeeded");
}
final LayoutOutput nextLayoutOutput = getLayoutOutput(node);
final Component layoutOutputComponent = nextLayoutOutput.getComponent();
final LayoutOutput currentLayoutOutput = getLayoutOutput(currentMountItem);
final Component itemComponent = currentLayoutOutput.getComponent();
final Object currentContent = currentMountItem.getContent();
final ComponentHost host = (ComponentHost) currentMountItem.getHost();
final ComponentContext currentContext = getComponentContext(currentMountItem);
final ComponentContext nextContext = getComponentContext(node);
final LithoLayoutData nextLayoutData = (LithoLayoutData) node.getLayoutData();
final LithoLayoutData currentLayoutData =
(LithoLayoutData) currentMountItem.getRenderTreeNode().getLayoutData();
if (layoutOutputComponent == null) {
throw new RuntimeException("Trying to update a MountItem with a null Component.");
}
if (isTracing) {
RenderCoreSystrace.beginSection("UpdateItem: " + node.getRenderUnit().getDescription());
}
// 1. Check if the mount item generated from the old component should be updated.
final boolean shouldUpdate =
shouldUpdateMountItem(
nextLayoutOutput,
nextLayoutData,
nextContext,
currentLayoutOutput,
currentLayoutData,
currentContext,
useUpdateValueFromLayoutOutput);
final boolean shouldUpdateViewInfo =
shouldUpdate || shouldUpdateViewInfo(nextLayoutOutput, currentLayoutOutput);
// 2. Reset all the properties like click handler, content description and tags related to
// this item if it needs to be updated. the update mount item will re-set the new ones.
if (shouldUpdateViewInfo) {
maybeUnsetViewAttributes(currentMountItem);
}
// 3. We will re-bind this later in 7 regardless so let's make sure it's currently unbound.
if (currentMountItem.isBound()) {
unbindComponentFromContent(currentMountItem, itemComponent, currentMountItem.getContent());
}
// 4. Re initialize the MountItem internal state with the new attributes from LayoutOutput
currentMountItem.update(node);
// 5. If the mount item is not valid for this component update its content and view attributes.
if (shouldUpdate) {
updateMountedContent(
currentMountItem,
layoutOutputComponent,
nextContext,
nextLayoutData,
itemComponent,
currentContext,
currentLayoutData);
}
if (shouldUpdateViewInfo) {
setViewAttributes(currentMountItem);
}
// 6. Set the mounted content on the Component and call the bind callback.
bindComponentToContent(
currentMountItem, layoutOutputComponent, nextContext, nextLayoutData, currentContent);
// 7. Update the bounds of the mounted content. This needs to be done regardless of whether
// the component has been updated or not since the mounted item might might have the same
// size and content but a different position.
updateBoundsForMountedLayoutOutput(node, nextLayoutOutput, currentMountItem);
if (currentMountItem.getContent() instanceof Drawable) {
maybeSetDrawableState(
host,
(Drawable) currentContent,
currentLayoutOutput.getFlags(),
currentLayoutOutput.getNodeInfo());
}
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.endSection();
}
return shouldUpdate;
}
static boolean shouldUpdateViewInfo(
final LayoutOutput nextLayoutOutput, final LayoutOutput currentLayoutOutput) {
final ViewNodeInfo nextViewNodeInfo = nextLayoutOutput.getViewNodeInfo();
final ViewNodeInfo currentViewNodeInfo = currentLayoutOutput.getViewNodeInfo();
if ((currentViewNodeInfo == null && nextViewNodeInfo != null)
|| (currentViewNodeInfo != null && !currentViewNodeInfo.isEquivalentTo(nextViewNodeInfo))) {
return true;
}
final NodeInfo nextNodeInfo = nextLayoutOutput.getNodeInfo();
final NodeInfo currentNodeInfo = currentLayoutOutput.getNodeInfo();
return (currentNodeInfo == null && nextNodeInfo != null)
|| (currentNodeInfo != null && !currentNodeInfo.isEquivalentTo(nextNodeInfo));
}
static boolean shouldUpdateMountItem(
final LayoutOutput nextLayoutOutput,
final @Nullable LithoLayoutData nextLayoutData,
final @Nullable ComponentContext nextContext,
final LayoutOutput currentLayoutOutput,
final @Nullable LithoLayoutData currentLayoutData,
final @Nullable ComponentContext currentContext,
final boolean useUpdateValueFromLayoutOutput) {
@LayoutOutput.UpdateState final int updateState = nextLayoutOutput.getUpdateState();
final Component currentComponent = currentLayoutOutput.getComponent();
final Component nextComponent = nextLayoutOutput.getComponent();
// If the two components have different sizes and the mounted content depends on the size we
// just return true immediately.
if (nextComponent.isMountSizeDependent()
&& !sameSize(
Preconditions.checkNotNull(nextLayoutData),
Preconditions.checkNotNull(currentLayoutData))) {
return true;
}
if (useUpdateValueFromLayoutOutput) {
if (updateState == LayoutOutput.STATE_UPDATED) {
// Check for incompatible ReferenceLifecycle.
return currentComponent instanceof DrawableComponent
&& nextComponent instanceof DrawableComponent
&& shouldUpdate(currentComponent, currentContext, nextComponent, nextContext);
} else if (updateState == LayoutOutput.STATE_DIRTY) {
return true;
}
}
return shouldUpdate(currentComponent, currentContext, nextComponent, nextContext);
}
private static boolean shouldUpdate(
Component currentComponent,
ComponentContext currentScopedContext,
Component nextComponent,
ComponentContext nextScopedContext) {
final boolean isTracing = RenderCoreSystrace.isEnabled();
try {
if (isTracing) {
RenderCoreSystrace.beginSection("MountState.shouldUpdate");
}
return currentComponent.shouldComponentUpdate(
currentScopedContext, currentComponent, nextScopedContext, nextComponent);
} catch (Exception e) {
ComponentUtils.handle(nextScopedContext, e);
return true;
} finally {
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
}
static boolean sameSize(final LithoLayoutData next, final LithoLayoutData current) {
return next.width == current.width && next.height == current.height;
}
private static void updateBoundsForMountedLayoutOutput(
final RenderTreeNode node, final LayoutOutput layoutOutput, final MountItem item) {
// MountState should never update the bounds of the top-level host as this
// should be done by the ViewGroup containing the LithoView.
if (node.getRenderUnit().getId() == ROOT_HOST_ID) {
return;
}
final Rect bounds = node.getBounds();
final boolean forceTraversal =
isMountableView(node.getRenderUnit()) && ((View) item.getContent()).isLayoutRequested();
applyBoundsToMountContent(
item.getContent(),
bounds.left,
bounds.top,
bounds.right,
bounds.bottom,
forceTraversal /* force */);
}
/** Prepare the {@link MountState} to mount a new {@link LayoutState}. */
private void prepareMount(LayoutState layoutState, @Nullable PerfEvent perfEvent) {
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("prepareMount");
}
final PrepareMountStats stats = unmountOrMoveOldItems(layoutState);
if (perfEvent != null) {
perfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, stats.unmountedCount);
perfEvent.markerAnnotate(PARAM_MOVED_COUNT, stats.movedCount);
perfEvent.markerAnnotate(PARAM_UNCHANGED_COUNT, stats.unchangedCount);
}
if (mIndexToItemMap.get(ROOT_HOST_ID) == null || mHostsByMarker.get(ROOT_HOST_ID) == null) {
// Mounting always starts with the root host.
registerHost(ROOT_HOST_ID, mLithoView);
// Root host is implicitly marked as mounted.
mIndexToItemMap.put(ROOT_HOST_ID, mRootHostMountItem);
}
final int outputCount = layoutState.getMountableOutputCount();
if (mLayoutOutputsIds == null || outputCount != mLayoutOutputsIds.length) {
mLayoutOutputsIds = new long[outputCount];
}
for (int i = 0; i < outputCount; i++) {
mLayoutOutputsIds[i] = layoutState.getMountableOutputAt(i).getRenderUnit().getId();
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
/**
* Go over all the mounted items from the leaves to the root and unmount only the items that are
* not present in the new LayoutOutputs. If an item is still present but in a new position move
* the item inside its host. The condition where an item changed host doesn't need any special
* treatment here since we mark them as removed and re-added when calculating the new
* LayoutOutputs
*/
private PrepareMountStats unmountOrMoveOldItems(LayoutState newLayoutState) {
mPrepareMountStats.reset();
if (mLayoutOutputsIds == null) {
return mPrepareMountStats;
}
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("unmountOrMoveOldItems");
}
// Traversing from the beginning since mLayoutOutputsIds unmounting won't remove entries there
// but only from mIndexToItemMap. If an host changes we're going to unmount it and recursively
// all its mounted children.
for (int i = 0; i < mLayoutOutputsIds.length; i++) {
final int newPosition = newLayoutState.getPositionForId(mLayoutOutputsIds[i]);
final @Nullable RenderTreeNode newRenderTreeNode =
newPosition != -1 ? newLayoutState.getMountableOutputAt(newPosition) : null;
final MountItem oldItem = getItemAt(i);
final boolean hasUnmountDelegate =
mUnmountDelegateExtension != null && oldItem != null
? mUnmountDelegateExtension.shouldDelegateUnmount(
mMountDelegate.getUnmountDelegateExtensionState(), oldItem)
: false;
if (hasUnmountDelegate) {
continue;
}
if (newPosition == -1) {
unmountItem(i, mHostsByMarker);
mPrepareMountStats.unmountedCount++;
} else {
final long newHostMarker =
i != 0 ? newRenderTreeNode.getParent().getRenderUnit().getId() : -1;
if (oldItem == null) {
// This was previously unmounted.
mPrepareMountStats.unmountedCount++;
} else if (oldItem.getHost() != mHostsByMarker.get(newHostMarker)) {
// If the id is the same but the parent host is different we simply unmount the item and
// re-mount it later. If the item to unmount is a ComponentHost, all the children will be
// recursively unmounted.
unmountItem(i, mHostsByMarker);
mPrepareMountStats.unmountedCount++;
} else if (mShouldUsePositionInParent
&& oldItem.getRenderTreeNode().getPositionInParent()
!= newRenderTreeNode.getPositionInParent()) {
// If a MountItem for this id exists and the hostMarker has not changed but its position
// in the outputs array has changed we need to update the position in the Host to ensure
// the z-ordering.
oldItem
.getHost()
.moveItem(
oldItem,
oldItem.getRenderTreeNode().getPositionInParent(),
newRenderTreeNode.getPositionInParent());
mPrepareMountStats.movedCount++;
} else if (!mShouldUsePositionInParent && newPosition != i) {
// If a MountItem for this id exists and the hostMarker has not changed but its position
// in the outputs array has changed we need to update the position in the Host to ensure
// the z-ordering.
oldItem.getHost().moveItem(oldItem, i, newPosition);
mPrepareMountStats.movedCount++;
} else {
mPrepareMountStats.unchangedCount++;
}
}
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
return mPrepareMountStats;
}
private void updateMountedContent(
final MountItem item,
final Component newComponent,
final ComponentContext newContext,
final LithoLayoutData nextLayoutData,
final Component previousComponent,
final ComponentContext previousContext,
final LithoLayoutData currentLayoutData) {
if (isHostSpec(newComponent)) {
return;
}
final Object previousContent = item.getContent();
// Call unmount and mount in sequence to make sure all the the resources are correctly
// de-allocated. It's possible for previousContent to equal null - when the root is
// interactive we create a LayoutOutput without content in order to set up click handling.
previousComponent.unmount(
previousContext, previousContent, (InterStagePropsContainer) currentLayoutData.mLayoutData);
newComponent.mount(
newContext, previousContent, (InterStagePropsContainer) nextLayoutData.mLayoutData);
}
private void mountLayoutOutput(
final int index,
final RenderTreeNode node,
final LayoutOutput layoutOutput,
final LayoutState layoutState) {
// 1. Resolve the correct host to mount our content to.
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("MountItem: " + node.getRenderUnit().getDescription());
RenderCoreSystrace.beginSection("MountItem:before " + node.getRenderUnit().getDescription());
}
final long startTime = System.nanoTime();
// parent should never be null
final long hostMarker = node.getParent().getRenderUnit().getId();
ComponentHost host = mHostsByMarker.get(hostMarker);
if (host == null) {
// Host has not yet been mounted - mount it now.
final int hostMountIndex = layoutState.getPositionForId(hostMarker);
final RenderTreeNode hostNode = layoutState.getMountableOutputAt(hostMountIndex);
final LayoutOutput hostLayoutOutput = getLayoutOutput(hostNode);
mountLayoutOutput(hostMountIndex, hostNode, hostLayoutOutput, layoutState);
host = mHostsByMarker.get(hostMarker);
}
// 2. Generate the component's mount state (this might also be a ComponentHost View).
final Component component = layoutOutput.getComponent();
if (component == null) {
throw new RuntimeException("Trying to mount a LayoutOutput with a null Component.");
}
final Object content;
if (component instanceof HostComponent) {
content =
acquireHostComponentContent(mContext.getAndroidContext(), (HostComponent) component);
} else {
content = MountItemsPool.acquireMountContent(mContext.getAndroidContext(), component);
}
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.beginSection("MountItem:mount " + node.getRenderUnit().getDescription());
}
final ComponentContext context = getContextForComponent(node);
final LithoLayoutData layoutData = (LithoLayoutData) node.getLayoutData();
component.mount(context, content, (InterStagePropsContainer) layoutData.mLayoutData);
// 3. If it's a ComponentHost, add the mounted View to the list of Hosts.
if (isHostSpec(component)) {
ComponentHost componentHost = (ComponentHost) content;
registerHost(node.getRenderUnit().getId(), componentHost);
}
// 4. Mount the content into the selected host.
final MountItem item = mountContent(index, component, content, host, node, layoutOutput);
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.beginSection("MountItem:bind " + node.getRenderUnit().getDescription());
}
// 5. Notify the component that mounting has completed
bindComponentToContent(item, component, context, layoutData, content);
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.beginSection(
"MountItem:applyBounds " + node.getRenderUnit().getDescription());
}
// 6. Apply the bounds to the Mount content now. It's important to do so after bind as calling
// bind might have triggered a layout request within a View.
final Rect bounds = node.getBounds();
applyBoundsToMountContent(
item.getContent(), bounds.left, bounds.top, bounds.right, bounds.bottom, true /* force */);
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.beginSection("MountItem:after " + node.getRenderUnit().getDescription());
}
// 6. Update the mount stats
if (mMountStats.isLoggingEnabled) {
mMountStats.mountTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.mountedNames.add(component.getSimpleName());
mMountStats.mountedCount++;
final ComponentContext scopedContext = getComponentContext(node);
mMountStats.extras.add(
LogTreePopulator.getAnnotationBundleFromLogger(scopedContext, context.getLogger()));
}
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.endSection();
}
}
// The content might be null because it's the LayoutSpec for the root host
// (the very first LayoutOutput).
private MountItem mountContent(
int index,
Component component,
Object content,
ComponentHost host,
RenderTreeNode node,
LayoutOutput layoutOutput) {
final MountItem item = new MountItem(node, host, content);
item.setMountData(new LithoMountData(content));
// Create and keep a MountItem even for the layoutSpec with null content
// that sets the root host interactions.
mIndexToItemMap.put(mLayoutOutputsIds[index], item);
if (component.hasChildLithoViews()) {
mCanMountIncrementallyMountItems.put(mLayoutOutputsIds[index], item);
}
final int positionInParent = item.getRenderTreeNode().getPositionInParent();
mount(host, mShouldUsePositionInParent ? positionInParent : index, content, item, node);
setViewAttributes(item);
return item;
}
private static void mount(
final ComponentHost host,
final int index,
final Object content,
final MountItem item,
final RenderTreeNode node) {
host.mount(index, item, node.getBounds());
}
private static void unmount(
final ComponentHost host,
final int index,
final Object content,
final MountItem item,
final LayoutOutput output) {
host.unmount(index, item);
}
private static void applyBoundsToMountContent(
Object content, int left, int top, int right, int bottom, boolean force) {
assertMainThread();
BoundsUtils.applyBoundsToMountContent(left, top, right, bottom, null, content, force);
}
private static void setViewAttributes(MountItem item) {
setViewAttributes(item.getContent(), getLayoutOutput(item));
}
static void setViewAttributes(Object content, LayoutOutput output) {
final Component component = output.getComponent();
if (!(content instanceof View)) {
return;
}
final View view = (View) content;
final NodeInfo nodeInfo = output.getNodeInfo();
if (nodeInfo != null) {
setClickHandler(nodeInfo.getClickHandler(), view);
setLongClickHandler(nodeInfo.getLongClickHandler(), view);
setFocusChangeHandler(nodeInfo.getFocusChangeHandler(), view);
setTouchHandler(nodeInfo.getTouchHandler(), view);
setInterceptTouchHandler(nodeInfo.getInterceptTouchHandler(), view);
setAccessibilityDelegate(view, nodeInfo);
setViewTag(view, nodeInfo.getViewTag());
setViewTags(view, nodeInfo.getViewTags());
setShadowElevation(view, nodeInfo.getShadowElevation());
setOutlineProvider(view, nodeInfo.getOutlineProvider());
setClipToOutline(view, nodeInfo.getClipToOutline());
setClipChildren(view, nodeInfo);
setContentDescription(view, nodeInfo.getContentDescription());
setFocusable(view, nodeInfo.getFocusState());
setClickable(view, nodeInfo.getClickableState());
setEnabled(view, nodeInfo.getEnabledState());
setSelected(view, nodeInfo.getSelectedState());
setScale(view, nodeInfo);
setAlpha(view, nodeInfo);
setRotation(view, nodeInfo);
setRotationX(view, nodeInfo);
setRotationY(view, nodeInfo);
setTransitionName(view, nodeInfo.getTransitionName());
}
setImportantForAccessibility(view, output.getImportantForAccessibility());
final ViewNodeInfo viewNodeInfo = output.getViewNodeInfo();
if (viewNodeInfo != null) {
final boolean isHostSpec = isHostSpec(component);
setViewLayerType(view, viewNodeInfo);
setViewStateListAnimator(view, viewNodeInfo);
if (LayoutOutput.areDrawableOutputsDisabled(output.getFlags())) {
setViewBackground(view, viewNodeInfo);
ViewUtils.setViewForeground(view, viewNodeInfo.getForeground());
// when background outputs are disabled, they are wrapped by a ComponentHost.
// A background can set the padding of a view, but ComponentHost should not have
// any padding because the layout calculation has already accounted for padding by
// translating the bounds of its children.
if (isHostSpec) {
view.setPadding(0, 0, 0, 0);
}
}
if (!isHostSpec) {
// Set view background, if applicable. Do this before padding
// as it otherwise overrides the padding.
setViewBackground(view, viewNodeInfo);
setViewPadding(view, viewNodeInfo);
ViewUtils.setViewForeground(view, viewNodeInfo.getForeground());
setViewLayoutDirection(view, viewNodeInfo);
}
}
}
private static void setViewLayerType(final View view, final ViewNodeInfo info) {
final int type = info.getLayerType();
if (type != LayerType.LAYER_TYPE_NOT_SET) {
view.setLayerType(info.getLayerType(), info.getLayoutPaint());
}
}
private static void unsetViewLayerType(final View view, final int mountFlags) {
int type = LithoMountData.getOriginalLayerType(mountFlags);
if (type != LayerType.LAYER_TYPE_NOT_SET) {
view.setLayerType(type, null);
}
}
private static void maybeUnsetViewAttributes(MountItem item) {
final LayoutOutput output = getLayoutOutput(item);
final int flags = getMountData(item).getDefaultAttributeValuesFlags();
unsetViewAttributes(item.getContent(), output, flags);
}
static void unsetViewAttributes(
final Object content, final LayoutOutput output, final int mountFlags) {
final Component component = output.getComponent();
final boolean isHostView = isHostSpec(component);
if (!(content instanceof View)) {
return;
}
final View view = (View) content;
final NodeInfo nodeInfo = output.getNodeInfo();
if (nodeInfo != null) {
if (nodeInfo.getClickHandler() != null) {
unsetClickHandler(view);
}
if (nodeInfo.getLongClickHandler() != null) {
unsetLongClickHandler(view);
}
if (nodeInfo.getFocusChangeHandler() != null) {
unsetFocusChangeHandler(view);
}
if (nodeInfo.getTouchHandler() != null) {
unsetTouchHandler(view);
}
if (nodeInfo.getInterceptTouchHandler() != null) {
unsetInterceptTouchEventHandler(view);
}
unsetViewTag(view);
unsetViewTags(view, nodeInfo.getViewTags());
unsetShadowElevation(view, nodeInfo.getShadowElevation());
unsetOutlineProvider(view, nodeInfo.getOutlineProvider());
unsetClipToOutline(view, nodeInfo.getClipToOutline());
unsetClipChildren(view, nodeInfo.getClipChildren());
if (!TextUtils.isEmpty(nodeInfo.getContentDescription())) {
unsetContentDescription(view);
}
unsetScale(view, nodeInfo);
unsetAlpha(view, nodeInfo);
unsetRotation(view, nodeInfo);
unsetRotationX(view, nodeInfo);
unsetRotationY(view, nodeInfo);
}
view.setClickable(isViewClickable(mountFlags));
view.setLongClickable(isViewLongClickable(mountFlags));
unsetFocusable(view, mountFlags);
unsetEnabled(view, mountFlags);
unsetSelected(view, mountFlags);
if (output.getImportantForAccessibility() != IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
unsetImportantForAccessibility(view);
}
unsetAccessibilityDelegate(view);
final ViewNodeInfo viewNodeInfo = output.getViewNodeInfo();
if (viewNodeInfo != null) {
unsetViewStateListAnimator(view, viewNodeInfo);
// Host view doesn't set its own padding, but gets absolute positions for inner content from
// Yoga. Also bg/fg is used as separate drawables instead of using View's bg/fg attribute.
if (LayoutOutput.areDrawableOutputsDisabled(output.getFlags())) {
unsetViewBackground(view, viewNodeInfo);
unsetViewForeground(view, viewNodeInfo);
}
if (!isHostView) {
unsetViewPadding(view, output, viewNodeInfo);
unsetViewBackground(view, viewNodeInfo);
unsetViewForeground(view, viewNodeInfo);
unsetViewLayoutDirection(view);
}
}
unsetViewLayerType(view, mountFlags);
}
/**
* Store a {@link NodeInfo} as a tag in {@code view}. {@link LithoView} contains the logic for
* setting/unsetting it whenever accessibility is enabled/disabled
*
* <p>For non {@link ComponentHost}s this is only done if any {@link EventHandler}s for
* accessibility events have been implemented, we want to preserve the original behaviour since
* {@code view} might have had a default delegate.
*/
private static void setAccessibilityDelegate(View view, NodeInfo nodeInfo) {
if (!(view instanceof ComponentHost) && !nodeInfo.needsAccessibilityDelegate()) {
return;
}
view.setTag(R.id.component_node_info, nodeInfo);
}
private static void unsetAccessibilityDelegate(View view) {
if (!(view instanceof ComponentHost) && view.getTag(R.id.component_node_info) == null) {
return;
}
view.setTag(R.id.component_node_info, null);
if (!(view instanceof ComponentHost)) {
ViewCompat.setAccessibilityDelegate(view, null);
}
}
/**
* Installs the click listeners that will dispatch the click handler defined in the component's
* props. Unconditionally set the clickable flag on the view.
*/
private static void setClickHandler(@Nullable EventHandler<ClickEvent> clickHandler, View view) {
if (clickHandler == null) {
return;
}
ComponentClickListener listener = getComponentClickListener(view);
if (listener == null) {
listener = new ComponentClickListener();
setComponentClickListener(view, listener);
}
listener.setEventHandler(clickHandler);
view.setClickable(true);
}
private static void unsetClickHandler(View view) {
final ComponentClickListener listener = getComponentClickListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
@Nullable
static ComponentClickListener getComponentClickListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentClickListener();
} else {
return (ComponentClickListener) v.getTag(R.id.component_click_listener);
}
}
static void setComponentClickListener(View v, ComponentClickListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentClickListener(listener);
} else {
v.setOnClickListener(listener);
v.setTag(R.id.component_click_listener, listener);
}
}
/**
* Installs the long click listeners that will dispatch the click handler defined in the
* component's props. Unconditionally set the clickable flag on the view.
*/
private static void setLongClickHandler(
@Nullable EventHandler<LongClickEvent> longClickHandler, View view) {
if (longClickHandler != null) {
ComponentLongClickListener listener = getComponentLongClickListener(view);
if (listener == null) {
listener = new ComponentLongClickListener();
setComponentLongClickListener(view, listener);
}
listener.setEventHandler(longClickHandler);
view.setLongClickable(true);
}
}
private static void unsetLongClickHandler(View view) {
final ComponentLongClickListener listener = getComponentLongClickListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
@Nullable
static ComponentLongClickListener getComponentLongClickListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentLongClickListener();
} else {
return (ComponentLongClickListener) v.getTag(R.id.component_long_click_listener);
}
}
static void setComponentLongClickListener(View v, ComponentLongClickListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentLongClickListener(listener);
} else {
v.setOnLongClickListener(listener);
v.setTag(R.id.component_long_click_listener, listener);
}
}
/**
* Installs the on focus change listeners that will dispatch the click handler defined in the
* component's props. Unconditionally set the clickable flag on the view.
*/
private static void setFocusChangeHandler(
@Nullable EventHandler<FocusChangedEvent> focusChangeHandler, View view) {
if (focusChangeHandler == null) {
return;
}
ComponentFocusChangeListener listener = getComponentFocusChangeListener(view);
if (listener == null) {
listener = new ComponentFocusChangeListener();
setComponentFocusChangeListener(view, listener);
}
listener.setEventHandler(focusChangeHandler);
}
private static void unsetFocusChangeHandler(View view) {
final ComponentFocusChangeListener listener = getComponentFocusChangeListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
static ComponentFocusChangeListener getComponentFocusChangeListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentFocusChangeListener();
} else {
return (ComponentFocusChangeListener) v.getTag(R.id.component_focus_change_listener);
}
}
static void setComponentFocusChangeListener(View v, ComponentFocusChangeListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentFocusChangeListener(listener);
} else {
v.setOnFocusChangeListener(listener);
v.setTag(R.id.component_focus_change_listener, listener);
}
}
/**
* Installs the touch listeners that will dispatch the touch handler defined in the component's
* props.
*/
private static void setTouchHandler(@Nullable EventHandler<TouchEvent> touchHandler, View view) {
if (touchHandler != null) {
ComponentTouchListener listener = getComponentTouchListener(view);
if (listener == null) {
listener = new ComponentTouchListener();
setComponentTouchListener(view, listener);
}
listener.setEventHandler(touchHandler);
}
}
private static void unsetTouchHandler(View view) {
final ComponentTouchListener listener = getComponentTouchListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
/** Sets the intercept touch handler defined in the component's props. */
private static void setInterceptTouchHandler(
@Nullable EventHandler<InterceptTouchEvent> interceptTouchHandler, View view) {
if (interceptTouchHandler == null) {
return;
}
if (view instanceof ComponentHost) {
((ComponentHost) view).setInterceptTouchEventHandler(interceptTouchHandler);
}
}
private static void unsetInterceptTouchEventHandler(View view) {
if (view instanceof ComponentHost) {
((ComponentHost) view).setInterceptTouchEventHandler(null);
}
}
@Nullable
static ComponentTouchListener getComponentTouchListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentTouchListener();
} else {
return (ComponentTouchListener) v.getTag(R.id.component_touch_listener);
}
}
static void setComponentTouchListener(View v, ComponentTouchListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentTouchListener(listener);
} else {
v.setOnTouchListener(listener);
v.setTag(R.id.component_touch_listener, listener);
}
}
private static void setViewTag(View view, @Nullable Object viewTag) {
view.setTag(viewTag);
}
private static void setViewTags(View view, @Nullable SparseArray<Object> viewTags) {
if (viewTags == null) {
return;
}
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTags(viewTags);
} else {
for (int i = 0, size = viewTags.size(); i < size; i++) {
view.setTag(viewTags.keyAt(i), viewTags.valueAt(i));
}
}
}
private static void unsetViewTag(View view) {
view.setTag(null);
}
private static void unsetViewTags(View view, @Nullable SparseArray<Object> viewTags) {
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTags(null);
} else {
if (viewTags != null) {
for (int i = 0, size = viewTags.size(); i < size; i++) {
view.setTag(viewTags.keyAt(i), null);
}
}
}
}
private static void setShadowElevation(View view, float shadowElevation) {
if (shadowElevation != 0) {
ViewCompat.setElevation(view, shadowElevation);
}
}
private static void unsetShadowElevation(View view, float shadowElevation) {
if (shadowElevation != 0) {
ViewCompat.setElevation(view, 0);
}
}
private static void setOutlineProvider(View view, @Nullable ViewOutlineProvider outlineProvider) {
if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setOutlineProvider(outlineProvider);
}
}
private static void unsetOutlineProvider(
View view, @Nullable ViewOutlineProvider outlineProvider) {
if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setOutlineProvider(ViewOutlineProvider.BACKGROUND);
}
}
private static void setClipToOutline(View view, boolean clipToOutline) {
if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setClipToOutline(clipToOutline);
}
}
private static void unsetClipToOutline(View view, boolean clipToOutline) {
if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setClipToOutline(false);
}
}
private static void setClipChildren(View view, NodeInfo nodeInfo) {
if (nodeInfo.isClipChildrenSet() && view instanceof ViewGroup) {
((ViewGroup) view).setClipChildren(nodeInfo.getClipChildren());
}
}
private static void unsetClipChildren(View view, boolean clipChildren) {
if (!clipChildren && view instanceof ViewGroup) {
// Default value for clipChildren is 'true'.
// If this ViewGroup had clipChildren set to 'false' before mounting we would reset this
// property here on recycling.
((ViewGroup) view).setClipChildren(true);
}
}
private static void setContentDescription(View view, @Nullable CharSequence contentDescription) {
if (TextUtils.isEmpty(contentDescription)) {
return;
}
view.setContentDescription(contentDescription);
}
private static void unsetContentDescription(View view) {
view.setContentDescription(null);
}
private static void setImportantForAccessibility(View view, int importantForAccessibility) {
if (importantForAccessibility == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
return;
}
ViewCompat.setImportantForAccessibility(view, importantForAccessibility);
}
private static void unsetImportantForAccessibility(View view) {
ViewCompat.setImportantForAccessibility(view, IMPORTANT_FOR_ACCESSIBILITY_AUTO);
}
private static void setFocusable(View view, @NodeInfo.FocusState int focusState) {
if (focusState == NodeInfo.FOCUS_SET_TRUE) {
view.setFocusable(true);
} else if (focusState == NodeInfo.FOCUS_SET_FALSE) {
view.setFocusable(false);
}
}
private static void unsetFocusable(View view, int flags) {
view.setFocusable(isViewFocusable(flags));
}
private static void setTransitionName(View view, @Nullable String transitionName) {
ViewCompat.setTransitionName(view, transitionName);
}
private static void setClickable(View view, @NodeInfo.FocusState int clickableState) {
if (clickableState == NodeInfo.CLICKABLE_SET_TRUE) {
view.setClickable(true);
} else if (clickableState == NodeInfo.CLICKABLE_SET_FALSE) {
view.setClickable(false);
}
}
private static void setEnabled(View view, @NodeInfo.EnabledState int enabledState) {
if (enabledState == NodeInfo.ENABLED_SET_TRUE) {
view.setEnabled(true);
} else if (enabledState == NodeInfo.ENABLED_SET_FALSE) {
view.setEnabled(false);
}
}
private static void unsetEnabled(View view, int flags) {
view.setEnabled(isViewEnabled(flags));
}
private static void setSelected(View view, @NodeInfo.SelectedState int selectedState) {
if (selectedState == NodeInfo.SELECTED_SET_TRUE) {
view.setSelected(true);
} else if (selectedState == NodeInfo.SELECTED_SET_FALSE) {
view.setSelected(false);
}
}
private static void unsetSelected(View view, int flags) {
view.setSelected(isViewSelected(flags));
}
private static void setScale(View view, NodeInfo nodeInfo) {
if (nodeInfo.isScaleSet()) {
final float scale = nodeInfo.getScale();
view.setScaleX(scale);
view.setScaleY(scale);
}
}
private static void unsetScale(View view, NodeInfo nodeInfo) {
if (nodeInfo.isScaleSet()) {
if (view.getScaleX() != 1) {
view.setScaleX(1);
}
if (view.getScaleY() != 1) {
view.setScaleY(1);
}
}
}
private static void setAlpha(View view, NodeInfo nodeInfo) {
if (nodeInfo.isAlphaSet()) {
view.setAlpha(nodeInfo.getAlpha());
}
}
private static void unsetAlpha(View view, NodeInfo nodeInfo) {
if (nodeInfo.isAlphaSet() && view.getAlpha() != 1) {
view.setAlpha(1);
}
}
private static void setRotation(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationSet()) {
view.setRotation(nodeInfo.getRotation());
}
}
private static void unsetRotation(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationSet() && view.getRotation() != 0) {
view.setRotation(0);
}
}
private static void setRotationX(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationXSet()) {
view.setRotationX(nodeInfo.getRotationX());
}
}
private static void unsetRotationX(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationXSet() && view.getRotationX() != 0) {
view.setRotationX(0);
}
}
private static void setRotationY(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationYSet()) {
view.setRotationY(nodeInfo.getRotationY());
}
}
private static void unsetRotationY(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationYSet() && view.getRotationY() != 0) {
view.setRotationY(0);
}
}
private static void setViewPadding(View view, ViewNodeInfo viewNodeInfo) {
if (!viewNodeInfo.hasPadding()) {
return;
}
view.setPadding(
viewNodeInfo.getPaddingLeft(),
viewNodeInfo.getPaddingTop(),
viewNodeInfo.getPaddingRight(),
viewNodeInfo.getPaddingBottom());
}
private static void unsetViewPadding(View view, LayoutOutput output, ViewNodeInfo viewNodeInfo) {
if (!viewNodeInfo.hasPadding()) {
return;
}
try {
view.setPadding(0, 0, 0, 0);
} catch (NullPointerException e) {
// T53931759 Gathering extra info around this NPE
ErrorReporter.getInstance()
.report(
LogLevel.ERROR,
"LITHO:NPE:UNSET_PADDING",
"From component: " + output.getComponent().getSimpleName(),
e,
0,
null);
}
}
private static void setViewBackground(View view, ViewNodeInfo viewNodeInfo) {
final Drawable background = viewNodeInfo.getBackground();
if (background != null) {
setBackgroundCompat(view, background);
}
}
private static void unsetViewBackground(View view, ViewNodeInfo viewNodeInfo) {
final Drawable background = viewNodeInfo.getBackground();
if (background != null) {
setBackgroundCompat(view, null);
}
}
@SuppressWarnings("deprecation")
private static void setBackgroundCompat(View view, Drawable drawable) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(drawable);
} else {
view.setBackground(drawable);
}
}
private static void unsetViewForeground(View view, ViewNodeInfo viewNodeInfo) {
final Drawable foreground = viewNodeInfo.getForeground();
if (foreground != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with foreground however "
+ "the current Android version doesn't support foreground on Views");
}
view.setForeground(null);
}
}
private static void setViewLayoutDirection(View view, ViewNodeInfo viewNodeInfo) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return;
}
final int viewLayoutDirection;
switch (viewNodeInfo.getLayoutDirection()) {
case LTR:
viewLayoutDirection = View.LAYOUT_DIRECTION_LTR;
break;
case RTL:
viewLayoutDirection = View.LAYOUT_DIRECTION_RTL;
break;
default:
viewLayoutDirection = View.LAYOUT_DIRECTION_INHERIT;
}
view.setLayoutDirection(viewLayoutDirection);
}
private static void unsetViewLayoutDirection(View view) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return;
}
view.setLayoutDirection(View.LAYOUT_DIRECTION_INHERIT);
}
private static void setViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) {
StateListAnimator stateListAnimator = viewNodeInfo.getStateListAnimator();
final int stateListAnimatorRes = viewNodeInfo.getStateListAnimatorRes();
if (stateListAnimator == null && stateListAnimatorRes == 0) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with stateListAnimator, "
+ "however the current Android version doesn't support stateListAnimator on Views");
}
if (stateListAnimator == null) {
stateListAnimator =
AnimatorInflater.loadStateListAnimator(view.getContext(), stateListAnimatorRes);
}
view.setStateListAnimator(stateListAnimator);
}
private static void unsetViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) {
if (viewNodeInfo.getStateListAnimator() == null
&& viewNodeInfo.getStateListAnimatorRes() == 0) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with stateListAnimator, "
+ "however the current Android version doesn't support stateListAnimator on Views");
}
view.setStateListAnimator(null);
}
private static void mountItemIncrementally(MountItem item, boolean processVisibilityOutputs) {
if (!isMountableView(item.getRenderTreeNode().getRenderUnit())) {
return;
}
// We can't just use the bounds of the View since we need the bounds relative to the
// hosting LithoView (which is what the localVisibleRect is measured relative to).
final View view = (View) item.getContent();
mountViewIncrementally(view, processVisibilityOutputs);
}
private static void mountViewIncrementally(View view, boolean processVisibilityOutputs) {
assertMainThread();
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("recursivelyNotifyVisibleBoundsChanged");
}
if (view instanceof LithoView) {
final LithoView lithoView = (LithoView) view;
if (lithoView.isIncrementalMountEnabled()) {
if (!processVisibilityOutputs) {
lithoView.notifyVisibleBoundsChanged(
new Rect(0, 0, view.getWidth(), view.getHeight()), false);
} else {
lithoView.notifyVisibleBoundsChanged();
}
}
} else if (view instanceof RenderCoreExtensionHost) {
((RenderCoreExtensionHost) view).notifyVisibleBoundsChanged();
} else if (view instanceof ViewGroup) {
final ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
final View childView = viewGroup.getChildAt(i);
mountViewIncrementally(childView, processVisibilityOutputs);
}
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
private String getMountItemDebugMessage(MountItem item) {
final int index = mIndexToItemMap.indexOfValue(item);
long id = -1;
int layoutOutputIndex = -1;
if (index > -1) {
id = mIndexToItemMap.keyAt(index);
for (int i = 0; i < mLayoutOutputsIds.length; i++) {
if (id == mLayoutOutputsIds[i]) {
layoutOutputIndex = i;
break;
}
}
}
final ComponentTree componentTree = mLithoView.getComponentTree();
final String rootComponent =
componentTree == null ? "<null_component_tree>" : componentTree.getRoot().getSimpleName();
return "rootComponent="
+ rootComponent
+ ", index="
+ layoutOutputIndex
+ ", mapIndex="
+ index
+ ", id="
+ id
+ ", disappearRange=["
+ mLastDisappearRangeStart
+ ","
+ mLastDisappearRangeEnd
+ "], contentType="
+ (item.getContent() != null ? item.getContent().getClass() : "<null_content>")
+ ", component="
+ getLayoutOutput(item).getComponent().getSimpleName()
+ ", host="
+ (item.getHost() != null ? item.getHost().getClass() : "<null_host>")
+ ", isRootHost="
+ (mHostsByMarker.get(ROOT_HOST_ID) == item.getHost());
}
@Override
public void unmountAllItems() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
for (int i = mLayoutOutputsIds.length - 1; i >= 0; i--) {
unmountItem(i, mHostsByMarker);
}
mPreviousLocalVisibleRect.setEmpty();
mNeedsRemount = true;
if (mVisibilityExtension != null) {
mVisibilityExtension.onUnbind(mVisibilityExtensionState);
mVisibilityExtension.onUnmount(mVisibilityExtensionState);
}
if (mTransitionsExtension != null) {
mTransitionsExtension.onUnbind(mTransitionsExtensionState);
mTransitionsExtension.onUnmount(mTransitionsExtensionState);
}
if (mMountDelegate != null) {
mMountDelegate.releaseAllAcquiredReferences();
}
clearLastMountedTree();
}
private void unmountItem(int index, LongSparseArray<ComponentHost> hostsByMarker) {
MountItem item = getItemAt(index);
if (item != null) {
unmountItem(item, hostsByMarker);
}
}
private void unmountItem(@Nullable MountItem item, LongSparseArray<ComponentHost> hostsByMarker) {
final long startTime = System.nanoTime();
// Already has been unmounted.
if (item == null) {
return;
}
final RenderTreeNode node = item.getRenderTreeNode();
final RenderUnit<?> unit = node.getRenderUnit();
final long id = unit.getId();
// The root host item should never be unmounted as it's a reference
// to the top-level LithoView.
if (id == ROOT_HOST_ID) {
mDynamicPropsManager.onUnbindComponent(
getLayoutOutput(node).getComponent(), mRootHostMountItem.getContent());
maybeUnsetViewAttributes(item);
return;
}
mIndexToItemMap.remove(id);
final Object content = item.getContent();
final boolean hasUnmountDelegate =
mUnmountDelegateExtension != null
&& mUnmountDelegateExtension.shouldDelegateUnmount(
mMountDelegate.getUnmountDelegateExtensionState(), item);
// Recursively unmount mounted children items.
// This is the case when mountDiffing is enabled and unmountOrMoveOldItems() has a matching
// sub tree. However, traversing the tree bottom-up, it needs to unmount a node holding that
// sub tree, that will still have mounted items. (Different sequence number on LayoutOutput id)
if ((content instanceof ComponentHost) && !(content instanceof LithoView)) {
final Host host = (Host) content;
for (int i = 0; i < node.getChildrenCount(); i++) {
unmountItem(mIndexToItemMap.get(node.getChildAt(i).getRenderUnit().getId()), hostsByMarker);
}
if (!hasUnmountDelegate && host.getMountItemCount() > 0) {
final LayoutOutput output = getLayoutOutput(item);
final Component component = output.getComponent();
ComponentsReporter.emitMessage(
ComponentsReporter.LogLevel.ERROR,
"UnmountItem:ChildsNotUnmounted",
"Recursively unmounting items from a ComponentHost, left some items behind maybe because not tracked by its MountState"
+ ", component: "
+ component.getSimpleName());
throw new IllegalStateException(
"Recursively unmounting items from a ComponentHost, left"
+ " some items behind maybe because not tracked by its MountState");
}
}
final ComponentHost host = (ComponentHost) item.getHost();
final LayoutOutput output = getLayoutOutput(item);
final Component component = output.getComponent();
if (component.hasChildLithoViews()) {
mCanMountIncrementallyMountItems.delete(id);
}
if (isHostSpec(component)) {
final ComponentHost componentHost = (ComponentHost) content;
hostsByMarker.removeAt(hostsByMarker.indexOfValue(componentHost));
}
if (hasUnmountDelegate) {
mUnmountDelegateExtension.unmount(
mMountDelegate.getUnmountDelegateExtensionState(), item, host);
} else {
/*
* The mounted content might contain other LithoViews which are not reachable from
* this MountState. If that content contains other LithoViews, we need to unmount them as well,
* so that their contents are recycled and reused next time.
*/
if (content instanceof HasLithoViewChildren) {
final ArrayList<LithoView> lithoViews = new ArrayList<>();
((HasLithoViewChildren) content).obtainLithoViewChildren(lithoViews);
for (int i = lithoViews.size() - 1; i >= 0; i--) {
final LithoView lithoView = lithoViews.get(i);
lithoView.unmountAllItems();
}
}
if (mShouldUsePositionInParent) {
final int index = item.getRenderTreeNode().getPositionInParent();
unmount(host, index, content, item, output);
} else {
// Find the index in the layout state to unmount
for (int mountIndex = mLayoutOutputsIds.length - 1; mountIndex >= 0; mountIndex--) {
if (mLayoutOutputsIds[mountIndex] == id) {
unmount(host, mountIndex, content, item, output);
break;
}
}
}
unbindMountItem(item);
}
if (mMountStats.isLoggingEnabled) {
mMountStats.unmountedTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.unmountedNames.add(component.getSimpleName());
mMountStats.unmountedCount++;
}
}
@Override
public void unbindMountItem(MountItem mountItem) {
final LayoutOutput output = getLayoutOutput(mountItem);
unbindAndUnmountLifecycle(mountItem);
applyUnbindBinders(output, mountItem);
try {
getMountData(mountItem)
.releaseMountContent(mContext.getAndroidContext(), mountItem, "unmountItem", this);
} catch (LithoMountData.ReleasingReleasedMountContentException e) {
throw new RuntimeException(e.getMessage() + " " + getMountItemDebugMessage(mountItem));
}
}
private void unbindAndUnmountLifecycle(MountItem item) {
final LayoutOutput layoutOutput = getLayoutOutput(item);
final Component component = layoutOutput.getComponent();
final Object content = item.getContent();
final ComponentContext context = getContextForComponent(item.getRenderTreeNode());
// Call the component's unmount() method.
if (item.isBound()) {
unbindComponentFromContent(item, component, content);
}
maybeUnsetViewAttributes(item);
final LithoLayoutData layoutData = (LithoLayoutData) item.getRenderTreeNode().getLayoutData();
component.unmount(context, content, (InterStagePropsContainer) layoutData.mLayoutData);
}
@Override
public boolean isRootItem(int position) {
final MountItem mountItem = getItemAt(position);
if (mountItem == null) {
return false;
}
return mountItem == mIndexToItemMap.get(ROOT_HOST_ID);
}
@Override
public @Nullable MountItem getRootItem() {
return mIndexToItemMap != null ? mIndexToItemMap.get(ROOT_HOST_ID) : null;
}
@Nullable
MountItem getItemAt(int i) {
assertMainThread();
// TODO simplify when replacing with getContent.
if (mIndexToItemMap == null || mLayoutOutputsIds == null) {
return null;
}
if (i >= mLayoutOutputsIds.length) {
return null;
}
return mIndexToItemMap.get(mLayoutOutputsIds[i]);
}
@Override
public Object getContentAt(int i) {
final MountItem mountItem = getItemAt(i);
if (mountItem == null) {
return null;
}
return mountItem.getContent();
}
@Nullable
@Override
public Object getContentById(long id) {
if (mIndexToItemMap == null) {
return null;
}
final MountItem mountItem = mIndexToItemMap.get(id);
if (mountItem == null) {
return null;
}
return mountItem.getContent();
}
public androidx.collection.LongSparseArray<MountItem> getIndexToItemMap() {
return mIndexToItemMap;
}
public void clearLastMountedTree() {
if (mTransitionsExtension != null) {
mTransitionsExtension.clearLastMountedTreeId(mTransitionsExtensionState);
}
mLastMountedComponentTreeId = ComponentTree.INVALID_ID;
}
private static class PrepareMountStats {
private int unmountedCount = 0;
private int movedCount = 0;
private int unchangedCount = 0;
private PrepareMountStats() {}
private void reset() {
unchangedCount = 0;
movedCount = 0;
unmountedCount = 0;
}
}
private static class MountStats {
private List<String> mountedNames;
private List<String> unmountedNames;
private List<String> updatedNames;
private List<String> visibilityHandlerNames;
private List<String> extras;
private List<Double> mountTimes;
private List<Double> unmountedTimes;
private List<Double> updatedTimes;
private List<Double> visibilityHandlerTimes;
private int mountedCount;
private int unmountedCount;
private int updatedCount;
private int noOpCount;
private double visibilityHandlersTotalTime;
private boolean isLoggingEnabled;
private boolean isInitialized;
private void enableLogging() {
isLoggingEnabled = true;
if (!isInitialized) {
isInitialized = true;
mountedNames = new ArrayList<>();
unmountedNames = new ArrayList<>();
updatedNames = new ArrayList<>();
visibilityHandlerNames = new ArrayList<>();
extras = new ArrayList<>();
mountTimes = new ArrayList<>();
unmountedTimes = new ArrayList<>();
updatedTimes = new ArrayList<>();
visibilityHandlerTimes = new ArrayList<>();
}
}
private void reset() {
mountedCount = 0;
unmountedCount = 0;
updatedCount = 0;
noOpCount = 0;
visibilityHandlersTotalTime = 0;
if (isInitialized) {
mountedNames.clear();
unmountedNames.clear();
updatedNames.clear();
visibilityHandlerNames.clear();
extras.clear();
mountTimes.clear();
unmountedTimes.clear();
updatedTimes.clear();
visibilityHandlerTimes.clear();
}
isLoggingEnabled = false;
}
}
/**
* Unbinds all the MountItems currently mounted on this MountState. Unbinding a MountItem means
* calling unbind on its {@link Component}. The MountItem is not yet unmounted after unbind is
* called and can be re-used in place to re-mount another {@link Component} with the same {@link
* Component}.
*/
void unbind() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("MountState.unbind");
RenderCoreSystrace.beginSection("MountState.unbindAllContent");
}
for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) {
MountItem mountItem = getItemAt(i);
if (mountItem == null || !mountItem.isBound()) {
continue;
}
unbindComponentFromContent(
mountItem, getLayoutOutput(mountItem).getComponent(), mountItem.getContent());
}
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.beginSection("MountState.unbindExtensions");
}
clearVisibilityItems();
if (mVisibilityExtension != null) {
mVisibilityExtension.onUnbind(mVisibilityExtensionState);
}
if (mTransitionsExtension != null) {
mTransitionsExtension.onUnbind(mTransitionsExtensionState);
}
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.endSection();
}
}
@Override
public void detach() {
assertMainThread();
unbind();
}
@Override
public void attach() {
rebind();
}
/**
* This is called when the {@link MountItem}s mounted on this {@link MountState} need to be
* re-bound with the same component. The common case here is a detach/attach happens on the {@link
* LithoView} that owns the MountState.
*/
void rebind() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("MountState.bind");
}
for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) {
final MountItem mountItem = getItemAt(i);
if (mountItem == null || mountItem.isBound()) {
continue;
}
final Component component = getLayoutOutput(mountItem).getComponent();
final Object content = mountItem.getContent();
final LithoLayoutData layoutData =
(LithoLayoutData) mountItem.getRenderTreeNode().getLayoutData();
bindComponentToContent(
mountItem, component, getComponentContext(mountItem), layoutData, content);
if (content instanceof View
&& !(content instanceof ComponentHost)
&& ((View) content).isLayoutRequested()) {
final View view = (View) content;
applyBoundsToMountContent(
view, view.getLeft(), view.getTop(), view.getRight(), view.getBottom(), true);
}
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
private boolean isAnimationLocked(RenderTreeNode renderTreeNode) {
if (mTransitionsExtension != null) {
if (mTransitionsExtensionState == null) {
throw new IllegalStateException("Need a state when using the TransitionsExtension.");
}
return mTransitionsExtensionState.ownsReference(renderTreeNode.getRenderUnit().getId());
}
return false;
}
/**
* @return true if this method did all the work that was necessary and there is no other content
* that needs mounting/unmounting in this mount step. If false then a full mount step should
* take place.
*/
private void performIncrementalMount(
LayoutState layoutState, Rect localVisibleRect, boolean processVisibilityOutputs) {
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("performIncrementalMount");
}
final ArrayList<IncrementalMountOutput> layoutOutputTops =
layoutState.getOutputsOrderedByTopBounds();
final ArrayList<IncrementalMountOutput> layoutOutputBottoms =
layoutState.getOutputsOrderedByBottomBounds();
final int count = layoutState.getMountableOutputCount();
if (localVisibleRect.top >= 0 || mPreviousLocalVisibleRect.top >= 0) {
// View is going on/off the top of the screen. Check the bottoms to see if there is anything
// that has moved on/off the top of the screen.
while (mPreviousBottomsIndex < count
&& localVisibleRect.top
>= layoutOutputBottoms.get(mPreviousBottomsIndex).getBounds().bottom) {
final RenderTreeNode node =
layoutState.getRenderTreeNode(layoutOutputBottoms.get(mPreviousBottomsIndex));
final long id = node.getRenderUnit().getId();
final int layoutOutputIndex = layoutState.getPositionForId(id);
if (!isAnimationLocked(node)) {
unmountItem(layoutOutputIndex, mHostsByMarker);
}
mPreviousBottomsIndex++;
}
while (mPreviousBottomsIndex > 0
&& localVisibleRect.top
<= layoutOutputBottoms.get(mPreviousBottomsIndex - 1).getBounds().bottom) {
mPreviousBottomsIndex--;
final RenderTreeNode node =
layoutState.getRenderTreeNode(layoutOutputBottoms.get(mPreviousBottomsIndex));
final LayoutOutput layoutOutput = getLayoutOutput(node);
final int layoutOutputIndex = layoutState.getPositionForId(node.getRenderUnit().getId());
if (getItemAt(layoutOutputIndex) == null) {
mountLayoutOutput(
layoutState.getPositionForId(node.getRenderUnit().getId()),
node,
layoutOutput,
layoutState);
mComponentIdsMountedInThisFrame.add(node.getRenderUnit().getId());
}
}
}
final int height = mLithoView.getHeight();
if (localVisibleRect.bottom < height || mPreviousLocalVisibleRect.bottom < height) {
// View is going on/off the bottom of the screen. Check the tops to see if there is anything
// that has changed.
while (mPreviousTopsIndex < count
&& localVisibleRect.bottom >= layoutOutputTops.get(mPreviousTopsIndex).getBounds().top) {
final RenderTreeNode node =
layoutState.getRenderTreeNode(layoutOutputTops.get(mPreviousTopsIndex));
final LayoutOutput layoutOutput = getLayoutOutput(node);
final int layoutOutputIndex = layoutState.getPositionForId(node.getRenderUnit().getId());
if (getItemAt(layoutOutputIndex) == null) {
mountLayoutOutput(
layoutState.getPositionForId(node.getRenderUnit().getId()),
node,
layoutOutput,
layoutState);
mComponentIdsMountedInThisFrame.add(node.getRenderUnit().getId());
}
mPreviousTopsIndex++;
}
while (mPreviousTopsIndex > 0
&& localVisibleRect.bottom
< layoutOutputTops.get(mPreviousTopsIndex - 1).getBounds().top) {
mPreviousTopsIndex--;
final RenderTreeNode node =
layoutState.getRenderTreeNode(layoutOutputTops.get(mPreviousTopsIndex));
final long id = node.getRenderUnit().getId();
final int layoutOutputIndex = layoutState.getPositionForId(id);
if (!isAnimationLocked(node)) {
unmountItem(layoutOutputIndex, mHostsByMarker);
}
}
}
if (!mLithoView.skipNotifyVisibleBoundsChangedCalls()) {
for (int i = 0, size = mCanMountIncrementallyMountItems.size(); i < size; i++) {
final MountItem mountItem = mCanMountIncrementallyMountItems.valueAt(i);
final long layoutOutputId = mCanMountIncrementallyMountItems.keyAt(i);
if (!mComponentIdsMountedInThisFrame.contains(layoutOutputId)) {
final int layoutOutputPosition = layoutState.getPositionForId(layoutOutputId);
if (layoutOutputPosition != -1) {
mountItemIncrementally(mountItem, processVisibilityOutputs);
}
}
}
}
mComponentIdsMountedInThisFrame.clear();
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
/**
* Collect transitions from layout time, mount time and from state updates.
*
* @param layoutState that is going to be mounted.
*/
void collectAllTransitions(LayoutState layoutState, ComponentTree componentTree) {
assertMainThread();
if (mTransitionsExtension != null) {
TransitionsExtension.collectAllTransitions(mTransitionsExtensionState, layoutState);
return;
}
}
/** @see LithoViewTestHelper#findTestItems(LithoView, String) */
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
Deque<TestItem> findTestItems(String testKey) {
if (mTestItemMap == null) {
throw new UnsupportedOperationException(
"Trying to access TestItems while "
+ "ComponentsConfiguration.isEndToEndTestRun is false.");
}
final Deque<TestItem> items = mTestItemMap.get(testKey);
return items == null ? new LinkedList<TestItem>() : items;
}
/**
* For HostComponents, we don't set a scoped context during layout calculation because we don't
* need one, as we could never call a state update on it. Instead it's okay to use the context
* that is passed to MountState from the LithoView, which is not scoped.
*/
private ComponentContext getContextForComponent(RenderTreeNode node) {
ComponentContext c = getComponentContext(node);
return c == null ? mContext : c;
}
private void bindComponentToContent(
final MountItem mountItem,
final Component component,
final ComponentContext context,
final LithoLayoutData layoutData,
final Object content) {
component.bind(
getContextForComponent(mountItem.getRenderTreeNode()),
content,
(InterStagePropsContainer) layoutData.mLayoutData);
mDynamicPropsManager.onBindComponentToContent(component, context, content);
mountItem.setIsBound(true);
}
private void unbindComponentFromContent(
MountItem mountItem, Component component, Object content) {
mDynamicPropsManager.onUnbindComponent(component, content);
RenderTreeNode node = mountItem.getRenderTreeNode();
component.unbind(
getContextForComponent(node),
content,
LithoLayoutData.getInterStageProps(node.getLayoutData()));
mountItem.setIsBound(false);
}
@VisibleForTesting
DynamicPropsManager getDynamicPropsManager() {
return mDynamicPropsManager;
}
private Object acquireHostComponentContent(Context context, HostComponent component) {
if (ComponentsConfiguration.hostComponentRecyclingByWindowIsEnabled) {
return MountItemsPool.acquireHostMountContent(
context, mLithoView.getWindowToken(), component);
} else if (ComponentsConfiguration.hostComponentRecyclingByMountStateIsEnabled) {
if (mHostMountContentPool != null) {
return mHostMountContentPool.acquire(context, component);
} else {
return component.createMountContent(context);
}
} else if (ComponentsConfiguration.unsafeHostComponentRecyclingIsEnabled) {
return MountItemsPool.acquireMountContent(context, component);
} else {
// Otherwise, recycling is disabled for hosts
return component.createMountContent(context);
}
}
void releaseHostComponentContent(Context context, HostComponent component, Object content) {
if (ComponentsConfiguration.hostComponentRecyclingByWindowIsEnabled) {
MountItemsPool.releaseHostMountContent(
context, mLithoView.getWindowToken(), component, content);
} else if (ComponentsConfiguration.hostComponentRecyclingByMountStateIsEnabled) {
if (mHostMountContentPool == null) {
mHostMountContentPool = (HostMountContentPool) component.createRecyclingPool();
}
mHostMountContentPool.release(content);
} else if (ComponentsConfiguration.unsafeHostComponentRecyclingIsEnabled) {
MountItemsPool.release(context, component, content);
} else {
// Otherwise, recycling is disabled for hosts
}
}
}
| litho-core/src/main/java/com/facebook/litho/MountState.java | /*
* Copyright (c) Meta Platforms, Inc. and 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 com.facebook.litho;
import static androidx.core.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.ComponentHostUtils.maybeSetDrawableState;
import static com.facebook.litho.FrameworkLogEvents.EVENT_MOUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_HAD_PREVIOUS_CT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_IS_DIRTY;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_EXTRAS;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOUNTED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MOVED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_NO_OP_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNCHANGED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UNMOUNTED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_CONTENT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_COUNT;
import static com.facebook.litho.FrameworkLogEvents.PARAM_UPDATED_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLERS_TOTAL_TIME;
import static com.facebook.litho.FrameworkLogEvents.PARAM_VISIBILITY_HANDLER_TIME;
import static com.facebook.litho.LayoutOutput.getLayoutOutput;
import static com.facebook.litho.LithoMountData.getMountData;
import static com.facebook.litho.LithoMountData.isViewClickable;
import static com.facebook.litho.LithoMountData.isViewEnabled;
import static com.facebook.litho.LithoMountData.isViewFocusable;
import static com.facebook.litho.LithoMountData.isViewLongClickable;
import static com.facebook.litho.LithoMountData.isViewSelected;
import static com.facebook.litho.LithoRenderUnit.getComponentContext;
import static com.facebook.litho.LithoRenderUnit.isMountableView;
import static com.facebook.litho.ThreadUtils.assertMainThread;
import static com.facebook.rendercore.MountState.ROOT_HOST_ID;
import android.animation.AnimatorInflater;
import android.animation.StateListAnimator;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.collection.LongSparseArray;
import androidx.core.util.Preconditions;
import androidx.core.view.ViewCompat;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.stats.LithoStats;
import com.facebook.rendercore.ErrorReporter;
import com.facebook.rendercore.Host;
import com.facebook.rendercore.LogLevel;
import com.facebook.rendercore.MountDelegate;
import com.facebook.rendercore.MountDelegateTarget;
import com.facebook.rendercore.MountItem;
import com.facebook.rendercore.MountItemsPool;
import com.facebook.rendercore.RenderCoreExtensionHost;
import com.facebook.rendercore.RenderCoreSystrace;
import com.facebook.rendercore.RenderTree;
import com.facebook.rendercore.RenderTreeNode;
import com.facebook.rendercore.RenderUnit;
import com.facebook.rendercore.UnmountDelegateExtension;
import com.facebook.rendercore.extensions.ExtensionState;
import com.facebook.rendercore.extensions.MountExtension;
import com.facebook.rendercore.incrementalmount.IncrementalMountOutput;
import com.facebook.rendercore.utils.BoundsUtils;
import com.facebook.rendercore.visibility.VisibilityItem;
import com.facebook.rendercore.visibility.VisibilityMountExtension;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Encapsulates the mounted state of a {@link Component}. Provides APIs to update state by recycling
* existing UI elements e.g. {@link Drawable}s.
*
* @see #mount(LayoutState, Rect, boolean)
* @see LithoView
* @see LayoutState
*/
@ThreadConfined(ThreadConfined.UI)
class MountState implements MountDelegateTarget {
private static final String INVALID_REENTRANT_MOUNTS = "MountState:InvalidReentrantMounts";
private static final double NS_IN_MS = 1000000.0;
private static final Rect sTempRect = new Rect();
// Holds the current list of mounted items.
// Should always be used within a draw lock.
private final LongSparseArray<MountItem> mIndexToItemMap;
// Holds a list of MountItems that are currently mounted which can mount incrementally.
private final LongSparseArray<MountItem> mCanMountIncrementallyMountItems;
// A map from test key to a list of one or more `TestItem`s which is only allocated
// and populated during test runs.
private final Map<String, Deque<TestItem>> mTestItemMap;
// Both these arrays are updated in prepareMount(), thus during mounting they hold the information
// about the LayoutState that is being mounted, not mLastMountedLayoutState
@Nullable private long[] mLayoutOutputsIds;
// True if we are receiving a new LayoutState and we need to completely
// refresh the content of the HostComponent. Always set from the main thread.
private boolean mIsDirty;
// True if MountState is currently performing mount.
private boolean mIsMounting;
// See #needsRemount()
private boolean mNeedsRemount;
// Holds the list of known component hosts during a mount pass.
private final LongSparseArray<ComponentHost> mHostsByMarker = new LongSparseArray<>();
private final ComponentContext mContext;
private final LithoView mLithoView;
private final Rect mPreviousLocalVisibleRect = new Rect();
private final PrepareMountStats mPrepareMountStats = new PrepareMountStats();
private final MountStats mMountStats = new MountStats();
private int mPreviousTopsIndex;
private int mPreviousBottomsIndex;
private int mLastMountedComponentTreeId = ComponentTree.INVALID_ID;
private @Nullable LayoutState mLayoutState;
private @Nullable LayoutState mLastMountedLayoutState;
private int mLastDisappearRangeStart = -1;
private int mLastDisappearRangeEnd = -1;
private final MountItem mRootHostMountItem;
private final @Nullable VisibilityMountExtension mVisibilityExtension;
private final @Nullable ExtensionState mVisibilityExtensionState;
private final Set<Long> mComponentIdsMountedInThisFrame = new HashSet<>();
private final DynamicPropsManager mDynamicPropsManager = new DynamicPropsManager();
private @Nullable MountDelegate mMountDelegate;
private @Nullable UnmountDelegateExtension mUnmountDelegateExtension;
private @Nullable TransitionsExtension mTransitionsExtension;
private @Nullable ExtensionState mTransitionsExtensionState;
private @Nullable HostMountContentPool mHostMountContentPool;
public final boolean mShouldUsePositionInParent =
ComponentsConfiguration.shouldUsePositionInParentForMounting;
public MountState(LithoView view) {
mIndexToItemMap = new LongSparseArray<>();
mCanMountIncrementallyMountItems = new LongSparseArray<>();
mContext = view.getComponentContext();
mLithoView = view;
mIsDirty = true;
mTestItemMap =
ComponentsConfiguration.isEndToEndTestRun ? new HashMap<String, Deque<TestItem>>() : null;
// The mount item representing the top-level root host (LithoView) which
// is always automatically mounted.
mRootHostMountItem = LithoMountData.createRootHostMountItem(mLithoView);
mMountDelegate = new MountDelegate(this);
if (ComponentsConfiguration.enableVisibilityExtension) {
mVisibilityExtension = VisibilityMountExtension.getInstance();
mVisibilityExtensionState = mMountDelegate.registerMountExtension(mVisibilityExtension);
VisibilityMountExtension.setRootHost(mVisibilityExtensionState, mLithoView);
} else {
mVisibilityExtension = null;
mVisibilityExtensionState = null;
}
// Using Incremental Mount Extension and the Transition Extension here is not allowed.
if (ComponentsConfiguration.enableTransitionsExtension) {
mTransitionsExtension =
TransitionsExtension.getInstance((AnimationsDebug.ENABLED ? AnimationsDebug.TAG : null));
mTransitionsExtensionState = mMountDelegate.registerMountExtension(mTransitionsExtension);
} else {
mTransitionsExtension = null;
mTransitionsExtensionState = null;
}
}
@Deprecated
@Override
public ExtensionState registerMountExtension(MountExtension mountExtensions) {
throw new UnsupportedOperationException("Must not be invoked when use this Litho's MountState");
}
/** @deprecated Only used for Litho's integration. Marked for removal. */
@Deprecated
@Override
public void unregisterAllExtensions() {
throw new UnsupportedOperationException("Must not be invoked when use this Litho's MountState");
}
/**
* To be called whenever the components needs to start the mount process from scratch e.g. when
* the component's props or layout change or when the components gets attached to a host.
*/
void setDirty() {
assertMainThread();
mIsDirty = true;
mPreviousLocalVisibleRect.setEmpty();
}
boolean isDirty() {
assertMainThread();
return mIsDirty;
}
/**
* True if we have manually unmounted content (e.g. via unmountAllItems) which means that while we
* may not have a new LayoutState, the mounted content does not match what the viewport for the
* LithoView may be.
*/
@Override
public boolean needsRemount() {
assertMainThread();
return mNeedsRemount;
}
/**
* Mount the layoutState on the pre-set HostView.
*
* @param layoutState a new {@link LayoutState} to mount
* @param localVisibleRect If this variable is null, then mount everything, since incremental
* mount is not enabled. Otherwise mount only what the rect (in local coordinates) contains
* @param processVisibilityOutputs whether to process visibility outputs as part of the mount
*/
void mount(
LayoutState layoutState, @Nullable Rect localVisibleRect, boolean processVisibilityOutputs) {
final ComponentTree componentTree = mLithoView.getComponentTree();
final boolean isIncrementalMountEnabled = componentTree.isIncrementalMountEnabled();
final boolean isVisibilityProcessingEnabled =
componentTree.isVisibilityProcessingEnabled() && processVisibilityOutputs;
assertMainThread();
if (layoutState == null) {
throw new IllegalStateException("Trying to mount a null layoutState");
}
if (mVisibilityExtension != null && mIsDirty) {
mVisibilityExtension.beforeMount(mVisibilityExtensionState, layoutState, localVisibleRect);
}
if (mTransitionsExtension != null && mIsDirty) {
mTransitionsExtension.beforeMount(mTransitionsExtensionState, layoutState, localVisibleRect);
}
mLayoutState = layoutState;
if (mIsMounting) {
ComponentsReporter.emitMessage(
ComponentsReporter.LogLevel.FATAL,
INVALID_REENTRANT_MOUNTS,
"Trying to mount while already mounting! "
+ getMountItemDebugMessage(mRootHostMountItem));
}
mIsMounting = true;
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
String sectionName =
mIsDirty
? (isIncrementalMountEnabled ? "incrementalMountDirty" : "mountDirty")
: (isIncrementalMountEnabled ? "incrementalMount" : "mount");
ComponentsSystrace.beginSectionWithArgs(sectionName)
.arg("treeId", layoutState.getComponentTreeId())
.arg("component", componentTree.getSimpleName())
.arg("logTag", componentTree.getContext().getLogTag())
.flush();
// We also would like to trace this section attributed with component name
// for component share analysis.
RenderCoreSystrace.beginSection(sectionName + "_" + componentTree.getSimpleName());
}
final ComponentsLogger logger = componentTree.getContext().getLogger();
final int componentTreeId = layoutState.getComponentTreeId();
if (componentTreeId != mLastMountedComponentTreeId) {
// If we're mounting a new ComponentTree, don't keep around and use the previous LayoutState
// since things like transition animations aren't relevant.
clearLastMountedLayoutState();
}
final PerfEvent mountPerfEvent =
logger == null
? null
: LogTreePopulator.populatePerfEventFromLogger(
componentTree.getContext(),
logger,
logger.newPerformanceEvent(componentTree.getContext(), EVENT_MOUNT));
if (mIsDirty) {
// Prepare the data structure for the new LayoutState and removes mountItems
// that are not present anymore if isUpdateMountInPlace is enabled.
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_START");
}
prepareMount(layoutState, mountPerfEvent);
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_END");
}
}
mMountStats.reset();
if (mountPerfEvent != null && logger.isTracing(mountPerfEvent)) {
mMountStats.enableLogging();
}
if (!isIncrementalMountEnabled
|| !performIncrementalMount(layoutState, localVisibleRect, processVisibilityOutputs)) {
final MountItem rootMountItem = mIndexToItemMap.get(ROOT_HOST_ID);
final Rect absoluteBounds = new Rect();
for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) {
final RenderTreeNode node = layoutState.getMountableOutputAt(i);
final LayoutOutput layoutOutput = getLayoutOutput(node);
final Component component = layoutOutput.getComponent();
final MountItem currentMountItem = getItemAt(i);
final boolean isMounted = currentMountItem != null;
final boolean isRoot = currentMountItem != null && currentMountItem == rootMountItem;
final boolean isMountable =
!isIncrementalMountEnabled
|| isMountedHostWithChildContent(currentMountItem)
|| Rect.intersects(localVisibleRect, node.getAbsoluteBounds(absoluteBounds))
|| isAnimationLocked(node)
|| isRoot;
if (isMountable && !isMounted) {
mountLayoutOutput(i, node, layoutOutput, layoutState);
if (isIncrementalMountEnabled) {
applyMountBinders(layoutOutput, getItemAt(i), i);
}
} else if (!isMountable && isMounted) {
unmountItem(i, mHostsByMarker);
} else if (isMounted) {
if (mIsDirty || (isRoot && mNeedsRemount)) {
final boolean useUpdateValueFromLayoutOutput =
mLastMountedLayoutState != null
&& mLastMountedLayoutState.getId() == layoutState.getPreviousLayoutStateId();
final long startTime = System.nanoTime();
final boolean itemUpdated =
updateMountItemIfNeeded(
node, currentMountItem, useUpdateValueFromLayoutOutput, componentTreeId, i);
if (mMountStats.isLoggingEnabled) {
if (itemUpdated) {
mMountStats.updatedNames.add(component.getSimpleName());
mMountStats.updatedTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.updatedCount++;
} else {
mMountStats.noOpCount++;
}
}
}
if (isIncrementalMountEnabled
&& component.hasChildLithoViews()
&& !mLithoView.skipNotifyVisibleBoundsChangedCalls()) {
mountItemIncrementally(currentMountItem, processVisibilityOutputs);
}
}
}
if (isIncrementalMountEnabled) {
setupPreviousMountableOutputData(layoutState, localVisibleRect);
}
}
if (isTracing) {
RenderCoreSystrace.endSection();
ComponentsSystrace.endSection(); // beginSectionWithArgs
RenderCoreSystrace.beginSection("RenderCoreExtension.afterMount");
}
afterMountMaybeUpdateAnimations();
if (isVisibilityProcessingEnabled) {
if (isTracing) {
RenderCoreSystrace.beginSection("LMS.processVisibilityOutputs");
}
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("EVENT_PROCESS_VISIBILITY_OUTPUTS_START");
}
processVisibilityOutputs(
layoutState, localVisibleRect, mPreviousLocalVisibleRect, mIsDirty, mountPerfEvent);
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("EVENT_PROCESS_VISIBILITY_OUTPUTS_END");
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
final boolean wasDirty = mIsDirty;
final boolean hadPreviousComponentTree =
(mLastMountedComponentTreeId != ComponentTree.INVALID_ID);
mIsDirty = false;
mNeedsRemount = false;
if (localVisibleRect != null) {
mPreviousLocalVisibleRect.set(localVisibleRect);
}
clearLastMountedLayoutState();
mLastMountedComponentTreeId = componentTreeId;
mLastMountedLayoutState = layoutState;
processTestOutputs(layoutState);
if (mountPerfEvent != null) {
logMountPerfEvent(logger, mountPerfEvent, wasDirty, hadPreviousComponentTree);
}
LithoStats.incrementComponentMountCount();
mIsMounting = false;
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
private void clearLastMountedLayoutState() {
mLastMountedLayoutState = null;
}
private void afterMountMaybeUpdateAnimations() {
if (mTransitionsExtension != null && mIsDirty) {
mTransitionsExtension.afterMount(mTransitionsExtensionState);
}
}
@Override
public void mount(RenderTree renderTree) {
final LayoutState layoutState = (LayoutState) renderTree.getRenderTreeData();
mount(layoutState);
}
/**
* Mount only. Similar shape to RenderCore's mount. For extras such as incremental mount,
* visibility outputs etc register an extension. To do: extract transitions logic from here.
*/
void mount(LayoutState layoutState) {
assertMainThread();
if (layoutState == null) {
throw new IllegalStateException("Trying to mount a null layoutState");
}
mLayoutState = layoutState;
if (mIsMounting) {
ComponentsReporter.emitMessage(
ComponentsReporter.LogLevel.FATAL,
INVALID_REENTRANT_MOUNTS,
"Trying to mount while already mounting! "
+ getMountItemDebugMessage(mRootHostMountItem));
}
mIsMounting = true;
final ComponentTree componentTree = mLithoView.getComponentTree();
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
ComponentsSystrace.beginSectionWithArgs("mount")
.arg("treeId", layoutState.getComponentTreeId())
.arg("component", componentTree.getSimpleName())
.arg("logTag", componentTree.getContext().getLogTag())
.flush();
}
final ComponentsLogger logger = componentTree.getContext().getLogger();
final int componentTreeId = layoutState.getComponentTreeId();
if (componentTreeId != mLastMountedComponentTreeId) {
// If we're mounting a new ComponentTree, don't keep around and use the previous LayoutState
// since things like transition animations aren't relevant.
clearLastMountedLayoutState();
}
final PerfEvent mountPerfEvent =
logger == null
? null
: LogTreePopulator.populatePerfEventFromLogger(
componentTree.getContext(),
logger,
logger.newPerformanceEvent(componentTree.getContext(), EVENT_MOUNT));
// Prepare the data structure for the new LayoutState and removes mountItems
// that are not present anymore if isUpdateMountInPlace is enabled.
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_START");
}
prepareMount(layoutState, mountPerfEvent);
if (mountPerfEvent != null) {
mountPerfEvent.markerPoint("PREPARE_MOUNT_END");
}
mMountStats.reset();
if (mountPerfEvent != null && logger.isTracing(mountPerfEvent)) {
mMountStats.enableLogging();
}
for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) {
final RenderTreeNode renderTreeNode = layoutState.getMountableOutputAt(i);
final LayoutOutput layoutOutput = getLayoutOutput(renderTreeNode);
final Component component = layoutOutput.getComponent();
if (isTracing) {
RenderCoreSystrace.beginSection(component.getSimpleName());
}
final MountItem currentMountItem = getItemAt(i);
final boolean isMounted = currentMountItem != null;
final boolean isMountable = isMountable(renderTreeNode, i);
if (!isMountable) {
if (isMounted) {
unmountItem(i, mHostsByMarker);
}
} else if (!isMounted) {
mountLayoutOutput(i, renderTreeNode, layoutOutput, layoutState);
applyMountBinders(layoutOutput, getItemAt(i), i);
} else {
final boolean useUpdateValueFromLayoutOutput =
mLastMountedLayoutState != null
&& mLastMountedLayoutState.getId() == layoutState.getPreviousLayoutStateId();
final long startTime = System.nanoTime();
final boolean itemUpdated =
updateMountItemIfNeeded(
renderTreeNode,
currentMountItem,
useUpdateValueFromLayoutOutput,
componentTreeId,
i);
if (mMountStats.isLoggingEnabled) {
if (itemUpdated) {
mMountStats.updatedNames.add(component.getSimpleName());
mMountStats.updatedTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.updatedCount++;
} else {
mMountStats.noOpCount++;
}
}
applyBindBinders(currentMountItem);
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
final boolean wasDirty = mIsDirty;
final boolean hadPreviousComponentTree =
(mLastMountedComponentTreeId != ComponentTree.INVALID_ID);
mIsDirty = false;
mNeedsRemount = false;
clearLastMountedLayoutState();
mLastMountedComponentTreeId = componentTreeId;
mLastMountedLayoutState = layoutState;
if (mountPerfEvent != null) {
logMountPerfEvent(logger, mountPerfEvent, wasDirty, hadPreviousComponentTree);
}
if (isTracing) {
ComponentsSystrace.endSection(); // beginSectionWithArgs
}
LithoStats.incrementComponentMountCount();
mIsMounting = false;
}
private void applyMountBinders(LayoutOutput layoutOutput, MountItem mountItem, int position) {
if (mTransitionsExtension != null) {
mTransitionsExtension.onBoundsAppliedToItem(
mTransitionsExtensionState,
mountItem.getRenderTreeNode().getRenderUnit(),
mountItem.getContent(),
mountItem.getRenderTreeNode().getLayoutData());
} else if (mMountDelegate != null) {
mMountDelegate.onMountItem(
mountItem.getRenderTreeNode().getRenderUnit(),
mountItem.getContent(),
mountItem.getRenderTreeNode().getLayoutData());
}
}
private void applyBindBinders(MountItem mountItem) {
if (mMountDelegate == null) {
return;
}
}
private void applyUnbindBinders(LayoutOutput output, MountItem mountItem) {
if (mTransitionsExtension != null) {
mTransitionsExtension.onUnbindItem(
mTransitionsExtensionState,
mountItem.getRenderTreeNode().getRenderUnit(),
output,
mountItem.getRenderTreeNode().getLayoutData());
} else if (mMountDelegate != null) {
mMountDelegate.onUnmountItem(
mountItem.getRenderTreeNode().getRenderUnit(), output, mountItem.getContent());
}
}
private boolean isMountable(RenderTreeNode renderTreeNode, int position) {
if (mMountDelegate == null) {
return true;
}
final boolean isLockedForMount = mMountDelegate.maybeLockForMount(renderTreeNode, position);
return isLockedForMount;
}
@Override
public void notifyMount(long id) {
if (mLayoutState == null) {
return;
}
final int position = mLayoutState.getPositionForId(id);
if (position < 0 || getItemAt(position) != null) {
return;
}
final RenderTreeNode node = mLayoutState.getMountableOutputAt(position);
mountLayoutOutput(position, node, getLayoutOutput(node), mLayoutState);
}
@Override
public void notifyUnmount(long id) {
final MountItem item = mIndexToItemMap.get(id);
if (item == null || mLayoutState == null) {
return;
}
final int position = mLayoutState.getPositionForId(id);
if (position >= 0) {
unmountItem(position, mHostsByMarker);
}
}
private void logMountPerfEvent(
ComponentsLogger logger,
PerfEvent mountPerfEvent,
boolean isDirty,
boolean hadPreviousComponentTree) {
if (!mMountStats.isLoggingEnabled) {
logger.cancelPerfEvent(mountPerfEvent);
return;
}
// MOUNT events that don't mount any content are not valuable enough to log at the moment.
// We will likely enable them again in the future. T31729233
if (mMountStats.mountedCount == 0 || mMountStats.mountedNames.isEmpty()) {
logger.cancelPerfEvent(mountPerfEvent);
return;
}
mountPerfEvent.markerAnnotate(PARAM_MOUNTED_COUNT, mMountStats.mountedCount);
mountPerfEvent.markerAnnotate(
PARAM_MOUNTED_CONTENT, mMountStats.mountedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_MOUNTED_TIME, mMountStats.mountTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, mMountStats.unmountedCount);
mountPerfEvent.markerAnnotate(
PARAM_UNMOUNTED_CONTENT, mMountStats.unmountedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_UNMOUNTED_TIME, mMountStats.unmountedTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_MOUNTED_EXTRAS, mMountStats.extras.toArray(new String[0]));
mountPerfEvent.markerAnnotate(PARAM_UPDATED_COUNT, mMountStats.updatedCount);
mountPerfEvent.markerAnnotate(
PARAM_UPDATED_CONTENT, mMountStats.updatedNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_UPDATED_TIME, mMountStats.updatedTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLERS_TOTAL_TIME, mMountStats.visibilityHandlersTotalTime);
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLER, mMountStats.visibilityHandlerNames.toArray(new String[0]));
mountPerfEvent.markerAnnotate(
PARAM_VISIBILITY_HANDLER_TIME, mMountStats.visibilityHandlerTimes.toArray(new Double[0]));
mountPerfEvent.markerAnnotate(PARAM_NO_OP_COUNT, mMountStats.noOpCount);
mountPerfEvent.markerAnnotate(PARAM_IS_DIRTY, isDirty);
mountPerfEvent.markerAnnotate(PARAM_HAD_PREVIOUS_CT, hadPreviousComponentTree);
logger.logPerfEvent(mountPerfEvent);
}
void processVisibilityOutputs(
LayoutState layoutState,
@Nullable Rect localVisibleRect,
Rect previousLocalVisibleRect,
boolean isDirty,
@Nullable PerfEvent mountPerfEvent) {
if (mVisibilityExtension == null) {
return;
}
if (isDirty) {
mVisibilityExtension.afterMount(mVisibilityExtensionState);
} else {
mVisibilityExtension.onVisibleBoundsChanged(mVisibilityExtensionState, localVisibleRect);
}
}
@VisibleForTesting
Map<String, VisibilityItem> getVisibilityIdToItemMap() {
return VisibilityMountExtension.getVisibilityIdToItemMap(mVisibilityExtensionState);
}
@VisibleForTesting
@Override
public ArrayList<Host> getHosts() {
final ArrayList<Host> hosts = new ArrayList<>();
for (int i = 0, size = mHostsByMarker.size(); i < size; i++) {
hosts.add(mHostsByMarker.valueAt(i));
}
return hosts;
}
@Override
public int getMountItemCount() {
return mIndexToItemMap.size();
}
@Override
public int getRenderUnitCount() {
assertMainThread();
return mLayoutOutputsIds == null ? 0 : mLayoutOutputsIds.length;
}
@Override
public @Nullable MountItem getMountItemAt(int position) {
return getItemAt(position);
}
@Override
public void setUnmountDelegateExtension(UnmountDelegateExtension unmountDelegateExtension) {
mUnmountDelegateExtension = unmountDelegateExtension;
}
@Override
public void removeUnmountDelegateExtension() {
mUnmountDelegateExtension = null;
}
@Nullable
@Override
public MountDelegate getMountDelegate() {
return mMountDelegate;
}
/** Clears and re-populates the test item map if we are in e2e test mode. */
private void processTestOutputs(LayoutState layoutState) {
if (mTestItemMap == null) {
return;
}
mTestItemMap.clear();
for (int i = 0, size = layoutState.getTestOutputCount(); i < size; i++) {
final TestOutput testOutput = layoutState.getTestOutputAt(i);
final long hostMarker = testOutput.getHostMarker();
final long layoutOutputId = testOutput.getLayoutOutputId();
final MountItem mountItem = layoutOutputId == -1 ? null : mIndexToItemMap.get(layoutOutputId);
final TestItem testItem = new TestItem();
testItem.setHost(hostMarker == -1 ? null : mHostsByMarker.get(hostMarker));
testItem.setBounds(testOutput.getBounds());
testItem.setTestKey(testOutput.getTestKey());
testItem.setContent(mountItem == null ? null : mountItem.getContent());
final Deque<TestItem> items = mTestItemMap.get(testOutput.getTestKey());
final Deque<TestItem> updatedItems = items == null ? new LinkedList<TestItem>() : items;
updatedItems.add(testItem);
mTestItemMap.put(testOutput.getTestKey(), updatedItems);
}
}
private static boolean isMountedHostWithChildContent(@Nullable MountItem mountItem) {
if (mountItem == null) {
return false;
}
final Object content = mountItem.getContent();
if (!(content instanceof ComponentHost)) {
return false;
}
final ComponentHost host = (ComponentHost) content;
return host.getMountItemCount() > 0;
}
private void setupPreviousMountableOutputData(LayoutState layoutState, Rect localVisibleRect) {
if (localVisibleRect.isEmpty()) {
return;
}
final ArrayList<IncrementalMountOutput> layoutOutputTops =
layoutState.getOutputsOrderedByTopBounds();
final ArrayList<IncrementalMountOutput> layoutOutputBottoms =
layoutState.getOutputsOrderedByBottomBounds();
final int mountableOutputCount = layoutState.getMountableOutputCount();
mPreviousTopsIndex = layoutState.getMountableOutputCount();
for (int i = 0; i < mountableOutputCount; i++) {
if (localVisibleRect.bottom <= layoutOutputTops.get(i).getBounds().top) {
mPreviousTopsIndex = i;
break;
}
}
mPreviousBottomsIndex = layoutState.getMountableOutputCount();
for (int i = 0; i < mountableOutputCount; i++) {
if (localVisibleRect.top < layoutOutputBottoms.get(i).getBounds().bottom) {
mPreviousBottomsIndex = i;
break;
}
}
}
List<LithoView> getChildLithoViewsFromCurrentlyMountedItems() {
final ArrayList<LithoView> childLithoViews = new ArrayList<>();
for (int i = 0; i < mIndexToItemMap.size(); i++) {
final long layoutOutputId = mIndexToItemMap.keyAt(i);
final MountItem mountItem = mIndexToItemMap.get(layoutOutputId);
if (mountItem != null && mountItem.getContent() instanceof HasLithoViewChildren) {
((HasLithoViewChildren) mountItem.getContent()).obtainLithoViewChildren(childLithoViews);
}
}
return childLithoViews;
}
void clearVisibilityItems() {
if (mVisibilityExtension != null) {
VisibilityMountExtension.clearVisibilityItems(mVisibilityExtensionState);
}
}
private void registerHost(long id, ComponentHost host) {
mHostsByMarker.put(id, host);
}
private static int computeRectArea(Rect rect) {
return rect.isEmpty() ? 0 : (rect.width() * rect.height());
}
private boolean updateMountItemIfNeeded(
RenderTreeNode node,
MountItem currentMountItem,
boolean useUpdateValueFromLayoutOutput,
int componentTreeId,
int index) {
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("updateMountItemIfNeeded");
}
final LayoutOutput nextLayoutOutput = getLayoutOutput(node);
final Component layoutOutputComponent = nextLayoutOutput.getComponent();
final LayoutOutput currentLayoutOutput = getLayoutOutput(currentMountItem);
final Component itemComponent = currentLayoutOutput.getComponent();
final Object currentContent = currentMountItem.getContent();
final ComponentHost host = (ComponentHost) currentMountItem.getHost();
final ComponentContext currentContext = getComponentContext(currentMountItem);
final ComponentContext nextContext = getComponentContext(node);
final LithoLayoutData nextLayoutData = (LithoLayoutData) node.getLayoutData();
final LithoLayoutData currentLayoutData =
(LithoLayoutData) currentMountItem.getRenderTreeNode().getLayoutData();
if (layoutOutputComponent == null) {
throw new RuntimeException("Trying to update a MountItem with a null Component.");
}
if (isTracing) {
RenderCoreSystrace.beginSection("UpdateItem: " + node.getRenderUnit().getDescription());
}
// 1. Check if the mount item generated from the old component should be updated.
final boolean shouldUpdate =
shouldUpdateMountItem(
nextLayoutOutput,
nextLayoutData,
nextContext,
currentLayoutOutput,
currentLayoutData,
currentContext,
useUpdateValueFromLayoutOutput);
final boolean shouldUpdateViewInfo =
shouldUpdate || shouldUpdateViewInfo(nextLayoutOutput, currentLayoutOutput);
// 2. Reset all the properties like click handler, content description and tags related to
// this item if it needs to be updated. the update mount item will re-set the new ones.
if (shouldUpdateViewInfo) {
maybeUnsetViewAttributes(currentMountItem);
}
// 3. We will re-bind this later in 7 regardless so let's make sure it's currently unbound.
if (currentMountItem.isBound()) {
unbindComponentFromContent(currentMountItem, itemComponent, currentMountItem.getContent());
}
// 4. Re initialize the MountItem internal state with the new attributes from LayoutOutput
currentMountItem.update(node);
// 5. If the mount item is not valid for this component update its content and view attributes.
if (shouldUpdate) {
updateMountedContent(
currentMountItem,
layoutOutputComponent,
nextContext,
nextLayoutData,
itemComponent,
currentContext,
currentLayoutData);
}
if (shouldUpdateViewInfo) {
setViewAttributes(currentMountItem);
}
// 6. Set the mounted content on the Component and call the bind callback.
bindComponentToContent(
currentMountItem, layoutOutputComponent, nextContext, nextLayoutData, currentContent);
// 7. Update the bounds of the mounted content. This needs to be done regardless of whether
// the component has been updated or not since the mounted item might might have the same
// size and content but a different position.
updateBoundsForMountedLayoutOutput(node, nextLayoutOutput, currentMountItem);
if (currentMountItem.getContent() instanceof Drawable) {
maybeSetDrawableState(
host,
(Drawable) currentContent,
currentLayoutOutput.getFlags(),
currentLayoutOutput.getNodeInfo());
}
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.endSection();
}
return shouldUpdate;
}
static boolean shouldUpdateViewInfo(
final LayoutOutput nextLayoutOutput, final LayoutOutput currentLayoutOutput) {
final ViewNodeInfo nextViewNodeInfo = nextLayoutOutput.getViewNodeInfo();
final ViewNodeInfo currentViewNodeInfo = currentLayoutOutput.getViewNodeInfo();
if ((currentViewNodeInfo == null && nextViewNodeInfo != null)
|| (currentViewNodeInfo != null && !currentViewNodeInfo.isEquivalentTo(nextViewNodeInfo))) {
return true;
}
final NodeInfo nextNodeInfo = nextLayoutOutput.getNodeInfo();
final NodeInfo currentNodeInfo = currentLayoutOutput.getNodeInfo();
return (currentNodeInfo == null && nextNodeInfo != null)
|| (currentNodeInfo != null && !currentNodeInfo.isEquivalentTo(nextNodeInfo));
}
static boolean shouldUpdateMountItem(
final LayoutOutput nextLayoutOutput,
final @Nullable LithoLayoutData nextLayoutData,
final @Nullable ComponentContext nextContext,
final LayoutOutput currentLayoutOutput,
final @Nullable LithoLayoutData currentLayoutData,
final @Nullable ComponentContext currentContext,
final boolean useUpdateValueFromLayoutOutput) {
@LayoutOutput.UpdateState final int updateState = nextLayoutOutput.getUpdateState();
final Component currentComponent = currentLayoutOutput.getComponent();
final Component nextComponent = nextLayoutOutput.getComponent();
// If the two components have different sizes and the mounted content depends on the size we
// just return true immediately.
if (nextComponent.isMountSizeDependent()
&& !sameSize(
Preconditions.checkNotNull(nextLayoutData),
Preconditions.checkNotNull(currentLayoutData))) {
return true;
}
if (useUpdateValueFromLayoutOutput) {
if (updateState == LayoutOutput.STATE_UPDATED) {
// Check for incompatible ReferenceLifecycle.
return currentComponent instanceof DrawableComponent
&& nextComponent instanceof DrawableComponent
&& shouldUpdate(currentComponent, currentContext, nextComponent, nextContext);
} else if (updateState == LayoutOutput.STATE_DIRTY) {
return true;
}
}
return shouldUpdate(currentComponent, currentContext, nextComponent, nextContext);
}
private static boolean shouldUpdate(
Component currentComponent,
ComponentContext currentScopedContext,
Component nextComponent,
ComponentContext nextScopedContext) {
final boolean isTracing = RenderCoreSystrace.isEnabled();
try {
if (isTracing) {
RenderCoreSystrace.beginSection("MountState.shouldUpdate");
}
return currentComponent.shouldComponentUpdate(
currentScopedContext, currentComponent, nextScopedContext, nextComponent);
} catch (Exception e) {
ComponentUtils.handle(nextScopedContext, e);
return true;
} finally {
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
}
static boolean sameSize(final LithoLayoutData next, final LithoLayoutData current) {
return next.width == current.width && next.height == current.height;
}
private static void updateBoundsForMountedLayoutOutput(
final RenderTreeNode node, final LayoutOutput layoutOutput, final MountItem item) {
// MountState should never update the bounds of the top-level host as this
// should be done by the ViewGroup containing the LithoView.
if (node.getRenderUnit().getId() == ROOT_HOST_ID) {
return;
}
final Rect bounds = node.getBounds();
final boolean forceTraversal =
isMountableView(node.getRenderUnit()) && ((View) item.getContent()).isLayoutRequested();
applyBoundsToMountContent(
item.getContent(),
bounds.left,
bounds.top,
bounds.right,
bounds.bottom,
forceTraversal /* force */);
}
/** Prepare the {@link MountState} to mount a new {@link LayoutState}. */
private void prepareMount(LayoutState layoutState, @Nullable PerfEvent perfEvent) {
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("prepareMount");
}
final PrepareMountStats stats = unmountOrMoveOldItems(layoutState);
if (perfEvent != null) {
perfEvent.markerAnnotate(PARAM_UNMOUNTED_COUNT, stats.unmountedCount);
perfEvent.markerAnnotate(PARAM_MOVED_COUNT, stats.movedCount);
perfEvent.markerAnnotate(PARAM_UNCHANGED_COUNT, stats.unchangedCount);
}
if (mIndexToItemMap.get(ROOT_HOST_ID) == null || mHostsByMarker.get(ROOT_HOST_ID) == null) {
// Mounting always starts with the root host.
registerHost(ROOT_HOST_ID, mLithoView);
// Root host is implicitly marked as mounted.
mIndexToItemMap.put(ROOT_HOST_ID, mRootHostMountItem);
}
final int outputCount = layoutState.getMountableOutputCount();
if (mLayoutOutputsIds == null || outputCount != mLayoutOutputsIds.length) {
mLayoutOutputsIds = new long[outputCount];
}
for (int i = 0; i < outputCount; i++) {
mLayoutOutputsIds[i] = layoutState.getMountableOutputAt(i).getRenderUnit().getId();
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
/**
* Go over all the mounted items from the leaves to the root and unmount only the items that are
* not present in the new LayoutOutputs. If an item is still present but in a new position move
* the item inside its host. The condition where an item changed host doesn't need any special
* treatment here since we mark them as removed and re-added when calculating the new
* LayoutOutputs
*/
private PrepareMountStats unmountOrMoveOldItems(LayoutState newLayoutState) {
mPrepareMountStats.reset();
if (mLayoutOutputsIds == null) {
return mPrepareMountStats;
}
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("unmountOrMoveOldItems");
}
// Traversing from the beginning since mLayoutOutputsIds unmounting won't remove entries there
// but only from mIndexToItemMap. If an host changes we're going to unmount it and recursively
// all its mounted children.
for (int i = 0; i < mLayoutOutputsIds.length; i++) {
final int newPosition = newLayoutState.getPositionForId(mLayoutOutputsIds[i]);
final @Nullable RenderTreeNode newRenderTreeNode =
newPosition != -1 ? newLayoutState.getMountableOutputAt(newPosition) : null;
final MountItem oldItem = getItemAt(i);
final boolean hasUnmountDelegate =
mUnmountDelegateExtension != null && oldItem != null
? mUnmountDelegateExtension.shouldDelegateUnmount(
mMountDelegate.getUnmountDelegateExtensionState(), oldItem)
: false;
if (hasUnmountDelegate) {
continue;
}
if (newPosition == -1) {
unmountItem(i, mHostsByMarker);
mPrepareMountStats.unmountedCount++;
} else {
final long newHostMarker =
i != 0 ? newRenderTreeNode.getParent().getRenderUnit().getId() : -1;
if (oldItem == null) {
// This was previously unmounted.
mPrepareMountStats.unmountedCount++;
} else if (oldItem.getHost() != mHostsByMarker.get(newHostMarker)) {
// If the id is the same but the parent host is different we simply unmount the item and
// re-mount it later. If the item to unmount is a ComponentHost, all the children will be
// recursively unmounted.
unmountItem(i, mHostsByMarker);
mPrepareMountStats.unmountedCount++;
} else if (mShouldUsePositionInParent
&& oldItem.getRenderTreeNode().getPositionInParent()
!= newRenderTreeNode.getPositionInParent()) {
// If a MountItem for this id exists and the hostMarker has not changed but its position
// in the outputs array has changed we need to update the position in the Host to ensure
// the z-ordering.
oldItem
.getHost()
.moveItem(
oldItem,
oldItem.getRenderTreeNode().getPositionInParent(),
newRenderTreeNode.getPositionInParent());
mPrepareMountStats.movedCount++;
} else if (!mShouldUsePositionInParent && newPosition != i) {
// If a MountItem for this id exists and the hostMarker has not changed but its position
// in the outputs array has changed we need to update the position in the Host to ensure
// the z-ordering.
oldItem.getHost().moveItem(oldItem, i, newPosition);
mPrepareMountStats.movedCount++;
} else {
mPrepareMountStats.unchangedCount++;
}
}
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
return mPrepareMountStats;
}
private void updateMountedContent(
final MountItem item,
final Component newComponent,
final ComponentContext newContext,
final LithoLayoutData nextLayoutData,
final Component previousComponent,
final ComponentContext previousContext,
final LithoLayoutData currentLayoutData) {
if (isHostSpec(newComponent)) {
return;
}
final Object previousContent = item.getContent();
// Call unmount and mount in sequence to make sure all the the resources are correctly
// de-allocated. It's possible for previousContent to equal null - when the root is
// interactive we create a LayoutOutput without content in order to set up click handling.
previousComponent.unmount(
previousContext, previousContent, (InterStagePropsContainer) currentLayoutData.mLayoutData);
newComponent.mount(
newContext, previousContent, (InterStagePropsContainer) nextLayoutData.mLayoutData);
}
private void mountLayoutOutput(
final int index,
final RenderTreeNode node,
final LayoutOutput layoutOutput,
final LayoutState layoutState) {
// 1. Resolve the correct host to mount our content to.
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("MountItem: " + node.getRenderUnit().getDescription());
RenderCoreSystrace.beginSection("MountItem:before " + node.getRenderUnit().getDescription());
}
final long startTime = System.nanoTime();
// parent should never be null
final long hostMarker = node.getParent().getRenderUnit().getId();
ComponentHost host = mHostsByMarker.get(hostMarker);
if (host == null) {
// Host has not yet been mounted - mount it now.
final int hostMountIndex = layoutState.getPositionForId(hostMarker);
final RenderTreeNode hostNode = layoutState.getMountableOutputAt(hostMountIndex);
final LayoutOutput hostLayoutOutput = getLayoutOutput(hostNode);
mountLayoutOutput(hostMountIndex, hostNode, hostLayoutOutput, layoutState);
host = mHostsByMarker.get(hostMarker);
}
// 2. Generate the component's mount state (this might also be a ComponentHost View).
final Component component = layoutOutput.getComponent();
if (component == null) {
throw new RuntimeException("Trying to mount a LayoutOutput with a null Component.");
}
final Object content;
if (component instanceof HostComponent) {
content =
acquireHostComponentContent(mContext.getAndroidContext(), (HostComponent) component);
} else {
content = MountItemsPool.acquireMountContent(mContext.getAndroidContext(), component);
}
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.beginSection("MountItem:mount " + node.getRenderUnit().getDescription());
}
final ComponentContext context = getContextForComponent(node);
final LithoLayoutData layoutData = (LithoLayoutData) node.getLayoutData();
component.mount(context, content, (InterStagePropsContainer) layoutData.mLayoutData);
// 3. If it's a ComponentHost, add the mounted View to the list of Hosts.
if (isHostSpec(component)) {
ComponentHost componentHost = (ComponentHost) content;
registerHost(node.getRenderUnit().getId(), componentHost);
}
// 4. Mount the content into the selected host.
final MountItem item = mountContent(index, component, content, host, node, layoutOutput);
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.beginSection("MountItem:bind " + node.getRenderUnit().getDescription());
}
// 5. Notify the component that mounting has completed
bindComponentToContent(item, component, context, layoutData, content);
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.beginSection(
"MountItem:applyBounds " + node.getRenderUnit().getDescription());
}
// 6. Apply the bounds to the Mount content now. It's important to do so after bind as calling
// bind might have triggered a layout request within a View.
final Rect bounds = node.getBounds();
applyBoundsToMountContent(
item.getContent(), bounds.left, bounds.top, bounds.right, bounds.bottom, true /* force */);
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.beginSection("MountItem:after " + node.getRenderUnit().getDescription());
}
// 6. Update the mount stats
if (mMountStats.isLoggingEnabled) {
mMountStats.mountTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.mountedNames.add(component.getSimpleName());
mMountStats.mountedCount++;
final ComponentContext scopedContext = getComponentContext(node);
mMountStats.extras.add(
LogTreePopulator.getAnnotationBundleFromLogger(scopedContext, context.getLogger()));
}
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.endSection();
}
}
// The content might be null because it's the LayoutSpec for the root host
// (the very first LayoutOutput).
private MountItem mountContent(
int index,
Component component,
Object content,
ComponentHost host,
RenderTreeNode node,
LayoutOutput layoutOutput) {
final MountItem item = new MountItem(node, host, content);
item.setMountData(new LithoMountData(content));
// Create and keep a MountItem even for the layoutSpec with null content
// that sets the root host interactions.
mIndexToItemMap.put(mLayoutOutputsIds[index], item);
if (component.hasChildLithoViews()) {
mCanMountIncrementallyMountItems.put(mLayoutOutputsIds[index], item);
}
final int positionInParent = item.getRenderTreeNode().getPositionInParent();
mount(host, mShouldUsePositionInParent ? positionInParent : index, content, item, node);
setViewAttributes(item);
return item;
}
private static void mount(
final ComponentHost host,
final int index,
final Object content,
final MountItem item,
final RenderTreeNode node) {
host.mount(index, item, node.getBounds());
}
private static void unmount(
final ComponentHost host,
final int index,
final Object content,
final MountItem item,
final LayoutOutput output) {
host.unmount(index, item);
}
private static void applyBoundsToMountContent(
Object content, int left, int top, int right, int bottom, boolean force) {
assertMainThread();
BoundsUtils.applyBoundsToMountContent(left, top, right, bottom, null, content, force);
}
private static void setViewAttributes(MountItem item) {
setViewAttributes(item.getContent(), getLayoutOutput(item));
}
static void setViewAttributes(Object content, LayoutOutput output) {
final Component component = output.getComponent();
if (!(content instanceof View)) {
return;
}
final View view = (View) content;
final NodeInfo nodeInfo = output.getNodeInfo();
if (nodeInfo != null) {
setClickHandler(nodeInfo.getClickHandler(), view);
setLongClickHandler(nodeInfo.getLongClickHandler(), view);
setFocusChangeHandler(nodeInfo.getFocusChangeHandler(), view);
setTouchHandler(nodeInfo.getTouchHandler(), view);
setInterceptTouchHandler(nodeInfo.getInterceptTouchHandler(), view);
setAccessibilityDelegate(view, nodeInfo);
setViewTag(view, nodeInfo.getViewTag());
setViewTags(view, nodeInfo.getViewTags());
setShadowElevation(view, nodeInfo.getShadowElevation());
setOutlineProvider(view, nodeInfo.getOutlineProvider());
setClipToOutline(view, nodeInfo.getClipToOutline());
setClipChildren(view, nodeInfo);
setContentDescription(view, nodeInfo.getContentDescription());
setFocusable(view, nodeInfo.getFocusState());
setClickable(view, nodeInfo.getClickableState());
setEnabled(view, nodeInfo.getEnabledState());
setSelected(view, nodeInfo.getSelectedState());
setScale(view, nodeInfo);
setAlpha(view, nodeInfo);
setRotation(view, nodeInfo);
setRotationX(view, nodeInfo);
setRotationY(view, nodeInfo);
setTransitionName(view, nodeInfo.getTransitionName());
}
setImportantForAccessibility(view, output.getImportantForAccessibility());
final ViewNodeInfo viewNodeInfo = output.getViewNodeInfo();
if (viewNodeInfo != null) {
final boolean isHostSpec = isHostSpec(component);
setViewLayerType(view, viewNodeInfo);
setViewStateListAnimator(view, viewNodeInfo);
if (LayoutOutput.areDrawableOutputsDisabled(output.getFlags())) {
setViewBackground(view, viewNodeInfo);
ViewUtils.setViewForeground(view, viewNodeInfo.getForeground());
// when background outputs are disabled, they are wrapped by a ComponentHost.
// A background can set the padding of a view, but ComponentHost should not have
// any padding because the layout calculation has already accounted for padding by
// translating the bounds of its children.
if (isHostSpec) {
view.setPadding(0, 0, 0, 0);
}
}
if (!isHostSpec) {
// Set view background, if applicable. Do this before padding
// as it otherwise overrides the padding.
setViewBackground(view, viewNodeInfo);
setViewPadding(view, viewNodeInfo);
ViewUtils.setViewForeground(view, viewNodeInfo.getForeground());
setViewLayoutDirection(view, viewNodeInfo);
}
}
}
private static void setViewLayerType(final View view, final ViewNodeInfo info) {
final int type = info.getLayerType();
if (type != LayerType.LAYER_TYPE_NOT_SET) {
view.setLayerType(info.getLayerType(), info.getLayoutPaint());
}
}
private static void unsetViewLayerType(final View view, final int mountFlags) {
int type = LithoMountData.getOriginalLayerType(mountFlags);
if (type != LayerType.LAYER_TYPE_NOT_SET) {
view.setLayerType(type, null);
}
}
private static void maybeUnsetViewAttributes(MountItem item) {
final LayoutOutput output = getLayoutOutput(item);
final int flags = getMountData(item).getDefaultAttributeValuesFlags();
unsetViewAttributes(item.getContent(), output, flags);
}
static void unsetViewAttributes(
final Object content, final LayoutOutput output, final int mountFlags) {
final Component component = output.getComponent();
final boolean isHostView = isHostSpec(component);
if (!(content instanceof View)) {
return;
}
final View view = (View) content;
final NodeInfo nodeInfo = output.getNodeInfo();
if (nodeInfo != null) {
if (nodeInfo.getClickHandler() != null) {
unsetClickHandler(view);
}
if (nodeInfo.getLongClickHandler() != null) {
unsetLongClickHandler(view);
}
if (nodeInfo.getFocusChangeHandler() != null) {
unsetFocusChangeHandler(view);
}
if (nodeInfo.getTouchHandler() != null) {
unsetTouchHandler(view);
}
if (nodeInfo.getInterceptTouchHandler() != null) {
unsetInterceptTouchEventHandler(view);
}
unsetViewTag(view);
unsetViewTags(view, nodeInfo.getViewTags());
unsetShadowElevation(view, nodeInfo.getShadowElevation());
unsetOutlineProvider(view, nodeInfo.getOutlineProvider());
unsetClipToOutline(view, nodeInfo.getClipToOutline());
unsetClipChildren(view, nodeInfo.getClipChildren());
if (!TextUtils.isEmpty(nodeInfo.getContentDescription())) {
unsetContentDescription(view);
}
unsetScale(view, nodeInfo);
unsetAlpha(view, nodeInfo);
unsetRotation(view, nodeInfo);
unsetRotationX(view, nodeInfo);
unsetRotationY(view, nodeInfo);
}
view.setClickable(isViewClickable(mountFlags));
view.setLongClickable(isViewLongClickable(mountFlags));
unsetFocusable(view, mountFlags);
unsetEnabled(view, mountFlags);
unsetSelected(view, mountFlags);
if (output.getImportantForAccessibility() != IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
unsetImportantForAccessibility(view);
}
unsetAccessibilityDelegate(view);
final ViewNodeInfo viewNodeInfo = output.getViewNodeInfo();
if (viewNodeInfo != null) {
unsetViewStateListAnimator(view, viewNodeInfo);
// Host view doesn't set its own padding, but gets absolute positions for inner content from
// Yoga. Also bg/fg is used as separate drawables instead of using View's bg/fg attribute.
if (LayoutOutput.areDrawableOutputsDisabled(output.getFlags())) {
unsetViewBackground(view, viewNodeInfo);
unsetViewForeground(view, viewNodeInfo);
}
if (!isHostView) {
unsetViewPadding(view, output, viewNodeInfo);
unsetViewBackground(view, viewNodeInfo);
unsetViewForeground(view, viewNodeInfo);
unsetViewLayoutDirection(view);
}
}
unsetViewLayerType(view, mountFlags);
}
/**
* Store a {@link NodeInfo} as a tag in {@code view}. {@link LithoView} contains the logic for
* setting/unsetting it whenever accessibility is enabled/disabled
*
* <p>For non {@link ComponentHost}s this is only done if any {@link EventHandler}s for
* accessibility events have been implemented, we want to preserve the original behaviour since
* {@code view} might have had a default delegate.
*/
private static void setAccessibilityDelegate(View view, NodeInfo nodeInfo) {
if (!(view instanceof ComponentHost) && !nodeInfo.needsAccessibilityDelegate()) {
return;
}
view.setTag(R.id.component_node_info, nodeInfo);
}
private static void unsetAccessibilityDelegate(View view) {
if (!(view instanceof ComponentHost) && view.getTag(R.id.component_node_info) == null) {
return;
}
view.setTag(R.id.component_node_info, null);
if (!(view instanceof ComponentHost)) {
ViewCompat.setAccessibilityDelegate(view, null);
}
}
/**
* Installs the click listeners that will dispatch the click handler defined in the component's
* props. Unconditionally set the clickable flag on the view.
*/
private static void setClickHandler(@Nullable EventHandler<ClickEvent> clickHandler, View view) {
if (clickHandler == null) {
return;
}
ComponentClickListener listener = getComponentClickListener(view);
if (listener == null) {
listener = new ComponentClickListener();
setComponentClickListener(view, listener);
}
listener.setEventHandler(clickHandler);
view.setClickable(true);
}
private static void unsetClickHandler(View view) {
final ComponentClickListener listener = getComponentClickListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
@Nullable
static ComponentClickListener getComponentClickListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentClickListener();
} else {
return (ComponentClickListener) v.getTag(R.id.component_click_listener);
}
}
static void setComponentClickListener(View v, ComponentClickListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentClickListener(listener);
} else {
v.setOnClickListener(listener);
v.setTag(R.id.component_click_listener, listener);
}
}
/**
* Installs the long click listeners that will dispatch the click handler defined in the
* component's props. Unconditionally set the clickable flag on the view.
*/
private static void setLongClickHandler(
@Nullable EventHandler<LongClickEvent> longClickHandler, View view) {
if (longClickHandler != null) {
ComponentLongClickListener listener = getComponentLongClickListener(view);
if (listener == null) {
listener = new ComponentLongClickListener();
setComponentLongClickListener(view, listener);
}
listener.setEventHandler(longClickHandler);
view.setLongClickable(true);
}
}
private static void unsetLongClickHandler(View view) {
final ComponentLongClickListener listener = getComponentLongClickListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
@Nullable
static ComponentLongClickListener getComponentLongClickListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentLongClickListener();
} else {
return (ComponentLongClickListener) v.getTag(R.id.component_long_click_listener);
}
}
static void setComponentLongClickListener(View v, ComponentLongClickListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentLongClickListener(listener);
} else {
v.setOnLongClickListener(listener);
v.setTag(R.id.component_long_click_listener, listener);
}
}
/**
* Installs the on focus change listeners that will dispatch the click handler defined in the
* component's props. Unconditionally set the clickable flag on the view.
*/
private static void setFocusChangeHandler(
@Nullable EventHandler<FocusChangedEvent> focusChangeHandler, View view) {
if (focusChangeHandler == null) {
return;
}
ComponentFocusChangeListener listener = getComponentFocusChangeListener(view);
if (listener == null) {
listener = new ComponentFocusChangeListener();
setComponentFocusChangeListener(view, listener);
}
listener.setEventHandler(focusChangeHandler);
}
private static void unsetFocusChangeHandler(View view) {
final ComponentFocusChangeListener listener = getComponentFocusChangeListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
static ComponentFocusChangeListener getComponentFocusChangeListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentFocusChangeListener();
} else {
return (ComponentFocusChangeListener) v.getTag(R.id.component_focus_change_listener);
}
}
static void setComponentFocusChangeListener(View v, ComponentFocusChangeListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentFocusChangeListener(listener);
} else {
v.setOnFocusChangeListener(listener);
v.setTag(R.id.component_focus_change_listener, listener);
}
}
/**
* Installs the touch listeners that will dispatch the touch handler defined in the component's
* props.
*/
private static void setTouchHandler(@Nullable EventHandler<TouchEvent> touchHandler, View view) {
if (touchHandler != null) {
ComponentTouchListener listener = getComponentTouchListener(view);
if (listener == null) {
listener = new ComponentTouchListener();
setComponentTouchListener(view, listener);
}
listener.setEventHandler(touchHandler);
}
}
private static void unsetTouchHandler(View view) {
final ComponentTouchListener listener = getComponentTouchListener(view);
if (listener != null) {
listener.setEventHandler(null);
}
}
/** Sets the intercept touch handler defined in the component's props. */
private static void setInterceptTouchHandler(
@Nullable EventHandler<InterceptTouchEvent> interceptTouchHandler, View view) {
if (interceptTouchHandler == null) {
return;
}
if (view instanceof ComponentHost) {
((ComponentHost) view).setInterceptTouchEventHandler(interceptTouchHandler);
}
}
private static void unsetInterceptTouchEventHandler(View view) {
if (view instanceof ComponentHost) {
((ComponentHost) view).setInterceptTouchEventHandler(null);
}
}
@Nullable
static ComponentTouchListener getComponentTouchListener(View v) {
if (v instanceof ComponentHost) {
return ((ComponentHost) v).getComponentTouchListener();
} else {
return (ComponentTouchListener) v.getTag(R.id.component_touch_listener);
}
}
static void setComponentTouchListener(View v, ComponentTouchListener listener) {
if (v instanceof ComponentHost) {
((ComponentHost) v).setComponentTouchListener(listener);
} else {
v.setOnTouchListener(listener);
v.setTag(R.id.component_touch_listener, listener);
}
}
private static void setViewTag(View view, @Nullable Object viewTag) {
view.setTag(viewTag);
}
private static void setViewTags(View view, @Nullable SparseArray<Object> viewTags) {
if (viewTags == null) {
return;
}
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTags(viewTags);
} else {
for (int i = 0, size = viewTags.size(); i < size; i++) {
view.setTag(viewTags.keyAt(i), viewTags.valueAt(i));
}
}
}
private static void unsetViewTag(View view) {
view.setTag(null);
}
private static void unsetViewTags(View view, @Nullable SparseArray<Object> viewTags) {
if (view instanceof ComponentHost) {
final ComponentHost host = (ComponentHost) view;
host.setViewTags(null);
} else {
if (viewTags != null) {
for (int i = 0, size = viewTags.size(); i < size; i++) {
view.setTag(viewTags.keyAt(i), null);
}
}
}
}
private static void setShadowElevation(View view, float shadowElevation) {
if (shadowElevation != 0) {
ViewCompat.setElevation(view, shadowElevation);
}
}
private static void unsetShadowElevation(View view, float shadowElevation) {
if (shadowElevation != 0) {
ViewCompat.setElevation(view, 0);
}
}
private static void setOutlineProvider(View view, @Nullable ViewOutlineProvider outlineProvider) {
if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setOutlineProvider(outlineProvider);
}
}
private static void unsetOutlineProvider(
View view, @Nullable ViewOutlineProvider outlineProvider) {
if (outlineProvider != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setOutlineProvider(ViewOutlineProvider.BACKGROUND);
}
}
private static void setClipToOutline(View view, boolean clipToOutline) {
if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setClipToOutline(clipToOutline);
}
}
private static void unsetClipToOutline(View view, boolean clipToOutline) {
if (clipToOutline && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.setClipToOutline(false);
}
}
private static void setClipChildren(View view, NodeInfo nodeInfo) {
if (nodeInfo.isClipChildrenSet() && view instanceof ViewGroup) {
((ViewGroup) view).setClipChildren(nodeInfo.getClipChildren());
}
}
private static void unsetClipChildren(View view, boolean clipChildren) {
if (!clipChildren && view instanceof ViewGroup) {
// Default value for clipChildren is 'true'.
// If this ViewGroup had clipChildren set to 'false' before mounting we would reset this
// property here on recycling.
((ViewGroup) view).setClipChildren(true);
}
}
private static void setContentDescription(View view, @Nullable CharSequence contentDescription) {
if (TextUtils.isEmpty(contentDescription)) {
return;
}
view.setContentDescription(contentDescription);
}
private static void unsetContentDescription(View view) {
view.setContentDescription(null);
}
private static void setImportantForAccessibility(View view, int importantForAccessibility) {
if (importantForAccessibility == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
return;
}
ViewCompat.setImportantForAccessibility(view, importantForAccessibility);
}
private static void unsetImportantForAccessibility(View view) {
ViewCompat.setImportantForAccessibility(view, IMPORTANT_FOR_ACCESSIBILITY_AUTO);
}
private static void setFocusable(View view, @NodeInfo.FocusState int focusState) {
if (focusState == NodeInfo.FOCUS_SET_TRUE) {
view.setFocusable(true);
} else if (focusState == NodeInfo.FOCUS_SET_FALSE) {
view.setFocusable(false);
}
}
private static void unsetFocusable(View view, int flags) {
view.setFocusable(isViewFocusable(flags));
}
private static void setTransitionName(View view, @Nullable String transitionName) {
ViewCompat.setTransitionName(view, transitionName);
}
private static void setClickable(View view, @NodeInfo.FocusState int clickableState) {
if (clickableState == NodeInfo.CLICKABLE_SET_TRUE) {
view.setClickable(true);
} else if (clickableState == NodeInfo.CLICKABLE_SET_FALSE) {
view.setClickable(false);
}
}
private static void setEnabled(View view, @NodeInfo.EnabledState int enabledState) {
if (enabledState == NodeInfo.ENABLED_SET_TRUE) {
view.setEnabled(true);
} else if (enabledState == NodeInfo.ENABLED_SET_FALSE) {
view.setEnabled(false);
}
}
private static void unsetEnabled(View view, int flags) {
view.setEnabled(isViewEnabled(flags));
}
private static void setSelected(View view, @NodeInfo.SelectedState int selectedState) {
if (selectedState == NodeInfo.SELECTED_SET_TRUE) {
view.setSelected(true);
} else if (selectedState == NodeInfo.SELECTED_SET_FALSE) {
view.setSelected(false);
}
}
private static void unsetSelected(View view, int flags) {
view.setSelected(isViewSelected(flags));
}
private static void setScale(View view, NodeInfo nodeInfo) {
if (nodeInfo.isScaleSet()) {
final float scale = nodeInfo.getScale();
view.setScaleX(scale);
view.setScaleY(scale);
}
}
private static void unsetScale(View view, NodeInfo nodeInfo) {
if (nodeInfo.isScaleSet()) {
if (view.getScaleX() != 1) {
view.setScaleX(1);
}
if (view.getScaleY() != 1) {
view.setScaleY(1);
}
}
}
private static void setAlpha(View view, NodeInfo nodeInfo) {
if (nodeInfo.isAlphaSet()) {
view.setAlpha(nodeInfo.getAlpha());
}
}
private static void unsetAlpha(View view, NodeInfo nodeInfo) {
if (nodeInfo.isAlphaSet() && view.getAlpha() != 1) {
view.setAlpha(1);
}
}
private static void setRotation(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationSet()) {
view.setRotation(nodeInfo.getRotation());
}
}
private static void unsetRotation(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationSet() && view.getRotation() != 0) {
view.setRotation(0);
}
}
private static void setRotationX(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationXSet()) {
view.setRotationX(nodeInfo.getRotationX());
}
}
private static void unsetRotationX(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationXSet() && view.getRotationX() != 0) {
view.setRotationX(0);
}
}
private static void setRotationY(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationYSet()) {
view.setRotationY(nodeInfo.getRotationY());
}
}
private static void unsetRotationY(View view, NodeInfo nodeInfo) {
if (nodeInfo.isRotationYSet() && view.getRotationY() != 0) {
view.setRotationY(0);
}
}
private static void setViewPadding(View view, ViewNodeInfo viewNodeInfo) {
if (!viewNodeInfo.hasPadding()) {
return;
}
view.setPadding(
viewNodeInfo.getPaddingLeft(),
viewNodeInfo.getPaddingTop(),
viewNodeInfo.getPaddingRight(),
viewNodeInfo.getPaddingBottom());
}
private static void unsetViewPadding(View view, LayoutOutput output, ViewNodeInfo viewNodeInfo) {
if (!viewNodeInfo.hasPadding()) {
return;
}
try {
view.setPadding(0, 0, 0, 0);
} catch (NullPointerException e) {
// T53931759 Gathering extra info around this NPE
ErrorReporter.getInstance()
.report(
LogLevel.ERROR,
"LITHO:NPE:UNSET_PADDING",
"From component: " + output.getComponent().getSimpleName(),
e,
0,
null);
}
}
private static void setViewBackground(View view, ViewNodeInfo viewNodeInfo) {
final Drawable background = viewNodeInfo.getBackground();
if (background != null) {
setBackgroundCompat(view, background);
}
}
private static void unsetViewBackground(View view, ViewNodeInfo viewNodeInfo) {
final Drawable background = viewNodeInfo.getBackground();
if (background != null) {
setBackgroundCompat(view, null);
}
}
@SuppressWarnings("deprecation")
private static void setBackgroundCompat(View view, Drawable drawable) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(drawable);
} else {
view.setBackground(drawable);
}
}
private static void unsetViewForeground(View view, ViewNodeInfo viewNodeInfo) {
final Drawable foreground = viewNodeInfo.getForeground();
if (foreground != null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with foreground however "
+ "the current Android version doesn't support foreground on Views");
}
view.setForeground(null);
}
}
private static void setViewLayoutDirection(View view, ViewNodeInfo viewNodeInfo) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return;
}
final int viewLayoutDirection;
switch (viewNodeInfo.getLayoutDirection()) {
case LTR:
viewLayoutDirection = View.LAYOUT_DIRECTION_LTR;
break;
case RTL:
viewLayoutDirection = View.LAYOUT_DIRECTION_RTL;
break;
default:
viewLayoutDirection = View.LAYOUT_DIRECTION_INHERIT;
}
view.setLayoutDirection(viewLayoutDirection);
}
private static void unsetViewLayoutDirection(View view) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return;
}
view.setLayoutDirection(View.LAYOUT_DIRECTION_INHERIT);
}
private static void setViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) {
StateListAnimator stateListAnimator = viewNodeInfo.getStateListAnimator();
final int stateListAnimatorRes = viewNodeInfo.getStateListAnimatorRes();
if (stateListAnimator == null && stateListAnimatorRes == 0) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with stateListAnimator, "
+ "however the current Android version doesn't support stateListAnimator on Views");
}
if (stateListAnimator == null) {
stateListAnimator =
AnimatorInflater.loadStateListAnimator(view.getContext(), stateListAnimatorRes);
}
view.setStateListAnimator(stateListAnimator);
}
private static void unsetViewStateListAnimator(View view, ViewNodeInfo viewNodeInfo) {
if (viewNodeInfo.getStateListAnimator() == null
&& viewNodeInfo.getStateListAnimatorRes() == 0) {
return;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
throw new IllegalStateException(
"MountState has a ViewNodeInfo with stateListAnimator, "
+ "however the current Android version doesn't support stateListAnimator on Views");
}
view.setStateListAnimator(null);
}
private static void mountItemIncrementally(MountItem item, boolean processVisibilityOutputs) {
if (!isMountableView(item.getRenderTreeNode().getRenderUnit())) {
return;
}
// We can't just use the bounds of the View since we need the bounds relative to the
// hosting LithoView (which is what the localVisibleRect is measured relative to).
final View view = (View) item.getContent();
mountViewIncrementally(view, processVisibilityOutputs);
}
private static void mountViewIncrementally(View view, boolean processVisibilityOutputs) {
assertMainThread();
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("recursivelyNotifyVisibleBoundsChanged");
}
if (view instanceof LithoView) {
final LithoView lithoView = (LithoView) view;
if (lithoView.isIncrementalMountEnabled()) {
if (!processVisibilityOutputs) {
lithoView.notifyVisibleBoundsChanged(
new Rect(0, 0, view.getWidth(), view.getHeight()), false);
} else {
lithoView.notifyVisibleBoundsChanged();
}
}
} else if (view instanceof RenderCoreExtensionHost) {
((RenderCoreExtensionHost) view).notifyVisibleBoundsChanged();
} else if (view instanceof ViewGroup) {
final ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
final View childView = viewGroup.getChildAt(i);
mountViewIncrementally(childView, processVisibilityOutputs);
}
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
private String getMountItemDebugMessage(MountItem item) {
final int index = mIndexToItemMap.indexOfValue(item);
long id = -1;
int layoutOutputIndex = -1;
if (index > -1) {
id = mIndexToItemMap.keyAt(index);
for (int i = 0; i < mLayoutOutputsIds.length; i++) {
if (id == mLayoutOutputsIds[i]) {
layoutOutputIndex = i;
break;
}
}
}
final ComponentTree componentTree = mLithoView.getComponentTree();
final String rootComponent =
componentTree == null ? "<null_component_tree>" : componentTree.getRoot().getSimpleName();
return "rootComponent="
+ rootComponent
+ ", index="
+ layoutOutputIndex
+ ", mapIndex="
+ index
+ ", id="
+ id
+ ", disappearRange=["
+ mLastDisappearRangeStart
+ ","
+ mLastDisappearRangeEnd
+ "], contentType="
+ (item.getContent() != null ? item.getContent().getClass() : "<null_content>")
+ ", component="
+ getLayoutOutput(item).getComponent().getSimpleName()
+ ", host="
+ (item.getHost() != null ? item.getHost().getClass() : "<null_host>")
+ ", isRootHost="
+ (mHostsByMarker.get(ROOT_HOST_ID) == item.getHost());
}
@Override
public void unmountAllItems() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
for (int i = mLayoutOutputsIds.length - 1; i >= 0; i--) {
unmountItem(i, mHostsByMarker);
}
mPreviousLocalVisibleRect.setEmpty();
mNeedsRemount = true;
if (mVisibilityExtension != null) {
mVisibilityExtension.onUnbind(mVisibilityExtensionState);
mVisibilityExtension.onUnmount(mVisibilityExtensionState);
}
if (mTransitionsExtension != null) {
mTransitionsExtension.onUnbind(mTransitionsExtensionState);
mTransitionsExtension.onUnmount(mTransitionsExtensionState);
}
if (mMountDelegate != null) {
mMountDelegate.releaseAllAcquiredReferences();
}
clearLastMountedTree();
}
private void unmountItem(int index, LongSparseArray<ComponentHost> hostsByMarker) {
MountItem item = getItemAt(index);
if (item != null) {
unmountItem(item, hostsByMarker);
}
}
private void unmountItem(@Nullable MountItem item, LongSparseArray<ComponentHost> hostsByMarker) {
final long startTime = System.nanoTime();
// Already has been unmounted.
if (item == null) {
return;
}
final RenderTreeNode node = item.getRenderTreeNode();
final RenderUnit<?> unit = node.getRenderUnit();
final long id = unit.getId();
// The root host item should never be unmounted as it's a reference
// to the top-level LithoView.
if (id == ROOT_HOST_ID) {
mDynamicPropsManager.onUnbindComponent(
getLayoutOutput(node).getComponent(), mRootHostMountItem.getContent());
maybeUnsetViewAttributes(item);
return;
}
mIndexToItemMap.remove(id);
final Object content = item.getContent();
final boolean hasUnmountDelegate =
mUnmountDelegateExtension != null
&& mUnmountDelegateExtension.shouldDelegateUnmount(
mMountDelegate.getUnmountDelegateExtensionState(), item);
// Recursively unmount mounted children items.
// This is the case when mountDiffing is enabled and unmountOrMoveOldItems() has a matching
// sub tree. However, traversing the tree bottom-up, it needs to unmount a node holding that
// sub tree, that will still have mounted items. (Different sequence number on LayoutOutput id)
if ((content instanceof ComponentHost) && !(content instanceof LithoView)) {
final Host host = (Host) content;
for (int i = 0; i < node.getChildrenCount(); i++) {
unmountItem(mIndexToItemMap.get(node.getChildAt(i).getRenderUnit().getId()), hostsByMarker);
}
if (!hasUnmountDelegate && host.getMountItemCount() > 0) {
final LayoutOutput output = getLayoutOutput(item);
final Component component = output.getComponent();
ComponentsReporter.emitMessage(
ComponentsReporter.LogLevel.ERROR,
"UnmountItem:ChildsNotUnmounted",
"Recursively unmounting items from a ComponentHost, left some items behind maybe because not tracked by its MountState"
+ ", component: "
+ component.getSimpleName());
throw new IllegalStateException(
"Recursively unmounting items from a ComponentHost, left"
+ " some items behind maybe because not tracked by its MountState");
}
}
final ComponentHost host = (ComponentHost) item.getHost();
final LayoutOutput output = getLayoutOutput(item);
final Component component = output.getComponent();
if (component.hasChildLithoViews()) {
mCanMountIncrementallyMountItems.delete(id);
}
if (isHostSpec(component)) {
final ComponentHost componentHost = (ComponentHost) content;
hostsByMarker.removeAt(hostsByMarker.indexOfValue(componentHost));
}
if (hasUnmountDelegate) {
mUnmountDelegateExtension.unmount(
mMountDelegate.getUnmountDelegateExtensionState(), item, host);
} else {
/*
* The mounted content might contain other LithoViews which are not reachable from
* this MountState. If that content contains other LithoViews, we need to unmount them as well,
* so that their contents are recycled and reused next time.
*/
if (content instanceof HasLithoViewChildren) {
final ArrayList<LithoView> lithoViews = new ArrayList<>();
((HasLithoViewChildren) content).obtainLithoViewChildren(lithoViews);
for (int i = lithoViews.size() - 1; i >= 0; i--) {
final LithoView lithoView = lithoViews.get(i);
lithoView.unmountAllItems();
}
}
if (mShouldUsePositionInParent) {
final int index = item.getRenderTreeNode().getPositionInParent();
unmount(host, index, content, item, output);
} else {
// Find the index in the layout state to unmount
for (int mountIndex = mLayoutOutputsIds.length - 1; mountIndex >= 0; mountIndex--) {
if (mLayoutOutputsIds[mountIndex] == id) {
unmount(host, mountIndex, content, item, output);
break;
}
}
}
unbindMountItem(item);
}
if (mMountStats.isLoggingEnabled) {
mMountStats.unmountedTimes.add((System.nanoTime() - startTime) / NS_IN_MS);
mMountStats.unmountedNames.add(component.getSimpleName());
mMountStats.unmountedCount++;
}
}
@Override
public void unbindMountItem(MountItem mountItem) {
final LayoutOutput output = getLayoutOutput(mountItem);
unbindAndUnmountLifecycle(mountItem);
applyUnbindBinders(output, mountItem);
try {
getMountData(mountItem)
.releaseMountContent(mContext.getAndroidContext(), mountItem, "unmountItem", this);
} catch (LithoMountData.ReleasingReleasedMountContentException e) {
throw new RuntimeException(e.getMessage() + " " + getMountItemDebugMessage(mountItem));
}
}
private void unbindAndUnmountLifecycle(MountItem item) {
final LayoutOutput layoutOutput = getLayoutOutput(item);
final Component component = layoutOutput.getComponent();
final Object content = item.getContent();
final ComponentContext context = getContextForComponent(item.getRenderTreeNode());
// Call the component's unmount() method.
if (item.isBound()) {
unbindComponentFromContent(item, component, content);
}
maybeUnsetViewAttributes(item);
final LithoLayoutData layoutData = (LithoLayoutData) item.getRenderTreeNode().getLayoutData();
component.unmount(context, content, (InterStagePropsContainer) layoutData.mLayoutData);
}
@Override
public boolean isRootItem(int position) {
final MountItem mountItem = getItemAt(position);
if (mountItem == null) {
return false;
}
return mountItem == mIndexToItemMap.get(ROOT_HOST_ID);
}
@Override
public @Nullable MountItem getRootItem() {
return mIndexToItemMap != null ? mIndexToItemMap.get(ROOT_HOST_ID) : null;
}
@Nullable
MountItem getItemAt(int i) {
assertMainThread();
// TODO simplify when replacing with getContent.
if (mIndexToItemMap == null || mLayoutOutputsIds == null) {
return null;
}
if (i >= mLayoutOutputsIds.length) {
return null;
}
return mIndexToItemMap.get(mLayoutOutputsIds[i]);
}
@Override
public Object getContentAt(int i) {
final MountItem mountItem = getItemAt(i);
if (mountItem == null) {
return null;
}
return mountItem.getContent();
}
@Nullable
@Override
public Object getContentById(long id) {
if (mIndexToItemMap == null) {
return null;
}
final MountItem mountItem = mIndexToItemMap.get(id);
if (mountItem == null) {
return null;
}
return mountItem.getContent();
}
public androidx.collection.LongSparseArray<MountItem> getIndexToItemMap() {
return mIndexToItemMap;
}
public void clearLastMountedTree() {
if (mTransitionsExtension != null) {
mTransitionsExtension.clearLastMountedTreeId(mTransitionsExtensionState);
}
mLastMountedComponentTreeId = ComponentTree.INVALID_ID;
}
private static class PrepareMountStats {
private int unmountedCount = 0;
private int movedCount = 0;
private int unchangedCount = 0;
private PrepareMountStats() {}
private void reset() {
unchangedCount = 0;
movedCount = 0;
unmountedCount = 0;
}
}
private static class MountStats {
private List<String> mountedNames;
private List<String> unmountedNames;
private List<String> updatedNames;
private List<String> visibilityHandlerNames;
private List<String> extras;
private List<Double> mountTimes;
private List<Double> unmountedTimes;
private List<Double> updatedTimes;
private List<Double> visibilityHandlerTimes;
private int mountedCount;
private int unmountedCount;
private int updatedCount;
private int noOpCount;
private double visibilityHandlersTotalTime;
private boolean isLoggingEnabled;
private boolean isInitialized;
private void enableLogging() {
isLoggingEnabled = true;
if (!isInitialized) {
isInitialized = true;
mountedNames = new ArrayList<>();
unmountedNames = new ArrayList<>();
updatedNames = new ArrayList<>();
visibilityHandlerNames = new ArrayList<>();
extras = new ArrayList<>();
mountTimes = new ArrayList<>();
unmountedTimes = new ArrayList<>();
updatedTimes = new ArrayList<>();
visibilityHandlerTimes = new ArrayList<>();
}
}
private void reset() {
mountedCount = 0;
unmountedCount = 0;
updatedCount = 0;
noOpCount = 0;
visibilityHandlersTotalTime = 0;
if (isInitialized) {
mountedNames.clear();
unmountedNames.clear();
updatedNames.clear();
visibilityHandlerNames.clear();
extras.clear();
mountTimes.clear();
unmountedTimes.clear();
updatedTimes.clear();
visibilityHandlerTimes.clear();
}
isLoggingEnabled = false;
}
}
/**
* Unbinds all the MountItems currently mounted on this MountState. Unbinding a MountItem means
* calling unbind on its {@link Component}. The MountItem is not yet unmounted after unbind is
* called and can be re-used in place to re-mount another {@link Component} with the same {@link
* Component}.
*/
void unbind() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("MountState.unbind");
RenderCoreSystrace.beginSection("MountState.unbindAllContent");
}
for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) {
MountItem mountItem = getItemAt(i);
if (mountItem == null || !mountItem.isBound()) {
continue;
}
unbindComponentFromContent(
mountItem, getLayoutOutput(mountItem).getComponent(), mountItem.getContent());
}
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.beginSection("MountState.unbindExtensions");
}
clearVisibilityItems();
if (mVisibilityExtension != null) {
mVisibilityExtension.onUnbind(mVisibilityExtensionState);
}
if (mTransitionsExtension != null) {
mTransitionsExtension.onUnbind(mTransitionsExtensionState);
}
if (isTracing) {
RenderCoreSystrace.endSection();
RenderCoreSystrace.endSection();
}
}
@Override
public void detach() {
assertMainThread();
unbind();
}
@Override
public void attach() {
rebind();
}
/**
* This is called when the {@link MountItem}s mounted on this {@link MountState} need to be
* re-bound with the same component. The common case here is a detach/attach happens on the {@link
* LithoView} that owns the MountState.
*/
void rebind() {
assertMainThread();
if (mLayoutOutputsIds == null) {
return;
}
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("MountState.bind");
}
for (int i = 0, size = mLayoutOutputsIds.length; i < size; i++) {
final MountItem mountItem = getItemAt(i);
if (mountItem == null || mountItem.isBound()) {
continue;
}
final Component component = getLayoutOutput(mountItem).getComponent();
final Object content = mountItem.getContent();
final LithoLayoutData layoutData =
(LithoLayoutData) mountItem.getRenderTreeNode().getLayoutData();
bindComponentToContent(
mountItem, component, getComponentContext(mountItem), layoutData, content);
if (content instanceof View
&& !(content instanceof ComponentHost)
&& ((View) content).isLayoutRequested()) {
final View view = (View) content;
applyBoundsToMountContent(
view, view.getLeft(), view.getTop(), view.getRight(), view.getBottom(), true);
}
}
if (isTracing) {
RenderCoreSystrace.endSection();
}
}
private boolean isAnimationLocked(RenderTreeNode renderTreeNode) {
if (mTransitionsExtension != null) {
if (mTransitionsExtensionState == null) {
throw new IllegalStateException("Need a state when using the TransitionsExtension.");
}
return mTransitionsExtensionState.ownsReference(renderTreeNode.getRenderUnit().getId());
}
return false;
}
/**
* @return true if this method did all the work that was necessary and there is no other content
* that needs mounting/unmounting in this mount step. If false then a full mount step should
* take place.
*/
private boolean performIncrementalMount(
LayoutState layoutState, Rect localVisibleRect, boolean processVisibilityOutputs) {
if (mPreviousLocalVisibleRect.isEmpty()) {
return false;
}
if (localVisibleRect.left != mPreviousLocalVisibleRect.left
|| localVisibleRect.right != mPreviousLocalVisibleRect.right) {
return false;
}
final boolean isTracing = RenderCoreSystrace.isEnabled();
if (isTracing) {
RenderCoreSystrace.beginSection("performIncrementalMount");
}
final ArrayList<IncrementalMountOutput> layoutOutputTops =
layoutState.getOutputsOrderedByTopBounds();
final ArrayList<IncrementalMountOutput> layoutOutputBottoms =
layoutState.getOutputsOrderedByBottomBounds();
final int count = layoutState.getMountableOutputCount();
if (localVisibleRect.top >= 0 || mPreviousLocalVisibleRect.top >= 0) {
// View is going on/off the top of the screen. Check the bottoms to see if there is anything
// that has moved on/off the top of the screen.
while (mPreviousBottomsIndex < count
&& localVisibleRect.top
>= layoutOutputBottoms.get(mPreviousBottomsIndex).getBounds().bottom) {
final RenderTreeNode node =
layoutState.getRenderTreeNode(layoutOutputBottoms.get(mPreviousBottomsIndex));
final long id = node.getRenderUnit().getId();
final int layoutOutputIndex = layoutState.getPositionForId(id);
if (!isAnimationLocked(node)) {
unmountItem(layoutOutputIndex, mHostsByMarker);
}
mPreviousBottomsIndex++;
}
while (mPreviousBottomsIndex > 0
&& localVisibleRect.top
<= layoutOutputBottoms.get(mPreviousBottomsIndex - 1).getBounds().bottom) {
mPreviousBottomsIndex--;
final RenderTreeNode node =
layoutState.getRenderTreeNode(layoutOutputBottoms.get(mPreviousBottomsIndex));
final LayoutOutput layoutOutput = getLayoutOutput(node);
final int layoutOutputIndex = layoutState.getPositionForId(node.getRenderUnit().getId());
if (getItemAt(layoutOutputIndex) == null) {
mountLayoutOutput(
layoutState.getPositionForId(node.getRenderUnit().getId()),
node,
layoutOutput,
layoutState);
mComponentIdsMountedInThisFrame.add(node.getRenderUnit().getId());
}
}
}
final int height = mLithoView.getHeight();
if (localVisibleRect.bottom < height || mPreviousLocalVisibleRect.bottom < height) {
// View is going on/off the bottom of the screen. Check the tops to see if there is anything
// that has changed.
while (mPreviousTopsIndex < count
&& localVisibleRect.bottom >= layoutOutputTops.get(mPreviousTopsIndex).getBounds().top) {
final RenderTreeNode node =
layoutState.getRenderTreeNode(layoutOutputTops.get(mPreviousTopsIndex));
final LayoutOutput layoutOutput = getLayoutOutput(node);
final int layoutOutputIndex = layoutState.getPositionForId(node.getRenderUnit().getId());
if (getItemAt(layoutOutputIndex) == null) {
mountLayoutOutput(
layoutState.getPositionForId(node.getRenderUnit().getId()),
node,
layoutOutput,
layoutState);
mComponentIdsMountedInThisFrame.add(node.getRenderUnit().getId());
}
mPreviousTopsIndex++;
}
while (mPreviousTopsIndex > 0
&& localVisibleRect.bottom
< layoutOutputTops.get(mPreviousTopsIndex - 1).getBounds().top) {
mPreviousTopsIndex--;
final RenderTreeNode node =
layoutState.getRenderTreeNode(layoutOutputTops.get(mPreviousTopsIndex));
final long id = node.getRenderUnit().getId();
final int layoutOutputIndex = layoutState.getPositionForId(id);
if (!isAnimationLocked(node)) {
unmountItem(layoutOutputIndex, mHostsByMarker);
}
}
}
if (!mLithoView.skipNotifyVisibleBoundsChangedCalls()) {
for (int i = 0, size = mCanMountIncrementallyMountItems.size(); i < size; i++) {
final MountItem mountItem = mCanMountIncrementallyMountItems.valueAt(i);
final long layoutOutputId = mCanMountIncrementallyMountItems.keyAt(i);
if (!mComponentIdsMountedInThisFrame.contains(layoutOutputId)) {
final int layoutOutputPosition = layoutState.getPositionForId(layoutOutputId);
if (layoutOutputPosition != -1) {
mountItemIncrementally(mountItem, processVisibilityOutputs);
}
}
}
}
mComponentIdsMountedInThisFrame.clear();
if (isTracing) {
RenderCoreSystrace.endSection();
}
return true;
}
/**
* Collect transitions from layout time, mount time and from state updates.
*
* @param layoutState that is going to be mounted.
*/
void collectAllTransitions(LayoutState layoutState, ComponentTree componentTree) {
assertMainThread();
if (mTransitionsExtension != null) {
TransitionsExtension.collectAllTransitions(mTransitionsExtensionState, layoutState);
return;
}
}
/** @see LithoViewTestHelper#findTestItems(LithoView, String) */
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
Deque<TestItem> findTestItems(String testKey) {
if (mTestItemMap == null) {
throw new UnsupportedOperationException(
"Trying to access TestItems while "
+ "ComponentsConfiguration.isEndToEndTestRun is false.");
}
final Deque<TestItem> items = mTestItemMap.get(testKey);
return items == null ? new LinkedList<TestItem>() : items;
}
/**
* For HostComponents, we don't set a scoped context during layout calculation because we don't
* need one, as we could never call a state update on it. Instead it's okay to use the context
* that is passed to MountState from the LithoView, which is not scoped.
*/
private ComponentContext getContextForComponent(RenderTreeNode node) {
ComponentContext c = getComponentContext(node);
return c == null ? mContext : c;
}
private void bindComponentToContent(
final MountItem mountItem,
final Component component,
final ComponentContext context,
final LithoLayoutData layoutData,
final Object content) {
component.bind(
getContextForComponent(mountItem.getRenderTreeNode()),
content,
(InterStagePropsContainer) layoutData.mLayoutData);
mDynamicPropsManager.onBindComponentToContent(component, context, content);
mountItem.setIsBound(true);
}
private void unbindComponentFromContent(
MountItem mountItem, Component component, Object content) {
mDynamicPropsManager.onUnbindComponent(component, content);
RenderTreeNode node = mountItem.getRenderTreeNode();
component.unbind(
getContextForComponent(node),
content,
LithoLayoutData.getInterStageProps(node.getLayoutData()));
mountItem.setIsBound(false);
}
@VisibleForTesting
DynamicPropsManager getDynamicPropsManager() {
return mDynamicPropsManager;
}
private Object acquireHostComponentContent(Context context, HostComponent component) {
if (ComponentsConfiguration.hostComponentRecyclingByWindowIsEnabled) {
return MountItemsPool.acquireHostMountContent(
context, mLithoView.getWindowToken(), component);
} else if (ComponentsConfiguration.hostComponentRecyclingByMountStateIsEnabled) {
if (mHostMountContentPool != null) {
return mHostMountContentPool.acquire(context, component);
} else {
return component.createMountContent(context);
}
} else if (ComponentsConfiguration.unsafeHostComponentRecyclingIsEnabled) {
return MountItemsPool.acquireMountContent(context, component);
} else {
// Otherwise, recycling is disabled for hosts
return component.createMountContent(context);
}
}
void releaseHostComponentContent(Context context, HostComponent component, Object content) {
if (ComponentsConfiguration.hostComponentRecyclingByWindowIsEnabled) {
MountItemsPool.releaseHostMountContent(
context, mLithoView.getWindowToken(), component, content);
} else if (ComponentsConfiguration.hostComponentRecyclingByMountStateIsEnabled) {
if (mHostMountContentPool == null) {
mHostMountContentPool = (HostMountContentPool) component.createRecyclingPool();
}
mHostMountContentPool.release(content);
} else if (ComponentsConfiguration.unsafeHostComponentRecyclingIsEnabled) {
MountItemsPool.release(context, component, content);
} else {
// Otherwise, recycling is disabled for hosts
}
}
}
| Improves systrace blocks [4/n]
Summary:
Ensure that LMS has a MountState.mount trace, and an extra Mount.mount <ComponentName> trace.
Following diffs could add a similar extra one for RCMS.
In order to do this the diff makes some major refactors to the flow of LMS.
* `performIncrementalMount` is now just the operation. It isn't used as a check to skip the mount loop.
* the check is pulled into a block of code which initialises a boolean, which is then used to branch the code.
* this new boolean is then also used to figure out which block should be traced.
Differential Revision: D34479349
fbshipit-source-id: b24a16f41f98b31dd8ae8617efe8f32b3bc86a26
| litho-core/src/main/java/com/facebook/litho/MountState.java | Improves systrace blocks [4/n] | <ide><path>itho-core/src/main/java/com/facebook/litho/MountState.java
<ide> throw new IllegalStateException("Trying to mount a null layoutState");
<ide> }
<ide>
<add> final boolean shouldIncrementallyMount =
<add> isIncrementalMountEnabled
<add> && localVisibleRect != null
<add> && !mPreviousLocalVisibleRect.isEmpty()
<add> && localVisibleRect.left == mPreviousLocalVisibleRect.left
<add> && localVisibleRect.right == mPreviousLocalVisibleRect.right;
<add>
<ide> if (mVisibilityExtension != null && mIsDirty) {
<ide> mVisibilityExtension.beforeMount(mVisibilityExtensionState, layoutState, localVisibleRect);
<ide> }
<ide>
<ide> final boolean isTracing = RenderCoreSystrace.isEnabled();
<ide> if (isTracing) {
<del> String sectionName =
<del> mIsDirty
<del> ? (isIncrementalMountEnabled ? "incrementalMountDirty" : "mountDirty")
<del> : (isIncrementalMountEnabled ? "incrementalMount" : "mount");
<del> ComponentsSystrace.beginSectionWithArgs(sectionName)
<add>
<add> if (mIsDirty && !shouldIncrementallyMount) {
<add> // Equivalent to RCMS MountState.mount
<add> RenderCoreSystrace.beginSection("MountState.mount");
<add> } else {
<add> // Trace special to LMS
<add> RenderCoreSystrace.beginSection(
<add> "LMS."
<add> + (shouldIncrementallyMount ? "incrementalMount" : "mount")
<add> + (mIsDirty ? "Dirty" : ""));
<add> }
<add>
<add> ComponentsSystrace.beginSectionWithArgs("MountState.mount: " + componentTree.getSimpleName())
<ide> .arg("treeId", layoutState.getComponentTreeId())
<ide> .arg("component", componentTree.getSimpleName())
<ide> .arg("logTag", componentTree.getContext().getLogTag())
<ide> .flush();
<del> // We also would like to trace this section attributed with component name
<del> // for component share analysis.
<del> RenderCoreSystrace.beginSection(sectionName + "_" + componentTree.getSimpleName());
<ide> }
<ide>
<ide> final ComponentsLogger logger = componentTree.getContext().getLogger();
<ide> mMountStats.enableLogging();
<ide> }
<ide>
<del> if (!isIncrementalMountEnabled
<del> || !performIncrementalMount(layoutState, localVisibleRect, processVisibilityOutputs)) {
<add> if (shouldIncrementallyMount) {
<add> performIncrementalMount(layoutState, localVisibleRect, processVisibilityOutputs);
<add> } else {
<add>
<ide> final MountItem rootMountItem = mIndexToItemMap.get(ROOT_HOST_ID);
<del>
<ide> final Rect absoluteBounds = new Rect();
<ide>
<ide> for (int i = 0, size = layoutState.getMountableOutputCount(); i < size; i++) {
<ide> * that needs mounting/unmounting in this mount step. If false then a full mount step should
<ide> * take place.
<ide> */
<del> private boolean performIncrementalMount(
<add> private void performIncrementalMount(
<ide> LayoutState layoutState, Rect localVisibleRect, boolean processVisibilityOutputs) {
<del> if (mPreviousLocalVisibleRect.isEmpty()) {
<del> return false;
<del> }
<del>
<del> if (localVisibleRect.left != mPreviousLocalVisibleRect.left
<del> || localVisibleRect.right != mPreviousLocalVisibleRect.right) {
<del> return false;
<del> }
<ide>
<ide> final boolean isTracing = RenderCoreSystrace.isEnabled();
<ide>
<ide> if (isTracing) {
<ide> RenderCoreSystrace.endSection();
<ide> }
<del>
<del> return true;
<ide> }
<ide> /**
<ide> * Collect transitions from layout time, mount time and from state updates. |
|
JavaScript | mit | 47da26e3500c321b17d320fc115288eb7a731952 | 0 | Fiware/webui.Xml3d.js,xml3d/xml3d.js,CCLDESTY/xml3d.js,ariyapour/xml3d.js,CCLDESTY/xml3d.js,ariyapour/xml3d.js,xml3d/xml3d.js,Fiware/webui.Xml3d.js | // dom.js
(function($) {
if ($)
return;
var doc = {};
var nativeGetElementById = document.getElementById;
doc.getElementById = function(id) {
var elem = nativeGetElementById.call(this, id);
if (elem) {
return elem;
} else {
var elems = this.getElementsByTagName("*");
for ( var i = 0; i < elems.length; i++) {
var node = elems[i];
if (node.getAttribute("id") === id) {
return node;
}
}
}
return null;
};
var nativeCreateElementNS = document.createElementNS;
doc.createElementNS = function(ns, name) {
var r = nativeCreateElementNS.call(this, ns, name);
if (ns == XML3D.xml3dNS || XML3D.classInfo[name.toLowerCase()]) {
XML3D.config.element(r, true);
}
return r;
};
var nativeCreateElement = document.createElement;
doc.createElement = function(name) {
var r = nativeCreateElement.call(this, name);
if (XML3D.classInfo[name.toLowerCase()] ) {
XML3D.config.element(r, true);
}
return r;
};
XML3D.extend(window.document, doc);
}(XML3D._native));
/*
* Workaround for DOMAttrModified issues in WebKit based browsers:
* https://bugs.webkit.org/show_bug.cgi?id=8191
*/
var MutationObserver = (window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver);
if (!MutationObserver && navigator.userAgent.indexOf("WebKit") != -1) {
var attrModifiedWorks = false;
var listener = function() {
attrModifiedWorks = true;
};
document.documentElement.addEventListener("DOMAttrModified", listener, false);
document.documentElement.setAttribute("___TEST___", true);
document.documentElement.removeAttribute("___TEST___");
document.documentElement.removeEventListener("DOMAttrModified", listener, false);
if (!attrModifiedWorks) {
Element.prototype.__setAttribute = HTMLElement.prototype.setAttribute;
Element.prototype.setAttribute = function(attrName, newVal) {
var prevVal = this.getAttribute(attrName);
this.__setAttribute(attrName, newVal);
newVal = this.getAttribute(attrName);
// if (newVal != prevVal)
{
var evt = document.createEvent("MutationEvent");
evt.initMutationEvent("DOMAttrModified", true, false, this, prevVal || "", newVal || "", attrName, (prevVal == null) ? MutationEvent.ADDITION
: MutationEvent.MODIFICATION);
this.dispatchEvent(evt);
}
};
Element.prototype.__removeAttribute = HTMLElement.prototype.removeAttribute;
Element.prototype.removeAttribute = function(attrName) {
var prevVal = this.getAttribute(attrName);
this.__removeAttribute(attrName);
var evt = document.createEvent("MutationEvent");
evt.initMutationEvent("DOMAttrModified", true, false, this, prevVal, "", attrName, MutationEvent.REMOVAL);
this.dispatchEvent(evt);
};
}
}
| src/interface/dom.js | // dom.js
(function($) {
if ($)
return;
var doc = {};
var nativeGetElementById = document.getElementById;
doc.getElementById = function(id) {
var elem = nativeGetElementById.call(this, id);
if (elem) {
return elem;
} else {
var elems = this.getElementsByTagName("*");
for ( var i = 0; i < elems.length; i++) {
var node = elems[i];
if (node.getAttribute("id") === id) {
return node;
}
}
}
return null;
};
var nativeCreateElementNS = document.createElementNS;
doc.createElementNS = function(ns, name) {
var r = nativeCreateElementNS.call(this, ns, name);
if (ns == XML3D.xml3dNS || XML3D.classInfo[name.toLowerCase()]) {
XML3D.config.element(r, true);
}
return r;
};
var nativeCreateElement = document.createElement;
doc.createElement = function(name) {
var r = nativeCreateElement.call(this, name);
if (XML3D.classInfo[name.toLowerCase()] ) {
XML3D.config.element(r, true);
}
return r;
};
XML3D.extend(window.document, doc);
}(XML3D._native));
/*
* Workaround for DOMAttrModified issues in WebKit based browsers:
* https://bugs.webkit.org/show_bug.cgi?id=8191
*/
if (navigator.userAgent.indexOf("WebKit") != -1) {
var attrModifiedWorks = false;
var listener = function() {
attrModifiedWorks = true;
};
document.documentElement.addEventListener("DOMAttrModified", listener, false);
document.documentElement.setAttribute("___TEST___", true);
document.documentElement.removeAttribute("___TEST___");
document.documentElement.removeEventListener("DOMAttrModified", listener, false);
if (!attrModifiedWorks) {
Element.prototype.__setAttribute = HTMLElement.prototype.setAttribute;
Element.prototype.setAttribute = function(attrName, newVal) {
var prevVal = this.getAttribute(attrName);
this.__setAttribute(attrName, newVal);
newVal = this.getAttribute(attrName);
// if (newVal != prevVal)
{
var evt = document.createEvent("MutationEvent");
evt.initMutationEvent("DOMAttrModified", true, false, this, prevVal || "", newVal || "", attrName, (prevVal == null) ? MutationEvent.ADDITION
: MutationEvent.MODIFICATION);
this.dispatchEvent(evt);
}
};
Element.prototype.__removeAttribute = HTMLElement.prototype.removeAttribute;
Element.prototype.removeAttribute = function(attrName) {
var prevVal = this.getAttribute(attrName);
this.__removeAttribute(attrName);
var evt = document.createEvent("MutationEvent");
evt.initMutationEvent("DOMAttrModified", true, false, this, prevVal, "", attrName, MutationEvent.REMOVAL);
this.dispatchEvent(evt);
};
}
}
| Add DOMAttrModified polyfill only if no MutationObserver is available.
| src/interface/dom.js | Add DOMAttrModified polyfill only if no MutationObserver is available. | <ide><path>rc/interface/dom.js
<ide> * Workaround for DOMAttrModified issues in WebKit based browsers:
<ide> * https://bugs.webkit.org/show_bug.cgi?id=8191
<ide> */
<del>if (navigator.userAgent.indexOf("WebKit") != -1) {
<add>var MutationObserver = (window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver);
<add>
<add>if (!MutationObserver && navigator.userAgent.indexOf("WebKit") != -1) {
<ide> var attrModifiedWorks = false;
<ide> var listener = function() {
<ide> attrModifiedWorks = true; |
|
Java | apache-2.0 | ccbbf277f305fdc1e33d98a7080994b4aa53abd9 | 0 | ResearchWorx/Cresco-Agent-Controller-Plugin | package ActiveMQ;
import java.util.Map;
import java.util.Timer;
import java.util.Map.Entry;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import plugincore.PluginEngine;
import shared.MsgEvent;
public class ActiveProducer
{
public Map<String,ActiveProducerWorker> producerWorkers;
private String URI;
private Timer timer;
class ClearProducerTask extends TimerTask
{
public void run()
{
for (Entry<String, ActiveProducerWorker> entry : producerWorkers.entrySet())
{
//System.out.println("Cleanup: " + entry.getKey() + "/" + entry.getValue());
ActiveProducerWorker apw = entry.getValue();
if(apw.isActive)
{
//System.out.println("Marking ActiveProducerWork [" + entry.getKey() + "] inactive");
apw.isActive = false;
producerWorkers.put(entry.getKey(),apw);
}
else
{
System.out.println("Shutting Down/Removing ActiveProducerWork [" + entry.getKey() + "]");
if(apw.shutdown())
{
producerWorkers.remove(entry.getKey());
}
}
}
}
}
public ActiveProducer(String URI)
{
try
{
producerWorkers = new ConcurrentHashMap<String,ActiveProducerWorker>();
this.URI = URI;
timer = new Timer();
timer.scheduleAtFixedRate(new ClearProducerTask(), 5000, 5000);//start at 5000 end at 5000
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("ActiveProducer Init " + ex.toString());
}
}
public boolean sendMessage(MsgEvent sm)
{
boolean isSent = false;
try
{
ActiveProducerWorker apw = null;
String agentPath = sm.getMsgRegion() + "_" + sm.getMsgAgent();
String dstPath = sm.getParam("dst_region") + "_" + sm.getParam("dst_agent");
if(producerWorkers.containsKey(dstPath))
{
if(PluginEngine.isReachableAgent(dstPath))
{
apw = producerWorkers.get(dstPath);
}
else
{
System.out.println(dstPath + " is unreachable...");
}
}
else
{
if (PluginEngine.isReachableAgent(dstPath))
{
System.out.println("Creating new ActiveProducerWorker [" + dstPath + "]");
apw = new ActiveProducerWorker(dstPath, URI);
producerWorkers.put(dstPath, apw);
}
else
{
System.out.println(dstPath + " is unreachable...");
}
}
if(apw != null)
{
apw.isActive = true;
apw.sendMessage(sm);
isSent = true;
}
else
{
System.out.println("apw is null");
}
}
catch(Exception ex)
{
System.out.println("ActiveProducer : sendMessage Error " + ex.toString());
}
return isSent;
}
} | src/main/java/ActiveMQ/ActiveProducer.java | package ActiveMQ;
import java.util.Map;
import java.util.Timer;
import java.util.Map.Entry;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import plugincore.PluginEngine;
import shared.MsgEvent;
public class ActiveProducer
{
public Map<String,ActiveProducerWorker> producerWorkers;
private String URI;
private Timer timer;
class ClearProducerTask extends TimerTask
{
public void run()
{
for (Entry<String, ActiveProducerWorker> entry : producerWorkers.entrySet())
{
//System.out.println("Cleanup: " + entry.getKey() + "/" + entry.getValue());
ActiveProducerWorker apw = entry.getValue();
if(apw.isActive)
{
//System.out.println("Marking ActiveProducerWork [" + entry.getKey() + "] inactive");
apw.isActive = false;
producerWorkers.put(entry.getKey(),apw);
}
else
{
System.out.println("Shutting Down/Removing ActiveProducerWork [" + entry.getKey() + "]");
if(apw.shutdown())
{
producerWorkers.remove(entry.getKey());
}
}
}
}
}
public ActiveProducer(String URI)
{
try
{
producerWorkers = new ConcurrentHashMap<String,ActiveProducerWorker>();
this.URI = URI;
timer = new Timer();
timer.scheduleAtFixedRate(new ClearProducerTask(), 5000, 5000);//start at 5000 end at 5000
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("ActiveProducer Init " + ex.toString());
}
}
public boolean sendMessage(MsgEvent sm)
{
boolean isSent = false;
try
{
ActiveProducerWorker apw = null;
String agentPath = sm.getMsgRegion() + "_" + sm.getMsgAgent();
String dstPath = sm.getParam("dst_region") + "_" + sm.getParam("dst_agent");
if(producerWorkers.containsKey(agentPath))
{
if(PluginEngine.isReachableAgent(agentPath))
{
apw = producerWorkers.get(agentPath);
}
else
{
System.out.println(agentPath + " is unreachable...");
}
}
else
{
if (PluginEngine.isReachableAgent(agentPath))
{
System.out.println("Creating new ActiveProducerWorker [" + agentPath + "]");
apw = new ActiveProducerWorker(agentPath, URI);
producerWorkers.put(agentPath, apw);
}
else
{
System.out.println(agentPath + " is unreachable...");
}
}
if(apw != null)
{
apw.isActive = true;
apw.sendMessage(sm);
isSent = true;
}
else
{
System.out.println("apw is null");
}
}
catch(Exception ex)
{
System.out.println("ActiveProducer : sendMessage Error " + ex.toString());
}
return isSent;
}
} | Looking into BrokerMonitor
| src/main/java/ActiveMQ/ActiveProducer.java | Looking into BrokerMonitor | <ide><path>rc/main/java/ActiveMQ/ActiveProducer.java
<ide> ActiveProducerWorker apw = null;
<ide> String agentPath = sm.getMsgRegion() + "_" + sm.getMsgAgent();
<ide> String dstPath = sm.getParam("dst_region") + "_" + sm.getParam("dst_agent");
<del> if(producerWorkers.containsKey(agentPath))
<add> if(producerWorkers.containsKey(dstPath))
<ide> {
<del> if(PluginEngine.isReachableAgent(agentPath))
<add> if(PluginEngine.isReachableAgent(dstPath))
<ide> {
<del> apw = producerWorkers.get(agentPath);
<add> apw = producerWorkers.get(dstPath);
<ide> }
<ide> else
<ide> {
<del> System.out.println(agentPath + " is unreachable...");
<add> System.out.println(dstPath + " is unreachable...");
<ide> }
<ide> }
<ide> else
<ide> {
<del> if (PluginEngine.isReachableAgent(agentPath))
<add> if (PluginEngine.isReachableAgent(dstPath))
<ide> {
<del> System.out.println("Creating new ActiveProducerWorker [" + agentPath + "]");
<del> apw = new ActiveProducerWorker(agentPath, URI);
<del> producerWorkers.put(agentPath, apw);
<add> System.out.println("Creating new ActiveProducerWorker [" + dstPath + "]");
<add> apw = new ActiveProducerWorker(dstPath, URI);
<add> producerWorkers.put(dstPath, apw);
<ide> }
<ide> else
<ide> {
<del> System.out.println(agentPath + " is unreachable...");
<add> System.out.println(dstPath + " is unreachable...");
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | error: pathspec 'main/src/courtscheduler/solver/move/TeamChangeMoveFactory.java' did not match any file(s) known to git
| e75beb8e4dfb2d629e984786ac100ef3bbcca8d9 | 1 | netinept/Court-Scheduler,netinept/Court-Scheduler,netinept/Court-Scheduler | /*
* Copyright 2010 JBoss 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 courtscheduler.solver.move;
import java.util.ArrayList;
import java.util.List;
import courtscheduler.domain.CourtSchedule;
import courtscheduler.domain.MatchAssignment;
import org.optaplanner.core.impl.heuristic.selector.move.factory.MoveListFactory;
import org.optaplanner.core.impl.move.Move;
import org.optaplanner.core.impl.solution.Solution;
import org.optaplanner.examples.nurserostering.domain.Employee;
import org.optaplanner.examples.nurserostering.domain.NurseRoster;
import org.optaplanner.examples.nurserostering.domain.ShiftAssignment;
import org.optaplanner.examples.nurserostering.domain.solver.MovableShiftAssignmentSelectionFilter;
import org.optaplanner.examples.nurserostering.solver.move.EmployeeChangeMove;
public class TeamChangeMoveFactory implements MoveListFactory {
private MovableShiftAssignmentSelectionFilter filter = new MovableShiftAssignmentSelectionFilter();
public List<Move> createMoveList(Solution solution) {
MatchAssignment courtSchedule = (MatchAssignment) solution;
List<Move> moveList = new ArrayList<Move>();
List<Employee> teamList = CourtSchedule.setTeamList();
for (MatchAssignment matchAssignment : CourtSchedule.getMatchAssignments()) {
if (filter.accept(courtSchedule, matchAssignment)) {
for (Employee team : teamList) {
moveList.add(new EmployeeChangeMove(matchAssignment, team));
}
}
}
return moveList;
}
}
| main/src/courtscheduler/solver/move/TeamChangeMoveFactory.java | #1129968 - Will - working on moveFactory
| main/src/courtscheduler/solver/move/TeamChangeMoveFactory.java | #1129968 - Will - working on moveFactory | <ide><path>ain/src/courtscheduler/solver/move/TeamChangeMoveFactory.java
<add>/*
<add> * Copyright 2010 JBoss Inc
<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>
<add>package courtscheduler.solver.move;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>import courtscheduler.domain.CourtSchedule;
<add>import courtscheduler.domain.MatchAssignment;
<add>import org.optaplanner.core.impl.heuristic.selector.move.factory.MoveListFactory;
<add>import org.optaplanner.core.impl.move.Move;
<add>import org.optaplanner.core.impl.solution.Solution;
<add>import org.optaplanner.examples.nurserostering.domain.Employee;
<add>import org.optaplanner.examples.nurserostering.domain.NurseRoster;
<add>import org.optaplanner.examples.nurserostering.domain.ShiftAssignment;
<add>import org.optaplanner.examples.nurserostering.domain.solver.MovableShiftAssignmentSelectionFilter;
<add>import org.optaplanner.examples.nurserostering.solver.move.EmployeeChangeMove;
<add>
<add>public class TeamChangeMoveFactory implements MoveListFactory {
<add>
<add> private MovableShiftAssignmentSelectionFilter filter = new MovableShiftAssignmentSelectionFilter();
<add>
<add> public List<Move> createMoveList(Solution solution) {
<add> MatchAssignment courtSchedule = (MatchAssignment) solution;
<add> List<Move> moveList = new ArrayList<Move>();
<add> List<Employee> teamList = CourtSchedule.setTeamList();
<add> for (MatchAssignment matchAssignment : CourtSchedule.getMatchAssignments()) {
<add> if (filter.accept(courtSchedule, matchAssignment)) {
<add> for (Employee team : teamList) {
<add> moveList.add(new EmployeeChangeMove(matchAssignment, team));
<add> }
<add> }
<add> }
<add> return moveList;
<add> }
<add>
<add>} |
|
Java | mit | c56e973f7fdd2211ef98b14ee1f78eb227145765 | 0 | sdsmdg/Cognizance | package in.co.sdslabs.cognizance;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.PointF;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/in.co.sdslabs.cognizance/databases/";
private static String DB_NAME = "cognizance14.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
private DatabaseHelper ourHelper;
// fields for table 1
public static final String KEY_ROWID_VENUE = "_id_venue";
public static final String KEY_MINX = "_minX";
public static final String KEY_MINY = "_minY";
public static final String KEY_MAXX = "_maxX";
public static final String KEY_MAXY = "_maxY";
public static final String KEY_TOUCH_VENUE = "_touch_venue";
public static final String DATABASE_TABLE1 = "table_venue";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist)
return;
else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
public DatabaseHelper getInstance(Context context) {
if (ourHelper == null) {
ourHelper = new DatabaseHelper(context);
}
return this;
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null)
checkDB.close();
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public ArrayList<String> getCategory() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM table_category_details",
null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("category")));
}
}
cursor.close();
return data;
}
public String getCategoryDescription(String category_name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_category_details WHERE category='"
+ category_name + "'", null);
String data = null;
if (cursor != null) {
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("category_description"));
cursor.close();
return data;
}
public ArrayList<String> getEventName(String category_name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE category='"
+ category_name + "'", null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("event_name")));
}
}
cursor.close();
return data;
}
public ArrayList<String> getEventoneLiner(String category_name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE category='"
+ category_name + "'", null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("one_liner")));
}
}
cursor.close();
return data;
}
public String getEventDescription(String eventname) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='"
+ eventname + "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext()) {
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("description"));
}
cursor.close();
return data;
}
public ArrayList<String> getEventNamex(int day) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE day= '" + day + "'",
null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("event_name")));
}
}
cursor.close();
return data;
}
public ArrayList<String> getEventoneLinerx(int day) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE day= '" + day + "'",
null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("one_liner")));
}
}
cursor.close();
return data;
}
public String getEventDescriptionx(String eventname, int day) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='"
+ eventname + "'AND day= '" + day + "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext()) {
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("description"));
}
cursor.close();
return data;
}
public String searchEntryForVenue(String x, String y) throws SQLException {
// TODO Auto-generated method stub
myDataBase = this.getReadableDatabase();
String[] columns = new String[] { KEY_ROWID_VENUE, KEY_MINX, KEY_MINY,
KEY_MAXX, KEY_MAXY, KEY_TOUCH_VENUE };
int ix = Integer.parseInt(x) * 2;
int iy = Integer.parseInt(y) * 2;
Cursor c = myDataBase.query(DATABASE_TABLE1, columns, KEY_MINX + "<="
+ ix + " AND " + KEY_MINY + "<=" + iy + " AND " + KEY_MAXX
+ ">=" + ix + " AND " + KEY_MAXY + ">=" + iy, null, null, null,
null);
try {
if (c != null) {
c.moveToFirst();
String venue = c.getString(5);
c.close();
return venue;
}
} catch (CursorIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
c.close();
return null;
}
return null;
}
public PointF searchPlaceForCoordinates(String selection) {
// TODO Auto-generated method stub
myDataBase = this.getReadableDatabase();
String[] columns = new String[] { KEY_MINX, KEY_MINY, KEY_MAXX,
KEY_MAXY, KEY_TOUCH_VENUE };
PointF coor = new PointF();
Cursor c = myDataBase.query(DATABASE_TABLE1, columns, KEY_TOUCH_VENUE
+ "==\"" + selection + "\"", null, null, null, null);
int iMinX = c.getColumnIndex(KEY_MINX);
int iMinY = c.getColumnIndex(KEY_MINY);
int iMaxX = c.getColumnIndex(KEY_MAXX);
int iMaxY = c.getColumnIndex(KEY_MAXY);
try {
if (c != null) {
c.moveToFirst();
coor.x = (Integer.parseInt(c.getString(iMinX)) + Integer
.parseInt(c.getString(iMaxX))) / 4;
coor.y = (Integer.parseInt(c.getString(iMinY)) + Integer
.parseInt(c.getString(iMaxY))) / 4;
c.close();
}
} catch (CursorIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return coor;
}
public String getVenue(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("venue_display"));
cursor.close();
return data;
}
public int getID(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
String category;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
category = cursor.getString(cursor.getColumnIndex("category"));
cursor.close();
cursor = db.rawQuery(
"SELECT * FROM table_category_details WHERE category= '"
+ category + "'", null);
int id;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
id = cursor.getInt(cursor.getColumnIndex("category"));
cursor.close();
return (id - 1);
}
public ArrayList<String> getcontactsname() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor.getColumnIndexOrThrow("name")));
}
// if(cursor.moveToNext()) cursor.moveToFirst();
}
cursor.close();
return list;
}
public ArrayList<String> getcontactsnumber() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor.getColumnIndexOrThrow("number")));
}
cursor.close();
}
return list;
}
public ArrayList<String> getcontactspost() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor.getColumnIndexOrThrow("position")));
}
// if(cursor.moveToNext()) cursor.moveToFirst();
}
cursor.close();
return list;
}
public ArrayList<String> getcontactsemail() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor.getColumnIndexOrThrow("email_id")));
}
cursor.close();
}
return list;
}
}
| Cognizance/src/in/co/sdslabs/cognizance/DatabaseHelper.java | package in.co.sdslabs.cognizance;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.PointF;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/in.co.sdslabs.cognizance/databases/";
private static String DB_NAME = "cognizance14.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
private DatabaseHelper ourHelper;
// fields for table 1
public static final String KEY_ROWID_VENUE = "_id_venue";
public static final String KEY_MINX = "_minX";
public static final String KEY_MINY = "_minY";
public static final String KEY_MAXX = "_maxX";
public static final String KEY_MAXY = "_maxY";
public static final String KEY_TOUCH_VENUE = "_touch_venue";
public static final String DATABASE_TABLE1 = "table_venue";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist)
return;
else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
public DatabaseHelper getInstance(Context context) {
if (ourHelper == null) {
ourHelper = new DatabaseHelper(context);
}
return this;
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null)
checkDB.close();
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public ArrayList<String> getCategory() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM table_category_details",
null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("category")));
}
}
cursor.close();
return data;
}
public String getCategoryDescription(String category_name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_category_details WHERE category='"
+ category_name + "'", null);
String data = null;
if (cursor != null) {
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("category_description"));
cursor.close();
return data;
}
public ArrayList<String> getEventName(String category_name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE category='"
+ category_name + "'", null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("event_name")));
}
}
cursor.close();
return data;
}
public ArrayList<String> getEventoneLiner(String category_name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE category='"
+ category_name + "'", null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("one_liner")));
}
}
cursor.close();
return data;
}
public String getEventDescription(String eventname) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='"
+ eventname + "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext()) {
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("description"));
}
cursor.close();
return data;
}
public ArrayList<String> getEventNamex(int day) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE day= '" + day + "'",
null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("event_name")));
}
}
cursor.close();
return data;
}
public ArrayList<String> getEventoneLinerx(int day) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE day= '" + day + "'",
null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("one_liner")));
}
}
cursor.close();
return data;
}
public String getEventDescriptionx(String eventname, int day) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='"
+ eventname + "'AND day= '" + day + "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext()) {
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("description"));
}
cursor.close();
return data;
}
public String searchEntryForVenue(String x, String y) throws SQLException {
// TODO Auto-generated method stub
myDataBase = ourHelper.getWritableDatabase();
String[] columns = new String[] { KEY_ROWID_VENUE, KEY_MINX, KEY_MINY,
KEY_MAXX, KEY_MAXY, KEY_TOUCH_VENUE };
int ix = Integer.parseInt(x) * 2;
int iy = Integer.parseInt(y) * 2;
Cursor c = myDataBase.query(DATABASE_TABLE1, columns, KEY_MINX + "<="
+ ix + " AND " + KEY_MINY + "<=" + iy + " AND " + KEY_MAXX
+ ">=" + ix + " AND " + KEY_MAXY + ">=" + iy, null, null, null,
null);
try {
if (c != null) {
c.moveToFirst();
String venue = c.getString(5);
c.close();
return venue;
}
} catch (CursorIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
c.close();
return null;
}
return null;
}
public PointF searchPlaceForCoordinates(String selection) {
// TODO Auto-generated method stub
myDataBase = ourHelper.getWritableDatabase();
String[] columns = new String[] { KEY_MINX, KEY_MINY, KEY_MAXX,
KEY_MAXY, KEY_TOUCH_VENUE };
PointF coor = new PointF();
Cursor c = myDataBase.query(DATABASE_TABLE1, columns, KEY_TOUCH_VENUE
+ "==\"" + selection + "\"", null, null, null, null);
int iMinX = c.getColumnIndex(KEY_MINX);
int iMinY = c.getColumnIndex(KEY_MINY);
int iMaxX = c.getColumnIndex(KEY_MAXX);
int iMaxY = c.getColumnIndex(KEY_MAXY);
try {
if (c != null) {
c.moveToFirst();
coor.x = (Integer.parseInt(c.getString(iMinX)) + Integer
.parseInt(c.getString(iMaxX))) / 4;
coor.y = (Integer.parseInt(c.getString(iMinY)) + Integer
.parseInt(c.getString(iMaxY))) / 4;
c.close();
}
} catch (CursorIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return coor;
}
public String getVenue(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("venue_display"));
cursor.close();
return data;
}
public int getID(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
String category;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
category = cursor.getString(cursor.getColumnIndex("category"));
cursor.close();
cursor = db.rawQuery(
"SELECT * FROM table_category_details WHERE category= '"
+ category + "'", null);
int id;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
id = cursor.getInt(cursor.getColumnIndex("category"));
cursor.close();
return (id - 1);
}
public ArrayList<String> getcontactsname() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor.getColumnIndexOrThrow("name")));
}
// if(cursor.moveToNext()) cursor.moveToFirst();
}
cursor.close();
return list;
}
public ArrayList<String> getcontactsnumber() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor.getColumnIndexOrThrow("number")));
}
cursor.close();
}
return list;
}
public ArrayList<String> getcontactspost() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor.getColumnIndexOrThrow("position")));
}
// if(cursor.moveToNext()) cursor.moveToFirst();
}
cursor.close();
return list;
}
public ArrayList<String> getcontactsemail() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor.getColumnIndexOrThrow("email_id")));
}
cursor.close();
}
return list;
}
}
| Fix map functions
| Cognizance/src/in/co/sdslabs/cognizance/DatabaseHelper.java | Fix map functions | <ide><path>ognizance/src/in/co/sdslabs/cognizance/DatabaseHelper.java
<ide>
<ide> public String searchEntryForVenue(String x, String y) throws SQLException {
<ide> // TODO Auto-generated method stub
<del> myDataBase = ourHelper.getWritableDatabase();
<add> myDataBase = this.getReadableDatabase();
<ide> String[] columns = new String[] { KEY_ROWID_VENUE, KEY_MINX, KEY_MINY,
<ide> KEY_MAXX, KEY_MAXY, KEY_TOUCH_VENUE };
<ide>
<ide>
<ide> public PointF searchPlaceForCoordinates(String selection) {
<ide> // TODO Auto-generated method stub
<del> myDataBase = ourHelper.getWritableDatabase();
<add> myDataBase = this.getReadableDatabase();
<ide> String[] columns = new String[] { KEY_MINX, KEY_MINY, KEY_MAXX,
<ide> KEY_MAXY, KEY_TOUCH_VENUE };
<ide> PointF coor = new PointF(); |
|
Java | mit | 7a34e590371e66eed4291b1bef7b89732384aebf | 0 | slemonide/sasuga,slemonide/JLife | package model;
import model.landscape.LandscapeCell;
import model.landscape.LandscapeCellX;
import model.landscape.LandscapeCellZ;
import model.wireworld.Conductor;
import model.wireworld.ElectronHead;
import model.wireworld.ElectronTail;
import java.util.Collection;
import java.util.Random;
/**
*
* @author Danil Platonov <[email protected]>, jacketsj <[email protected]>
* @version 0.1
* @since 0.1
*
* A player is a cell with health, strength, agility, hunger (in percents)
* and a 10-item inventory of cells (or nulls)
*
* invariant
* 0 <= health, strength, agility, hunger <= 100
* inventory.length == INVENTORY_SIZE
* hungerDelay >= 0
* selectedInventorySlot < inventory.length
* 0 <= rotation <= 2 * Math.PI
*/
public class Player extends ActiveCell {
private static final int MIN_HUNGER_DELAY = World.TICKS_PER_SECOND; // in ticks
private static final int STRENGTH_REDUCTION_THRESHOLD = 30;
private static final int AGILITY_REDUCTION_THRESHOLD = 20;
private static final int HEALTH_REDUCTION_THRESHOLD = 5;
private static final float ROTATION_SPEED = 0.01f;
public static final int INVENTORY_SIZE = 10;
private static Player instance;
private int health;
private int strength;
private int agility;
private int hunger;
private Inventory inventory;
private int hungerDelay;
private float rotation;
private Position selectedBlock;
private Position selectedBlockFace;
/**
* Create a cell at the given position with randomly chosen stats
*
* @param position position of this cell
*/
private Player(Position position) {
super(position);
setName("Player");
selectedBlock = position;
selectedBlockFace = position;
Random random = new Random();
rotation = 0;
health = 10 + random.nextInt(91);
strength = 20 + random.nextInt(81);
agility = 30 + random.nextInt(71);
hunger = 40 + random.nextInt(61);
inventory = new Inventory(INVENTORY_SIZE);
inventory.setInventoryItem(1, new InventoryItem("Say Hi",
() -> System.out.println("Hi")));
inventory.setInventoryItem(2, new InventoryItem("Cell",
() -> World.getInstance().add(new Cell(getSelectedBlockFace()))));
inventory.setInventoryItem(3, new InventoryItem("Random Walk",
() -> World.getInstance().add(new RandomWalkCell(getSelectedBlockFace()))));
inventory.setInventoryItem(4, new InventoryItem("Landscape",
() -> World.getInstance().add(new LandscapeCell(getSelectedBlockFace()))));
inventory.setInventoryItem(5, new InventoryItem("Landscape X",
() -> World.getInstance().add(new LandscapeCellX(getSelectedBlockFace()))));
inventory.setInventoryItem(6, new InventoryItem("Landscape Z",
() -> World.getInstance().add(new LandscapeCellZ(getSelectedBlockFace()))));
inventory.setInventoryItem(7, new InventoryItem("Wireworld Wire",
() -> World.getInstance().add(new Conductor(getSelectedBlockFace()))));
inventory.setInventoryItem(8, new InventoryItem("Electron Head",
() -> World.getInstance().add(new ElectronHead(getSelectedBlockFace()))));
inventory.setInventoryItem(9, new InventoryItem("Electron Tail",
() -> World.getInstance().add(new ElectronTail(getSelectedBlockFace()))));
hasValidState();
}
/**
* Singleton pattern
* @return the player
*/
public static Player getInstance() {
if (instance == null){
instance = new Player(new Position(0,0,0));
}
return instance;
}
/**
* Reset the player to the original state
*/
public void reset() {
instance = new Player(new Position(0,0,0));
}
/**
* Hunger tick lowers player's hunger by one, and
* lowers player's stats, if below certain thresholds individual to each stat
* Counts MIN_HUNGER_DELAY world ticks between each hunger tick
*/
@Override
public void tick() {
if (hungerDelay > MIN_HUNGER_DELAY) {
int hunger = getHunger();
setHunger(Math.max(hunger - 1, 0));
//Reduce strength
if (hunger < STRENGTH_REDUCTION_THRESHOLD) {
setStrength(Math.max(getStrength() - (int) (3.0 / ((hunger + 1) * 0.1)), 0));
//Reduce agility
if (hunger < AGILITY_REDUCTION_THRESHOLD) {
setAgility(Math.max(getAgility() - (int) (1.0 / ((hunger + 1) * 0.1)), 0));
//Reduce health
if (hunger < HEALTH_REDUCTION_THRESHOLD) {
setHealth(Math.max(getHealth() - (int) (1.0 / ((hunger + 1) * 0.1)), 0));
}
}
}
hungerDelay = 0;
}else{
hungerDelay++;
}
hasValidState();
}
@Override
public Collection<? extends Cell> tickToAdd() {
return null;
}
@Override
public Collection<? extends Position> tickToRemove() {
return null;
}
public int getHealth() {
return health;
}
public int getStrength() {
return strength;
}
public int getAgility() {
return agility;
}
public int getHunger() {
return hunger;
}
public void setHealth(int health) {
if (!validPercentage(health)) {
return;
}
this.health = health;
hasValidState();
setChanged();
notifyObservers();
}
public void setStrength(int strength) {
if (!validPercentage(health)) {
return;
}
this.strength = strength;
hasValidState();
setChanged();
notifyObservers();
}
public void setAgility(int agility) {
if (!validPercentage(health)) {
return;
}
this.agility = agility;
hasValidState();
setChanged();
notifyObservers();
}
public void setHunger(int hunger) {
if (!validPercentage(health)) {
return;
}
this.hunger = hunger;
hasValidState();
setChanged();
notifyObservers();
}
public Inventory getInventory() {
return inventory;
}
public void rotateCounterClockWise() {
rotation += ROTATION_SPEED;
rotation = (float) (rotation % (Math.PI * 2));
hasValidState();
setChanged();
notifyObservers();
}
public void rotateClockWise() {
rotation -= ROTATION_SPEED;
rotation = (float) (rotation % (Math.PI * 2));
hasValidState();
setChanged();
notifyObservers();
}
public float getRotation() {
return rotation;
}
/**
* @param value percentage
* @return true if 0 <= percentage <= 100, false otherwise
*/
private boolean validPercentage(int value) {
return (0 <= value && value <= 100);
}
/**
* Check invariant.
*/
private void hasValidState() {
assert validPercentage(health);
assert validPercentage(strength);
assert validPercentage(agility);
assert validPercentage(hunger);
//assert inventory.length == INVENTORY_SIZE;
assert hungerDelay >= 0;
//assert selectedInventorySlot < inventory.length;
assert (0 <= rotation && rotation <= 2 * Math.PI);
}
public Position getSelectedBlock() {
return selectedBlock;
}
public Position getSelectedBlockFace() {
return selectedBlockFace;
}
public void setSelectedBlock(Position selectedBlock) {
this.selectedBlock = selectedBlock;
}
public void setSelectedBlockFace(Position selectedBlockFace) {
this.selectedBlockFace = selectedBlockFace;
}
}
| src/model/Player.java | package model;
import model.landscape.LandscapeCell;
import model.landscape.LandscapeCellX;
import model.landscape.LandscapeCellZ;
import model.wireworld.Conductor;
import model.wireworld.ElectronHead;
import model.wireworld.ElectronTail;
import java.util.Collection;
import java.util.Random;
/**
*
* @author Danil Platonov <[email protected]>, jacketsj <[email protected]>
* @version 0.1
* @since 0.1
*
* A player is a cell with health, strength, agility, hunger (in percents)
* and a 10-item inventory of cells (or nulls)
*
* invariant
* 0 <= health, strength, agility, hunger <= 100
* inventory.length == INVENTORY_SIZE
* hungerDelay >= 0
* selectedInventorySlot < inventory.length
* 0 <= rotation <= 2 * Math.PI
*/
public class Player extends ActiveCell {
private static final int MIN_HUNGER_DELAY = World.TICKS_PER_SECOND; // in ticks
private static final int STRENGTH_REDUCTION_THRESHOLD = 30;
private static final int AGILITY_REDUCTION_THRESHOLD = 20;
private static final int HEALTH_REDUCTION_THRESHOLD = 5;
private static final float ROTATION_SPEED = 0.01f;
public static final int INVENTORY_SIZE = 10;
private static Player instance;
private int health;
private int strength;
private int agility;
private int hunger;
private Inventory inventory;
private int hungerDelay;
private float rotation;
private Position selectedBlock;
private Position selectedBlockFace;
/**
* Create a cell at the given position with randomly chosen stats
*
* @param position position of this cell
*/
private Player(Position position) {
super(position);
setName("Player");
Random random = new Random();
rotation = 0;
health = 10 + random.nextInt(91);
strength = 20 + random.nextInt(81);
agility = 30 + random.nextInt(71);
hunger = 40 + random.nextInt(61);
inventory = new Inventory(INVENTORY_SIZE);
inventory.setInventoryItem(1, new InventoryItem("Say Hi",
() -> System.out.println("Hi")));
inventory.setInventoryItem(2, new InventoryItem("Cell",
() -> World.getInstance().add(new Cell(getSelectedBlock()))));
inventory.setInventoryItem(3, new InventoryItem("Random Walk",
() -> World.getInstance().add(new RandomWalkCell(getSelectedBlock()))));
inventory.setInventoryItem(4, new InventoryItem("Landscape",
() -> World.getInstance().add(new LandscapeCell(getSelectedBlock()))));
inventory.setInventoryItem(5, new InventoryItem("Landscape X",
() -> World.getInstance().add(new LandscapeCellX(getSelectedBlock()))));
inventory.setInventoryItem(6, new InventoryItem("Landscape Z",
() -> World.getInstance().add(new LandscapeCellZ(getSelectedBlock()))));
inventory.setInventoryItem(7, new InventoryItem("Wireworld Wire",
() -> World.getInstance().add(new Conductor(getSelectedBlock()))));
inventory.setInventoryItem(8, new InventoryItem("Electron Head",
() -> World.getInstance().add(new ElectronHead(getSelectedBlock()))));
inventory.setInventoryItem(9, new InventoryItem("Electron Tail",
() -> World.getInstance().add(new ElectronTail(getSelectedBlock()))));
hasValidState();
}
/**
* Singleton pattern
* @return the player
*/
public static Player getInstance() {
if (instance == null){
instance = new Player(new Position(0,0,0));
}
return instance;
}
/**
* Reset the player to the original state
*/
public void reset() {
instance = new Player(new Position(0,0,0));
}
/**
* Hunger tick lowers player's hunger by one, and
* lowers player's stats, if below certain thresholds individual to each stat
* Counts MIN_HUNGER_DELAY world ticks between each hunger tick
*/
@Override
public void tick() {
if (hungerDelay > MIN_HUNGER_DELAY) {
int hunger = getHunger();
setHunger(Math.max(hunger - 1, 0));
//Reduce strength
if (hunger < STRENGTH_REDUCTION_THRESHOLD) {
setStrength(Math.max(getStrength() - (int) (3.0 / ((hunger + 1) * 0.1)), 0));
//Reduce agility
if (hunger < AGILITY_REDUCTION_THRESHOLD) {
setAgility(Math.max(getAgility() - (int) (1.0 / ((hunger + 1) * 0.1)), 0));
//Reduce health
if (hunger < HEALTH_REDUCTION_THRESHOLD) {
setHealth(Math.max(getHealth() - (int) (1.0 / ((hunger + 1) * 0.1)), 0));
}
}
}
hungerDelay = 0;
}else{
hungerDelay++;
}
hasValidState();
}
@Override
public Collection<? extends Cell> tickToAdd() {
return null;
}
@Override
public Collection<? extends Position> tickToRemove() {
return null;
}
public int getHealth() {
return health;
}
public int getStrength() {
return strength;
}
public int getAgility() {
return agility;
}
public int getHunger() {
return hunger;
}
public void setHealth(int health) {
if (!validPercentage(health)) {
return;
}
this.health = health;
hasValidState();
setChanged();
notifyObservers();
}
public void setStrength(int strength) {
if (!validPercentage(health)) {
return;
}
this.strength = strength;
hasValidState();
setChanged();
notifyObservers();
}
public void setAgility(int agility) {
if (!validPercentage(health)) {
return;
}
this.agility = agility;
hasValidState();
setChanged();
notifyObservers();
}
public void setHunger(int hunger) {
if (!validPercentage(health)) {
return;
}
this.hunger = hunger;
hasValidState();
setChanged();
notifyObservers();
}
public Inventory getInventory() {
return inventory;
}
public void rotateCounterClockWise() {
rotation += ROTATION_SPEED;
rotation = (float) (rotation % (Math.PI * 2));
hasValidState();
setChanged();
notifyObservers();
}
public void rotateClockWise() {
rotation -= ROTATION_SPEED;
rotation = (float) (rotation % (Math.PI * 2));
hasValidState();
setChanged();
notifyObservers();
}
public float getRotation() {
return rotation;
}
/**
* @param value percentage
* @return true if 0 <= percentage <= 100, false otherwise
*/
private boolean validPercentage(int value) {
return (0 <= value && value <= 100);
}
/**
* Check invariant.
*/
private void hasValidState() {
assert validPercentage(health);
assert validPercentage(strength);
assert validPercentage(agility);
assert validPercentage(hunger);
//assert inventory.length == INVENTORY_SIZE;
assert hungerDelay >= 0;
//assert selectedInventorySlot < inventory.length;
assert (0 <= rotation && rotation <= 2 * Math.PI);
}
public Position getSelectedBlock() {
return selectedBlock;
}
public Position getSelectedBlockFace() {
return selectedBlockFace;
}
public void setSelectedBlock(Position selectedBlock) {
this.selectedBlock = selectedBlock;
}
public void setSelectedBlockFace(Position selectedBlockFace) {
this.selectedBlockFace = selectedBlockFace;
}
}
| If there is a cell closer than CURSOR_DISTANCE, move cursor position to it instead
Make it impossible to replace blocks using cursor (i.e. cursor will place blocks on top of the selected block)
Left mouse click destroys the cell, right mouse click builds a cell
(issue #30)
| src/model/Player.java | If there is a cell closer than CURSOR_DISTANCE, move cursor position to it instead Make it impossible to replace blocks using cursor (i.e. cursor will place blocks on top of the selected block) Left mouse click destroys the cell, right mouse click builds a cell (issue #30) | <ide><path>rc/model/Player.java
<ide> super(position);
<ide> setName("Player");
<ide>
<add> selectedBlock = position;
<add> selectedBlockFace = position;
<add>
<ide> Random random = new Random();
<ide>
<ide> rotation = 0;
<ide> inventory.setInventoryItem(1, new InventoryItem("Say Hi",
<ide> () -> System.out.println("Hi")));
<ide> inventory.setInventoryItem(2, new InventoryItem("Cell",
<del> () -> World.getInstance().add(new Cell(getSelectedBlock()))));
<add> () -> World.getInstance().add(new Cell(getSelectedBlockFace()))));
<ide> inventory.setInventoryItem(3, new InventoryItem("Random Walk",
<del> () -> World.getInstance().add(new RandomWalkCell(getSelectedBlock()))));
<add> () -> World.getInstance().add(new RandomWalkCell(getSelectedBlockFace()))));
<ide> inventory.setInventoryItem(4, new InventoryItem("Landscape",
<del> () -> World.getInstance().add(new LandscapeCell(getSelectedBlock()))));
<add> () -> World.getInstance().add(new LandscapeCell(getSelectedBlockFace()))));
<ide> inventory.setInventoryItem(5, new InventoryItem("Landscape X",
<del> () -> World.getInstance().add(new LandscapeCellX(getSelectedBlock()))));
<add> () -> World.getInstance().add(new LandscapeCellX(getSelectedBlockFace()))));
<ide> inventory.setInventoryItem(6, new InventoryItem("Landscape Z",
<del> () -> World.getInstance().add(new LandscapeCellZ(getSelectedBlock()))));
<add> () -> World.getInstance().add(new LandscapeCellZ(getSelectedBlockFace()))));
<ide> inventory.setInventoryItem(7, new InventoryItem("Wireworld Wire",
<del> () -> World.getInstance().add(new Conductor(getSelectedBlock()))));
<add> () -> World.getInstance().add(new Conductor(getSelectedBlockFace()))));
<ide> inventory.setInventoryItem(8, new InventoryItem("Electron Head",
<del> () -> World.getInstance().add(new ElectronHead(getSelectedBlock()))));
<add> () -> World.getInstance().add(new ElectronHead(getSelectedBlockFace()))));
<ide> inventory.setInventoryItem(9, new InventoryItem("Electron Tail",
<del> () -> World.getInstance().add(new ElectronTail(getSelectedBlock()))));
<add> () -> World.getInstance().add(new ElectronTail(getSelectedBlockFace()))));
<ide>
<ide> hasValidState();
<ide> } |
|
Java | mpl-2.0 | 0f9dc35c4099ff829d0ad5efd1bd8c6bc323e8ec | 0 | andrewmoko/openmrs-module-openhmis.cashier,andrewmoko/openmrs-module-openhmis.cashier,andrewmoko/openmrs-module-openhmis.cashier | /*
* The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and
* limitations under the License.
*
* Copyright (C) OpenHMIS. All Rights Reserved.
*/
package org.openmrs.module.openhmis.cashier.web.controller;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.openmrs.api.context.Context;
import org.openmrs.module.jasperreport.JasperReport;
import org.openmrs.module.jasperreport.ReportGenerator;
import org.openmrs.module.openhmis.cashier.ModuleSettings;
import org.openmrs.module.openhmis.cashier.api.IBillService;
import org.openmrs.module.openhmis.cashier.api.model.Bill;
import org.openmrs.module.openhmis.cashier.api.util.PrivilegeConstants;
import org.openmrs.module.openhmis.cashier.web.CashierWebConstants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping(value = CashierWebConstants.RECEIPT)
public class ReceiptController {
@RequestMapping(method = RequestMethod.GET)
public void get(@RequestParam(value = "billId", required = false) Integer billId,
HttpServletResponse response) throws IOException {
if (billId == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
IBillService service = Context.getService(IBillService.class);
Bill bill = service.getById(billId);
if (!validateBill(billId, bill, response)) {
return;
}
JasperReport report = ModuleSettings.getReceiptReport();
if (report == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Configuration error: need to specify global " +
"option for default report ID.");
return;
}
if (generateReport(billId, response, bill, report)) {
bill.setReceiptPrinted(true);
service.save(bill);
}
}
private boolean generateReport(Integer billId, HttpServletResponse response, Bill bill, JasperReport report)
throws IOException {
String name = report.getName();
if (StringUtils.isEmpty(bill.getReceiptNumber())) {
report.setName(bill.getReceiptNumber());
} else {
report.setName(String.valueOf(billId));
}
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("billId", bill.getId());
try {
ReportGenerator.generateHtmlAndWriteToResponse(report, params, response);
} catch (IOException e) {
if (StringUtils.isEmpty(bill.getReceiptNumber())) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating report for receipt '" +
bill.getReceiptNumber() + "'");
} else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating report for bill '" +
billId + "'");
}
return false;
} finally {
// Reset the report name
report.setName(name);
}
return true;
}
private boolean validateBill(Integer billId, Bill bill, HttpServletResponse response) throws IOException {
if (bill == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Could not find bill with bill Id '" +
billId + "'");
return false;
}
if (bill.isReceiptPrinted() && !Context.hasPrivilege(PrivilegeConstants.REPRINT_RECEIPT)) {
if (StringUtils.isEmpty(bill.getReceiptNumber())) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "You do not have permission to reprint receipt '" +
bill.getReceiptNumber() + "'");
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "You do not have permission to reprint bill '" +
billId + "'");
}
return false;
}
return true;
}
}
| omod_1.x/src/main/java/org/openmrs/module/openhmis/cashier/web/controller/ReceiptController.java | /*
* The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and
* limitations under the License.
*
* Copyright (C) OpenHMIS. All Rights Reserved.
*/
package org.openmrs.module.openhmis.cashier.web.controller;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.openmrs.api.context.Context;
import org.openmrs.module.jasperreport.JasperReport;
import org.openmrs.module.jasperreport.ReportGenerator;
import org.openmrs.module.openhmis.cashier.ModuleSettings;
import org.openmrs.module.openhmis.cashier.api.IBillService;
import org.openmrs.module.openhmis.cashier.api.model.Bill;
import org.openmrs.module.openhmis.cashier.api.util.PrivilegeConstants;
import org.openmrs.module.openhmis.cashier.web.CashierWebConstants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping(value = CashierWebConstants.RECEIPT)
public class ReceiptController {
@RequestMapping(method = RequestMethod.GET)
public void get(@RequestParam(value = "billId", required = false) Integer billId,
HttpServletResponse response) throws IOException {
if (billId == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
IBillService service = Context.getService(IBillService.class);
Bill bill = service.getById(billId);
if (!validateBill(billId, bill, response)) {
return;
}
JasperReport report = ModuleSettings.getReceiptReport();
if (report == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Configuration error: need to specify global " +
"option for default report ID.");
return;
}
if (generateReport(billId, response, bill, report)) {
bill.setReceiptPrinted(true);
service.save(bill);
}
}
private boolean generateReport(Integer billId, HttpServletResponse response, Bill bill, JasperReport report)
throws IOException {
String name = report.getName();
if (bill.getReceiptNumber() != null) {
report.setName(bill.getReceiptNumber());
} else {
report.setName(String.valueOf(billId));
}
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("billId", bill.getId());
try {
ReportGenerator.generateHtmlAndWriteToResponse(report, params, response);
} catch (IOException e) {
if (bill.getReceiptNumber() != null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating report for receipt '" +
bill.getReceiptNumber() + "'");
} else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating report for bill '" +
billId + "'");
}
return false;
} finally {
// Reset the report name
report.setName(name);
}
return true;
}
private boolean validateBill(Integer billId, Bill bill, HttpServletResponse response) throws IOException {
if (bill == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Could not find bill with bill Id '" +
billId + "'");
return false;
}
if (bill.isReceiptPrinted() && !Context.hasPrivilege(PrivilegeConstants.REPRINT_RECEIPT)) {
if (bill.getReceiptNumber() != null) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "You do not have permission to reprint receipt '" +
bill.getReceiptNumber() + "'");
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "You do not have permission to reprint bill '" +
billId + "'");
}
return false;
}
return true;
}
}
| using string utils
| omod_1.x/src/main/java/org/openmrs/module/openhmis/cashier/web/controller/ReceiptController.java | using string utils | <ide><path>mod_1.x/src/main/java/org/openmrs/module/openhmis/cashier/web/controller/ReceiptController.java
<ide>
<ide> import javax.servlet.http.HttpServletResponse;
<ide>
<add>import org.apache.commons.lang3.StringUtils;
<ide> import org.openmrs.api.context.Context;
<ide> import org.openmrs.module.jasperreport.JasperReport;
<ide> import org.openmrs.module.jasperreport.ReportGenerator;
<ide> private boolean generateReport(Integer billId, HttpServletResponse response, Bill bill, JasperReport report)
<ide> throws IOException {
<ide> String name = report.getName();
<del> if (bill.getReceiptNumber() != null) {
<add> if (StringUtils.isEmpty(bill.getReceiptNumber())) {
<ide> report.setName(bill.getReceiptNumber());
<ide> } else {
<ide> report.setName(String.valueOf(billId));
<ide> try {
<ide> ReportGenerator.generateHtmlAndWriteToResponse(report, params, response);
<ide> } catch (IOException e) {
<del> if (bill.getReceiptNumber() != null) {
<add> if (StringUtils.isEmpty(bill.getReceiptNumber())) {
<ide> response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating report for receipt '" +
<ide> bill.getReceiptNumber() + "'");
<ide> } else {
<ide> }
<ide>
<ide> if (bill.isReceiptPrinted() && !Context.hasPrivilege(PrivilegeConstants.REPRINT_RECEIPT)) {
<del> if (bill.getReceiptNumber() != null) {
<add> if (StringUtils.isEmpty(bill.getReceiptNumber())) {
<ide> response.sendError(HttpServletResponse.SC_FORBIDDEN, "You do not have permission to reprint receipt '" +
<ide> bill.getReceiptNumber() + "'");
<ide> } else { |
|
JavaScript | agpl-3.0 | 814d52a5b148ea1eba8006e0e439f442cefe40d7 | 0 | telefonicaid/PopBox,telefonicaid/PopBox |
// Axis Class
(function (PBDV, THREE, undefined) {
"use strict";
/* Constructor */
var Axis = function( size, titles, options ) {
/* Private State */
this.size = size;
this.options = options;
// Array of displayed messages
this.texts = [];
// Axis frame
this.frame = createFrame( size, titles, this.texts );
// Divisions grid
this.grid = createGrid( size, options, this.texts );
// Full 3D axis object
this.threeAxis = createAxis(this.frame, this.grid, size);
}
/* Private Methods */
var createAxis = function( frame, grid, size) {
// Creation of the Three.js Axis 3D Object
var axis = new THREE.Object3D();
// Setting Axis properties
axis.add( frame );
axis.add( grid );
axis.position.set(-size.x/2, -size.y/2, -size.z/2);
return axis;
}
var v = function(x, y, z) {
return new THREE.Vector3(x, y, z);
}
var createFrame = function( size, titles, texts ) {
var lineMat = new THREE.LineBasicMaterial({
color : 0x424242,
linewidth : 2
});
var lineGeo = new THREE.Geometry();
lineGeo.vertices.push(
v(0,0,0), v(size.x,0,0),
v(0,0,0), v(0,size.y,0),
v(size.x,0,0), v(size.x,size.y,0),
v(0,size.y,0), v(size.x,size.y,0)
);
if (size.z >= 0) {
lineGeo.vertices.push(
v(0,0,0), v(0,0,size.z),
v(size.x,0,0), v(size.x,0,size.z),
v(0,size.y,0), v(0,size.y,size.z),
v(size.x,size.y,0), v(size.x,size.y,size.z),
v(0,0,size.z), v(0,size.y,size.z),
v(0,size.y,size.z), v(size.x,size.y,size.z),
v(size.x,size.y,size.z), v(size.x,0,size.z),
v(size.x,0,size.z), v(0,0,size.z)
);
}
var frame = new THREE.Object3D();
var line = new THREE.Line(lineGeo,lineMat);
line.type = THREE.LinePieces;
frame.add(line);
setTitles( frame, size, titles, texts );
return frame;
}
var createGrid = function( size, options, texts ) {
var grid = new THREE.Object3D();
var coords = [ 'x', 'y', 'z' ];
for (var i = 0; i < coords.length; i++) {
var part = setPart( coords[i], size, options, texts );
grid.add( part );
};
return grid;
}
var setPart = function ( coord, size, options, texts, maxHeigth ) {
var MaxDiv = PBDV.Constants.Axis.MaxDiv;
var maxHeigth = maxHeigth || 10000;
var divisions;
var part = new THREE.Object3D();
var lineMat = new THREE.LineBasicMaterial({
color : 0x808080,
linewidth : 1
});
var lineGeo = new THREE.Geometry();
var line = new THREE.Line(lineGeo,lineMat);
line.type = THREE.LinePieces;
var value, aux;
var position = {
x : 0,
y : 0,
z : 0
};
switch (coord) {
case 'x' : aux = options.queues;
var q = options.queues;
var d = (q.end - q.start)/q.interval;
divisions = (d < MaxDiv.X) ? d : MaxDiv.X;
position.y = -size.y/50;
position.z = size.z + size.z/50;
part.name = 'gridX';
break;
case 'y' : aux = {start : 0, end : maxHeigth};
divisions = MaxDiv.Y;
position.x = -size.x/50;
position.z = size.z + size.z/50;
part.name = 'gridY';
break;
case 'z' : aux = options.payload;
var p = options.payload;
var d = (p.end - p.start)/p.interval;
divisions = (d < MaxDiv.Z) ? d : MaxDiv.Z;
position.x = size.x + size.x/50;
position.y = -size.y/50;
part.name = 'gridZ';
break;
}
var amount = size[coord] / divisions;
amount = amount + 0.0000000000000005 //quickfix for precision
amount = amount.toFixed(16);
amount = parseFloat(amount);
if (divisions == 0) amount = size[coord];
var a, b, c;
for (var i = amount; i < size[coord]; i += amount) {
switch (coord) {
case 'x' : a = v(i, 0, 0);
b = v(i, size.y, 0);
c = v(i, 0, size.z);
value = Math.round(options.queues.start + (options.queues.end/divisions)*i/amount);
position.x = i;
break;
case 'y' : a = v(0, i, 0);
b = v(size.x, i, 0);
c = v(0, i, size.z);
value = Math.round((maxHeigth/divisions)*i/amount);
position.y = i;
break;
case 'z' : a = v(0, 0, i);
b = v(size.x, 0, i);
c = v(0, size.y, i);
value = Math.round(options.payload.start + (options.payload.end/divisions)*i/amount);
position.z = i;
break;
}
lineGeo.vertices.push(
a, b,
a, c
);
setValue(value, position, line, texts);
}
value = aux.start;
position[coord] = 0;
setValue(value, position, line, texts);
value = aux.end;
position[coord] = size[coord];
setValue(value, position, line, texts);
part.add(line);
return part;
}
var setTitles = function( frame, size, titles, texts ) {
var titleX;
titleX = PBDV.Utils.createText2D( titles.x );
titleX.position.x = frame.position.x + size.x/2;
titleX.position.y = frame.position.y - size.y/10;
titleX.position.z = frame.position.z + size.z + size.z/10;
texts.push(titleX);
frame.add(titleX);
var titleY;
titleY = PBDV.Utils.createText2D( titles.y );
titleY.position.x = frame.position.x - size.x/10;
titleY.position.y = frame.position.y + size.y/2;
titleY.position.z = frame.position.z + size.z + size.z/10;
texts.push(titleY);
frame.add(titleY);
var titleZ;
titleZ = PBDV.Utils.createText2D( titles.z );
titleZ.position.x = frame.position.x + size.x + size.x/10;
titleZ.position.y = frame.position.y - size.y/10;
titleZ.position.z = frame.position.z + size.z/2;
texts.push(titleZ);
frame.add(titleZ);
}
var setValue = function ( value, position, part, texts ) {
var text = PBDV.Utils.createText2D( value, 50 );
text.position.x = position.x;
text.position.y = position.y;
text.position.z = position.z;
texts.push(text);
part.add(text);
}
/* Public API */
Axis.prototype = {
animate : function ( camera ) {
if (this.texts) {
for (var i = 0; i < this.texts.length; i++) {
this.texts[i].lookAt(camera.position);
this.texts[i].rotation = camera.rotation;
}
}
},
rescale : function ( maxHeigth ) {
this.grid.remove(this.grid.getChildByName('gridY', true));
this.grid.add(setPart('y', this.size, this.options, this.texts, maxHeigth));
}
}
// Exported to the namespace
PBDV.Axis = Axis;
})( window.PBDV = window.PBDV || {}, // Namespace
THREE); // Dependencies
| benchmark/public/js/Axis.js |
// Axis Class
(function (PBDV, THREE, undefined) {
"use strict";
/* Constructor */
var Axis = function( size, titles, options ) {
/* Private State */
this.size = size;
this.options = options;
// Array of displayed messages
this.texts = [];
// Axis frame
this.frame = createFrame( size, titles, this.texts );
// Divisions grid
this.grid = createGrid( size, options, this.texts );
// Full 3D axis object
this.threeAxis = createAxis(this.frame, this.grid, size);
}
/* Private Methods */
var createAxis = function( frame, grid, size) {
// Creation of the Three.js Axis 3D Object
var axis = new THREE.Object3D();
// Setting Axis properties
axis.add( frame );
axis.add( grid );
axis.position.set(-size.x/2, -size.y/2, -size.z/2);
return axis;
}
var v = function(x, y, z) {
return new THREE.Vector3(x, y, z);
}
var createFrame = function( size, titles, texts ) {
var lineMat = new THREE.LineBasicMaterial({
color : 0x424242,
linewidth : 2
});
var lineGeo = new THREE.Geometry();
lineGeo.vertices.push(
v(0,0,0), v(size.x,0,0),
v(0,0,0), v(0,size.y,0),
v(size.x,0,0), v(size.x,size.y,0),
v(0,size.y,0), v(size.x,size.y,0)
);
if (size.z >= 0) {
lineGeo.vertices.push(
v(0,0,0), v(0,0,size.z),
v(size.x,0,0), v(size.x,0,size.z),
v(0,size.y,0), v(0,size.y,size.z),
v(size.x,size.y,0), v(size.x,size.y,size.z),
v(0,0,size.z), v(0,size.y,size.z),
v(0,size.y,size.z), v(size.x,size.y,size.z),
v(size.x,size.y,size.z), v(size.x,0,size.z),
v(size.x,0,size.z), v(0,0,size.z)
);
}
var frame = new THREE.Object3D();
var line = new THREE.Line(lineGeo,lineMat);
line.type = THREE.LinePieces;
frame.add(line);
setTitles( frame, size, titles, texts );
return frame;
}
var createGrid = function( size, options, texts ) {
var grid = new THREE.Object3D();
var coords = [ 'x', 'y', 'z' ];
for (var i = 0; i < coords.length; i++) {
var part = setPart( coords[i], size, options, texts );
grid.add( part );
};
return grid;
}
var setPart = function ( coord, size, options, texts, maxHeigth ) {
var MaxDiv = PBDV.Constants.Axis.MaxDiv;
var maxHeigth = maxHeigth || 10000;
var divisions;
var part = new THREE.Object3D();
var lineMat = new THREE.LineBasicMaterial({
color : 0x808080,
linewidth : 1
});
var lineGeo = new THREE.Geometry();
var line = new THREE.Line(lineGeo,lineMat);
line.type = THREE.LinePieces;
var value, aux;
var position = {
x : 0,
y : 0,
z : 0
};
switch (coord) {
case 'x' : aux = options.queues;
var q = options.queues;
var d = (q.end - q.start)/q.interval;
divisions = d < MaxDiv.X ? d : MaxDiv.X;
position.y = -size.y/50;
position.z = size.z + size.z/50;
part.name = 'gridX';
break;
case 'y' : aux = {start : 0, end : maxHeigth};
divisions = MaxDiv.Y;
position.x = -size.x/50;
position.z = size.z + size.z/50;
part.name = 'gridY';
break;
case 'z' : aux = options.payload;
var p = options.payload;
var d = (p.end - p.start)/p.interval;
divisions = d < MaxDiv.Z ? d : MaxDiv.Z;
position.x = size.x + size.x/50;
position.y = -size.y/50;
part.name = 'gridZ';
break;
}
var amount = size[coord] / divisions;
amount = amount + 0.0000000000000005 //quickfix for precision
amount = amount.toFixed(16);
amount = parseFloat(amount);
if (divisions == 0) amount = size[coord];
var a, b, c;
for (var i = amount; i < size[coord]; i += amount) {
switch (coord) {
case 'x' : a = v(i, 0, 0);
b = v(i, size.y, 0);
c = v(i, 0, size.z);
value = Math.round(options.queues.start + options.queues.interval*i/amount);
position.x = i;
break;
case 'y' : a = v(0, i, 0);
b = v(size.x, i, 0);
c = v(0, i, size.z);
value = Math.round((maxHeigth/divisions)*i/amount);
position.y = i;
break;
case 'z' : a = v(0, 0, i);
b = v(size.x, 0, i);
c = v(0, size.y, i);
value = Math.round(options.payload.start + options.payload.interval*i/amount);
position.z = i;
break;
}
lineGeo.vertices.push(
a, b,
a, c
);
setValue(value, position, line, texts);
}
value = aux.start;
position[coord] = 0;
setValue(value, position, line, texts);
value = aux.end;
position[coord] = size[coord];
setValue(value, position, line, texts);
part.add(line);
return part;
}
var setTitles = function( frame, size, titles, texts ) {
var titleX;
titleX = PBDV.Utils.createText2D( titles.x );
titleX.position.x = frame.position.x + size.x/2;
titleX.position.y = frame.position.y - size.y/10;
titleX.position.z = frame.position.z + size.z + size.z/10;
texts.push(titleX);
frame.add(titleX);
var titleY;
titleY = PBDV.Utils.createText2D( titles.y );
titleY.position.x = frame.position.x - size.x/10;
titleY.position.y = frame.position.y + size.y/2;
titleY.position.z = frame.position.z + size.z + size.z/10;
texts.push(titleY);
frame.add(titleY);
var titleZ;
titleZ = PBDV.Utils.createText2D( titles.z );
titleZ.position.x = frame.position.x + size.x + size.x/10;
titleZ.position.y = frame.position.y - size.y/10;
titleZ.position.z = frame.position.z + size.z/2;
texts.push(titleZ);
frame.add(titleZ);
}
var setValue = function ( value, position, part, texts ) {
var text = PBDV.Utils.createText2D( value, 50 );
text.position.x = position.x;
text.position.y = position.y;
text.position.z = position.z;
texts.push(text);
part.add(text);
}
/* Public API */
Axis.prototype = {
animate : function ( camera ) {
if (this.texts) {
for (var i = 0; i < this.texts.length; i++) {
this.texts[i].lookAt(camera.position);
this.texts[i].rotation = camera.rotation;
}
}
},
rescale : function ( maxHeigth ) {
this.grid.remove(this.grid.getChildByName('gridY', true));
this.grid.add(setPart('y', this.size, this.options, this.texts, maxHeigth));
}
}
// Exported to the namespace
PBDV.Axis = Axis;
})( window.PBDV = window.PBDV || {}, // Namespace
THREE); // Dependencies
| Fixed number not showing correctly when the maximun number of divisions is reached
| benchmark/public/js/Axis.js | Fixed number not showing correctly when the maximun number of divisions is reached | <ide><path>enchmark/public/js/Axis.js
<ide>
<ide> if (size.z >= 0) {
<ide> lineGeo.vertices.push(
<del> v(0,0,0), v(0,0,size.z),
<add> v(0,0,0), v(0,0,size.z),
<ide> v(size.x,0,0), v(size.x,0,size.z),
<ide> v(0,size.y,0), v(0,size.y,size.z),
<del> v(size.x,size.y,0), v(size.x,size.y,size.z),
<del>
<del> v(0,0,size.z), v(0,size.y,size.z),
<add> v(size.x,size.y,0), v(size.x,size.y,size.z),
<add>
<add> v(0,0,size.z), v(0,size.y,size.z),
<ide> v(0,size.y,size.z), v(size.x,size.y,size.z),
<ide> v(size.x,size.y,size.z), v(size.x,0,size.z),
<ide> v(size.x,0,size.z), v(0,0,size.z)
<ide> case 'x' : aux = options.queues;
<ide> var q = options.queues;
<ide> var d = (q.end - q.start)/q.interval;
<del> divisions = d < MaxDiv.X ? d : MaxDiv.X;
<add> divisions = (d < MaxDiv.X) ? d : MaxDiv.X;
<ide> position.y = -size.y/50;
<ide> position.z = size.z + size.z/50;
<ide> part.name = 'gridX';
<ide> case 'z' : aux = options.payload;
<ide> var p = options.payload;
<ide> var d = (p.end - p.start)/p.interval;
<del> divisions = d < MaxDiv.Z ? d : MaxDiv.Z;
<add> divisions = (d < MaxDiv.Z) ? d : MaxDiv.Z;
<ide> position.x = size.x + size.x/50;
<ide> position.y = -size.y/50;
<ide> part.name = 'gridZ';
<ide> case 'x' : a = v(i, 0, 0);
<ide> b = v(i, size.y, 0);
<ide> c = v(i, 0, size.z);
<del> value = Math.round(options.queues.start + options.queues.interval*i/amount);
<add> value = Math.round(options.queues.start + (options.queues.end/divisions)*i/amount);
<ide> position.x = i;
<ide> break;
<ide>
<ide> case 'z' : a = v(0, 0, i);
<ide> b = v(size.x, 0, i);
<ide> c = v(0, size.y, i);
<del> value = Math.round(options.payload.start + options.payload.interval*i/amount);
<add> value = Math.round(options.payload.start + (options.payload.end/divisions)*i/amount);
<ide> position.z = i;
<ide> break;
<ide> } |
|
JavaScript | mit | b80088486f6d756702058e77c0a34dd2b84e00de | 0 | steins024/projection-grid,steins024/projection-grid | import _ from 'underscore';
import Backbone from 'backbone';
import ListView from 'backbone-virtualized-listview';
import { HeaderView, FooterView } from './header-footer-view.js';
import rowTemplate from './row.jade';
import tableFixedTemplate from './table-fixed.jade';
import tableStaticTemplate from './table-static.jade';
import tableStickyTemplate from './table-sticky.jade';
import columnGroupTemplate from './column-group.jade';
const STATE_OPTIONS = ['cols', 'headRows', 'bodyRows', 'footRows', 'events'];
const HEADER_TYPES = ['static', 'fixed', 'sticky'];
export class TableView extends Backbone.View {
initialize({ scrolling = {}, classes = [] }) {
this._props = {
scrolling: this._normalizeScrollingConfig(scrolling),
classes,
};
this._state = {
cols: [],
headRows: [],
bodyRows: [],
footRows: [],
events: {},
};
this._listView = new ListView({
el: this.$el,
virtualized: this._props.scrolling.virtualized,
viewport: this._props.scrolling.viewport,
});
this._headerView = new HeaderView({ tableView: this });
this._footerView = new FooterView({ tableView: this });
}
_normalizeHeaderConfig(config) {
const header = {};
if (_.isString(config)) {
header.type = config;
} else if (_.isFunction(config) || _.isFinite(config)) {
header.type = 'sticky';
header.offset = config;
} else if (_.isObject(config) && _.isString(config.type)) {
_.extend(header, _.pick(config, 'type', 'offset'));
}
if (!_.contains(HEADER_TYPES, header.type)) {
header.type = 'static';
}
if (header.type === 'sticky' && !_.isFinite(_.result(header, 'offset'))) {
header.offset = 0;
}
return header;
}
_normalizeScrollingConfig({
viewport,
virtualized = false,
header = 'static',
}) {
const scrolling = { viewport, virtualized };
scrolling.header = this._normalizeHeaderConfig(header);
if (scrolling.header.type === 'fixed') {
scrolling.viewport = '.viewport';
}
return scrolling;
}
get headerType() {
return this._props.scrolling.header.type;
}
set(state = {}, callback = _.noop) {
const isSet = key => !_.isUndefined(state[key]);
const listState = {};
_.extend(this._state, _.pick(state, STATE_OPTIONS));
if (isSet('bodyRows')) {
const bodyRows = this._state.bodyRows;
listState.items = {
length: bodyRows.length,
slice(start, stop) {
return _.map(bodyRows.slice(start, stop), row => ({ row }));
},
};
}
if (isSet('events')) {
listState.events = state.events;
}
this._renderColumnGroup();
if (this._headerView) {
this._headerView.redraw();
}
if (this._footerView) {
this._footerView.redraw();
}
this._listView.set(listState, callback);
return this;
}
_renderColumnGroup() {
this.$colgroup = this.$('colgroup.column-group');
this.$colgroup.html(columnGroupTemplate(this._state));
}
_renderHeader() {
this._headerView.setElement(this.$('thead.header'));
this._headerView.render();
}
_renderFooter() {
this._footerView.setElement(this.$('tfoot.footer'));
this._footerView.render();
}
/**
* This is simulating `{ position: sticky }`, but it's still far from perfect.
*
* 1. For window viewport
* * Use `{ postion: fixed }`
* * Adjust the width and the horizontal location on the fly
* * Put an dummy filler into the content flow to take the place of header
*
* The issues are
* * If the subviews in header changes, they have to notify the grid
* manually to update the filler's size
* * The header doesn't follow the table tightly on horizontal scroll, as
* the `scroll` event is triggered after repaint for most browsers
*
* 2. For element viewport
* * Use `{ position: relative }`
* * Adjust the vertical location on the fly
*
* The issues are
* * The header doesn't follow the table tightly on vertical scroll, as
* the `scroll` event is triggered after repaint for most browsers. The
* sticky header could be very jumpy on IE and Edge.
*
* We wish all browsers support `{ position: sticky }` in a not too far
* future. So that we can have a perfect solution with native support.
*
*/
_hookUpStickyHeader(listView) {
const viewport = listView.viewport;
const isWindow = viewport.$el.get(0) === window;
const $tableContainer = this.$('.table-container');
const $stickyHeader = this.$('.sticky-header');
const $stickyHeaderFiller = this.$('.sticky-header-filler');
const $table = this.$('.sticky-header-filler + table');
const adjustStickyHeader = () => {
if (!this.$el.is(':visible')) {
return;
}
const topVP = listView.viewport.getMetrics().outer.top;
const offset = _.result(this._props.scrolling.header, 'offset', 0);
const rectContainer = $tableContainer.get(0).getBoundingClientRect();
const topCur = rectContainer.top;
if (isWindow) {
const sticky = topCur < topVP + offset;
$stickyHeaderFiller.css({
display: sticky ? 'block' : 'none',
height: sticky ? $stickyHeader.height() : '',
});
$stickyHeader.css({
position: sticky ? 'fixed' : 'static',
top: sticky ? topVP + offset : '',
width: sticky ? $tableContainer.width() : '',
left: sticky ? rectContainer.left : '',
});
} else {
$stickyHeaderFiller.css({
display: 'none',
});
$stickyHeader.css({
position: 'relative',
top: Math.min(Math.max(topVP + offset - topCur, 0), $table.height()),
});
}
};
listView.viewport.on('change', adjustStickyHeader);
listView.on('didRedraw', adjustStickyHeader);
}
_renderStatic(callback) {
this._listView.set({
model: {
classes: this._props.classes,
},
listTemplate: tableStaticTemplate,
itemTemplate: rowTemplate,
}).render(() => {
this._renderColumnGroup();
this._renderHeader();
this._renderFooter();
callback();
});
}
_renderFixed(callback) {
this._listView.set({
model: {
classes: this._props.classes,
},
listTemplate: tableFixedTemplate,
itemTemplate: rowTemplate,
}).render(() => {
this._renderColumnGroup();
this._renderHeader();
this._renderFooter();
callback();
});
this._listView.on('didRedraw', () => {
const widthViewport = this.$('.viewport').get(0).clientWidth;
const widthContainer = this.el.clientWidth;
const widthScrollbar = widthContainer - widthViewport;
const widthTable = this.$('.viewport > table').get(0).offsetWidth;
this.$el.width(widthTable + widthScrollbar);
this.$('.fixed-header').width(widthTable);
});
}
_renderSticky(callback) {
this._listView.set({
model: {
classes: this._props.classes,
},
listTemplate: tableStickyTemplate,
itemTemplate: rowTemplate,
}).render(() => {
this._renderColumnGroup();
this._renderHeader();
this._hookUpStickyHeader(this._listView);
this._renderFooter();
callback();
});
}
render(callback = _.noop) {
const header = this._props.scrolling.header;
switch (header.type) {
default:
case 'static':
this._renderStatic(callback);
break;
case 'fixed':
this._renderFixed(callback);
break;
case 'sticky':
this._renderSticky(callback);
break;
}
return this;
}
remove() {
if (this._headerView) {
this._headerView.remove();
}
if (this._listView) {
this._listView.remove();
}
if (this._footerView) {
this._footerView.remove();
}
super.remove();
}
scrollToItem(...args) {
this._listView.scrollToItem(...args);
}
indexOfElement(el) {
const $elTr = this._listView.$(el).closest('tr', this._listView.$container);
if ($elTr.length > 0) {
return $elTr.index() + this._listView.indexFirst - 1;
}
return null;
}
}
| js/vnext/layout/table-view.js | import _ from 'underscore';
import Backbone from 'backbone';
import ListView from 'backbone-virtualized-listview';
import { HeaderView, FooterView } from './header-footer-view.js';
import rowTemplate from './row.jade';
import tableFixedTemplate from './table-fixed.jade';
import tableStaticTemplate from './table-static.jade';
import tableStickyTemplate from './table-sticky.jade';
import columnGroupTemplate from './column-group.jade';
const STATE_OPTIONS = ['cols', 'headRows', 'bodyRows', 'footRows', 'events'];
const HEADER_TYPES = ['static', 'fixed', 'sticky'];
export class TableView extends Backbone.View {
initialize({ scrolling = {}, classes = [] }) {
this._props = {
scrolling: this._normalizeScrollingConfig(scrolling),
classes,
};
this._state = {
cols: [],
headRows: [],
bodyRows: [],
footRows: [],
events: {},
};
this._listView = new ListView({
el: this.$el,
virtualized: this._props.scrolling.virtualized,
viewport: this._props.scrolling.viewport,
});
this._headerView = new HeaderView({ tableView: this });
this._footerView = new FooterView({ tableView: this });
}
_normalizeHeaderConfig(config) {
const header = {};
if (_.isString(config)) {
header.type = config;
} else if (_.isFunction(config) || _.isFinite(config)) {
header.type = 'sticky';
header.offset = config;
} else if (_.isObject(config) && _.isString(config.type)) {
_.extend(header, _.pick(config, 'type', 'offset'));
}
if (!_.contains(HEADER_TYPES, header.type)) {
header.type = 'static';
}
if (header.type === 'sticky' && !_.isFinite(_.result(header, 'offset'))) {
header.offset = 0;
}
return header;
}
_normalizeScrollingConfig({
viewport,
virtualized = false,
header = 'static',
}) {
const scrolling = { viewport, virtualized };
scrolling.header = this._normalizeHeaderConfig(header);
if (scrolling.header.type === 'fixed') {
scrolling.viewport = '.viewport';
}
return scrolling;
}
get headerType() {
return this._props.scrolling.header.type;
}
set(state = {}, callback = _.noop) {
const isSet = key => !_.isUndefined(state[key]);
const listState = {};
_.extend(this._state, _.pick(state, STATE_OPTIONS));
if (isSet('bodyRows')) {
const bodyRows = this._state.bodyRows;
listState.items = {
length: bodyRows.length,
slice(start, stop) {
return _.map(bodyRows.slice(start, stop), row => ({ row }));
},
};
}
if (isSet('events')) {
listState.events = state.events;
}
this._renderColumnGroup();
if (this._headerView) {
this._headerView.redraw();
}
if (this._footerView) {
this._footerView.redraw();
}
this._listView.set(listState, callback);
return this;
}
_renderColumnGroup() {
this.$colgroup = this.$('colgroup.column-group');
this.$colgroup.html(columnGroupTemplate(this._state));
}
_renderHeader() {
this._headerView.setElement(this.$('thead.header'));
this._headerView.render();
}
_renderFooter() {
this._footerView.setElement(this.$('tfoot.footer'));
this._footerView.render();
}
/**
* This is simulating `{ position: sticky }`, but it's still far from perfect.
*
* 1. For window viewport
* * Use `{ postion: fixed }`
* * Adjust the width and the horizontal location on the fly
* * Put an dummy filler into the content flow to take the place of header
*
* The issues are
* * If the subviews in header changes, they have to notify the grid
* manually to update the filler's size
* * The header doesn't follow the table tightly on horizontal scroll, as
* the `scroll` event is triggered after repaint for most browsers
*
* 2. For element viewport
* * Use `{ position: relative }`
* * Adjust the vertical location on the fly
*
* The issues are
* * The header doesn't follow the table tightly on vertical scroll, as
* the `scroll` event is triggered after repaint for most browsers. The
* sticky header could be very jumpy on IE and Edge.
*
* We wish all browsers support `{ position: sticky }` in a not too far
* future. So that we can have a perfect solution with native support.
*
*/
_hookUpStickyHeader(listView) {
const viewport = listView.viewport;
const isWindow = viewport.$el.get(0) === window;
const $tableContainer = this.$('.table-container');
const $stickyHeader = this.$('.sticky-header');
const $stickyHeaderFiller = this.$('.sticky-header-filler');
const $table = this.$('.sticky-header-filler + table');
const adjustStickyHeader = () => {
const topVP = listView.viewport.getMetrics().outer.top;
const offset = _.result(this._props.scrolling.header, 'offset', 0);
const rectContainer = $tableContainer.get(0).getBoundingClientRect();
const topCur = rectContainer.top;
if (isWindow) {
const sticky = topCur < topVP + offset;
$stickyHeaderFiller.css({
display: sticky ? 'block' : 'none',
height: sticky ? $stickyHeader.height() : '',
});
$stickyHeader.css({
position: sticky ? 'fixed' : 'static',
top: sticky ? topVP + offset : '',
width: sticky ? $tableContainer.width() : '',
left: sticky ? rectContainer.left : '',
});
} else {
$stickyHeaderFiller.css({
display: 'none',
});
$stickyHeader.css({
position: 'relative',
top: Math.min(Math.max(topVP + offset - topCur, 0), $table.height()),
});
}
};
listView.viewport.on('change', adjustStickyHeader);
listView.on('didRedraw', adjustStickyHeader);
}
_renderStatic(callback) {
this._listView.set({
model: {
classes: this._props.classes,
},
listTemplate: tableStaticTemplate,
itemTemplate: rowTemplate,
}).render(() => {
this._renderColumnGroup();
this._renderHeader();
this._renderFooter();
callback();
});
}
_renderFixed(callback) {
this._listView.set({
model: {
classes: this._props.classes,
},
listTemplate: tableFixedTemplate,
itemTemplate: rowTemplate,
}).render(() => {
this._renderColumnGroup();
this._renderHeader();
this._renderFooter();
callback();
});
this._listView.on('didRedraw', () => {
const widthViewport = this.$('.viewport').get(0).clientWidth;
const widthContainer = this.el.clientWidth;
const widthScrollbar = widthContainer - widthViewport;
const widthTable = this.$('.viewport > table').get(0).offsetWidth;
this.$el.width(widthTable + widthScrollbar);
this.$('.fixed-header').width(widthTable);
});
}
_renderSticky(callback) {
this._listView.set({
model: {
classes: this._props.classes,
},
listTemplate: tableStickyTemplate,
itemTemplate: rowTemplate,
}).render(() => {
this._renderColumnGroup();
this._renderHeader();
this._hookUpStickyHeader(this._listView);
this._renderFooter();
callback();
});
}
render(callback = _.noop) {
const header = this._props.scrolling.header;
switch (header.type) {
default:
case 'static':
this._renderStatic(callback);
break;
case 'fixed':
this._renderFixed(callback);
break;
case 'sticky':
this._renderSticky(callback);
break;
}
return this;
}
remove() {
if (this._headerView) {
this._headerView.remove();
}
if (this._listView) {
this._listView.remove();
}
if (this._footerView) {
this._footerView.remove();
}
super.remove();
}
scrollToItem(...args) {
this._listView.scrollToItem(...args);
}
indexOfElement(el) {
const $elTr = this._listView.$(el).closest('tr', this._listView.$container);
if ($elTr.length > 0) {
return $elTr.index() + this._listView.indexFirst - 1;
}
return null;
}
}
| Only adjust the sticky header when the grid is visible
| js/vnext/layout/table-view.js | Only adjust the sticky header when the grid is visible | <ide><path>s/vnext/layout/table-view.js
<ide> const $stickyHeaderFiller = this.$('.sticky-header-filler');
<ide> const $table = this.$('.sticky-header-filler + table');
<ide> const adjustStickyHeader = () => {
<add> if (!this.$el.is(':visible')) {
<add> return;
<add> }
<add>
<ide> const topVP = listView.viewport.getMetrics().outer.top;
<ide> const offset = _.result(this._props.scrolling.header, 'offset', 0);
<ide> const rectContainer = $tableContainer.get(0).getBoundingClientRect(); |
|
Java | apache-2.0 | d8695b6f5795b5b6f17e0708413421899ead266e | 0 | NLeSC/Xenon,NLeSC/Xenon | /**
* Copyright 2013 Netherlands eScience Center
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.esciencecenter.xenon.adaptors.ssh;
import java.io.File;
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import nl.esciencecenter.xenon.XenonException;
import nl.esciencecenter.xenon.XenonPropertyDescription;
import nl.esciencecenter.xenon.XenonPropertyDescription.Component;
import nl.esciencecenter.xenon.XenonPropertyDescription.Type;
import nl.esciencecenter.xenon.credentials.Credential;
import nl.esciencecenter.xenon.credentials.Credentials;
import nl.esciencecenter.xenon.engine.Adaptor;
import nl.esciencecenter.xenon.engine.XenonEngine;
import nl.esciencecenter.xenon.engine.XenonProperties;
import nl.esciencecenter.xenon.engine.XenonPropertyDescriptionImplementation;
import nl.esciencecenter.xenon.engine.util.ImmutableArray;
import nl.esciencecenter.xenon.files.Files;
import nl.esciencecenter.xenon.jobs.Jobs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.ConfigRepository;
import com.jcraft.jsch.HostKey;
import com.jcraft.jsch.HostKeyRepository;
import com.jcraft.jsch.IdentityRepository;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.agentproxy.AgentProxyException;
import com.jcraft.jsch.agentproxy.Connector;
import com.jcraft.jsch.agentproxy.ConnectorFactory;
import com.jcraft.jsch.agentproxy.RemoteIdentityRepository;
public class SshAdaptor extends Adaptor {
private static final Logger LOGGER = LoggerFactory.getLogger(SshAdaptor.class);
/** The name of this adaptor */
public static final String ADAPTOR_NAME = "ssh";
/** The default SSH port */
protected static final int DEFAULT_PORT = 22;
/** A description of this adaptor */
private static final String ADAPTOR_DESCRIPTION = "The SSH adaptor implements all functionality with remote ssh servers.";
/** The schemes supported by this adaptor */
protected static final ImmutableArray<String> ADAPTOR_SCHEME = new ImmutableArray<>("ssh", "sftp");
/** The locations supported by this adaptor */
private static final ImmutableArray<String> ADAPTOR_LOCATIONS = new ImmutableArray<>("[user@]host[:port]");
/** All our own properties start with this prefix. */
public static final String PREFIX = XenonEngine.ADAPTORS + "ssh.";
/** Enable strict host key checking. */
public static final String STRICT_HOST_KEY_CHECKING = PREFIX + "strictHostKeyChecking";
/** Enable the use of an ssh-agent */
public static final String AGENT = PREFIX + "agent";
/** Enable the use of ssh-agent-forwarding */
public static final String AGENT_FORWARDING = PREFIX + "agentForwarding";
/** Load the known_hosts file by default. */
public static final String LOAD_STANDARD_KNOWN_HOSTS = PREFIX + "loadKnownHosts";
/** Load the OpenSSH config file by default. */
public static final String LOAD_SSH_CONFIG = PREFIX + "loadSshConfig";
/** OpenSSH config filename. */
public static final String SSH_CONFIG_FILE = PREFIX + "sshConfigFile";
/** Enable strict host key checking. */
public static final String AUTOMATICALLY_ADD_HOST_KEY = PREFIX + "autoAddHostKey";
/** Add gateway to access machine. */
public static final String GATEWAY = PREFIX + "gateway";
/** All our own queue properties start with this prefix. */
public static final String QUEUE = PREFIX + "queue.";
/** Maximum history length for finished jobs */
public static final String MAX_HISTORY = QUEUE + "historySize";
/** Property for maximum history length for finished jobs */
public static final String POLLING_DELAY = QUEUE + "pollingDelay";
/** Local multi queue properties start with this prefix. */
public static final String MULTIQ = QUEUE + "multi.";
/** Property for the maximum number of concurrent jobs in the multi queue. */
public static final String MULTIQ_MAX_CONCURRENT = MULTIQ + "maxConcurrentJobs";
/** Ssh adaptor information start with this prefix. */
public static final String INFO = PREFIX + "info.";
/** Ssh job information start with this prefix. */
public static final String JOBS = INFO + "jobs.";
/** How many jobs have been submitted using this adaptor. */
public static final String SUBMITTED = JOBS + "submitted";
/** List of properties supported by this SSH adaptor */
private static final ImmutableArray<XenonPropertyDescription> VALID_PROPERTIES = new ImmutableArray<XenonPropertyDescription>(
new XenonPropertyDescriptionImplementation(AUTOMATICALLY_ADD_HOST_KEY, Type.BOOLEAN, EnumSet.of(Component.SCHEDULER,
Component.FILESYSTEM), "true", "Automatically add unknown host keys to known_hosts."),
new XenonPropertyDescriptionImplementation(STRICT_HOST_KEY_CHECKING, Type.BOOLEAN, EnumSet.of(Component.SCHEDULER,
Component.FILESYSTEM), "true", "Enable strict host key checking."),
new XenonPropertyDescriptionImplementation(LOAD_STANDARD_KNOWN_HOSTS, Type.BOOLEAN, EnumSet.of(Component.XENON),
"true", "Load the standard known_hosts file."),
new XenonPropertyDescriptionImplementation(LOAD_SSH_CONFIG, Type.BOOLEAN, EnumSet.of(Component.XENON),
"true", "Load the OpenSSH config file."),
new XenonPropertyDescriptionImplementation(SSH_CONFIG_FILE, Type.BOOLEAN, EnumSet.of(Component.XENON),
null, "OpenSSH config filename."),
new XenonPropertyDescriptionImplementation(AGENT, Type.BOOLEAN, EnumSet.of(Component.XENON),
"false", "Use a (local) ssh-agent."),
new XenonPropertyDescriptionImplementation(AGENT_FORWARDING, Type.BOOLEAN, EnumSet.of(Component.XENON),
"false", "Use ssh-agent forwarding"),
new XenonPropertyDescriptionImplementation(POLLING_DELAY, Type.LONG, EnumSet.of(Component.SCHEDULER), "1000",
"The polling delay for monitoring running jobs (in milliseconds)."),
new XenonPropertyDescriptionImplementation(MULTIQ_MAX_CONCURRENT, Type.INTEGER, EnumSet.of(Component.SCHEDULER), "4",
"The maximum number of concurrent jobs in the multiq.."),
new XenonPropertyDescriptionImplementation(GATEWAY, Type.STRING, EnumSet.of(Component.SCHEDULER, Component.FILESYSTEM),
null, "The gateway machine used to create an SSH tunnel to the target."));
private final SshFiles filesAdaptor;
private final SshJobs jobsAdaptor;
private final SshCredentials credentialsAdaptor;
private final boolean useAgent;
private JSch jsch;
public SshAdaptor(XenonEngine xenonEngine, Map<String, String> properties) throws XenonException {
this(xenonEngine, new JSch(), properties);
}
public SshAdaptor(XenonEngine xenonEngine, JSch jsch, Map<String, String> properties) throws XenonException {
super(xenonEngine, ADAPTOR_NAME, ADAPTOR_DESCRIPTION, ADAPTOR_SCHEME, ADAPTOR_LOCATIONS, VALID_PROPERTIES,
new XenonProperties(VALID_PROPERTIES, Component.XENON, properties));
this.filesAdaptor = new SshFiles(this, xenonEngine);
this.jobsAdaptor = new SshJobs(getProperties(), this, xenonEngine);
this.credentialsAdaptor = new SshCredentials(this);
this.jsch = jsch;
if (getProperties().getBooleanProperty(SshAdaptor.LOAD_STANDARD_KNOWN_HOSTS)) {
String knownHosts = System.getProperty("user.home") + "/.ssh/known_hosts";
LOGGER.debug("Setting ssh known hosts file to: " + knownHosts);
if (new File(knownHosts).exists()) {
setKnownHostsFile(knownHosts);
} else if (getProperties().propertySet(SshAdaptor.LOAD_STANDARD_KNOWN_HOSTS)) {
// property was explicitly set, throw an error because it does not exist
throw new XenonException(SshAdaptor.ADAPTOR_NAME, "Cannot load known_hosts file: " + knownHosts + " does not exist");
} else {
// implictly ignore
LOGGER.debug("known_hosts file " + knownHosts + " does not exist, not checking hosts with signatures of known hosts.");
}
}
if (getProperties().getBooleanProperty(SshAdaptor.LOAD_SSH_CONFIG)) {
String sshConfig = getProperties().getProperty(SshAdaptor.SSH_CONFIG_FILE);
if (sshConfig == null) {
sshConfig = System.getProperty("user.home") + "/.ssh/config";
}
LOGGER.debug("Setting ssh known hosts file to: " + sshConfig);
setConfigFile(sshConfig, !getProperties().propertySet(SshAdaptor.LOAD_SSH_CONFIG));
}
if (getProperties().getBooleanProperty(SshAdaptor.AGENT)) {
// Connect to the local ssh-agent
LOGGER.debug("Connecting to ssh-agent");
Connector connector;
try {
ConnectorFactory cf = ConnectorFactory.getDefault();
connector = cf.createConnector();
} catch(AgentProxyException e){
throw new XenonException(SshAdaptor.ADAPTOR_NAME, "Failed to connect to ssh-agent", e);
}
IdentityRepository ident = new RemoteIdentityRepository(connector);
jsch.setIdentityRepository(ident);
useAgent = true;
} else {
useAgent = false;
}
if (getProperties().getBooleanProperty(SshAdaptor.AGENT_FORWARDING)) {
// Enable ssh-agent-forwarding
LOGGER.warn("TODO: Enabling ssh-agent-forwarding");
}
if (jsch.getConfigRepository() == null) {
jsch.setConfigRepository(ConfigRepository.nullConfig);
}
}
private void setKnownHostsFile(String knownHostsFile) throws XenonException {
try {
jsch.setKnownHosts(knownHostsFile);
} catch (JSchException e) {
throw new XenonException(SshAdaptor.ADAPTOR_NAME, "Could not set known_hosts file", e);
}
if (LOGGER.isDebugEnabled()) {
HostKeyRepository hkr = jsch.getHostKeyRepository();
HostKey[] hks = hkr.getHostKey();
if (hks != null) {
LOGGER.debug("Host keys in " + hkr.getKnownHostsRepositoryID());
for (HostKey hk : hks) {
LOGGER.debug(hk.getHost() + " " + hk.getType() + " " + hk.getFingerPrint(jsch));
}
LOGGER.debug("");
} else {
LOGGER.debug("No keys in " + knownHostsFile);
}
}
}
private void setConfigFile(String sshConfigFile, boolean ignoreFail) throws XenonException {
try {
ConfigRepository configRepository = OpenSSHConfig.parse(new File(sshConfigFile));
jsch.setConfigRepository(configRepository);
} catch (IOException|XenonException ex) {
if (ignoreFail) {
LOGGER.warn("OpenSSH config file cannot be read.");
} else {
throw new XenonException(SshAdaptor.ADAPTOR_NAME, "Cannot read OpenSSH config file", ex);
}
}
}
@Override
public XenonPropertyDescription[] getSupportedProperties() {
return VALID_PROPERTIES.asArray();
}
@Override
public Files filesAdaptor() {
return filesAdaptor;
}
@Override
public Jobs jobsAdaptor() {
return jobsAdaptor;
}
@Override
public Credentials credentialsAdaptor() {
return credentialsAdaptor;
}
@Override
public void end() {
jobsAdaptor.end();
filesAdaptor.end();
}
public ConfigRepository getSshConfig() {
return jsch.getConfigRepository();
}
protected SshMultiplexedSession createNewSession(SshLocation location, Credential credential, XenonProperties properties)
throws XenonException {
return new SshMultiplexedSession(this, jsch, location, credential, properties);
}
protected boolean usingAgent() {
return useAgent;
}
@Override
public Map<String, String> getAdaptorSpecificInformation() {
Map<String,String> result = new HashMap<>(2);
jobsAdaptor.getAdaptorSpecificInformation(result);
return result;
}
}
| src/main/java/nl/esciencecenter/xenon/adaptors/ssh/SshAdaptor.java | /**
* Copyright 2013 Netherlands eScience Center
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.esciencecenter.xenon.adaptors.ssh;
import java.io.File;
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import nl.esciencecenter.xenon.XenonException;
import nl.esciencecenter.xenon.XenonPropertyDescription;
import nl.esciencecenter.xenon.XenonPropertyDescription.Component;
import nl.esciencecenter.xenon.XenonPropertyDescription.Type;
import nl.esciencecenter.xenon.credentials.Credential;
import nl.esciencecenter.xenon.credentials.Credentials;
import nl.esciencecenter.xenon.engine.Adaptor;
import nl.esciencecenter.xenon.engine.XenonEngine;
import nl.esciencecenter.xenon.engine.XenonProperties;
import nl.esciencecenter.xenon.engine.XenonPropertyDescriptionImplementation;
import nl.esciencecenter.xenon.engine.util.ImmutableArray;
import nl.esciencecenter.xenon.files.Files;
import nl.esciencecenter.xenon.jobs.Jobs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.ConfigRepository;
import com.jcraft.jsch.HostKey;
import com.jcraft.jsch.HostKeyRepository;
import com.jcraft.jsch.IdentityRepository;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.agentproxy.AgentProxyException;
import com.jcraft.jsch.agentproxy.Connector;
import com.jcraft.jsch.agentproxy.ConnectorFactory;
import com.jcraft.jsch.agentproxy.RemoteIdentityRepository;
public class SshAdaptor extends Adaptor {
private static final Logger LOGGER = LoggerFactory.getLogger(SshAdaptor.class);
/** The name of this adaptor */
public static final String ADAPTOR_NAME = "ssh";
/** The default SSH port */
protected static final int DEFAULT_PORT = 22;
/** A description of this adaptor */
private static final String ADAPTOR_DESCRIPTION = "The SSH adaptor implements all functionality with remote ssh servers.";
/** The schemes supported by this adaptor */
protected static final ImmutableArray<String> ADAPTOR_SCHEME = new ImmutableArray<>("ssh", "sftp");
/** The locations supported by this adaptor */
private static final ImmutableArray<String> ADAPTOR_LOCATIONS = new ImmutableArray<>("[user@]host[:port]");
/** All our own properties start with this prefix. */
public static final String PREFIX = XenonEngine.ADAPTORS + "ssh.";
/** Enable strict host key checking. */
public static final String STRICT_HOST_KEY_CHECKING = PREFIX + "strictHostKeyChecking";
/** Enable the use of an ssh-agent */
public static final String AGENT = PREFIX + "agent";
/** Enable the use of ssh-agent-forwarding */
public static final String AGENT_FORWARDING = PREFIX + "agentForwarding";
/** Load the known_hosts file by default. */
public static final String LOAD_STANDARD_KNOWN_HOSTS = PREFIX + "loadKnownHosts";
/** Load the OpenSSH config file by default. */
public static final String LOAD_SSH_CONFIG = PREFIX + "loadSshConfig";
/** OpenSSH config filename. */
public static final String SSH_CONFIG_FILE = PREFIX + "sshConfigFile";
/** Enable strict host key checking. */
public static final String AUTOMATICALLY_ADD_HOST_KEY = PREFIX + "autoAddHostKey";
/** Add gateway to access machine. */
public static final String GATEWAY = PREFIX + "gateway";
/** All our own queue properties start with this prefix. */
public static final String QUEUE = PREFIX + "queue.";
/** Maximum history length for finished jobs */
public static final String MAX_HISTORY = QUEUE + "historySize";
/** Property for maximum history length for finished jobs */
public static final String POLLING_DELAY = QUEUE + "pollingDelay";
/** Local multi queue properties start with this prefix. */
public static final String MULTIQ = QUEUE + "multi.";
/** Property for the maximum number of concurrent jobs in the multi queue. */
public static final String MULTIQ_MAX_CONCURRENT = MULTIQ + "maxConcurrentJobs";
/** Ssh adaptor information start with this prefix. */
public static final String INFO = PREFIX + "info.";
/** Ssh job information start with this prefix. */
public static final String JOBS = INFO + "jobs.";
/** How many jobs have been submitted using this adaptor. */
public static final String SUBMITTED = JOBS + "submitted";
/** List of properties supported by this SSH adaptor */
private static final ImmutableArray<XenonPropertyDescription> VALID_PROPERTIES = new ImmutableArray<XenonPropertyDescription>(
new XenonPropertyDescriptionImplementation(AUTOMATICALLY_ADD_HOST_KEY, Type.BOOLEAN, EnumSet.of(Component.SCHEDULER,
Component.FILESYSTEM), "true", "Automatically add unknown host keys to known_hosts."),
new XenonPropertyDescriptionImplementation(STRICT_HOST_KEY_CHECKING, Type.BOOLEAN, EnumSet.of(Component.SCHEDULER,
Component.FILESYSTEM), "true", "Enable strict host key checking."),
new XenonPropertyDescriptionImplementation(LOAD_STANDARD_KNOWN_HOSTS, Type.BOOLEAN, EnumSet.of(Component.XENON),
"true", "Load the standard known_hosts file."),
new XenonPropertyDescriptionImplementation(LOAD_SSH_CONFIG, Type.BOOLEAN, EnumSet.of(Component.XENON),
"true", "Load the OpenSSH config file."),
new XenonPropertyDescriptionImplementation(SSH_CONFIG_FILE, Type.BOOLEAN, EnumSet.of(Component.XENON),
null, "OpenSSH config filename."),
new XenonPropertyDescriptionImplementation(AGENT, Type.BOOLEAN, EnumSet.of(Component.XENON),
"false", "Use a (local) ssh-agent."),
new XenonPropertyDescriptionImplementation(AGENT_FORWARDING, Type.BOOLEAN, EnumSet.of(Component.XENON),
"false", "Use ssh-agent forwarding"),
new XenonPropertyDescriptionImplementation(POLLING_DELAY, Type.LONG, EnumSet.of(Component.SCHEDULER), "1000",
"The polling delay for monitoring running jobs (in milliseconds)."),
new XenonPropertyDescriptionImplementation(MULTIQ_MAX_CONCURRENT, Type.INTEGER, EnumSet.of(Component.SCHEDULER), "4",
"The maximum number of concurrent jobs in the multiq.."),
new XenonPropertyDescriptionImplementation(GATEWAY, Type.STRING, EnumSet.of(Component.SCHEDULER, Component.FILESYSTEM),
null, "The gateway machine used to create an SSH tunnel to the target."));
private final SshFiles filesAdaptor;
private final SshJobs jobsAdaptor;
private final SshCredentials credentialsAdaptor;
private final boolean useAgent;
private JSch jsch;
public SshAdaptor(XenonEngine xenonEngine, Map<String, String> properties) throws XenonException {
this(xenonEngine, new JSch(), properties);
}
public SshAdaptor(XenonEngine xenonEngine, JSch jsch, Map<String, String> properties) throws XenonException {
super(xenonEngine, ADAPTOR_NAME, ADAPTOR_DESCRIPTION, ADAPTOR_SCHEME, ADAPTOR_LOCATIONS, VALID_PROPERTIES,
new XenonProperties(VALID_PROPERTIES, Component.XENON, properties));
this.filesAdaptor = new SshFiles(this, xenonEngine);
this.jobsAdaptor = new SshJobs(getProperties(), this, xenonEngine);
this.credentialsAdaptor = new SshCredentials(this);
this.jsch = jsch;
if (getProperties().getBooleanProperty(SshAdaptor.LOAD_STANDARD_KNOWN_HOSTS)) {
String knownHosts = System.getProperty("user.home") + "/.ssh/known_hosts";
LOGGER.debug("Setting ssh known hosts file to: " + knownHosts);
setKnownHostsFile(knownHosts);
}
if (getProperties().getBooleanProperty(SshAdaptor.LOAD_SSH_CONFIG)) {
String sshConfig = getProperties().getProperty(SshAdaptor.SSH_CONFIG_FILE);
if (sshConfig == null) {
sshConfig = System.getProperty("user.home") + "/.ssh/config";
}
LOGGER.debug("Setting ssh known hosts file to: " + sshConfig);
setConfigFile(sshConfig, !getProperties().propertySet(SshAdaptor.LOAD_SSH_CONFIG));
}
if (getProperties().getBooleanProperty(SshAdaptor.AGENT)) {
// Connect to the local ssh-agent
LOGGER.debug("Connecting to ssh-agent");
Connector connector;
try {
ConnectorFactory cf = ConnectorFactory.getDefault();
connector = cf.createConnector();
} catch(AgentProxyException e){
throw new XenonException(SshAdaptor.ADAPTOR_NAME, "Failed to connect to ssh-agent", e);
}
IdentityRepository ident = new RemoteIdentityRepository(connector);
jsch.setIdentityRepository(ident);
useAgent = true;
} else {
useAgent = false;
}
if (getProperties().getBooleanProperty(SshAdaptor.AGENT_FORWARDING)) {
// Enable ssh-agent-forwarding
LOGGER.warn("TODO: Enabling ssh-agent-forwarding");
}
if (jsch.getConfigRepository() == null) {
jsch.setConfigRepository(ConfigRepository.nullConfig);
}
}
private void setKnownHostsFile(String knownHostsFile) throws XenonException {
try {
jsch.setKnownHosts(knownHostsFile);
} catch (JSchException e) {
throw new XenonException(SshAdaptor.ADAPTOR_NAME, "Could not set known_hosts file", e);
}
if (LOGGER.isDebugEnabled()) {
HostKeyRepository hkr = jsch.getHostKeyRepository();
HostKey[] hks = hkr.getHostKey();
if (hks != null) {
LOGGER.debug("Host keys in " + hkr.getKnownHostsRepositoryID());
for (HostKey hk : hks) {
LOGGER.debug(hk.getHost() + " " + hk.getType() + " " + hk.getFingerPrint(jsch));
}
LOGGER.debug("");
} else {
LOGGER.debug("No keys in " + knownHostsFile);
}
}
}
private void setConfigFile(String sshConfigFile, boolean ignoreFail) throws XenonException {
try {
ConfigRepository configRepository = OpenSSHConfig.parse(new File(sshConfigFile));
jsch.setConfigRepository(configRepository);
} catch (IOException|XenonException ex) {
if (ignoreFail) {
LOGGER.warn("OpenSSH config file cannot be read.");
} else {
throw new XenonException(SshAdaptor.ADAPTOR_NAME, "Cannot read OpenSSH config file", ex);
}
}
}
@Override
public XenonPropertyDescription[] getSupportedProperties() {
return VALID_PROPERTIES.asArray();
}
@Override
public Files filesAdaptor() {
return filesAdaptor;
}
@Override
public Jobs jobsAdaptor() {
return jobsAdaptor;
}
@Override
public Credentials credentialsAdaptor() {
return credentialsAdaptor;
}
@Override
public void end() {
jobsAdaptor.end();
filesAdaptor.end();
}
public ConfigRepository getSshConfig() {
return jsch.getConfigRepository();
}
protected SshMultiplexedSession createNewSession(SshLocation location, Credential credential, XenonProperties properties)
throws XenonException {
return new SshMultiplexedSession(this, jsch, location, credential, properties);
}
protected boolean usingAgent() {
return useAgent;
}
@Override
public Map<String, String> getAdaptorSpecificInformation() {
Map<String,String> result = new HashMap<>(2);
jobsAdaptor.getAdaptorSpecificInformation(result);
return result;
}
}
| Only load known_hosts if it exists or is requested
| src/main/java/nl/esciencecenter/xenon/adaptors/ssh/SshAdaptor.java | Only load known_hosts if it exists or is requested | <ide><path>rc/main/java/nl/esciencecenter/xenon/adaptors/ssh/SshAdaptor.java
<ide> if (getProperties().getBooleanProperty(SshAdaptor.LOAD_STANDARD_KNOWN_HOSTS)) {
<ide> String knownHosts = System.getProperty("user.home") + "/.ssh/known_hosts";
<ide> LOGGER.debug("Setting ssh known hosts file to: " + knownHosts);
<del> setKnownHostsFile(knownHosts);
<add> if (new File(knownHosts).exists()) {
<add> setKnownHostsFile(knownHosts);
<add> } else if (getProperties().propertySet(SshAdaptor.LOAD_STANDARD_KNOWN_HOSTS)) {
<add> // property was explicitly set, throw an error because it does not exist
<add> throw new XenonException(SshAdaptor.ADAPTOR_NAME, "Cannot load known_hosts file: " + knownHosts + " does not exist");
<add> } else {
<add> // implictly ignore
<add> LOGGER.debug("known_hosts file " + knownHosts + " does not exist, not checking hosts with signatures of known hosts.");
<add> }
<ide> }
<ide>
<ide> if (getProperties().getBooleanProperty(SshAdaptor.LOAD_SSH_CONFIG)) { |
|
JavaScript | mit | 08bb0f35a944cd36d8b39584c9ef1338655be189 | 0 | stevekinney/file-bin | 'use strict';
const fs = require('fs');
const path = require('path');
const async = require('async');
const RSVP = require('rsvp');
const filterOutDirectories = require('./lib/filter-out-directories');
function FileBin(baseDirectory, validExtensions) {
if (!(this instanceof FileBin)) {
throw new Error('Must be instantiated with the "new" keyword.');
}
this.base = baseDirectory || __dirname;
this.validExtensions = validExtensions || [];
}
FileBin.prototype.find = function (fileName) {
return new RSVP.Promise((resolve, reject) => {
fs.readFile(path.join(this.base, fileName), (error, file) => {
if (error) { return reject(error); }
return resolve(formatFile(fileName, file));
});
});
};
FileBin.prototype.list = function () {
return new RSVP.Promise((resolve, reject) => {
fs.readdir(this.base, (error, files) => {
if (error) { return reject(error); }
files = filterInvalidExtensions(this, files);
return filterOutDirectories(this.base, files).then(resolve);
});
});
};
FileBin.prototype.all = function () {
return new RSVP.Promise((resolve, reject) => {
this.list().then(fileNames => {
var promises = fileNames.map(this.find, this);
RSVP.all(promises).then(resolve);
}).catch(reject);
});
};
FileBin.prototype.write = function (fileName, data) {
var fullPath = path.join(this.base, fileName);
return new RSVP.Promise((resolve, reject) => {
fs.writeFile(fullPath, data, (error) => {
if (error) { reject(error); }
resolve(formatFile(fileName, data));
});
});
};
FileBin.prototype.destroy = function (fileName) {
return new RSVP.Promise((resolve, reject) => {
fs.unlink(path.join(this.base, fileName), (error) => {
if (error) { return reject(error); }
resolve(true);
});
});
};
function filterInvalidExtensions(instance, files) {
if (!instance.validExtensions.length) { return files; }
return files.filter(file => {
return instance.validExtensions.indexOf(path.extname(file)) !== -1;
});
}
function formatFile(fileName, content) {
return {
id: fileName,
content: content
};
}
module.exports = FileBin;
| index.js | 'use strict';
const fs = require('fs');
const path = require('path');
const async = require('async');
const RSVP = require('rsvp');
const filterOutDirectories = require('./lib/filter-out-directories');
function FileBin(baseDirectory, validExtensions) {
if (!(this instanceof FileBin)) {
throw new Error('Must be instantiated with the "new" keyword.');
}
this.base = baseDirectory || __dirname;
this.validExtensions = validExtensions || [];
}
FileBin.prototype.find = function (fileName) {
return new RSVP.Promise((resolve, reject) => {
fs.readFile(path.join(this.base, fileName), (error, file) => {
if (error) { return reject(error); }
return resolve(formatFile(fileName, file));
});
});
};
FileBin.prototype.list = function () {
return new RSVP.Promise((resolve, reject) => {
fs.readdir(this.base, (error, files) => {
if (error) { return reject(error); }
files = filterInvalidExtensions(this, files);
return filterOutDirectories(this.base, files).then(resolve);
});
});
};
FileBin.prototype.all = function () {
return new RSVP.Promise((resolve, reject) => {
this.list().then(fileNames => {
var promises = fileNames.map(this.find, this);
RSVP.all(promises).then(resolve);
}).catch(reject);
});
};
FileBin.prototype.write = function (fileName, data) {
var fullPath = path.join(this.base, fileName);
return new RSVP.Promise((resolve, reject) => {
fs.writeFile(fullPath, data, (error) => {
if (error) { reject(error); }
resolve(formatFile(fileName, data));
});
});
};
FileBin.prototype.destroy = function (fileName) {
return new RSVP.Promise((resolve, reject) => {
fs.unlink(path.join(this.base, fileName), (error) => {
if (error) { return reject(error); }
resolve(formatFile(fileName));
});
});
};
function filterInvalidExtensions(instance, files) {
if (!instance.validExtensions.length) { return files; }
return files.filter(file => {
return instance.validExtensions.indexOf(path.extname(file)) !== -1;
});
}
function formatFile(fileName, content) {
return {
id: fileName,
content: content
};
}
module.exports = FileBin;
| Updated the destroy method to resolve true instead of the expired path
| index.js | Updated the destroy method to resolve true instead of the expired path | <ide><path>ndex.js
<ide> return new RSVP.Promise((resolve, reject) => {
<ide> fs.unlink(path.join(this.base, fileName), (error) => {
<ide> if (error) { return reject(error); }
<del> resolve(formatFile(fileName));
<add> resolve(true);
<ide> });
<ide> });
<ide> }; |
|
Java | apache-2.0 | 5f7a7f3822553446f54bfd22f95feaab19a64cf0 | 0 | kushalsharma/agera,google/agera | /*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.agera;
import static com.google.android.agera.Observables.updateDispatcher;
import static com.google.android.agera.Preconditions.checkNotNull;
import com.google.android.agera.RepositoryCompilerStates.REventSource;
import android.os.Looper;
import android.support.annotation.NonNull;
/**
* Utility methods for obtaining {@link Repository} instances.
*
* <p>Any {@link Repository} created by this class have to be created from a {@link Looper} thread
* or they will throw an {@link IllegalStateException}
*/
public final class Repositories {
/**
* Returns a static {@link Repository} of the given {@code object}.
*/
@NonNull
public static <T> Repository<T> repository(@NonNull final T object) {
return new SimpleRepository<>(object);
}
/**
* Starts the declaration of a compiled repository. See more at {@link RepositoryCompilerStates}.
*/
@NonNull
public static <T> REventSource<T, T> repositoryWithInitialValue(@NonNull final T initialValue) {
return RepositoryCompiler.repositoryWithInitialValue(initialValue);
}
/**
* Returns a {@link MutableRepository} with the given {@code object} as the initial data.
*/
@NonNull
public static <T> MutableRepository<T> mutableRepository(@NonNull final T object) {
return new SimpleRepository<>(object);
}
private static final class SimpleRepository<T> implements MutableRepository<T> {
@NonNull
private final UpdateDispatcher updateDispatcher;
@NonNull
private T reference;
SimpleRepository(@NonNull final T reference) {
this.updateDispatcher = updateDispatcher();
this.reference = checkNotNull(reference);
}
@NonNull
@Override
public synchronized T get() {
return reference;
}
@Override
public void accept(@NonNull final T reference) {
synchronized (this) {
if (reference.equals(this.reference)) {
// Keep the old reference to have a slight performance edge if GC is generational.
return;
}
this.reference = reference;
}
updateDispatcher.update();
}
@Override
public void addUpdatable(@NonNull final Updatable updatable) {
updateDispatcher.addUpdatable(updatable);
}
@Override
public void removeUpdatable(@NonNull final Updatable updatable) {
updateDispatcher.removeUpdatable(updatable);
}
}
private Repositories() {}
}
| agera/src/main/java/com/google/android/agera/Repositories.java | /*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.agera;
import static com.google.android.agera.Observables.updateDispatcher;
import static com.google.android.agera.Preconditions.checkNotNull;
import com.google.android.agera.RepositoryCompilerStates.REventSource;
import android.os.Looper;
import android.support.annotation.NonNull;
/**
* Utility methods for obtaining {@link Repository} instances.
*
* <p>Any {@link Repository} created by this class have to be created from a {@link Looper} thread
* or they will throw an {@link IllegalStateException}
*/
public final class Repositories {
/**
* Returns a static {@link Repository} of the given {@code object}.
*/
@NonNull
public static <T> Repository<T> repository(@NonNull final T object) {
return new SimpleRepository<>(object);
}
/**
* Starts the declaration of a compiled repository. See more at {@link RepositoryCompilerStates}.
*/
@NonNull
public static <T> REventSource<T, T> repositoryWithInitialValue(@NonNull final T initialValue) {
return RepositoryCompiler.repositoryWithInitialValue(initialValue);
}
/**
* Returns a {@link MutableRepository} with the given {@code object} as the initial data.
*/
@NonNull
public static <T> MutableRepository<T> mutableRepository(@NonNull final T object) {
return new SimpleRepository<>(object);
}
private static final class SimpleRepository<T> implements MutableRepository<T> {
@NonNull
private final UpdateDispatcher updateDispatcher;
@NonNull
private T reference;
SimpleRepository(@NonNull final T reference) {
this.updateDispatcher = updateDispatcher();
this.reference = checkNotNull(reference);
}
@NonNull
@Override
public synchronized T get() {
return reference;
}
@Override
public synchronized void accept(@NonNull final T reference) {
if (reference.equals(this.reference)) {
// Keep the old reference to have a slight performance edge if GC is generational.
return;
}
this.reference = reference;
updateDispatcher.update();
}
@Override
public void addUpdatable(@NonNull final Updatable updatable) {
updateDispatcher.addUpdatable(updatable);
}
@Override
public void removeUpdatable(@NonNull final Updatable updatable) {
updateDispatcher.removeUpdatable(updatable);
}
}
private Repositories() {}
}
| Improved performance on SimpleRepository (#57)
Excluded the update from the lock around reference | agera/src/main/java/com/google/android/agera/Repositories.java | Improved performance on SimpleRepository (#57) | <ide><path>gera/src/main/java/com/google/android/agera/Repositories.java
<ide> }
<ide>
<ide> @Override
<del> public synchronized void accept(@NonNull final T reference) {
<del> if (reference.equals(this.reference)) {
<del> // Keep the old reference to have a slight performance edge if GC is generational.
<del> return;
<add> public void accept(@NonNull final T reference) {
<add> synchronized (this) {
<add> if (reference.equals(this.reference)) {
<add> // Keep the old reference to have a slight performance edge if GC is generational.
<add> return;
<add> }
<add> this.reference = reference;
<ide> }
<del> this.reference = reference;
<ide> updateDispatcher.update();
<ide> }
<ide> |
|
Java | mit | db5fc4a56ad1a622d3064cc90df0000d379a57bd | 0 | 8-Bit-Warframe/Lost-Sector | package com.ezardlabs.lostsector.objects;
import com.ezardlabs.dethsquare.Screen;
import com.ezardlabs.dethsquare.Script;
import com.ezardlabs.dethsquare.Transform;
import com.ezardlabs.dethsquare.Vector2;
public class CameraMovement extends Script {
private FollowType followType;
private Transform target;
private Vector2 offset = new Vector2(-450, 0);
private boolean isQuaking = false;
private long quakeEndPoint = 0;
private float quakeStrength = 0;
enum FollowType {
DIRECT,
SMOOTH
}
public CameraMovement() {
this(null, FollowType.DIRECT);
}
public CameraMovement(Transform target, FollowType followType) {
this.target = target;
this.followType = followType;
}
public void start() {
if (target != null) {
follow(target);
update();
smoothFollow(target);
}
}
public void update() {
if (target != null) {
float x = target.position.x - offset.x;
float y = target.position.y + offset.y;
float cameraX;
if (x < (Screen.width / 2) / Screen.scale) {
cameraX = 0;
} else {
cameraX = x - (Screen.width / 2) / Screen.scale;
}
float cameraY;
if (y < (Screen.height / 2) / Screen.scale) {
cameraY = 0;
} else {
cameraY = y - (Screen.height / 2) / Screen.scale;
}
switch (followType) {
case DIRECT:
transform.position.x = cameraX;
transform.position.y = cameraY;
break;
case SMOOTH:
float dx = cameraX - transform.position.x;
float dy = cameraY - transform.position.y;
double h = Math.sqrt(dx * dx + dy * dy);
float dn = (float) (h / Math.sqrt(2.0D));
if (dn != 0) {
transform.position.x += dx / dn * (dn * 0.04F);
transform.position.y += dy / dn * (dn * 0.2f);
}
break;
default:
break;
}
}
if (isQuaking) updateQuake();
}
public void follow(Transform target) {
followType = FollowType.DIRECT;
this.target = target;
}
public void follow(Transform target, Vector2 offset) {
followType = FollowType.DIRECT;
this.target = target;
this.offset = offset;
}
public void smoothFollow(Transform target) {
followType = FollowType.SMOOTH;
this.target = target;
}
public void smoothFollow(Transform target, Vector2 offset) {
followType = FollowType.SMOOTH;
this.target = target;
this.offset = offset;
}
public void startQuake(long length, float strengthFactor) {
this.quakeStrength = strengthFactor * 3.125f;
this.quakeEndPoint = (System.currentTimeMillis() + length);
this.isQuaking = true;
}
private void updateQuake() {
transform.position.x += (int) (35.0F * this.quakeStrength - Math.random() * 70.0D * this.quakeStrength);
transform.position.y += (int) (35.0F * this.quakeStrength - Math.random() * 70.0D * this.quakeStrength);
if (System.currentTimeMillis() >= this.quakeEndPoint) {
this.isQuaking = false;
}
}
}
| src/main/java/com/ezardlabs/lostsector/objects/CameraMovement.java | package com.ezardlabs.lostsector.objects;
import com.ezardlabs.dethsquare.Screen;
import com.ezardlabs.dethsquare.Script;
import com.ezardlabs.dethsquare.Transform;
import com.ezardlabs.dethsquare.Vector2;
public class CameraMovement extends Script {
private int followType = 0;
private Transform target;
private Vector2 offset = new Vector2(-450, 0);
private boolean isQuaking = false;
private long quakeEndPoint = 0;
private float quakeStrength = 0;
public void start() {
if (target != null) {
follow(target);
update();
smoothFollow(target);
}
}
public void update() {
if (target != null) {
float x = target.position.x - offset.x;
float y = target.position.y + offset.y;
float cameraX;
if (x < (Screen.width / 2) / Screen.scale) {
cameraX = 0;
} else {
cameraX = x - (Screen.width / 2) / Screen.scale;
}
float cameraY;
if (y < (Screen.height / 2) / Screen.scale) {
cameraY = 0;
} else {
cameraY = y - (Screen.height / 2) / Screen.scale;
}
switch (followType) {
case 1:
transform.position.x = cameraX;
transform.position.y = cameraY;
break;
case 2:
float dx = cameraX - transform.position.x;
float dy = cameraY - transform.position.y;
double h = Math.sqrt(dx * dx + dy * dy);
float dn = (float) (h / Math.sqrt(2.0D));
if (dn != 0) {
transform.position.x += dx / dn * (dn * 0.04F);
transform.position.y += dy / dn * (dn * 0.2f);
}
break;
default:
break;
}
}
if (isQuaking) updateQuake();
}
public void follow(Transform target) {
followType = 1;
this.target = target;
}
public void follow(Transform target, Vector2 offset) {
followType = 1;
this.target = target;
this.offset = offset;
}
public void smoothFollow(Transform target) {
followType = 2;
this.target = target;
}
public void smoothFollow(Transform target, Vector2 offset) {
followType = 2;
this.target = target;
this.offset = offset;
}
public void startQuake(long length, float strengthFactor) {
this.quakeStrength = strengthFactor * 3.125f;
this.quakeEndPoint = (System.currentTimeMillis() + length);
this.isQuaking = true;
}
private void updateQuake() {
transform.position.x += (int) (35.0F * this.quakeStrength - Math.random() * 70.0D * this.quakeStrength);
transform.position.y += (int) (35.0F * this.quakeStrength - Math.random() * 70.0D * this.quakeStrength);
if (System.currentTimeMillis() >= this.quakeEndPoint) {
this.isQuaking = false;
}
}
}
| Allow camera follow type to be specified in the constructor
| src/main/java/com/ezardlabs/lostsector/objects/CameraMovement.java | Allow camera follow type to be specified in the constructor | <ide><path>rc/main/java/com/ezardlabs/lostsector/objects/CameraMovement.java
<ide> import com.ezardlabs.dethsquare.Vector2;
<ide>
<ide> public class CameraMovement extends Script {
<del> private int followType = 0;
<add> private FollowType followType;
<ide> private Transform target;
<ide> private Vector2 offset = new Vector2(-450, 0);
<ide> private boolean isQuaking = false;
<ide> private long quakeEndPoint = 0;
<ide> private float quakeStrength = 0;
<add>
<add> enum FollowType {
<add> DIRECT,
<add> SMOOTH
<add> }
<add>
<add> public CameraMovement() {
<add> this(null, FollowType.DIRECT);
<add> }
<add>
<add> public CameraMovement(Transform target, FollowType followType) {
<add> this.target = target;
<add> this.followType = followType;
<add> }
<ide>
<ide> public void start() {
<ide> if (target != null) {
<ide> cameraY = y - (Screen.height / 2) / Screen.scale;
<ide> }
<ide> switch (followType) {
<del> case 1:
<add> case DIRECT:
<ide> transform.position.x = cameraX;
<ide> transform.position.y = cameraY;
<ide> break;
<del> case 2:
<add> case SMOOTH:
<ide> float dx = cameraX - transform.position.x;
<ide> float dy = cameraY - transform.position.y;
<ide> double h = Math.sqrt(dx * dx + dy * dy);
<ide> }
<ide>
<ide> public void follow(Transform target) {
<del> followType = 1;
<add> followType = FollowType.DIRECT;
<ide> this.target = target;
<ide> }
<ide>
<ide> public void follow(Transform target, Vector2 offset) {
<del> followType = 1;
<add> followType = FollowType.DIRECT;
<ide> this.target = target;
<ide> this.offset = offset;
<ide> }
<ide>
<ide> public void smoothFollow(Transform target) {
<del> followType = 2;
<add> followType = FollowType.SMOOTH;
<ide> this.target = target;
<ide> }
<ide>
<ide> public void smoothFollow(Transform target, Vector2 offset) {
<del> followType = 2;
<add> followType = FollowType.SMOOTH;
<ide> this.target = target;
<ide> this.offset = offset;
<ide> } |
|
Java | mit | 82235d9fd120aae20f68d9cd236587ba86a30f44 | 0 | classgraph/classgraph,lukehutch/fast-classpath-scanner,lukehutch/fast-classpath-scanner | /*
* This file is part of ClassGraph.
*
* Author: Luke Hutchison
*
* Hosted at: https://github.com/classgraph/classgraph
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Luke Hutchison
*
* 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 io.github.classgraph;
import java.io.File;
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import io.github.classgraph.Classfile.ClassContainment;
import nonapi.io.github.classgraph.json.Id;
import nonapi.io.github.classgraph.scanspec.ScanSpec;
import nonapi.io.github.classgraph.types.ParseException;
import nonapi.io.github.classgraph.types.TypeUtils;
import nonapi.io.github.classgraph.types.TypeUtils.ModifierType;
/** Holds metadata about a class encountered during a scan. */
public class ClassInfo extends ScanResultObject implements Comparable<ClassInfo>, HasName {
/** The name of the class. */
@Id
protected String name;
/** Class modifier flags, e.g. Modifier.PUBLIC */
private int modifiers;
/**
* This annotation has the {@link Inherited} meta-annotation, which means that any class that this annotation is
* applied to also implicitly causes the annotation to annotate all subclasses too.
*/
boolean isInherited;
/** The class type signature string. */
protected String typeSignatureStr;
/** The class type signature, parsed. */
private transient ClassTypeSignature typeSignature;
/** The fully-qualified defining method name, for anonymous inner classes. */
private String fullyQualifiedDefiningMethodName;
/**
* If true, this class is only being referenced by another class' classfile as a superclass / implemented
* interface / annotation, but this class is not itself a whitelisted (non-blacklisted) class, or in a
* whitelisted (non-blacklisted) package.
*
* If false, this classfile was matched during scanning (i.e. its classfile contents read), i.e. this class is a
* whitelisted (and non-blacklisted) class in a whitelisted (and non-blacklisted) package.
*/
protected boolean isExternalClass = true;
/**
* Set to true when the class is actually scanned (as opposed to just referenced as a superclass, interface or
* annotation of a scanned class).
*/
protected boolean isScannedClass;
/** The classpath element that this class was found within. */
transient ClasspathElement classpathElement;
/** The {@link Resource} for the classfile of this class. */
protected transient Resource classfileResource;
/** The classloader this class was obtained from. */
transient ClassLoader classLoader;
/** Info on the class module. */
ModuleInfo moduleInfo;
/** Info on the package containing the class. */
PackageInfo packageInfo;
/** Info on class annotations, including optional annotation param values. */
AnnotationInfoList annotationInfo;
/** Info on fields. */
FieldInfoList fieldInfo;
/** Info on fields. */
MethodInfoList methodInfo;
/** For annotations, the default values of parameters. */
AnnotationParameterValueList annotationDefaultParamValues;
/**
* Names of classes referenced by this class in class refs and type signatures in the constant pool of the
* classfile.
*/
private Set<String> referencedClassNames;
/** A list of ClassInfo objects for classes referenced by this class. */
private ClassInfoList referencedClasses;
/**
* Set to true once any Object[] arrays of boxed types in annotationDefaultParamValues have been lazily
* converted to primitive arrays.
*/
transient boolean annotationDefaultParamValuesHasBeenConvertedToPrimitive;
/** The set of classes related to this one. */
private Map<RelType, Set<ClassInfo>> relatedClasses;
/**
* The override order for a class' fields or methods (base class, followed by interfaces, followed by
* superclasses).
*/
private transient List<ClassInfo> overrideOrder;
// -------------------------------------------------------------------------------------------------------------
/** The modifier bit for annotations. */
private static final int ANNOTATION_CLASS_MODIFIER = 0x2000;
/** The constant empty return value used when no classes are reachable. */
private static final ReachableAndDirectlyRelatedClasses NO_REACHABLE_CLASSES = //
new ReachableAndDirectlyRelatedClasses(Collections.<ClassInfo> emptySet(),
Collections.<ClassInfo> emptySet());
// -------------------------------------------------------------------------------------------------------------
/** Default constructor for deserialization. */
ClassInfo() {
super();
}
/**
* Constructor.
*
* @param name
* the name
* @param classModifiers
* the class modifiers
* @param classfileResource
* the classfile resource
*/
protected ClassInfo(final String name, final int classModifiers, final Resource classfileResource) {
super();
this.name = name;
if (name.endsWith(";")) {
// Spot check to make sure class names were parsed from descriptors
throw new IllegalArgumentException("Bad class name");
}
setModifiers(classModifiers);
this.classfileResource = classfileResource;
this.relatedClasses = new EnumMap<>(RelType.class);
}
// -------------------------------------------------------------------------------------------------------------
/** How classes are related. */
enum RelType {
// Classes:
/**
* Superclasses of this class, if this is a regular class.
*
* <p>
* (Should consist of only one entry, or null if superclass is java.lang.Object or unknown).
*/
SUPERCLASSES,
/** Subclasses of this class, if this is a regular class. */
SUBCLASSES,
/** Indicates that an inner class is contained within this one. */
CONTAINS_INNER_CLASS,
/** Indicates that an outer class contains this one. (Should only have zero or one entries.) */
CONTAINED_WITHIN_OUTER_CLASS,
// Interfaces:
/**
* Interfaces that this class implements, if this is a regular class, or superinterfaces, if this is an
* interface.
*
* <p>
* (May also include annotations, since annotations are interfaces, so you can implement an annotation.)
*/
IMPLEMENTED_INTERFACES,
/**
* Classes that implement this interface (including sub-interfaces), if this is an interface.
*/
CLASSES_IMPLEMENTING,
// Class annotations:
/**
* Annotations on this class, if this is a regular class, or meta-annotations on this annotation, if this is
* an annotation.
*/
CLASS_ANNOTATIONS,
/** Classes annotated with this annotation, if this is an annotation. */
CLASSES_WITH_ANNOTATION,
// Method annotations:
/** Annotations on one or more methods of this class. */
METHOD_ANNOTATIONS,
/**
* Classes that have one or more methods annotated with this annotation, if this is an annotation.
*/
CLASSES_WITH_METHOD_ANNOTATION,
/**
* Classes that have one or more non-private (inherited) methods annotated with this annotation, if this is
* an annotation.
*/
CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION,
/** Annotations on one or more parameters of methods of this class. */
METHOD_PARAMETER_ANNOTATIONS,
/**
* Classes that have one or more methods that have one or more parameters annotated with this annotation, if
* this is an annotation.
*/
CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,
/**
* Classes that have one or more non-private (inherited) methods that have one or more parameters annotated
* with this annotation, if this is an annotation.
*/
CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION,
// Field annotations:
/** Annotations on one or more fields of this class. */
FIELD_ANNOTATIONS,
/**
* Classes that have one or more fields annotated with this annotation, if this is an annotation.
*/
CLASSES_WITH_FIELD_ANNOTATION,
/**
* Classes that have one or more non-private (inherited) fields annotated with this annotation, if this is
* an annotation.
*/
CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION,
}
/**
* Add a class with a given relationship type. Return whether the collection changed as a result of the call.
*
* @param relType
* the {@link RelType}
* @param classInfo
* the {@link ClassInfo}
* @return true, if successful
*/
boolean addRelatedClass(final RelType relType, final ClassInfo classInfo) {
Set<ClassInfo> classInfoSet = relatedClasses.get(relType);
if (classInfoSet == null) {
relatedClasses.put(relType, classInfoSet = new LinkedHashSet<>(4));
}
return classInfoSet.add(classInfo);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get a ClassInfo object, or create it if it doesn't exist. N.B. not threadsafe, so ClassInfo objects should
* only ever be constructed by a single thread.
*
* @param className
* the class name
* @param classNameToClassInfo
* the map from class name to class info
* @return the {@link ClassInfo} object.
*/
static ClassInfo getOrCreateClassInfo(final String className,
final Map<String, ClassInfo> classNameToClassInfo) {
// Look for array class names
int numArrayDims = 0;
String baseClassName = className;
while (baseClassName.endsWith("[]")) {
numArrayDims++;
baseClassName = baseClassName.substring(0, baseClassName.length() - 2);
}
// Be resilient to the use of class descriptors rather than class names (should not be needed)
while (baseClassName.startsWith("[")) {
numArrayDims++;
baseClassName = baseClassName.substring(1);
}
if (baseClassName.endsWith(";")) {
baseClassName = baseClassName.substring(baseClassName.length() - 1);
}
baseClassName = baseClassName.replace('/', '.');
ClassInfo classInfo = classNameToClassInfo.get(className);
if (classInfo == null) {
classNameToClassInfo.put(className, //
classInfo = numArrayDims == 0 //
? new ClassInfo(baseClassName, /* classModifiers = */ 0, /* classfileResource = */ null)
: new ArrayClassInfo(new ArrayTypeSignature(baseClassName, numArrayDims)));
}
return classInfo;
}
/**
* Set class modifiers.
*
* @param modifiers
* the class modifiers
*/
void setModifiers(final int modifiers) {
this.modifiers |= modifiers;
}
/**
* Set isInterface status.
*
* @param isInterface
* true if this is an interface
*/
void setIsInterface(final boolean isInterface) {
if (isInterface) {
this.modifiers |= Modifier.INTERFACE;
}
}
/**
* Set isInterface status.
*
* @param isAnnotation
* true if this is an annotation
*/
void setIsAnnotation(final boolean isAnnotation) {
if (isAnnotation) {
this.modifiers |= ANNOTATION_CLASS_MODIFIER;
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Add a superclass to this class.
*
* @param superclassName
* the superclass name
* @param classNameToClassInfo
* the map from class name to class info
*/
void addSuperclass(final String superclassName, final Map<String, ClassInfo> classNameToClassInfo) {
if (superclassName != null && !superclassName.equals("java.lang.Object")) {
final ClassInfo superclassClassInfo = getOrCreateClassInfo(superclassName, classNameToClassInfo);
this.addRelatedClass(RelType.SUPERCLASSES, superclassClassInfo);
superclassClassInfo.addRelatedClass(RelType.SUBCLASSES, this);
}
}
/**
* Add an implemented interface to this class.
*
* @param interfaceName
* the interface name
* @param classNameToClassInfo
* the map from class name to class info
*/
void addImplementedInterface(final String interfaceName, final Map<String, ClassInfo> classNameToClassInfo) {
final ClassInfo interfaceClassInfo = getOrCreateClassInfo(interfaceName, classNameToClassInfo);
interfaceClassInfo.setIsInterface(true);
this.addRelatedClass(RelType.IMPLEMENTED_INTERFACES, interfaceClassInfo);
interfaceClassInfo.addRelatedClass(RelType.CLASSES_IMPLEMENTING, this);
}
/**
* Add class containment info.
*
* @param classContainmentEntries
* the class containment entries
* @param classNameToClassInfo
* the map from class name to class info
*/
static void addClassContainment(final List<ClassContainment> classContainmentEntries,
final Map<String, ClassInfo> classNameToClassInfo) {
for (final ClassContainment classContainment : classContainmentEntries) {
final ClassInfo innerClassInfo = ClassInfo.getOrCreateClassInfo(classContainment.innerClassName,
classNameToClassInfo);
innerClassInfo.setModifiers(classContainment.innerClassModifierBits);
final ClassInfo outerClassInfo = ClassInfo.getOrCreateClassInfo(classContainment.outerClassName,
classNameToClassInfo);
innerClassInfo.addRelatedClass(RelType.CONTAINED_WITHIN_OUTER_CLASS, outerClassInfo);
outerClassInfo.addRelatedClass(RelType.CONTAINS_INNER_CLASS, innerClassInfo);
}
}
/**
* Add containing method name, for anonymous inner classes.
*
* @param fullyQualifiedDefiningMethodName
* the fully qualified defining method name
*/
void addFullyQualifiedDefiningMethodName(final String fullyQualifiedDefiningMethodName) {
this.fullyQualifiedDefiningMethodName = fullyQualifiedDefiningMethodName;
}
/**
* Add an annotation to this class.
*
* @param classAnnotationInfo
* the class annotation info
* @param classNameToClassInfo
* the map from class name to class info
*/
void addClassAnnotation(final AnnotationInfo classAnnotationInfo,
final Map<String, ClassInfo> classNameToClassInfo) {
final ClassInfo annotationClassInfo = getOrCreateClassInfo(classAnnotationInfo.getName(),
classNameToClassInfo);
annotationClassInfo.setModifiers(ANNOTATION_CLASS_MODIFIER);
if (this.annotationInfo == null) {
this.annotationInfo = new AnnotationInfoList(2);
}
this.annotationInfo.add(classAnnotationInfo);
this.addRelatedClass(RelType.CLASS_ANNOTATIONS, annotationClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_ANNOTATION, this);
// Record use of @Inherited meta-annotation
if (classAnnotationInfo.getName().equals(Inherited.class.getName())) {
isInherited = true;
}
}
/**
* Add field or method annotation cross-links.
*
* @param annotationInfoList
* the annotation info list
* @param isField
* the is field
* @param modifiers
* the field or method modifiers
* @param classNameToClassInfo
* the map from class name to class info
*/
private void addFieldOrMethodAnnotationInfo(final AnnotationInfoList annotationInfoList, final boolean isField,
final int modifiers, final Map<String, ClassInfo> classNameToClassInfo) {
if (annotationInfoList != null) {
for (final AnnotationInfo fieldAnnotationInfo : annotationInfoList) {
final ClassInfo annotationClassInfo = getOrCreateClassInfo(fieldAnnotationInfo.getName(),
classNameToClassInfo);
annotationClassInfo.setModifiers(ANNOTATION_CLASS_MODIFIER);
// Mark this class as having a field or method with this annotation
this.addRelatedClass(isField ? RelType.FIELD_ANNOTATIONS : RelType.METHOD_ANNOTATIONS,
annotationClassInfo);
annotationClassInfo.addRelatedClass(
isField ? RelType.CLASSES_WITH_FIELD_ANNOTATION : RelType.CLASSES_WITH_METHOD_ANNOTATION,
this);
// For non-private methods/fields, also add to nonprivate (inherited) mapping
if (!Modifier.isPrivate(modifiers)) {
annotationClassInfo.addRelatedClass(isField ? RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION
: RelType.CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION, this);
}
}
}
}
/**
* Add field info.
*
* @param fieldInfoList
* the field info list
* @param classNameToClassInfo
* the map from class name to class info
*/
void addFieldInfo(final FieldInfoList fieldInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final FieldInfo fi : fieldInfoList) {
// Index field annotations
addFieldOrMethodAnnotationInfo(fi.annotationInfo, /* isField = */ true, fi.getModifiers(),
classNameToClassInfo);
}
if (this.fieldInfo == null) {
this.fieldInfo = fieldInfoList;
} else {
this.fieldInfo.addAll(fieldInfoList);
}
}
/**
* Add method info.
*
* @param methodInfoList
* the method info list
* @param classNameToClassInfo
* the map from class name to class info
*/
void addMethodInfo(final MethodInfoList methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final MethodInfo mi : methodInfoList) {
// Index method annotations
addFieldOrMethodAnnotationInfo(mi.annotationInfo, /* isField = */ false, mi.getModifiers(),
classNameToClassInfo);
// Index method parameter annotations
if (mi.parameterAnnotationInfo != null) {
for (int i = 0; i < mi.parameterAnnotationInfo.length; i++) {
final AnnotationInfo[] paramAnnotationInfoArr = mi.parameterAnnotationInfo[i];
if (paramAnnotationInfoArr != null) {
for (int j = 0; j < paramAnnotationInfoArr.length; j++) {
final AnnotationInfo methodParamAnnotationInfo = paramAnnotationInfoArr[j];
final ClassInfo annotationClassInfo = getOrCreateClassInfo(
methodParamAnnotationInfo.getName(), classNameToClassInfo);
annotationClassInfo.setModifiers(ANNOTATION_CLASS_MODIFIER);
this.addRelatedClass(RelType.METHOD_PARAMETER_ANNOTATIONS, annotationClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,
this);
// For non-private methods/fields, also add to nonprivate (inherited) mapping
if (!Modifier.isPrivate(mi.getModifiers())) {
annotationClassInfo.addRelatedClass(
RelType.CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION, this);
}
}
}
}
}
}
if (this.methodInfo == null) {
this.methodInfo = methodInfoList;
} else {
this.methodInfo.addAll(methodInfoList);
}
}
/**
* Set the class type signature, including any type params.
*
* @param typeSignatureStr
* the type signature str
*/
void setTypeSignature(final String typeSignatureStr) {
this.typeSignatureStr = typeSignatureStr;
}
/**
* Add annotation default values. (Only called in the case of annotation class definitions, when the annotation
* has default parameter values.)
*
* @param paramNamesAndValues
* the default param names and values, if this is an annotation
*/
void addAnnotationParamDefaultValues(final AnnotationParameterValueList paramNamesAndValues) {
setIsAnnotation(true);
if (this.annotationDefaultParamValues == null) {
this.annotationDefaultParamValues = paramNamesAndValues;
} else {
this.annotationDefaultParamValues.addAll(paramNamesAndValues);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Add a class that has just been scanned (as opposed to just referenced by a scanned class). Not threadsafe,
* should be run in single threaded context.
*
* @param className
* the class name
* @param classModifiers
* the class modifiers
* @param isExternalClass
* true if this is an external class
* @param classNameToClassInfo
* the map from class name to class info
* @param classpathElement
* the classpath element
* @param classfileResource
* the classfile resource
* @return the class info
*/
static ClassInfo addScannedClass(final String className, final int classModifiers,
final boolean isExternalClass, final Map<String, ClassInfo> classNameToClassInfo,
final ClasspathElement classpathElement, final Resource classfileResource) {
ClassInfo classInfo = classNameToClassInfo.get(className);
if (classInfo == null) {
// This is the first time this class has been seen, add it
classNameToClassInfo.put(className,
classInfo = new ClassInfo(className, classModifiers, classfileResource));
} else {
// There was a previous placeholder ClassInfo class added, due to the class being referred
// to as a superclass, interface or annotation. The isScannedClass field should be false
// in this case, since the actual class definition wasn't reached before now.
if (classInfo.isScannedClass) {
// The class should not have been scanned more than once, because of classpath masking
throw new IllegalArgumentException("Class " + className
+ " should not have been encountered more than once due to classpath masking --"
+ " please report this bug at: https://github.com/classgraph/classgraph/issues");
}
// Set the classfileResource for the placeholder class
classInfo.classfileResource = classfileResource;
// Add any additional modifier bits
classInfo.modifiers |= classModifiers;
}
// Mark the class as scanned
classInfo.isScannedClass = true;
// Mark the class as non-external if it is a whitelisted class
classInfo.isExternalClass = isExternalClass;
// Remember which classpath element (zipfile / classpath root directory / module) the class was found in
classInfo.classpathElement = classpathElement;
// Remember which classloader is used to load the class
classInfo.classLoader = classpathElement.getClassLoader();
return classInfo;
}
// -------------------------------------------------------------------------------------------------------------
/** The class type to return. */
private enum ClassType {
/** Get all class types. */
ALL,
/** A standard class (not an interface or annotation). */
STANDARD_CLASS,
/**
* An interface (this is named "implemented interface" rather than just "interface" to distinguish it from
* an annotation.)
*/
IMPLEMENTED_INTERFACE,
/** An annotation. */
ANNOTATION,
/** An interface or annotation (used since you can actually implement an annotation). */
INTERFACE_OR_ANNOTATION,
}
/**
* Filter classes according to scan spec and class type.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @param strictWhitelist
* If true, exclude class if it is is external, blacklisted, or a system class.
* @param classTypes
* the class types
* @return the filtered classes.
*/
private static Set<ClassInfo> filterClassInfo(final Collection<ClassInfo> classes, final ScanSpec scanSpec,
final boolean strictWhitelist, final ClassType... classTypes) {
if (classes == null) {
return Collections.<ClassInfo> emptySet();
}
boolean includeAllTypes = classTypes.length == 0;
boolean includeStandardClasses = false;
boolean includeImplementedInterfaces = false;
boolean includeAnnotations = false;
for (final ClassType classType : classTypes) {
switch (classType) {
case ALL:
includeAllTypes = true;
break;
case STANDARD_CLASS:
includeStandardClasses = true;
break;
case IMPLEMENTED_INTERFACE:
includeImplementedInterfaces = true;
break;
case ANNOTATION:
includeAnnotations = true;
break;
case INTERFACE_OR_ANNOTATION:
includeImplementedInterfaces = includeAnnotations = true;
break;
default:
throw new IllegalArgumentException("Unknown ClassType: " + classType);
}
}
if (includeStandardClasses && includeImplementedInterfaces && includeAnnotations) {
includeAllTypes = true;
}
final Set<ClassInfo> classInfoSetFiltered = new LinkedHashSet<>(classes.size());
for (final ClassInfo classInfo : classes) {
// Check class type against requested type(s)
if ((includeAllTypes //
|| includeStandardClasses && classInfo.isStandardClass()
|| includeImplementedInterfaces && classInfo.isImplementedInterface()
|| includeAnnotations && classInfo.isAnnotation()) //
// Always check blacklist
&& !scanSpec.classOrPackageIsBlacklisted(classInfo.name) //
// Always return whitelisted classes, or external classes if enableExternalClasses is true
&& (!classInfo.isExternalClass || scanSpec.enableExternalClasses
// Return external (non-whitelisted) classes if viewing class hierarchy "upwards"
|| !strictWhitelist)) {
// Class passed strict whitelist criteria
classInfoSetFiltered.add(classInfo);
}
}
return classInfoSetFiltered;
}
/**
* A set of classes that indirectly reachable through a directed path, for a given relationship type, and a set
* of classes that is directly related (only one relationship step away).
*/
static class ReachableAndDirectlyRelatedClasses {
/** The reachable classes. */
final Set<ClassInfo> reachableClasses;
/** The directly related classes. */
final Set<ClassInfo> directlyRelatedClasses;
/**
* Constructor.
*
* @param reachableClasses
* the reachable classes
* @param directlyRelatedClasses
* the directly related classes
*/
private ReachableAndDirectlyRelatedClasses(final Set<ClassInfo> reachableClasses,
final Set<ClassInfo> directlyRelatedClasses) {
this.reachableClasses = reachableClasses;
this.directlyRelatedClasses = directlyRelatedClasses;
}
}
/**
* Get the classes related to this one (the transitive closure) for the given relationship type, and those
* directly related.
*
* @param relType
* the rel type
* @param strictWhitelist
* the strict whitelist
* @param classTypes
* the class types
* @return the reachable and directly related classes
*/
private ReachableAndDirectlyRelatedClasses filterClassInfo(final RelType relType, final boolean strictWhitelist,
final ClassType... classTypes) {
Set<ClassInfo> directlyRelatedClasses = this.relatedClasses.get(relType);
if (directlyRelatedClasses == null) {
return NO_REACHABLE_CLASSES;
} else {
// Clone collection to prevent users modifying contents accidentally or intentionally
directlyRelatedClasses = new LinkedHashSet<>(directlyRelatedClasses);
}
final Set<ClassInfo> reachableClasses = new LinkedHashSet<>(directlyRelatedClasses);
if (relType == RelType.METHOD_ANNOTATIONS || relType == RelType.METHOD_PARAMETER_ANNOTATIONS
|| relType == RelType.FIELD_ANNOTATIONS) {
// For method and field annotations, need to change the RelType when finding meta-annotations
for (final ClassInfo annotation : directlyRelatedClasses) {
reachableClasses.addAll(
annotation.filterClassInfo(RelType.CLASS_ANNOTATIONS, strictWhitelist).reachableClasses);
}
} else if (relType == RelType.CLASSES_WITH_METHOD_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION
|| relType == RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION
|| relType == RelType.CLASSES_WITH_FIELD_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION) {
// If looking for meta-annotated methods or fields, need to find all meta-annotated annotations, then
// look for the methods or fields that they annotate
for (final ClassInfo subAnnotation : this.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION,
strictWhitelist, ClassType.ANNOTATION).reachableClasses) {
final Set<ClassInfo> annotatedClasses = subAnnotation.relatedClasses.get(relType);
if (annotatedClasses != null) {
reachableClasses.addAll(annotatedClasses);
}
}
} else {
// For other relationship types, the reachable type stays the same over the transitive closure. Find the
// transitive closure, breaking cycles where necessary.
final LinkedList<ClassInfo> queue = new LinkedList<>(directlyRelatedClasses);
while (!queue.isEmpty()) {
final ClassInfo head = queue.removeFirst();
final Set<ClassInfo> headRelatedClasses = head.relatedClasses.get(relType);
if (headRelatedClasses != null) {
for (final ClassInfo directlyReachableFromHead : headRelatedClasses) {
// Don't get in cycle
if (reachableClasses.add(directlyReachableFromHead)) {
queue.add(directlyReachableFromHead);
}
}
}
}
}
if (reachableClasses.isEmpty()) {
return NO_REACHABLE_CLASSES;
}
if (relType == RelType.CLASS_ANNOTATIONS || relType == RelType.METHOD_ANNOTATIONS
|| relType == RelType.METHOD_PARAMETER_ANNOTATIONS || relType == RelType.FIELD_ANNOTATIONS) {
// Special case -- don't inherit java.lang.annotation.* meta-annotations as related meta-annotations
// (but still return them as direct meta-annotations on annotation classes).
Set<ClassInfo> reachableClassesToRemove = null;
for (final ClassInfo reachableClassInfo : reachableClasses) {
// Remove all java.lang.annotation annotations that are not directly related to this class
if (reachableClassInfo.getName().startsWith("java.lang.annotation.")
&& !directlyRelatedClasses.contains(reachableClassInfo)) {
if (reachableClassesToRemove == null) {
reachableClassesToRemove = new LinkedHashSet<>();
}
reachableClassesToRemove.add(reachableClassInfo);
}
}
if (reachableClassesToRemove != null) {
reachableClasses.removeAll(reachableClassesToRemove);
}
}
return new ReachableAndDirectlyRelatedClasses(
filterClassInfo(reachableClasses, scanResult.scanSpec, strictWhitelist, classTypes),
filterClassInfo(directlyRelatedClasses, scanResult.scanSpec, strictWhitelist, classTypes));
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get all classes found during the scan.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) {
return new ClassInfoList(
ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.ALL),
/* sortByName = */ true);
}
/**
* Get all standard classes found during the scan.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all standard classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllStandardClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) {
return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true,
ClassType.STANDARD_CLASS), /* sortByName = */ true);
}
/**
* Get all implemented interface (non-annotation interface) classes found during the scan.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all annotation classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllImplementedInterfaceClasses(final Collection<ClassInfo> classes,
final ScanSpec scanSpec) {
return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true,
ClassType.IMPLEMENTED_INTERFACE), /* sortByName = */ true);
}
/**
* Get all annotation classes found during the scan. See also
* {@link #getAllInterfacesOrAnnotationClasses(Collection, ScanSpec, ScanResult)} ()}.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all annotation classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllAnnotationClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) {
return new ClassInfoList(
ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.ANNOTATION),
/* sortByName = */ true);
}
/**
* Get all interface or annotation classes found during the scan. (Annotations are technically interfaces, and
* they can be implemented.)
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all whitelisted interfaces found during the scan, or the empty list if none.
*/
static ClassInfoList getAllInterfacesOrAnnotationClasses(final Collection<ClassInfo> classes,
final ScanSpec scanSpec) {
return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true,
ClassType.INTERFACE_OR_ANNOTATION), /* sortByName = */ true);
}
// -------------------------------------------------------------------------------------------------------------
// Predicates
/**
* Get the name of the class.
*
* @return The name of the class.
*/
@Override
public String getName() {
return name;
}
/**
* Get simple name from fully-qualified class name. Returns everything after the last '.' in the class name, or
* the whole string if the class is in the root package. (Note that this is not the same as the result of
* {@link Class#getSimpleName()}, which returns "" for anonymous classes.)
*
* @param className
* the class name
* @return The simple name of the class.
*/
static String getSimpleName(final String className) {
return className.substring(className.lastIndexOf('.') + 1);
}
/**
* Get the simple name of the class. Returns everything after the last '.' in the class name, or the whole
* string if the class is in the root package. (Note that this is not the same as the result of
* {@link Class#getSimpleName()}, which returns "" for anonymous classes.)
*
* @return The simple name of the class.
*/
public String getSimpleName() {
return getSimpleName(name);
}
/**
* Get the {@link ModuleInfo} object for the class.
*
* @return the {@link ModuleInfo} object for the class, or null if the class is not part of a named module.
*/
public ModuleInfo getModuleInfo() {
return moduleInfo;
}
/**
* Get the {@link PackageInfo} object for the class.
*
* @return the {@link PackageInfo} object for the package that contains the class.
*/
public PackageInfo getPackageInfo() {
return packageInfo;
}
/**
* Get the name of the class' package.
*
* @return The name of the class' package.
*/
public String getPackageName() {
return PackageInfo.getParentPackageName(name);
}
/**
* Checks if this is an external class.
*
* @return true if this class is an external class, i.e. was referenced by a whitelisted class as a superclass,
* interface, or annotation, but is not itself a whitelisted class.
*/
public boolean isExternalClass() {
return isExternalClass;
}
/**
* Get the class modifier bits.
*
* @return The class modifier bits, e.g. {@link Modifier#PUBLIC}.
*/
public int getModifiers() {
return modifiers;
}
/**
* Get the class modifiers as a String.
*
* @return The field modifiers as a string, e.g. "public static final". For the modifier bits, call
* {@link #getModifiers()}.
*/
public String getModifiersStr() {
final StringBuilder buf = new StringBuilder();
TypeUtils.modifiersToString(modifiers, ModifierType.CLASS, /* ignored */ false, buf);
return buf.toString();
}
/**
* Checks if the class is public.
*
* @return true if this class is a public class.
*/
public boolean isPublic() {
return (modifiers & Modifier.PUBLIC) != 0;
}
/**
* Checks if the class is abstract.
*
* @return true if this class is an abstract class.
*/
public boolean isAbstract() {
return (modifiers & 0x400) != 0;
}
/**
* Checks if the class is synthetic.
*
* @return true if this class is a synthetic class.
*/
public boolean isSynthetic() {
return (modifiers & 0x1000) != 0;
}
/**
* Checks if the class is final.
*
* @return true if this class is a final class.
*/
public boolean isFinal() {
return (modifiers & Modifier.FINAL) != 0;
}
/**
* Checks if the class is static.
*
* @return true if this class is static.
*/
public boolean isStatic() {
return Modifier.isStatic(modifiers);
}
/**
* Checks if the class is an annotation.
*
* @return true if this class is an annotation class.
*/
public boolean isAnnotation() {
return (modifiers & ANNOTATION_CLASS_MODIFIER) != 0;
}
/**
* Checks if is the class an interface and is not an annotation.
*
* @return true if this class is an interface and is not an annotation (annotations are interfaces, and can be
* implemented).
*/
public boolean isInterface() {
return isInterfaceOrAnnotation() && !isAnnotation();
}
/**
* Checks if is an interface or an annotation.
*
* @return true if this class is an interface or an annotation (annotations are interfaces, and can be
* implemented).
*/
public boolean isInterfaceOrAnnotation() {
return (modifiers & Modifier.INTERFACE) != 0;
}
/**
* Checks if is the class is an {@link Enum}.
*
* @return true if this class is an {@link Enum}.
*/
public boolean isEnum() {
return (modifiers & 0x4000) != 0;
}
/**
* Checks if this class is a standard class.
*
* @return true if this class is a standard class (i.e. is not an annotation or interface).
*/
public boolean isStandardClass() {
return !(isAnnotation() || isInterface());
}
/**
* Checks if this class is an array class. Returns false unless this {@link ClassInfo} is an instance of
* {@link ArrayClassInfo}.
*
* @return true if this is an array class.
*/
public boolean isArrayClass() {
return this instanceof ArrayClassInfo;
}
/**
* Checks if this class extends the named superclass.
*
* @param superclassName
* The name of a superclass.
* @return true if this class extends the named superclass.
*/
public boolean extendsSuperclass(final String superclassName) {
return getSuperclasses().containsName(superclassName);
}
/**
* Checks if this class is an inner class.
*
* @return true if this is an inner class (call {@link #isAnonymousInnerClass()} to test if this is an anonymous
* inner class). If true, the containing class can be determined by calling {@link #getOuterClasses()}.
*/
public boolean isInnerClass() {
return !getOuterClasses().isEmpty();
}
/**
* Checks if this class is an outer class.
*
* @return true if this class contains inner classes. If true, the inner classes can be determined by calling
* {@link #getInnerClasses()}.
*/
public boolean isOuterClass() {
return !getInnerClasses().isEmpty();
}
/**
* Checks if this class is an anonymous inner class.
*
* @return true if this is an anonymous inner class. If true, the name of the containing method can be obtained
* by calling {@link #getFullyQualifiedDefiningMethodName()}.
*/
public boolean isAnonymousInnerClass() {
return fullyQualifiedDefiningMethodName != null;
}
/**
* Checks whether this class is an implemented interface (meaning a standard, non-annotation interface, or an
* annotation that has also been implemented as an interface by some class).
*
* <p>
* Annotations are interfaces, but you can also implement an annotation, so to we return whether an interface
* (even an annotation) is implemented by a class or extended by a subinterface, or (failing that) if it is not
* an interface but not an annotation.
*
* @return true if this class is an implemented interface.
*/
public boolean isImplementedInterface() {
return relatedClasses.get(RelType.CLASSES_IMPLEMENTING) != null || isInterface();
}
/**
* Checks whether this class implements the named interface.
*
* @param interfaceName
* The name of an interface.
* @return true if this class implements the named interface.
*/
public boolean implementsInterface(final String interfaceName) {
return getInterfaces().containsName(interfaceName);
}
/**
* Checks whether this class has the named annotation.
*
* @param annotationName
* The name of an annotation.
* @return true if this class has the named annotation.
*/
public boolean hasAnnotation(final String annotationName) {
return getAnnotations().containsName(annotationName);
}
/**
* Checks whether this class has the named declared field.
*
* @param fieldName
* The name of a field.
* @return true if this class declares a field of the given name.
*/
public boolean hasDeclaredField(final String fieldName) {
return getDeclaredFieldInfo().containsName(fieldName);
}
/**
* Checks whether this class or one of its superclasses has the named field.
*
* @param fieldName
* The name of a field.
* @return true if this class or one of its superclasses declares a field of the given name.
*/
public boolean hasField(final String fieldName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredField(fieldName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class declares a field with the named annotation.
*
* @param fieldAnnotationName
* The name of a field annotation.
* @return true if this class declares a field with the named annotation.
*/
public boolean hasDeclaredFieldAnnotation(final String fieldAnnotationName) {
for (final FieldInfo fi : getDeclaredFieldInfo()) {
if (fi.hasAnnotation(fieldAnnotationName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class or one of its superclasses declares a field with the named annotation.
*
* @param fieldAnnotationName
* The name of a field annotation.
* @return true if this class or one of its superclasses declares a field with the named annotation.
*/
public boolean hasFieldAnnotation(final String fieldAnnotationName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredFieldAnnotation(fieldAnnotationName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class declares a field of the given name.
*
* @param methodName
* The name of a method.
* @return true if this class declares a field of the given name.
*/
public boolean hasDeclaredMethod(final String methodName) {
return getDeclaredMethodInfo().containsName(methodName);
}
/**
* Checks whether this class or one of its superclasses or interfaces declares a method of the given name.
*
* @param methodName
* The name of a method.
* @return true if this class or one of its superclasses or interfaces declares a method of the given name.
*/
public boolean hasMethod(final String methodName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredMethod(methodName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class declares a method with the named annotation.
*
* @param methodAnnotationName
* The name of a method annotation.
* @return true if this class declares a method with the named annotation.
*/
public boolean hasDeclaredMethodAnnotation(final String methodAnnotationName) {
for (final MethodInfo mi : getDeclaredMethodInfo()) {
if (mi.hasAnnotation(methodAnnotationName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class or one of its superclasses or interfaces declares a method with the named
* annotation.
*
* @param methodAnnotationName
* The name of a method annotation.
* @return true if this class or one of its superclasses or interfaces declares a method with the named
* annotation.
*/
public boolean hasMethodAnnotation(final String methodAnnotationName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredMethodAnnotation(methodAnnotationName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class declares a method with the named annotation.
*
* @param methodParameterAnnotationName
* The name of a method annotation.
* @return true if this class declares a method with the named annotation.
*/
public boolean hasDeclaredMethodParameterAnnotation(final String methodParameterAnnotationName) {
for (final MethodInfo mi : getDeclaredMethodInfo()) {
if (mi.hasParameterAnnotation(methodParameterAnnotationName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class or one of its superclasses or interfaces has a method with the named annotation.
*
* @param methodParameterAnnotationName
* The name of a method annotation.
* @return true if this class or one of its superclasses or interfaces has a method with the named annotation.
*/
public boolean hasMethodParameterAnnotation(final String methodParameterAnnotationName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredMethodParameterAnnotation(methodParameterAnnotationName)) {
return true;
}
}
return false;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Recurse to interfaces and superclasses to get the order that fields and methods are overridden in.
*
* @param visited
* visited
* @param overrideOrderOut
* the override order
* @return the override order
*/
private List<ClassInfo> getOverrideOrder(final Set<ClassInfo> visited, final List<ClassInfo> overrideOrderOut) {
if (visited.add(this)) {
overrideOrderOut.add(this);
for (final ClassInfo iface : getInterfaces()) {
iface.getOverrideOrder(visited, overrideOrderOut);
}
final ClassInfo superclass = getSuperclass();
if (superclass != null) {
superclass.getOverrideOrder(visited, overrideOrderOut);
}
}
return overrideOrderOut;
}
/**
* Get the order that fields and methods are overridden in (base class first).
*
* @return the override order
*/
private List<ClassInfo> getOverrideOrder() {
if (overrideOrder == null) {
overrideOrder = getOverrideOrder(new HashSet<ClassInfo>(), new ArrayList<ClassInfo>());
}
return overrideOrder;
}
// -------------------------------------------------------------------------------------------------------------
// Standard classes
/**
* Get the subclasses of this class, sorted in order of name. Call {@link ClassInfoList#directOnly()} to get
* direct subclasses.
*
* @return the list of subclasses of this class, or the empty list if none.
*/
public ClassInfoList getSubclasses() {
if (getName().equals("java.lang.Object")) {
// Make an exception for querying all subclasses of java.lang.Object
return scanResult.getAllClasses();
} else {
return new ClassInfoList(
this.filterClassInfo(RelType.SUBCLASSES, /* strictWhitelist = */ !isExternalClass),
/* sortByName = */ true);
}
}
/**
* Get all superclasses of this class, in ascending order in the class hierarchy. Does not include
* superinterfaces, if this is an interface (use {@link #getInterfaces()} to get superinterfaces of an
* interface.}
*
* @return the list of all superclasses of this class, or the empty list if none.
*/
public ClassInfoList getSuperclasses() {
return new ClassInfoList(this.filterClassInfo(RelType.SUPERCLASSES, /* strictWhitelist = */ false),
/* sortByName = */ false);
}
/**
* Get the single direct superclass of this class, or null if none. Does not return the superinterfaces, if this
* is an interface (use {@link #getInterfaces()} to get superinterfaces of an interface.}
*
* @return the superclass of this class, or null if none.
*/
public ClassInfo getSuperclass() {
final Set<ClassInfo> superClasses = relatedClasses.get(RelType.SUPERCLASSES);
if (superClasses == null || superClasses.isEmpty()) {
return null;
} else if (superClasses.size() > 2) {
throw new IllegalArgumentException("More than one superclass: " + superClasses);
} else {
final ClassInfo superclass = superClasses.iterator().next();
if (superclass.getName().equals("java.lang.Object")) {
return null;
} else {
return superclass;
}
}
}
/**
* Get the containing outer classes, if this is an inner class.
*
* @return A list of the containing outer classes, if this is an inner class, otherwise the empty list. Note
* that all containing outer classes are returned, not just the innermost of the containing outer
* classes.
*/
public ClassInfoList getOuterClasses() {
return new ClassInfoList(
this.filterClassInfo(RelType.CONTAINED_WITHIN_OUTER_CLASS, /* strictWhitelist = */ false),
/* sortByName = */ false);
}
/**
* Get the inner classes contained within this class, if this is an outer class.
*
* @return A list of the inner classes contained within this class, or the empty list if none.
*/
public ClassInfoList getInnerClasses() {
return new ClassInfoList(this.filterClassInfo(RelType.CONTAINS_INNER_CLASS, /* strictWhitelist = */ false),
/* sortByName = */ true);
}
/**
* Gets fully-qualified method name (i.e. fully qualified classname, followed by dot, followed by method name)
* for the defining method, if this is an anonymous inner class.
*
* @return The fully-qualified method name (i.e. fully qualified classname, followed by dot, followed by method
* name) for the defining method, if this is an anonymous inner class, or null if not.
*/
public String getFullyQualifiedDefiningMethodName() {
return fullyQualifiedDefiningMethodName;
}
// -------------------------------------------------------------------------------------------------------------
// Interfaces
/**
* Get the interfaces implemented by this class or by one of its superclasses, if this is a standard class, or
* the superinterfaces extended by this interface, if this is an interface.
*
* @return The list of interfaces implemented by this class or by one of its superclasses, if this is a standard
* class, or the superinterfaces extended by this interface, if this is an interface. Returns the empty
* list if none.
*/
public ClassInfoList getInterfaces() {
// Classes also implement the interfaces of their superclasses
final ReachableAndDirectlyRelatedClasses implementedInterfaces = this
.filterClassInfo(RelType.IMPLEMENTED_INTERFACES, /* strictWhitelist = */ false);
final Set<ClassInfo> allInterfaces = new LinkedHashSet<>(implementedInterfaces.reachableClasses);
for (final ClassInfo superclass : this.filterClassInfo(RelType.SUPERCLASSES,
/* strictWhitelist = */ false).reachableClasses) {
final Set<ClassInfo> superclassImplementedInterfaces = superclass.filterClassInfo(
RelType.IMPLEMENTED_INTERFACES, /* strictWhitelist = */ false).reachableClasses;
allInterfaces.addAll(superclassImplementedInterfaces);
}
return new ClassInfoList(allInterfaces, implementedInterfaces.directlyRelatedClasses,
/* sortByName = */ true);
}
/**
* Get the classes (and their subclasses) that implement this interface, if this is an interface.
*
* @return the list of the classes (and their subclasses) that implement this interface, if this is an
* interface, otherwise returns the empty list.
*/
public ClassInfoList getClassesImplementing() {
if (!isInterface()) {
throw new IllegalArgumentException("Class is not an interface: " + getName());
}
// Subclasses of implementing classes also implement the interface
final ReachableAndDirectlyRelatedClasses implementingClasses = this
.filterClassInfo(RelType.CLASSES_IMPLEMENTING, /* strictWhitelist = */ !isExternalClass);
final Set<ClassInfo> allImplementingClasses = new LinkedHashSet<>(implementingClasses.reachableClasses);
for (final ClassInfo implementingClass : implementingClasses.reachableClasses) {
final Set<ClassInfo> implementingSubclasses = implementingClass.filterClassInfo(RelType.SUBCLASSES,
/* strictWhitelist = */ !implementingClass.isExternalClass).reachableClasses;
allImplementingClasses.addAll(implementingSubclasses);
}
return new ClassInfoList(allImplementingClasses, implementingClasses.directlyRelatedClasses,
/* sortByName = */ true);
}
// -------------------------------------------------------------------------------------------------------------
// Annotations
/**
* Get the annotations and meta-annotations on this class. (Call {@link #getAnnotationInfo()} instead, if you
* need the parameter values of annotations, rather than just the annotation classes.)
*
* <p>
* Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of
* its subclasses.
*
* <p>
* Filters out meta-annotations in the {@code java.lang.annotation} package.
*
* @return the list of annotations and meta-annotations on this class.
*/
public ClassInfoList getAnnotations() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
// Get all annotations on this class
final ReachableAndDirectlyRelatedClasses annotationClasses = this.filterClassInfo(RelType.CLASS_ANNOTATIONS,
/* strictWhitelist = */ false);
// Check for any @Inherited annotations on superclasses
Set<ClassInfo> inheritedSuperclassAnnotations = null;
for (final ClassInfo superclass : getSuperclasses()) {
for (final ClassInfo superclassAnnotation : superclass.filterClassInfo(RelType.CLASS_ANNOTATIONS,
/* strictWhitelist = */ false).reachableClasses) {
// Check if any of the meta-annotations on this annotation are @Inherited,
// which causes an annotation to annotate a class and all of its subclasses.
if (superclassAnnotation != null && superclassAnnotation.isInherited) {
// superclassAnnotation has an @Inherited meta-annotation
if (inheritedSuperclassAnnotations == null) {
inheritedSuperclassAnnotations = new LinkedHashSet<>();
}
inheritedSuperclassAnnotations.add(superclassAnnotation);
}
}
}
if (inheritedSuperclassAnnotations == null) {
// No inherited superclass annotations
return new ClassInfoList(annotationClasses, /* sortByName = */ true);
} else {
// Merge inherited superclass annotations and annotations on this class
inheritedSuperclassAnnotations.addAll(annotationClasses.reachableClasses);
return new ClassInfoList(inheritedSuperclassAnnotations, annotationClasses.directlyRelatedClasses,
/* sortByName = */ true);
}
}
/**
* Get the annotations or meta-annotations on fields, methods or method parametres declared by the class, (not
* including fields, methods or method parameters declared by the interfaces or superclasses of this class).
*
* @param relType
* One of {@link RelType#FIELD_ANNOTATIONS}, {@link RelType#METHOD_ANNOTATIONS} or
* {@link RelType#METHOD_PARAMETER_ANNOTATIONS}.
* @return A list of annotations or meta-annotations on fields or methods declared by the class, (not including
* fields or methods declared by the interfaces or superclasses of this class), as a list of
* {@link ClassInfo} objects, or the empty list if none.
*/
private ClassInfoList getFieldOrMethodAnnotations(final RelType relType) {
final boolean isField = relType == RelType.FIELD_ANNOTATIONS;
if (!(isField ? scanResult.scanSpec.enableFieldInfo : scanResult.scanSpec.enableMethodInfo)
|| !scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enable" + (isField ? "Field" : "Method")
+ "Info() and " + "#enableAnnotationInfo() before #scan()");
}
final ReachableAndDirectlyRelatedClasses fieldOrMethodAnnotations = this.filterClassInfo(relType,
/* strictWhitelist = */ false, ClassType.ANNOTATION);
final Set<ClassInfo> fieldOrMethodAnnotationsAndMetaAnnotations = new LinkedHashSet<>(
fieldOrMethodAnnotations.reachableClasses);
return new ClassInfoList(fieldOrMethodAnnotationsAndMetaAnnotations,
fieldOrMethodAnnotations.directlyRelatedClasses, /* sortByName = */ true);
}
/**
* Get the classes that have this class as a field, method or method parameter annotation.
*
* @param relType
* One of {@link RelType#CLASSES_WITH_FIELD_ANNOTATION},
* {@link RelType#CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION},
* {@link RelType#CLASSES_WITH_METHOD_ANNOTATION},
* {@link RelType#CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION},
* {@link RelType#CLASSES_WITH_METHOD_PARAMETER_ANNOTATION}, or
* {@link RelType#CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION}.
* @return A list of classes that have a declared method with this annotation or meta-annotation, or the empty
* list if none.
*/
private ClassInfoList getClassesWithFieldOrMethodAnnotation(final RelType relType) {
final boolean isField = relType == RelType.CLASSES_WITH_FIELD_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION;
if (!(isField ? scanResult.scanSpec.enableFieldInfo : scanResult.scanSpec.enableMethodInfo)
|| !scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enable" + (isField ? "Field" : "Method")
+ "Info() and " + "#enableAnnotationInfo() before #scan()");
}
final ReachableAndDirectlyRelatedClasses classesWithDirectlyAnnotatedFieldsOrMethods = this
.filterClassInfo(relType, /* strictWhitelist = */ !isExternalClass);
final ReachableAndDirectlyRelatedClasses annotationsWithThisMetaAnnotation = this.filterClassInfo(
RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass, ClassType.ANNOTATION);
if (annotationsWithThisMetaAnnotation.reachableClasses.isEmpty()) {
// This annotation does not meta-annotate another annotation that annotates a method
return new ClassInfoList(classesWithDirectlyAnnotatedFieldsOrMethods, /* sortByName = */ true);
} else {
// Take the union of all classes with fields or methods directly annotated by this annotation,
// and classes with fields or methods meta-annotated by this annotation
final Set<ClassInfo> allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods = new LinkedHashSet<>(
classesWithDirectlyAnnotatedFieldsOrMethods.reachableClasses);
for (final ClassInfo metaAnnotatedAnnotation : annotationsWithThisMetaAnnotation.reachableClasses) {
allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods
.addAll(metaAnnotatedAnnotation.filterClassInfo(relType,
/* strictWhitelist = */ !metaAnnotatedAnnotation.isExternalClass).reachableClasses);
}
return new ClassInfoList(allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods,
classesWithDirectlyAnnotatedFieldsOrMethods.directlyRelatedClasses, /* sortByName = */ true);
}
}
/**
* Get a list of the annotations on this class, or the empty list if none.
*
* <p>
* Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of
* its subclasses.
*
* @return A list of {@link AnnotationInfo} objects for the annotations on this class, or the empty list if
* none.
*/
public AnnotationInfoList getAnnotationInfo() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
return AnnotationInfoList.getIndirectAnnotations(annotationInfo, this);
}
/**
* Get a the named non-{@link Repeatable} annotation on this class, or null if the class does not have the named
* annotation. (Use {@link #getAnnotationInfoRepeatable(String)} for {@link Repeatable} annotations.)
*
* <p>
* Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of
* its subclasses.
*
* <p>
* Note that if you need to get multiple named annotations, it is faster to call {@link #getAnnotationInfo()},
* and then get the named annotations from the returned {@link AnnotationInfoList}, so that the returned list
* doesn't have to be built multiple times.
*
* @param annotationName
* The annotation name.
* @return An {@link AnnotationInfo} object representing the named annotation on this class, or null if the
* class does not have the named annotation.
*/
public AnnotationInfo getAnnotationInfo(final String annotationName) {
return getAnnotationInfo().get(annotationName);
}
/**
* Get a the named {@link Repeatable} annotation on this class, or the empty list if the class does not have the
* named annotation.
*
* <p>
* Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of
* its subclasses.
*
* <p>
* Note that if you need to get multiple named annotations, it is faster to call {@link #getAnnotationInfo()},
* and then get the named annotations from the returned {@link AnnotationInfoList}, so that the returned list
* doesn't have to be built multiple times.
*
* @param annotationName
* The annotation name.
* @return An {@link AnnotationInfoList} of all instances of the named annotation on this class, or the empty
* list if the class does not have the named annotation.
*/
public AnnotationInfoList getAnnotationInfoRepeatable(final String annotationName) {
return getAnnotationInfo().getRepeatable(annotationName);
}
/**
* Get the default parameter values for this annotation, if this is an annotation class.
*
* @return A list of {@link AnnotationParameterValue} objects for each of the default parameter values for this
* annotation, if this is an annotation class with default parameter values, otherwise the empty list.
*/
public AnnotationParameterValueList getAnnotationDefaultParameterValues() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
if (!isAnnotation()) {
throw new IllegalArgumentException("Class is not an annotation: " + getName());
}
if (annotationDefaultParamValues == null) {
return AnnotationParameterValueList.EMPTY_LIST;
}
if (!annotationDefaultParamValuesHasBeenConvertedToPrimitive) {
annotationDefaultParamValues.convertWrapperArraysToPrimitiveArrays(this);
annotationDefaultParamValuesHasBeenConvertedToPrimitive = true;
}
return annotationDefaultParamValues;
}
/**
* Get the classes that have this class as an annotation.
*
* @return A list of standard classes and non-annotation interfaces that are annotated by this class, if this is
* an annotation class, or the empty list if none. Also handles the {@link Inherited} meta-annotation,
* which causes an annotation on a class to be inherited by all of its subclasses.
*/
public ClassInfoList getClassesWithAnnotation() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
if (!isAnnotation()) {
throw new IllegalArgumentException("Class is not an annotation: " + getName());
}
// Get classes that have this annotation
final ReachableAndDirectlyRelatedClasses classesWithAnnotation = this
.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass);
if (isInherited) {
// If this is an inherited annotation, add into the result all subclasses of the annotated classes.
final Set<ClassInfo> classesWithAnnotationAndTheirSubclasses = new LinkedHashSet<>(
classesWithAnnotation.reachableClasses);
for (final ClassInfo classWithAnnotation : classesWithAnnotation.reachableClasses) {
classesWithAnnotationAndTheirSubclasses.addAll(classWithAnnotation.getSubclasses());
}
return new ClassInfoList(classesWithAnnotationAndTheirSubclasses,
classesWithAnnotation.directlyRelatedClasses, /* sortByName = */ true);
} else {
// If not inherited, only return the annotated classes
return new ClassInfoList(classesWithAnnotation, /* sortByName = */ true);
}
}
/**
* Get the classes that have this class as a direct annotation.
*
* @return The list of classes that are directly (i.e. are not meta-annotated) annotated with the requested
* annotation, or the empty list if none.
*/
ClassInfoList getClassesWithAnnotationDirectOnly() {
return new ClassInfoList(
this.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass),
/* sortByName = */ true);
}
// -------------------------------------------------------------------------------------------------------------
// Methods
/**
* Get the declared methods, constructors, and/or static initializer methods of the class.
*
* @param methodName
* the method name
* @param getNormalMethods
* whether to get normal methods
* @param getConstructorMethods
* whether to get constructor methods
* @param getStaticInitializerMethods
* whether to get static initializer methods
* @return the declared method info
*/
private MethodInfoList getDeclaredMethodInfo(final String methodName, final boolean getNormalMethods,
final boolean getConstructorMethods, final boolean getStaticInitializerMethods) {
if (!scanResult.scanSpec.enableMethodInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableMethodInfo() before #scan()");
}
if (methodInfo == null) {
return MethodInfoList.EMPTY_LIST;
}
if (methodName == null) {
// If no method name is provided, filter for methods with the right type (normal method / constructor /
// static initializer)
final MethodInfoList methodInfoList = new MethodInfoList();
for (final MethodInfo mi : methodInfo) {
final String miName = mi.getName();
final boolean isConstructor = "<init>".equals(miName);
// (Currently static initializer methods are never returned by public methods)
final boolean isStaticInitializer = "<clinit>".equals(miName);
if ((isConstructor && getConstructorMethods) || (isStaticInitializer && getStaticInitializerMethods)
|| (!isConstructor && !isStaticInitializer && getNormalMethods)) {
methodInfoList.add(mi);
}
}
return methodInfoList;
} else {
// If method name is provided, filter for methods whose name matches, and ignore method type
boolean hasMethodWithName = false;
for (final MethodInfo f : methodInfo) {
if (f.getName().equals(methodName)) {
hasMethodWithName = true;
break;
}
}
if (!hasMethodWithName) {
return MethodInfoList.EMPTY_LIST;
}
final MethodInfoList methodInfoList = new MethodInfoList();
for (final MethodInfo mi : methodInfo) {
if (mi.getName().equals(methodName)) {
methodInfoList.add(mi);
}
}
return methodInfoList;
}
}
/**
* Get the methods, constructors, and/or static initializer methods of the class.
*
* @param methodName
* the method name
* @param getNormalMethods
* whether to get normal methods
* @param getConstructorMethods
* whether to get constructor methods
* @param getStaticInitializerMethods
* whether to get static initializer methods
* @return the method info
*/
private MethodInfoList getMethodInfo(final String methodName, final boolean getNormalMethods,
final boolean getConstructorMethods, final boolean getStaticInitializerMethods) {
if (!scanResult.scanSpec.enableMethodInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableMethodInfo() before #scan()");
}
// Implement method/constructor overriding
final MethodInfoList methodInfoList = new MethodInfoList();
final Set<Entry<String, String>> nameAndTypeDescriptorSet = new HashSet<>();
for (final ClassInfo ci : getOverrideOrder()) {
for (final MethodInfo mi : ci.getDeclaredMethodInfo(methodName, getNormalMethods, getConstructorMethods,
getStaticInitializerMethods)) {
// If method/constructor has not been overridden by method of same name and type descriptor
if (nameAndTypeDescriptorSet
.add(new SimpleEntry<>(mi.getName(), mi.getTypeDescriptor().toString()))) {
// Add method/constructor to output order
methodInfoList.add(mi);
}
}
}
return methodInfoList;
}
/**
* Returns information on visible methods declared by this class, but not by its interfaces or superclasses,
* that are not constructors. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one method of a given name with different type signatures, due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* @return the list of {@link MethodInfo} objects for visible methods declared by this class, or the empty list
* if no methods were found.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getDeclaredMethodInfo() {
return getDeclaredMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true,
/* getConstructorMethods = */ false, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on visible methods declared by this class, or by its interfaces or superclasses, that are
* not constructors. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one method of a given name with different type signatures, due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* @return the list of {@link MethodInfo} objects for visible methods of this class, its interfaces and
* superclasses, or the empty list if no methods were found.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getMethodInfo() {
return getMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true,
/* getConstructorMethods = */ false, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on visible constructors declared by this class, but not by its interfaces or
* superclasses. Constructors have the method name of {@code "<init>"}. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one constructor of a given name with different type signatures, due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public constructors, unless
* {@link ClassGraph#ignoreMethodVisibility()} was called before the scan.
*
* @return the list of {@link MethodInfo} objects for visible constructors declared by this class, or the empty
* list if no constructors were found or visible.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getDeclaredConstructorInfo() {
return getDeclaredMethodInfo(/* methodName = */ null, /* getNormalMethods = */ false,
/* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on visible constructors declared by this class, or by its interfaces or superclasses.
* Constructors have the method name of {@code "<init>"}. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one method of a given name with different type signatures, due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* @return the list of {@link MethodInfo} objects for visible constructors of this class and its superclasses,
* or the empty list if no methods were found.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getConstructorInfo() {
return getMethodInfo(/* methodName = */ null, /* getNormalMethods = */ false,
/* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on visible methods and constructors declared by this class, but not by its interfaces or
* superclasses. Constructors have the method name of {@code "<init>"} and static initializer blocks have the
* name of {@code "<clinit>"}. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one method or constructor or method of a given name with different type signatures,
* due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods and constructors, unless
* {@link ClassGraph#ignoreMethodVisibility()} was called before the scan. If method visibility is ignored, the
* result may include a reference to a private static class initializer block, with a method name of
* {@code "<clinit>"}.
*
* @return the list of {@link MethodInfo} objects for visible methods and constructors of this class, or the
* empty list if no methods or constructors were found or visible.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getDeclaredMethodAndConstructorInfo() {
return getDeclaredMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true,
/* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on visible constructors declared by this class, or by its interfaces or superclasses.
* Constructors have the method name of {@code "<init>"} and static initializer blocks have the name of
* {@code "<clinit>"}. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one method of a given name with different type signatures, due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* @return the list of {@link MethodInfo} objects for visible methods and constructors of this class, its
* interfaces and superclasses, or the empty list if no methods were found.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getMethodAndConstructorInfo() {
return getMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true,
/* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on the method(s) or constructor(s) of the given name declared by this class, but not by
* its interfaces or superclasses. Constructors have the method name of {@code "<init>"}. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* <p>
* May return info for multiple methods with the same name (with different type signatures).
*
* @param methodName
* The method name to query.
* @return a list of {@link MethodInfo} objects for the method(s) with the given name, or the empty list if the
* method was not found in this class (or is not visible).
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getDeclaredMethodInfo(final String methodName) {
return getDeclaredMethodInfo(methodName, /* ignored */ false, /* ignored */ false, /* ignored */ false);
}
/**
* Returns information on the method(s) or constructor(s) of the given name declared by this class, but not by
* its interfaces or superclasses. Constructors have the method name of {@code "<init>"}. See also:
*
* <ul>
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* <p>
* May return info for multiple methods with the same name (with different type signatures).
*
* @param methodName
* The method name to query.
* @return a list of {@link MethodInfo} objects for the method(s) with the given name, or the empty list if the
* method was not found in this class (or is not visible).
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getMethodInfo(final String methodName) {
return getMethodInfo(methodName, /* ignored */ false, /* ignored */ false, /* ignored */ false);
}
/**
* Get all method annotations.
*
* @return A list of all annotations or meta-annotations on methods declared by the class, (not including
* methods declared by the interfaces or superclasses of this class), as a list of {@link ClassInfo}
* objects, or the empty list if none. N.B. these annotations do not contain specific annotation
* parameters -- call {@link MethodInfo#getAnnotationInfo()} to get details on specific method
* annotation instances.
*/
public ClassInfoList getMethodAnnotations() {
return getFieldOrMethodAnnotations(RelType.METHOD_ANNOTATIONS);
}
/**
* Get all method parameter annotations.
*
* @return A list of all annotations or meta-annotations on methods declared by the class, (not including
* methods declared by the interfaces or superclasses of this class), as a list of {@link ClassInfo}
* objects, or the empty list if none. N.B. these annotations do not contain specific annotation
* parameters -- call {@link MethodInfo#getAnnotationInfo()} to get details on specific method
* annotation instances.
*/
public ClassInfoList getMethodParameterAnnotations() {
return getFieldOrMethodAnnotations(RelType.METHOD_PARAMETER_ANNOTATIONS);
}
/**
* Get all classes that have this class as a method annotation, and their subclasses, if the method is
* non-private.
*
* @return A list of classes that have a declared method with this annotation or meta-annotation, or the empty
* list if none.
*/
public ClassInfoList getClassesWithMethodAnnotation() {
// Get all classes that have a method annotated or meta-annotated with this annotation
final Set<ClassInfo> classesWithMethodAnnotation = new HashSet<>(
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_METHOD_ANNOTATION));
// Add subclasses of all classes with a method that is non-privately annotated or meta-annotated with
// this annotation (non-private methods are inherited)
for (final ClassInfo classWithNonprivateMethodAnnotationOrMetaAnnotation : //
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION)) {
classesWithMethodAnnotation.addAll(classWithNonprivateMethodAnnotationOrMetaAnnotation.getSubclasses());
}
return new ClassInfoList(classesWithMethodAnnotation,
new HashSet<>(getClassesWithMethodAnnotationDirectOnly()), /* sortByName = */ true);
}
/**
* Get all classes that have this class as a method parameter annotation, and their subclasses, if the method is
* non-private.
*
* @return A list of classes that have a declared method with a parameter that is annotated with this annotation
* or meta-annotation, or the empty list if none.
*/
public ClassInfoList getClassesWithMethodParameterAnnotation() {
// Get all classes that have a method annotated or meta-annotated with this annotation
final Set<ClassInfo> classesWithMethodParameterAnnotation = new HashSet<>(
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION));
// Add subclasses of all classes with a method that is non-privately annotated or meta-annotated with
// this annotation (non-private methods are inherited)
for (final ClassInfo classWithNonprivateMethodParameterAnnotationOrMetaAnnotation : //
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION)) {
classesWithMethodParameterAnnotation
.addAll(classWithNonprivateMethodParameterAnnotationOrMetaAnnotation.getSubclasses());
}
return new ClassInfoList(classesWithMethodParameterAnnotation,
new HashSet<>(getClassesWithMethodParameterAnnotationDirectOnly()), /* sortByName = */ true);
}
/**
* Get the classes that have this class as a direct method annotation.
*
* @return A list of classes that declare methods that are directly annotated (i.e. are not meta-annotated) with
* the requested method annotation, or the empty list if none.
*/
ClassInfoList getClassesWithMethodAnnotationDirectOnly() {
return new ClassInfoList(this.filterClassInfo(RelType.CLASSES_WITH_METHOD_ANNOTATION,
/* strictWhitelist = */ !isExternalClass), /* sortByName = */ true);
}
/**
* Get the classes that have this class as a direct method parameter annotation.
*
* @return A list of classes that declare methods with parameters that are directly annotated (i.e. are not
* meta-annotated) with the requested method annotation, or the empty list if none.
*/
ClassInfoList getClassesWithMethodParameterAnnotationDirectOnly() {
return new ClassInfoList(this.filterClassInfo(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,
/* strictWhitelist = */ !isExternalClass), /* sortByName = */ true);
}
// -------------------------------------------------------------------------------------------------------------
// Fields
/**
* Returns information on all visible fields declared by this class, but not by its superclasses. See also:
*
* <ul>
* <li>{@link #getFieldInfo(String)}
* <li>{@link #getDeclaredFieldInfo(String)}
* <li>{@link #getFieldInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableFieldInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public fields, unless {@link ClassGraph#ignoreFieldVisibility()} was
* called before the scan.
*
* @return the list of FieldInfo objects for visible fields declared by this class, or the empty list if no
* fields were found or visible.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableFieldInfo()} was not called prior to initiating the scan.
*/
public FieldInfoList getDeclaredFieldInfo() {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
return fieldInfo == null ? FieldInfoList.EMPTY_LIST : fieldInfo;
}
/**
* Returns information on all visible fields declared by this class, or by its superclasses. See also:
*
* <ul>
* <li>{@link #getFieldInfo(String)}
* <li>{@link #getDeclaredFieldInfo(String)}
* <li>{@link #getDeclaredFieldInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableFieldInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public fields, unless {@link ClassGraph#ignoreFieldVisibility()} was
* called before the scan.
*
* @return the list of FieldInfo objects for visible fields of this class or its superclases, or the empty list
* if no fields were found or visible.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableFieldInfo()} was not called prior to initiating the scan.
*/
public FieldInfoList getFieldInfo() {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
// Implement field overriding
final FieldInfoList fieldInfoList = new FieldInfoList();
final Set<String> fieldNameSet = new HashSet<>();
for (final ClassInfo ci : getOverrideOrder()) {
for (final FieldInfo fi : ci.getDeclaredFieldInfo()) {
// If field has not been overridden by field of same name
if (fieldNameSet.add(fi.getName())) {
// Add field to output order
fieldInfoList.add(fi);
}
}
}
return fieldInfoList;
}
/**
* Returns information on the named field declared by the class, but not by its superclasses. See also:
*
* <ul>
* <li>{@link #getFieldInfo(String)}
* <li>{@link #getFieldInfo()}
* <li>{@link #getDeclaredFieldInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableFieldInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public fields, unless {@link ClassGraph#ignoreFieldVisibility()} was
* called before the scan.
*
* @param fieldName
* The field name.
* @return the {@link FieldInfo} object for the named field declared by this class, or null if the field was not
* found in this class (or is not visible).
* @throws IllegalArgumentException
* if {@link ClassGraph#enableFieldInfo()} was not called prior to initiating the scan.
*/
public FieldInfo getDeclaredFieldInfo(final String fieldName) {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
if (fieldInfo == null) {
return null;
}
for (final FieldInfo fi : fieldInfo) {
if (fi.getName().equals(fieldName)) {
return fi;
}
}
return null;
}
/**
* Returns information on the named filed declared by this class, or by its superclasses. See also:
*
* <ul>
* <li>{@link #getDeclaredFieldInfo(String)}
* <li>{@link #getFieldInfo()}
* <li>{@link #getDeclaredFieldInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableFieldInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public fields, unless {@link ClassGraph#ignoreFieldVisibility()} was
* called before the scan.
*
* @param fieldName
* The field name.
* @return the {@link FieldInfo} object for the named field of this class or its superclases, or the empty list
* if no fields were found or visible.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableFieldInfo()} was not called prior to initiating the scan.
*/
public FieldInfo getFieldInfo(final String fieldName) {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
// Implement field overriding
for (final ClassInfo ci : getOverrideOrder()) {
final FieldInfo fi = ci.getDeclaredFieldInfo(fieldName);
if (fi != null) {
return fi;
}
}
return null;
}
/**
* Get all field annotations.
*
* @return A list of all annotations on fields of this class, or the empty list if none. N.B. these annotations
* do not contain specific annotation parameters -- call {@link FieldInfo#getAnnotationInfo()} to get
* details on specific field annotation instances.
*/
public ClassInfoList getFieldAnnotations() {
return getFieldOrMethodAnnotations(RelType.FIELD_ANNOTATIONS);
}
/**
* Get the classes that have this class as a field annotation or meta-annotation.
*
* @return A list of classes that have a field with this annotation or meta-annotation, or the empty list if
* none.
*/
public ClassInfoList getClassesWithFieldAnnotation() {
// Get all classes that have a field annotated or meta-annotated with this annotation
final Set<ClassInfo> classesWithMethodAnnotation = new HashSet<>(
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_FIELD_ANNOTATION));
// Add subclasses of all classes with a field that is non-privately annotated or meta-annotated with
// this annotation (non-private fields are inherited)
for (final ClassInfo classWithNonprivateMethodAnnotationOrMetaAnnotation : //
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION)) {
classesWithMethodAnnotation.addAll(classWithNonprivateMethodAnnotationOrMetaAnnotation.getSubclasses());
}
return new ClassInfoList(classesWithMethodAnnotation,
new HashSet<>(getClassesWithMethodAnnotationDirectOnly()), /* sortByName = */ true);
}
/**
* Get the classes that have this class as a direct field annotation.
*
* @return A list of classes that declare fields that are directly annotated (i.e. are not meta-annotated) with
* the requested method annotation, or the empty list if none.
*/
ClassInfoList getClassesWithFieldAnnotationDirectOnly() {
return new ClassInfoList(this.filterClassInfo(RelType.CLASSES_WITH_FIELD_ANNOTATION,
/* strictWhitelist = */ !isExternalClass), /* sortByName = */ true);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the parsed type signature for the class.
*
* @return The parsed type signature for the class, including any generic type parameters, or null if not
* available (probably indicating the class is not generic).
*/
public ClassTypeSignature getTypeSignature() {
if (typeSignatureStr == null) {
return null;
}
if (typeSignature == null) {
try {
typeSignature = ClassTypeSignature.parse(typeSignatureStr, this);
typeSignature.setScanResult(scanResult);
} catch (final ParseException e) {
throw new IllegalArgumentException(e);
}
}
return typeSignature;
}
/**
* Get the type signature string for the class.
*
* @return The type signature string for the class, including any generic type parameters, or null if not
* available (probably indicating the class is not generic).
*/
public String getTypeSignatureStr() {
return typeSignatureStr;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the {@link URI} of the classpath element that this class was found within.
*
* @return The {@link URI} of the classpath element that this class was found within.
* @throws IllegalArgumentException
* if the classpath element does not have a valid URI (e.g. for modules whose location URI is null).
*/
public URI getClasspathElementURI() {
if (classpathElement == null) {
throw new IllegalArgumentException("Classpath element is not known for this classpath element");
}
return classpathElement.getURI();
}
/**
* Get the {@link URL} of the classpath element or module that this class was found within. Use
* {@link #getClasspathElementURI()} instead if the resource may have come from a system module, or if this is a
* jlink'd runtime image, since "jrt:" URI schemes used by system modules and jlink'd runtime images are not
* suppored by {@link URL}, and this will cause {@link IllegalArgumentException} to be thrown.
*
* @return The {@link URL} of the classpath element that this class was found within.
* @throws IllegalArgumentException
* if the classpath element URI cannot be converted to a {@link URL} (in particular, if the URI has
* a {@code jrt:/} scheme).
*/
public URL getClasspathElementURL() {
if (classpathElement == null) {
throw new IllegalArgumentException("Classpath element is not known for this classpath element");
}
try {
return classpathElement.getURI().toURL();
} catch (final MalformedURLException e) {
throw new IllegalArgumentException("Could not get classpath element URL", e);
}
}
/**
* Get the {@link File} for the classpath element package root dir or jar that this class was found within, or
* null if this class was found in a module. (See also {@link #getModuleRef}.)
*
* @return The {@link File} for the classpath element package root dir or jar that this class was found within,
* or null if this class was found in a module (see {@link #getModuleRef}). May also return null if the
* classpath element was an http/https URL, and the jar was downloaded directly to RAM, rather than to a
* temp file on disk (e.g. if the temp dir is not writeable).
*/
public File getClasspathElementFile() {
if (classpathElement == null) {
throw new IllegalArgumentException("Classpath element is not known for this classpath element");
}
return classpathElement.getFile();
}
/**
* Get the module that this class was found within, as a {@link ModuleRef}, or null if this class was found in a
* directory or jar in the classpath. (See also {@link #getClasspathElementFile()}.)
*
* @return The module that this class was found within, as a {@link ModuleRef}, or null if this class was found
* in a directory or jar in the classpath. (See also {@link #getClasspathElementFile()}.)
*/
public ModuleRef getModuleRef() {
if (classpathElement == null) {
throw new IllegalArgumentException("Classpath element is not known for this classpath element");
}
return classpathElement instanceof ClasspathElementModule
? ((ClasspathElementModule) classpathElement).getModuleRef()
: null;
}
/**
* The {@link Resource} for the classfile of this class.
*
* @return The {@link Resource} for the classfile of this class. Returns null if the classfile for this class
* was not actually read during the scan, e.g. because this class was not itself whitelisted, but was
* referenced by a whitelisted class.
*/
public Resource getResource() {
return classfileResource;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Obtain a {@code Class<?>} reference for the class named by this {@link ClassInfo} object, casting it to the
* requested interface or superclass type. Causes the ClassLoader to load the class, if it is not already
* loaded.
*
* <p>
* <b>Important note:</b> since {@code superclassOrInterfaceType} is a class reference for an already-loaded
* class, it is critical that {@code superclassOrInterfaceType} is loaded by the same classloader as the class
* referred to by this {@code ClassInfo} object, otherwise the class cast will fail.
*
* @param <T>
* the superclass or interface type
* @param superclassOrInterfaceType
* The {@link Class} reference for the type to cast the loaded class to.
* @param ignoreExceptions
* If true, return null if any exceptions or errors thrown during classloading, or if attempting to
* cast the resulting {@code Class<?>} reference to the requested superclass or interface type fails.
* If false, {@link IllegalArgumentException} is thrown if the class could not be loaded or could not
* be cast to the requested type.
* @return The class reference, or null, if ignoreExceptions is true and there was an exception or error loading
* the class.
* @throws IllegalArgumentException
* if ignoreExceptions is false and there were problems loading the class, or casting it to the
* requested type.
*/
@Override
public <T> Class<T> loadClass(final Class<T> superclassOrInterfaceType, final boolean ignoreExceptions) {
return super.loadClass(superclassOrInterfaceType, ignoreExceptions);
}
/**
* Obtain a {@code Class<?>} reference for the class named by this {@link ClassInfo} object, casting it to the
* requested interface or superclass type. Causes the ClassLoader to load the class, if it is not already
* loaded.
*
* <p>
* <b>Important note:</b> since {@code superclassOrInterfaceType} is a class reference for an already-loaded
* class, it is critical that {@code superclassOrInterfaceType} is loaded by the same classloader as the class
* referred to by this {@code ClassInfo} object, otherwise the class cast will fail.
*
* @param <T>
* The superclass or interface type
* @param superclassOrInterfaceType
* The type to cast the loaded class to.
* @return The class reference.
* @throws IllegalArgumentException
* if there were problems loading the class or casting it to the requested type.
*/
@Override
public <T> Class<T> loadClass(final Class<T> superclassOrInterfaceType) {
return super.loadClass(superclassOrInterfaceType, /* ignoreExceptions = */ false);
}
/**
* Obtain a {@code Class<?>} reference for the class named by this {@link ClassInfo} object. Causes the
* ClassLoader to load the class, if it is not already loaded.
*
* @param ignoreExceptions
* Whether or not to ignore exceptions
* @return The class reference, or null, if ignoreExceptions is true and there was an exception or error loading
* the class.
* @throws IllegalArgumentException
* if ignoreExceptions is false and there were problems loading the class.
*/
@Override
public Class<?> loadClass(final boolean ignoreExceptions) {
return super.loadClass(ignoreExceptions);
}
/**
* Obtain a {@code Class<?>} reference for the class named by this {@link ClassInfo} object. Causes the
* ClassLoader to load the class, if it is not already loaded.
*
* @return The class reference.
* @throws IllegalArgumentException
* if there were problems loading the class.
*/
@Override
public Class<?> loadClass() {
return super.loadClass(/* ignoreExceptions = */ false);
}
// -------------------------------------------------------------------------------------------------------------
/* (non-Javadoc)
* @see io.github.classgraph.ScanResultObject#getClassName()
*/
@Override
protected String getClassName() {
return name;
}
/* (non-Javadoc)
* @see io.github.classgraph.ScanResultObject#getClassInfo()
*/
@Override
protected ClassInfo getClassInfo() {
return this;
}
/* (non-Javadoc)
* @see io.github.classgraph.ScanResultObject#setScanResult(io.github.classgraph.ScanResult)
*/
@Override
void setScanResult(final ScanResult scanResult) {
super.setScanResult(scanResult);
if (this.typeSignature != null) {
this.typeSignature.setScanResult(scanResult);
}
if (annotationInfo != null) {
for (final AnnotationInfo ai : annotationInfo) {
ai.setScanResult(scanResult);
}
}
if (fieldInfo != null) {
for (final FieldInfo fi : fieldInfo) {
fi.setScanResult(scanResult);
}
}
if (methodInfo != null) {
for (final MethodInfo mi : methodInfo) {
mi.setScanResult(scanResult);
}
}
if (annotationDefaultParamValues != null) {
for (final AnnotationParameterValue apv : annotationDefaultParamValues) {
apv.setScanResult(scanResult);
}
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Handle {@link Repeatable} annotations.
*
* @param allRepeatableAnnotationNames
* the names of all repeatable annotations
*/
void handleRepeatableAnnotations(final Set<String> allRepeatableAnnotationNames) {
if (annotationInfo != null) {
annotationInfo.handleRepeatableAnnotations(allRepeatableAnnotationNames, this,
RelType.CLASS_ANNOTATIONS, RelType.CLASSES_WITH_ANNOTATION, null);
}
if (fieldInfo != null) {
for (final FieldInfo fi : fieldInfo) {
fi.handleRepeatableAnnotations(allRepeatableAnnotationNames);
}
}
if (methodInfo != null) {
for (final MethodInfo mi : methodInfo) {
mi.handleRepeatableAnnotations(allRepeatableAnnotationNames);
}
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Add names of classes referenced by this class.
*
* @param refdClassNames
* the referenced class names
*/
void addReferencedClassNames(final Set<String> refdClassNames) {
if (this.referencedClassNames == null) {
this.referencedClassNames = refdClassNames;
} else {
this.referencedClassNames.addAll(refdClassNames);
}
}
/**
* Get {@link ClassInfo} objects for any classes referenced in this class' type descriptor, or the type
* descriptors of fields, methods or annotations.
*
* @param classNameToClassInfo
* the map from class name to {@link ClassInfo}.
* @param refdClassInfo
* the referenced class info
*/
@Override
protected void findReferencedClassInfo(final Map<String, ClassInfo> classNameToClassInfo,
final Set<ClassInfo> refdClassInfo) {
// Add this class to the set of references
super.findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
if (this.referencedClassNames != null) {
for (final String refdClassName : this.referencedClassNames) {
final ClassInfo classInfo = ClassInfo.getOrCreateClassInfo(refdClassName, classNameToClassInfo);
classInfo.setScanResult(scanResult);
refdClassInfo.add(classInfo);
}
}
getMethodInfo().findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
getFieldInfo().findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
getAnnotationInfo().findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
if (annotationDefaultParamValues != null) {
annotationDefaultParamValues.findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
}
final ClassTypeSignature classSig = getTypeSignature();
if (classSig != null) {
classSig.findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Set the list of ClassInfo objects for classes referenced by this class.
*
* @param refdClasses
* the referenced classes
*/
void setReferencedClasses(final ClassInfoList refdClasses) {
this.referencedClasses = refdClasses;
}
/**
* Get the class dependencies.
*
* @return A {@link ClassInfoList} of {@link ClassInfo} objects for all classes referenced by this class. Note
* that you need to call {@link ClassGraph#enableInterClassDependencies()} before
* {@link ClassGraph#scan()} for this method to work. You should also call
* {@link ClassGraph#enableExternalClasses()} before {@link ClassGraph#scan()} if you want
* non-whitelisted classes to appear in the result.
*/
public ClassInfoList getClassDependencies() {
if (!scanResult.scanSpec.enableInterClassDependencies) {
throw new IllegalArgumentException(
"Please call ClassGraph#enableInterClassDependencies() before #scan()");
}
return referencedClasses == null ? ClassInfoList.EMPTY_LIST : referencedClasses;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Compare based on class name.
*
* @param o
* the other object
* @return the comparison result
*/
@Override
public int compareTo(final ClassInfo o) {
return this.name.compareTo(o.name);
}
/**
* Use class name for equals().
*
* @param obj
* the other object
* @return Whether the objects were equal.
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof ClassInfo)) {
return false;
}
final ClassInfo other = (ClassInfo) obj;
return name.equals(other.name);
}
/**
* Use hash code of class name.
*
* @return the hashcode
*/
@Override
public int hashCode() {
return name == null ? 0 : name.hashCode();
}
/**
* To string.
*
* @param typeNameOnly
* if true, convert type name to string only.
* @return the string
*/
protected String toString(final boolean typeNameOnly) {
final ClassTypeSignature typeSig = getTypeSignature();
if (typeSig != null) {
// Generic classes
return typeSig.toString(name, typeNameOnly, modifiers, isAnnotation(), isInterface());
} else {
// Non-generic classes
final StringBuilder buf = new StringBuilder();
if (typeNameOnly) {
buf.append(name);
} else {
TypeUtils.modifiersToString(modifiers, ModifierType.CLASS, /* ignored */ false, buf);
if (buf.length() > 0) {
buf.append(' ');
}
buf.append(isAnnotation() ? "@interface "
: isInterface() ? "interface " : (modifiers & 0x4000) != 0 ? "enum " : "class ");
buf.append(name);
final ClassInfo superclass = getSuperclass();
if (superclass != null && !superclass.getName().equals("java.lang.Object")) {
buf.append(" extends ").append(superclass.toString(/* typeNameOnly = */ true));
}
final Set<ClassInfo> interfaces = this.filterClassInfo(RelType.IMPLEMENTED_INTERFACES,
/* strictWhitelist = */ false).directlyRelatedClasses;
if (!interfaces.isEmpty()) {
buf.append(isInterface() ? " extends " : " implements ");
boolean first = true;
for (final ClassInfo iface : interfaces) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(iface.toString(/* typeNameOnly = */ true));
}
}
}
return buf.toString();
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return toString(false);
}
}
| src/main/java/io/github/classgraph/ClassInfo.java | /*
* This file is part of ClassGraph.
*
* Author: Luke Hutchison
*
* Hosted at: https://github.com/classgraph/classgraph
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Luke Hutchison
*
* 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 io.github.classgraph;
import java.io.File;
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import io.github.classgraph.Classfile.ClassContainment;
import nonapi.io.github.classgraph.json.Id;
import nonapi.io.github.classgraph.scanspec.ScanSpec;
import nonapi.io.github.classgraph.types.ParseException;
import nonapi.io.github.classgraph.types.TypeUtils;
import nonapi.io.github.classgraph.types.TypeUtils.ModifierType;
/** Holds metadata about a class encountered during a scan. */
public class ClassInfo extends ScanResultObject implements Comparable<ClassInfo>, HasName {
/** The name of the class. */
@Id
protected String name;
/** Class modifier flags, e.g. Modifier.PUBLIC */
private int modifiers;
/**
* This annotation has the {@link Inherited} meta-annotation, which means that any class that this annotation is
* applied to also implicitly causes the annotation to annotate all subclasses too.
*/
boolean isInherited;
/** The class type signature string. */
protected String typeSignatureStr;
/** The class type signature, parsed. */
private transient ClassTypeSignature typeSignature;
/** The fully-qualified defining method name, for anonymous inner classes. */
private String fullyQualifiedDefiningMethodName;
/**
* If true, this class is only being referenced by another class' classfile as a superclass / implemented
* interface / annotation, but this class is not itself a whitelisted (non-blacklisted) class, or in a
* whitelisted (non-blacklisted) package.
*
* If false, this classfile was matched during scanning (i.e. its classfile contents read), i.e. this class is a
* whitelisted (and non-blacklisted) class in a whitelisted (and non-blacklisted) package.
*/
protected boolean isExternalClass = true;
/**
* Set to true when the class is actually scanned (as opposed to just referenced as a superclass, interface or
* annotation of a scanned class).
*/
protected boolean isScannedClass;
/** The classpath element that this class was found within. */
transient ClasspathElement classpathElement;
/** The {@link Resource} for the classfile of this class. */
protected transient Resource classfileResource;
/** The classloader this class was obtained from. */
transient ClassLoader classLoader;
/** Info on the class module. */
ModuleInfo moduleInfo;
/** Info on the package containing the class. */
PackageInfo packageInfo;
/** Info on class annotations, including optional annotation param values. */
AnnotationInfoList annotationInfo;
/** Info on fields. */
FieldInfoList fieldInfo;
/** Info on fields. */
MethodInfoList methodInfo;
/** For annotations, the default values of parameters. */
AnnotationParameterValueList annotationDefaultParamValues;
/**
* Names of classes referenced by this class in class refs and type signatures in the constant pool of the
* classfile.
*/
private Set<String> referencedClassNames;
/** A list of ClassInfo objects for classes referenced by this class. */
private ClassInfoList referencedClasses;
/**
* Set to true once any Object[] arrays of boxed types in annotationDefaultParamValues have been lazily
* converted to primitive arrays.
*/
transient boolean annotationDefaultParamValuesHasBeenConvertedToPrimitive;
/** The set of classes related to this one. */
private Map<RelType, Set<ClassInfo>> relatedClasses;
/**
* The override order for a class' fields or methods (base class, followed by interfaces, followed by
* superclasses).
*/
private transient List<ClassInfo> overrideOrder;
// -------------------------------------------------------------------------------------------------------------
/** The modifier bit for annotations. */
private static final int ANNOTATION_CLASS_MODIFIER = 0x2000;
/** The constant empty return value used when no classes are reachable. */
private static final ReachableAndDirectlyRelatedClasses NO_REACHABLE_CLASSES = //
new ReachableAndDirectlyRelatedClasses(Collections.<ClassInfo> emptySet(),
Collections.<ClassInfo> emptySet());
// -------------------------------------------------------------------------------------------------------------
/** Default constructor for deserialization. */
ClassInfo() {
super();
}
/**
* Constructor.
*
* @param name
* the name
* @param classModifiers
* the class modifiers
* @param classfileResource
* the classfile resource
*/
protected ClassInfo(final String name, final int classModifiers, final Resource classfileResource) {
super();
this.name = name;
if (name.endsWith(";")) {
// Spot check to make sure class names were parsed from descriptors
throw new IllegalArgumentException("Bad class name");
}
setModifiers(classModifiers);
this.classfileResource = classfileResource;
this.relatedClasses = new EnumMap<>(RelType.class);
}
// -------------------------------------------------------------------------------------------------------------
/** How classes are related. */
enum RelType {
// Classes:
/**
* Superclasses of this class, if this is a regular class.
*
* <p>
* (Should consist of only one entry, or null if superclass is java.lang.Object or unknown).
*/
SUPERCLASSES,
/** Subclasses of this class, if this is a regular class. */
SUBCLASSES,
/** Indicates that an inner class is contained within this one. */
CONTAINS_INNER_CLASS,
/** Indicates that an outer class contains this one. (Should only have zero or one entries.) */
CONTAINED_WITHIN_OUTER_CLASS,
// Interfaces:
/**
* Interfaces that this class implements, if this is a regular class, or superinterfaces, if this is an
* interface.
*
* <p>
* (May also include annotations, since annotations are interfaces, so you can implement an annotation.)
*/
IMPLEMENTED_INTERFACES,
/**
* Classes that implement this interface (including sub-interfaces), if this is an interface.
*/
CLASSES_IMPLEMENTING,
// Class annotations:
/**
* Annotations on this class, if this is a regular class, or meta-annotations on this annotation, if this is
* an annotation.
*/
CLASS_ANNOTATIONS,
/** Classes annotated with this annotation, if this is an annotation. */
CLASSES_WITH_ANNOTATION,
// Method annotations:
/** Annotations on one or more methods of this class. */
METHOD_ANNOTATIONS,
/**
* Classes that have one or more methods annotated with this annotation, if this is an annotation.
*/
CLASSES_WITH_METHOD_ANNOTATION,
/**
* Classes that have one or more non-private (inherited) methods annotated with this annotation, if this is
* an annotation.
*/
CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION,
/** Annotations on one or more parameters of methods of this class. */
METHOD_PARAMETER_ANNOTATIONS,
/**
* Classes that have one or more methods that have one or more parameters annotated with this annotation, if
* this is an annotation.
*/
CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,
/**
* Classes that have one or more non-private (inherited) methods that have one or more parameters annotated
* with this annotation, if this is an annotation.
*/
CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION,
// Field annotations:
/** Annotations on one or more fields of this class. */
FIELD_ANNOTATIONS,
/**
* Classes that have one or more fields annotated with this annotation, if this is an annotation.
*/
CLASSES_WITH_FIELD_ANNOTATION,
/**
* Classes that have one or more non-private (inherited) fields annotated with this annotation, if this is
* an annotation.
*/
CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION,
}
/**
* Add a class with a given relationship type. Return whether the collection changed as a result of the call.
*
* @param relType
* the {@link RelType}
* @param classInfo
* the {@link ClassInfo}
* @return true, if successful
*/
boolean addRelatedClass(final RelType relType, final ClassInfo classInfo) {
Set<ClassInfo> classInfoSet = relatedClasses.get(relType);
if (classInfoSet == null) {
relatedClasses.put(relType, classInfoSet = new LinkedHashSet<>(4));
}
return classInfoSet.add(classInfo);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get a ClassInfo object, or create it if it doesn't exist. N.B. not threadsafe, so ClassInfo objects should
* only ever be constructed by a single thread.
*
* @param className
* the class name
* @param classNameToClassInfo
* the map from class name to class info
* @return the {@link ClassInfo} object.
*/
static ClassInfo getOrCreateClassInfo(final String className,
final Map<String, ClassInfo> classNameToClassInfo) {
// Look for array class names
int numArrayDims = 0;
String baseClassName = className;
while (baseClassName.endsWith("[]")) {
numArrayDims++;
baseClassName = baseClassName.substring(0, baseClassName.length() - 2);
}
// Be resilient to the use of class descriptors rather than class names (should not be needed)
while (baseClassName.startsWith("[")) {
numArrayDims++;
baseClassName = baseClassName.substring(1);
}
if (baseClassName.endsWith(";")) {
baseClassName = baseClassName.substring(baseClassName.length() - 1);
}
baseClassName = baseClassName.replace('/', '.');
ClassInfo classInfo = classNameToClassInfo.get(className);
if (classInfo == null) {
classNameToClassInfo.put(className, //
classInfo = numArrayDims == 0 //
? new ClassInfo(baseClassName, /* classModifiers = */ 0, /* classfileResource = */ null)
: new ArrayClassInfo(new ArrayTypeSignature(baseClassName, numArrayDims)));
}
return classInfo;
}
/**
* Set class modifiers.
*
* @param modifiers
* the class modifiers
*/
void setModifiers(final int modifiers) {
this.modifiers |= modifiers;
}
/**
* Set isInterface status.
*
* @param isInterface
* true if this is an interface
*/
void setIsInterface(final boolean isInterface) {
if (isInterface) {
this.modifiers |= Modifier.INTERFACE;
}
}
/**
* Set isInterface status.
*
* @param isAnnotation
* true if this is an annotation
*/
void setIsAnnotation(final boolean isAnnotation) {
if (isAnnotation) {
this.modifiers |= ANNOTATION_CLASS_MODIFIER;
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Add a superclass to this class.
*
* @param superclassName
* the superclass name
* @param classNameToClassInfo
* the map from class name to class info
*/
void addSuperclass(final String superclassName, final Map<String, ClassInfo> classNameToClassInfo) {
if (superclassName != null && !superclassName.equals("java.lang.Object")) {
final ClassInfo superclassClassInfo = getOrCreateClassInfo(superclassName, classNameToClassInfo);
this.addRelatedClass(RelType.SUPERCLASSES, superclassClassInfo);
superclassClassInfo.addRelatedClass(RelType.SUBCLASSES, this);
}
}
/**
* Add an implemented interface to this class.
*
* @param interfaceName
* the interface name
* @param classNameToClassInfo
* the map from class name to class info
*/
void addImplementedInterface(final String interfaceName, final Map<String, ClassInfo> classNameToClassInfo) {
final ClassInfo interfaceClassInfo = getOrCreateClassInfo(interfaceName, classNameToClassInfo);
interfaceClassInfo.setIsInterface(true);
this.addRelatedClass(RelType.IMPLEMENTED_INTERFACES, interfaceClassInfo);
interfaceClassInfo.addRelatedClass(RelType.CLASSES_IMPLEMENTING, this);
}
/**
* Add class containment info.
*
* @param classContainmentEntries
* the class containment entries
* @param classNameToClassInfo
* the map from class name to class info
*/
static void addClassContainment(final List<ClassContainment> classContainmentEntries,
final Map<String, ClassInfo> classNameToClassInfo) {
for (final ClassContainment classContainment : classContainmentEntries) {
final ClassInfo innerClassInfo = ClassInfo.getOrCreateClassInfo(classContainment.innerClassName,
classNameToClassInfo);
innerClassInfo.setModifiers(classContainment.innerClassModifierBits);
final ClassInfo outerClassInfo = ClassInfo.getOrCreateClassInfo(classContainment.outerClassName,
classNameToClassInfo);
innerClassInfo.addRelatedClass(RelType.CONTAINED_WITHIN_OUTER_CLASS, outerClassInfo);
outerClassInfo.addRelatedClass(RelType.CONTAINS_INNER_CLASS, innerClassInfo);
}
}
/**
* Add containing method name, for anonymous inner classes.
*
* @param fullyQualifiedDefiningMethodName
* the fully qualified defining method name
*/
void addFullyQualifiedDefiningMethodName(final String fullyQualifiedDefiningMethodName) {
this.fullyQualifiedDefiningMethodName = fullyQualifiedDefiningMethodName;
}
/**
* Add an annotation to this class.
*
* @param classAnnotationInfo
* the class annotation info
* @param classNameToClassInfo
* the map from class name to class info
*/
void addClassAnnotation(final AnnotationInfo classAnnotationInfo,
final Map<String, ClassInfo> classNameToClassInfo) {
final ClassInfo annotationClassInfo = getOrCreateClassInfo(classAnnotationInfo.getName(),
classNameToClassInfo);
annotationClassInfo.setModifiers(ANNOTATION_CLASS_MODIFIER);
if (this.annotationInfo == null) {
this.annotationInfo = new AnnotationInfoList(2);
}
this.annotationInfo.add(classAnnotationInfo);
this.addRelatedClass(RelType.CLASS_ANNOTATIONS, annotationClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_ANNOTATION, this);
// Record use of @Inherited meta-annotation
if (classAnnotationInfo.getName().equals(Inherited.class.getName())) {
isInherited = true;
}
}
/**
* Add field or method annotation cross-links.
*
* @param annotationInfoList
* the annotation info list
* @param isField
* the is field
* @param modifiers
* the field or method modifiers
* @param classNameToClassInfo
* the map from class name to class info
*/
private void addFieldOrMethodAnnotationInfo(final AnnotationInfoList annotationInfoList, final boolean isField,
final int modifiers, final Map<String, ClassInfo> classNameToClassInfo) {
if (annotationInfoList != null) {
for (final AnnotationInfo fieldAnnotationInfo : annotationInfoList) {
final ClassInfo annotationClassInfo = getOrCreateClassInfo(fieldAnnotationInfo.getName(),
classNameToClassInfo);
annotationClassInfo.setModifiers(ANNOTATION_CLASS_MODIFIER);
// Mark this class as having a field or method with this annotation
this.addRelatedClass(isField ? RelType.FIELD_ANNOTATIONS : RelType.METHOD_ANNOTATIONS,
annotationClassInfo);
annotationClassInfo.addRelatedClass(
isField ? RelType.CLASSES_WITH_FIELD_ANNOTATION : RelType.CLASSES_WITH_METHOD_ANNOTATION,
this);
// For non-private methods/fields, also add to nonprivate (inherited) mapping
if (!Modifier.isPrivate(modifiers)) {
annotationClassInfo.addRelatedClass(isField ? RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION
: RelType.CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION, this);
}
}
}
}
/**
* Add field info.
*
* @param fieldInfoList
* the field info list
* @param classNameToClassInfo
* the map from class name to class info
*/
void addFieldInfo(final FieldInfoList fieldInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final FieldInfo fi : fieldInfoList) {
// Index field annotations
addFieldOrMethodAnnotationInfo(fi.annotationInfo, /* isField = */ true, fi.getModifiers(),
classNameToClassInfo);
}
if (this.fieldInfo == null) {
this.fieldInfo = fieldInfoList;
} else {
this.fieldInfo.addAll(fieldInfoList);
}
}
/**
* Add method info.
*
* @param methodInfoList
* the method info list
* @param classNameToClassInfo
* the map from class name to class info
*/
void addMethodInfo(final MethodInfoList methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) {
for (final MethodInfo mi : methodInfoList) {
// Index method annotations
addFieldOrMethodAnnotationInfo(mi.annotationInfo, /* isField = */ false, mi.getModifiers(),
classNameToClassInfo);
// Index method parameter annotations
if (mi.parameterAnnotationInfo != null) {
for (int i = 0; i < mi.parameterAnnotationInfo.length; i++) {
final AnnotationInfo[] paramAnnotationInfoArr = mi.parameterAnnotationInfo[i];
if (paramAnnotationInfoArr != null) {
for (int j = 0; j < paramAnnotationInfoArr.length; j++) {
final AnnotationInfo methodParamAnnotationInfo = paramAnnotationInfoArr[j];
final ClassInfo annotationClassInfo = getOrCreateClassInfo(
methodParamAnnotationInfo.getName(), classNameToClassInfo);
annotationClassInfo.setModifiers(ANNOTATION_CLASS_MODIFIER);
this.addRelatedClass(RelType.METHOD_PARAMETER_ANNOTATIONS, annotationClassInfo);
annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,
this);
// For non-private methods/fields, also add to nonprivate (inherited) mapping
if (!Modifier.isPrivate(mi.getModifiers())) {
annotationClassInfo.addRelatedClass(
RelType.CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION, this);
}
}
}
}
}
}
if (this.methodInfo == null) {
this.methodInfo = methodInfoList;
} else {
this.methodInfo.addAll(methodInfoList);
}
}
/**
* Set the class type signature, including any type params.
*
* @param typeSignatureStr
* the type signature str
*/
void setTypeSignature(final String typeSignatureStr) {
this.typeSignatureStr = typeSignatureStr;
}
/**
* Add annotation default values. (Only called in the case of annotation class definitions, when the annotation
* has default parameter values.)
*
* @param paramNamesAndValues
* the default param names and values, if this is an annotation
*/
void addAnnotationParamDefaultValues(final AnnotationParameterValueList paramNamesAndValues) {
setIsAnnotation(true);
if (this.annotationDefaultParamValues == null) {
this.annotationDefaultParamValues = paramNamesAndValues;
} else {
this.annotationDefaultParamValues.addAll(paramNamesAndValues);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Add a class that has just been scanned (as opposed to just referenced by a scanned class). Not threadsafe,
* should be run in single threaded context.
*
* @param className
* the class name
* @param classModifiers
* the class modifiers
* @param isExternalClass
* true if this is an external class
* @param classNameToClassInfo
* the map from class name to class info
* @param classpathElement
* the classpath element
* @param classfileResource
* the classfile resource
* @return the class info
*/
static ClassInfo addScannedClass(final String className, final int classModifiers,
final boolean isExternalClass, final Map<String, ClassInfo> classNameToClassInfo,
final ClasspathElement classpathElement, final Resource classfileResource) {
ClassInfo classInfo = classNameToClassInfo.get(className);
if (classInfo == null) {
// This is the first time this class has been seen, add it
classNameToClassInfo.put(className,
classInfo = new ClassInfo(className, classModifiers, classfileResource));
} else {
// There was a previous placeholder ClassInfo class added, due to the class being referred
// to as a superclass, interface or annotation. The isScannedClass field should be false
// in this case, since the actual class definition wasn't reached before now.
if (classInfo.isScannedClass) {
// The class should not have been scanned more than once, because of classpath masking
throw new IllegalArgumentException("Class " + className
+ " should not have been encountered more than once due to classpath masking --"
+ " please report this bug at: https://github.com/classgraph/classgraph/issues");
}
// Set the classfileResource for the placeholder class
classInfo.classfileResource = classfileResource;
// Add any additional modifier bits
classInfo.modifiers |= classModifiers;
}
// Mark the class as scanned
classInfo.isScannedClass = true;
// Mark the class as non-external if it is a whitelisted class
classInfo.isExternalClass = isExternalClass;
// Remember which classpath element (zipfile / classpath root directory / module) the class was found in
classInfo.classpathElement = classpathElement;
// Remember which classloader is used to load the class
classInfo.classLoader = classpathElement.getClassLoader();
return classInfo;
}
// -------------------------------------------------------------------------------------------------------------
/** The class type to return. */
private enum ClassType {
/** Get all class types. */
ALL,
/** A standard class (not an interface or annotation). */
STANDARD_CLASS,
/**
* An interface (this is named "implemented interface" rather than just "interface" to distinguish it from
* an annotation.)
*/
IMPLEMENTED_INTERFACE,
/** An annotation. */
ANNOTATION,
/** An interface or annotation (used since you can actually implement an annotation). */
INTERFACE_OR_ANNOTATION,
}
/**
* Filter classes according to scan spec and class type.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @param strictWhitelist
* If true, exclude class if it is is external, blacklisted, or a system class.
* @param classTypes
* the class types
* @return the filtered classes.
*/
private static Set<ClassInfo> filterClassInfo(final Collection<ClassInfo> classes, final ScanSpec scanSpec,
final boolean strictWhitelist, final ClassType... classTypes) {
if (classes == null) {
return Collections.<ClassInfo> emptySet();
}
boolean includeAllTypes = classTypes.length == 0;
boolean includeStandardClasses = false;
boolean includeImplementedInterfaces = false;
boolean includeAnnotations = false;
for (final ClassType classType : classTypes) {
switch (classType) {
case ALL:
includeAllTypes = true;
break;
case STANDARD_CLASS:
includeStandardClasses = true;
break;
case IMPLEMENTED_INTERFACE:
includeImplementedInterfaces = true;
break;
case ANNOTATION:
includeAnnotations = true;
break;
case INTERFACE_OR_ANNOTATION:
includeImplementedInterfaces = includeAnnotations = true;
break;
default:
throw new IllegalArgumentException("Unknown ClassType: " + classType);
}
}
if (includeStandardClasses && includeImplementedInterfaces && includeAnnotations) {
includeAllTypes = true;
}
final Set<ClassInfo> classInfoSetFiltered = new LinkedHashSet<>(classes.size());
for (final ClassInfo classInfo : classes) {
// Check class type against requested type(s)
if ((includeAllTypes //
|| includeStandardClasses && classInfo.isStandardClass()
|| includeImplementedInterfaces && classInfo.isImplementedInterface()
|| includeAnnotations && classInfo.isAnnotation()) //
// Always check blacklist
&& !scanSpec.classOrPackageIsBlacklisted(classInfo.name) //
// Always return whitelisted classes, or external classes if enableExternalClasses is true
&& (!classInfo.isExternalClass || scanSpec.enableExternalClasses
// Return external (non-whitelisted) classes if viewing class hierarchy "upwards"
|| !strictWhitelist)) {
// Class passed strict whitelist criteria
classInfoSetFiltered.add(classInfo);
}
}
return classInfoSetFiltered;
}
/**
* A set of classes that indirectly reachable through a directed path, for a given relationship type, and a set
* of classes that is directly related (only one relationship step away).
*/
static class ReachableAndDirectlyRelatedClasses {
/** The reachable classes. */
final Set<ClassInfo> reachableClasses;
/** The directly related classes. */
final Set<ClassInfo> directlyRelatedClasses;
/**
* Constructor.
*
* @param reachableClasses
* the reachable classes
* @param directlyRelatedClasses
* the directly related classes
*/
private ReachableAndDirectlyRelatedClasses(final Set<ClassInfo> reachableClasses,
final Set<ClassInfo> directlyRelatedClasses) {
this.reachableClasses = reachableClasses;
this.directlyRelatedClasses = directlyRelatedClasses;
}
}
/**
* Get the classes related to this one (the transitive closure) for the given relationship type, and those
* directly related.
*
* @param relType
* the rel type
* @param strictWhitelist
* the strict whitelist
* @param classTypes
* the class types
* @return the reachable and directly related classes
*/
private ReachableAndDirectlyRelatedClasses filterClassInfo(final RelType relType, final boolean strictWhitelist,
final ClassType... classTypes) {
Set<ClassInfo> directlyRelatedClasses = this.relatedClasses.get(relType);
if (directlyRelatedClasses == null) {
return NO_REACHABLE_CLASSES;
} else {
// Clone collection to prevent users modifying contents accidentally or intentionally
directlyRelatedClasses = new LinkedHashSet<>(directlyRelatedClasses);
}
final Set<ClassInfo> reachableClasses = new LinkedHashSet<>(directlyRelatedClasses);
if (relType == RelType.METHOD_ANNOTATIONS || relType == RelType.METHOD_PARAMETER_ANNOTATIONS
|| relType == RelType.FIELD_ANNOTATIONS) {
// For method and field annotations, need to change the RelType when finding meta-annotations
for (final ClassInfo annotation : directlyRelatedClasses) {
reachableClasses.addAll(
annotation.filterClassInfo(RelType.CLASS_ANNOTATIONS, strictWhitelist).reachableClasses);
}
} else if (relType == RelType.CLASSES_WITH_METHOD_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION
|| relType == RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION
|| relType == RelType.CLASSES_WITH_FIELD_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION) {
// If looking for meta-annotated methods or fields, need to find all meta-annotated annotations, then
// look for the methods or fields that they annotate
for (final ClassInfo subAnnotation : this.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION,
strictWhitelist, ClassType.ANNOTATION).reachableClasses) {
final Set<ClassInfo> annotatedClasses = subAnnotation.relatedClasses.get(relType);
if (annotatedClasses != null) {
reachableClasses.addAll(annotatedClasses);
}
}
} else {
// For other relationship types, the reachable type stays the same over the transitive closure. Find the
// transitive closure, breaking cycles where necessary.
final LinkedList<ClassInfo> queue = new LinkedList<>(directlyRelatedClasses);
while (!queue.isEmpty()) {
final ClassInfo head = queue.removeFirst();
final Set<ClassInfo> headRelatedClasses = head.relatedClasses.get(relType);
if (headRelatedClasses != null) {
for (final ClassInfo directlyReachableFromHead : headRelatedClasses) {
// Don't get in cycle
if (reachableClasses.add(directlyReachableFromHead)) {
queue.add(directlyReachableFromHead);
}
}
}
}
}
if (reachableClasses.isEmpty()) {
return NO_REACHABLE_CLASSES;
}
if (relType == RelType.CLASS_ANNOTATIONS || relType == RelType.METHOD_ANNOTATIONS
|| relType == RelType.METHOD_PARAMETER_ANNOTATIONS || relType == RelType.FIELD_ANNOTATIONS) {
// Special case -- don't inherit java.lang.annotation.* meta-annotations as related meta-annotations
// (but still return them as direct meta-annotations on annotation classes).
Set<ClassInfo> reachableClassesToRemove = null;
for (final ClassInfo reachableClassInfo : reachableClasses) {
// Remove all java.lang.annotation annotations that are not directly related to this class
if (reachableClassInfo.getName().startsWith("java.lang.annotation.")
&& !directlyRelatedClasses.contains(reachableClassInfo)) {
if (reachableClassesToRemove == null) {
reachableClassesToRemove = new LinkedHashSet<>();
}
reachableClassesToRemove.add(reachableClassInfo);
}
}
if (reachableClassesToRemove != null) {
reachableClasses.removeAll(reachableClassesToRemove);
}
}
return new ReachableAndDirectlyRelatedClasses(
filterClassInfo(reachableClasses, scanResult.scanSpec, strictWhitelist, classTypes),
filterClassInfo(directlyRelatedClasses, scanResult.scanSpec, strictWhitelist, classTypes));
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get all classes found during the scan.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) {
return new ClassInfoList(
ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.ALL),
/* sortByName = */ true);
}
/**
* Get all standard classes found during the scan.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all standard classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllStandardClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) {
return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true,
ClassType.STANDARD_CLASS), /* sortByName = */ true);
}
/**
* Get all implemented interface (non-annotation interface) classes found during the scan.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all annotation classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllImplementedInterfaceClasses(final Collection<ClassInfo> classes,
final ScanSpec scanSpec) {
return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true,
ClassType.IMPLEMENTED_INTERFACE), /* sortByName = */ true);
}
/**
* Get all annotation classes found during the scan. See also
* {@link #getAllInterfacesOrAnnotationClasses(Collection, ScanSpec, ScanResult)} ()}.
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all annotation classes found during the scan, or the empty list if none.
*/
static ClassInfoList getAllAnnotationClasses(final Collection<ClassInfo> classes, final ScanSpec scanSpec) {
return new ClassInfoList(
ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true, ClassType.ANNOTATION),
/* sortByName = */ true);
}
/**
* Get all interface or annotation classes found during the scan. (Annotations are technically interfaces, and
* they can be implemented.)
*
* @param classes
* the classes
* @param scanSpec
* the scan spec
* @return A list of all whitelisted interfaces found during the scan, or the empty list if none.
*/
static ClassInfoList getAllInterfacesOrAnnotationClasses(final Collection<ClassInfo> classes,
final ScanSpec scanSpec) {
return new ClassInfoList(ClassInfo.filterClassInfo(classes, scanSpec, /* strictWhitelist = */ true,
ClassType.INTERFACE_OR_ANNOTATION), /* sortByName = */ true);
}
// -------------------------------------------------------------------------------------------------------------
// Predicates
/**
* Get the name of the class.
*
* @return The name of the class.
*/
@Override
public String getName() {
return name;
}
/**
* Get simple name from fully-qualified class name. Returns everything after the last '.' in the class name, or
* the whole string if the class is in the root package. (Note that this is not the same as the result of
* {@link Class#getSimpleName()}, which returns "" for anonymous classes.)
*
* @param className
* the class name
* @return The simple name of the class.
*/
static String getSimpleName(final String className) {
return className.substring(className.lastIndexOf('.') + 1);
}
/**
* Get the simple name of the class. Returns everything after the last '.' in the class name, or the whole
* string if the class is in the root package. (Note that this is not the same as the result of
* {@link Class#getSimpleName()}, which returns "" for anonymous classes.)
*
* @return The simple name of the class.
*/
public String getSimpleName() {
return getSimpleName(name);
}
/**
* Get the {@link ModuleInfo} object for the class.
*
* @return the {@link ModuleInfo} object for the class, or null if the class is not part of a named module.
*/
public ModuleInfo getModuleInfo() {
return moduleInfo;
}
/**
* Get the {@link PackageInfo} object for the class.
*
* @return the {@link PackageInfo} object for the package that contains the class.
*/
public PackageInfo getPackageInfo() {
return packageInfo;
}
/**
* Get the name of the class' package.
*
* @return The name of the class' package.
*/
public String getPackageName() {
return PackageInfo.getParentPackageName(name);
}
/**
* Checks if this is an external class.
*
* @return true if this class is an external class, i.e. was referenced by a whitelisted class as a superclass,
* interface, or annotation, but is not itself a whitelisted class.
*/
public boolean isExternalClass() {
return isExternalClass;
}
/**
* Get the class modifier bits.
*
* @return The class modifier bits, e.g. {@link Modifier#PUBLIC}.
*/
public int getModifiers() {
return modifiers;
}
/**
* Get the class modifiers as a String.
*
* @return The field modifiers as a string, e.g. "public static final". For the modifier bits, call
* {@link #getModifiers()}.
*/
public String getModifiersStr() {
final StringBuilder buf = new StringBuilder();
TypeUtils.modifiersToString(modifiers, ModifierType.CLASS, /* ignored */ false, buf);
return buf.toString();
}
/**
* Checks if the class is public.
*
* @return true if this class is a public class.
*/
public boolean isPublic() {
return (modifiers & Modifier.PUBLIC) != 0;
}
/**
* Checks if the class is abstract.
*
* @return true if this class is an abstract class.
*/
public boolean isAbstract() {
return (modifiers & 0x400) != 0;
}
/**
* Checks if the class is synthetic.
*
* @return true if this class is a synthetic class.
*/
public boolean isSynthetic() {
return (modifiers & 0x1000) != 0;
}
/**
* Checks if the class is final.
*
* @return true if this class is a final class.
*/
public boolean isFinal() {
return (modifiers & Modifier.FINAL) != 0;
}
/**
* Checks if the class is static.
*
* @return true if this class is static.
*/
public boolean isStatic() {
return Modifier.isStatic(modifiers);
}
/**
* Checks if the class is an annotation.
*
* @return true if this class is an annotation class.
*/
public boolean isAnnotation() {
return (modifiers & ANNOTATION_CLASS_MODIFIER) != 0;
}
/**
* Checks if is the class an interface and is not an annotation.
*
* @return true if this class is an interface and is not an annotation (annotations are interfaces, and can be
* implemented).
*/
public boolean isInterface() {
return isInterfaceOrAnnotation() && !isAnnotation();
}
/**
* Checks if is an interface or an annotation.
*
* @return true if this class is an interface or an annotation (annotations are interfaces, and can be
* implemented).
*/
public boolean isInterfaceOrAnnotation() {
return (modifiers & Modifier.INTERFACE) != 0;
}
/**
* Checks if is the class is an {@link Enum}.
*
* @return true if this class is an {@link Enum}.
*/
public boolean isEnum() {
return (modifiers & 0x4000) != 0;
}
/**
* Checks if this class is a standard class.
*
* @return true if this class is a standard class (i.e. is not an annotation or interface).
*/
public boolean isStandardClass() {
return !(isAnnotation() || isInterface());
}
/**
* Checks if this class is an array class. Returns false unless this {@link ClassInfo} is an instance of
* {@link ArrayClassInfo}.
*
* @return true if this is an array class.
*/
public boolean isArrayClass() {
return this instanceof ArrayClassInfo;
}
/**
* Checks if this class extends the named superclass.
*
* @param superclassName
* The name of a superclass.
* @return true if this class extends the named superclass.
*/
public boolean extendsSuperclass(final String superclassName) {
return getSuperclasses().containsName(superclassName);
}
/**
* Checks if this class is an inner class.
*
* @return true if this is an inner class (call {@link #isAnonymousInnerClass()} to test if this is an anonymous
* inner class). If true, the containing class can be determined by calling {@link #getOuterClasses()}.
*/
public boolean isInnerClass() {
return !getOuterClasses().isEmpty();
}
/**
* Checks if this class is an outer class.
*
* @return true if this class contains inner classes. If true, the inner classes can be determined by calling
* {@link #getInnerClasses()}.
*/
public boolean isOuterClass() {
return !getInnerClasses().isEmpty();
}
/**
* Checks if this class is an anonymous inner class.
*
* @return true if this is an anonymous inner class. If true, the name of the containing method can be obtained
* by calling {@link #getFullyQualifiedDefiningMethodName()}.
*/
public boolean isAnonymousInnerClass() {
return fullyQualifiedDefiningMethodName != null;
}
/**
* Checks whether this class is an implemented interface (meaning a standard, non-annotation interface, or an
* annotation that has also been implemented as an interface by some class).
*
* <p>
* Annotations are interfaces, but you can also implement an annotation, so to we return whether an interface
* (even an annotation) is implemented by a class or extended by a subinterface, or (failing that) if it is not
* an interface but not an annotation.
*
* @return true if this class is an implemented interface.
*/
public boolean isImplementedInterface() {
return relatedClasses.get(RelType.CLASSES_IMPLEMENTING) != null || isInterface();
}
/**
* Checks whether this class implements the named interface.
*
* @param interfaceName
* The name of an interface.
* @return true if this class implements the named interface.
*/
public boolean implementsInterface(final String interfaceName) {
return getInterfaces().containsName(interfaceName);
}
/**
* Checks whether this class has the named annotation.
*
* @param annotationName
* The name of an annotation.
* @return true if this class has the named annotation.
*/
public boolean hasAnnotation(final String annotationName) {
return getAnnotations().containsName(annotationName);
}
/**
* Checks whether this class has the named declared field.
*
* @param fieldName
* The name of a field.
* @return true if this class declares a field of the given name.
*/
public boolean hasDeclaredField(final String fieldName) {
return getDeclaredFieldInfo().containsName(fieldName);
}
/**
* Checks whether this class or one of its superclasses has the named field.
*
* @param fieldName
* The name of a field.
* @return true if this class or one of its superclasses declares a field of the given name.
*/
public boolean hasField(final String fieldName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredField(fieldName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class declares a field with the named annotation.
*
* @param fieldAnnotationName
* The name of a field annotation.
* @return true if this class declares a field with the named annotation.
*/
public boolean hasDeclaredFieldAnnotation(final String fieldAnnotationName) {
for (final FieldInfo fi : getDeclaredFieldInfo()) {
if (fi.hasAnnotation(fieldAnnotationName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class or one of its superclasses declares a field with the named annotation.
*
* @param fieldAnnotationName
* The name of a field annotation.
* @return true if this class or one of its superclasses declares a field with the named annotation.
*/
public boolean hasFieldAnnotation(final String fieldAnnotationName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredFieldAnnotation(fieldAnnotationName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class declares a field of the given name.
*
* @param methodName
* The name of a method.
* @return true if this class declares a field of the given name.
*/
public boolean hasDeclaredMethod(final String methodName) {
return getDeclaredMethodInfo().containsName(methodName);
}
/**
* Checks whether this class or one of its superclasses or interfaces declares a method of the given name.
*
* @param methodName
* The name of a method.
* @return true if this class or one of its superclasses or interfaces declares a method of the given name.
*/
public boolean hasMethod(final String methodName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredMethod(methodName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class declares a method with the named annotation.
*
* @param methodAnnotationName
* The name of a method annotation.
* @return true if this class declares a method with the named annotation.
*/
public boolean hasDeclaredMethodAnnotation(final String methodAnnotationName) {
for (final MethodInfo mi : getDeclaredMethodInfo()) {
if (mi.hasAnnotation(methodAnnotationName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class or one of its superclasses or interfaces declares a method with the named
* annotation.
*
* @param methodAnnotationName
* The name of a method annotation.
* @return true if this class or one of its superclasses or interfaces declares a method with the named
* annotation.
*/
public boolean hasMethodAnnotation(final String methodAnnotationName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredMethodAnnotation(methodAnnotationName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class declares a method with the named annotation.
*
* @param methodParameterAnnotationName
* The name of a method annotation.
* @return true if this class declares a method with the named annotation.
*/
public boolean hasDeclaredMethodParameterAnnotation(final String methodParameterAnnotationName) {
for (final MethodInfo mi : getDeclaredMethodInfo()) {
if (mi.hasParameterAnnotation(methodParameterAnnotationName)) {
return true;
}
}
return false;
}
/**
* Checks whether this class or one of its superclasses or interfaces has a method with the named annotation.
*
* @param methodParameterAnnotationName
* The name of a method annotation.
* @return true if this class or one of its superclasses or interfaces has a method with the named annotation.
*/
public boolean hasMethodParameterAnnotation(final String methodParameterAnnotationName) {
for (final ClassInfo ci : getOverrideOrder()) {
if (ci.hasDeclaredMethodParameterAnnotation(methodParameterAnnotationName)) {
return true;
}
}
return false;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Recurse to interfaces and superclasses to get the order that fields and methods are overridden in.
*
* @param visited
* visited
* @param overrideOrderOut
* the override order
* @return the override order
*/
private List<ClassInfo> getOverrideOrder(final Set<ClassInfo> visited, final List<ClassInfo> overrideOrderOut) {
if (visited.add(this)) {
overrideOrderOut.add(this);
for (final ClassInfo iface : getInterfaces()) {
iface.getOverrideOrder(visited, overrideOrderOut);
}
final ClassInfo superclass = getSuperclass();
if (superclass != null) {
superclass.getOverrideOrder(visited, overrideOrderOut);
}
}
return overrideOrderOut;
}
/**
* Get the order that fields and methods are overridden in (base class first).
*
* @return the override order
*/
private List<ClassInfo> getOverrideOrder() {
if (overrideOrder == null) {
overrideOrder = getOverrideOrder(new HashSet<ClassInfo>(), new ArrayList<ClassInfo>());
}
return overrideOrder;
}
// -------------------------------------------------------------------------------------------------------------
// Standard classes
/**
* Get the subclasses of this class, sorted in order of name. Call {@link ClassInfoList#directOnly()} to get
* direct subclasses.
*
* @return the list of subclasses of this class, or the empty list if none.
*/
public ClassInfoList getSubclasses() {
if (getName().equals("java.lang.Object")) {
// Make an exception for querying all subclasses of java.lang.Object
return scanResult.getAllClasses();
} else {
return new ClassInfoList(
this.filterClassInfo(RelType.SUBCLASSES, /* strictWhitelist = */ !isExternalClass),
/* sortByName = */ true);
}
}
/**
* Get all superclasses of this class, in ascending order in the class hierarchy. Does not include
* superinterfaces, if this is an interface (use {@link #getInterfaces()} to get superinterfaces of an
* interface.}
*
* @return the list of all superclasses of this class, or the empty list if none.
*/
public ClassInfoList getSuperclasses() {
return new ClassInfoList(this.filterClassInfo(RelType.SUPERCLASSES, /* strictWhitelist = */ false),
/* sortByName = */ false);
}
/**
* Get the single direct superclass of this class, or null if none. Does not return the superinterfaces, if this
* is an interface (use {@link #getInterfaces()} to get superinterfaces of an interface.}
*
* @return the superclass of this class, or null if none.
*/
public ClassInfo getSuperclass() {
final Set<ClassInfo> superClasses = relatedClasses.get(RelType.SUPERCLASSES);
if (superClasses == null || superClasses.isEmpty()) {
return null;
} else if (superClasses.size() > 2) {
throw new IllegalArgumentException("More than one superclass: " + superClasses);
} else {
final ClassInfo superclass = superClasses.iterator().next();
if (superclass.getName().equals("java.lang.Object")) {
return null;
} else {
return superclass;
}
}
}
/**
* Get the containing outer classes, if this is an inner class.
*
* @return A list of the containing outer classes, if this is an inner class, otherwise the empty list. Note
* that all containing outer classes are returned, not just the innermost of the containing outer
* classes.
*/
public ClassInfoList getOuterClasses() {
return new ClassInfoList(
this.filterClassInfo(RelType.CONTAINED_WITHIN_OUTER_CLASS, /* strictWhitelist = */ false),
/* sortByName = */ false);
}
/**
* Get the inner classes contained within this class, if this is an outer class.
*
* @return A list of the inner classes contained within this class, or the empty list if none.
*/
public ClassInfoList getInnerClasses() {
return new ClassInfoList(this.filterClassInfo(RelType.CONTAINS_INNER_CLASS, /* strictWhitelist = */ false),
/* sortByName = */ true);
}
/**
* Gets fully-qualified method name (i.e. fully qualified classname, followed by dot, followed by method name)
* for the defining method, if this is an anonymous inner class.
*
* @return The fully-qualified method name (i.e. fully qualified classname, followed by dot, followed by method
* name) for the defining method, if this is an anonymous inner class, or null if not.
*/
public String getFullyQualifiedDefiningMethodName() {
return fullyQualifiedDefiningMethodName;
}
// -------------------------------------------------------------------------------------------------------------
// Interfaces
/**
* Get the interfaces implemented by this class or by one of its superclasses, if this is a standard class, or
* the superinterfaces extended by this interface, if this is an interface.
*
* @return The list of interfaces implemented by this class or by one of its superclasses, if this is a standard
* class, or the superinterfaces extended by this interface, if this is an interface. Returns the empty
* list if none.
*/
public ClassInfoList getInterfaces() {
// Classes also implement the interfaces of their superclasses
final ReachableAndDirectlyRelatedClasses implementedInterfaces = this
.filterClassInfo(RelType.IMPLEMENTED_INTERFACES, /* strictWhitelist = */ false);
final Set<ClassInfo> allInterfaces = new LinkedHashSet<>(implementedInterfaces.reachableClasses);
for (final ClassInfo superclass : this.filterClassInfo(RelType.SUPERCLASSES,
/* strictWhitelist = */ false).reachableClasses) {
final Set<ClassInfo> superclassImplementedInterfaces = superclass.filterClassInfo(
RelType.IMPLEMENTED_INTERFACES, /* strictWhitelist = */ false).reachableClasses;
allInterfaces.addAll(superclassImplementedInterfaces);
}
return new ClassInfoList(allInterfaces, implementedInterfaces.directlyRelatedClasses,
/* sortByName = */ true);
}
/**
* Get the classes (and their subclasses) that implement this interface, if this is an interface.
*
* @return the list of the classes (and their subclasses) that implement this interface, if this is an
* interface, otherwise returns the empty list.
*/
public ClassInfoList getClassesImplementing() {
if (!isInterface()) {
throw new IllegalArgumentException("Class is not an interface: " + getName());
}
// Subclasses of implementing classes also implement the interface
final ReachableAndDirectlyRelatedClasses implementingClasses = this
.filterClassInfo(RelType.CLASSES_IMPLEMENTING, /* strictWhitelist = */ !isExternalClass);
final Set<ClassInfo> allImplementingClasses = new LinkedHashSet<>(implementingClasses.reachableClasses);
for (final ClassInfo implementingClass : implementingClasses.reachableClasses) {
final Set<ClassInfo> implementingSubclasses = implementingClass.filterClassInfo(RelType.SUBCLASSES,
/* strictWhitelist = */ !implementingClass.isExternalClass).reachableClasses;
allImplementingClasses.addAll(implementingSubclasses);
}
return new ClassInfoList(allImplementingClasses, implementingClasses.directlyRelatedClasses,
/* sortByName = */ true);
}
// -------------------------------------------------------------------------------------------------------------
// Annotations
/**
* Get the annotations and meta-annotations on this class. (Call {@link #getAnnotationInfo()} instead, if you
* need the parameter values of annotations, rather than just the annotation classes.)
*
* <p>
* Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of
* its subclasses.
*
* <p>
* Filters out meta-annotations in the {@code java.lang.annotation} package.
*
* @return the list of annotations and meta-annotations on this class.
*/
public ClassInfoList getAnnotations() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
// Get all annotations on this class
final ReachableAndDirectlyRelatedClasses annotationClasses = this.filterClassInfo(RelType.CLASS_ANNOTATIONS,
/* strictWhitelist = */ false);
// Check for any @Inherited annotations on superclasses
Set<ClassInfo> inheritedSuperclassAnnotations = null;
for (final ClassInfo superclass : getSuperclasses()) {
for (final ClassInfo superclassAnnotation : superclass.filterClassInfo(RelType.CLASS_ANNOTATIONS,
/* strictWhitelist = */ false).reachableClasses) {
// Check if any of the meta-annotations on this annotation are @Inherited,
// which causes an annotation to annotate a class and all of its subclasses.
if (superclassAnnotation != null && superclassAnnotation.isInherited) {
// superclassAnnotation has an @Inherited meta-annotation
if (inheritedSuperclassAnnotations == null) {
inheritedSuperclassAnnotations = new LinkedHashSet<>();
}
inheritedSuperclassAnnotations.add(superclassAnnotation);
}
}
}
if (inheritedSuperclassAnnotations == null) {
// No inherited superclass annotations
return new ClassInfoList(annotationClasses, /* sortByName = */ true);
} else {
// Merge inherited superclass annotations and annotations on this class
inheritedSuperclassAnnotations.addAll(annotationClasses.reachableClasses);
return new ClassInfoList(inheritedSuperclassAnnotations, annotationClasses.directlyRelatedClasses,
/* sortByName = */ true);
}
}
/**
* Get the annotations or meta-annotations on fields, methods or method parametres declared by the class, (not
* including fields, methods or method parameters declared by the interfaces or superclasses of this class).
*
* @param relType
* One of {@link RelType#FIELD_ANNOTATIONS}, {@link RelType#METHOD_ANNOTATIONS} or
* {@link RelType#METHOD_PARAMETER_ANNOTATIONS}.
* @return A list of annotations or meta-annotations on fields or methods declared by the class, (not including
* fields or methods declared by the interfaces or superclasses of this class), as a list of
* {@link ClassInfo} objects, or the empty list if none.
*/
private ClassInfoList getFieldOrMethodAnnotations(final RelType relType) {
final boolean isField = relType == RelType.FIELD_ANNOTATIONS;
if (!(isField ? scanResult.scanSpec.enableFieldInfo : scanResult.scanSpec.enableMethodInfo)
|| !scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enable" + (isField ? "Field" : "Method")
+ "Info() and " + "#enableAnnotationInfo() before #scan()");
}
final ReachableAndDirectlyRelatedClasses fieldOrMethodAnnotations = this.filterClassInfo(relType,
/* strictWhitelist = */ false, ClassType.ANNOTATION);
final Set<ClassInfo> fieldOrMethodAnnotationsAndMetaAnnotations = new LinkedHashSet<>(
fieldOrMethodAnnotations.reachableClasses);
return new ClassInfoList(fieldOrMethodAnnotationsAndMetaAnnotations,
fieldOrMethodAnnotations.directlyRelatedClasses, /* sortByName = */ true);
}
/**
* Get the classes that have this class as a field, method or method parameter annotation.
*
* @param relType
* One of {@link RelType#CLASSES_WITH_FIELD_ANNOTATION},
* {@link RelType#CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION},
* {@link RelType#CLASSES_WITH_METHOD_ANNOTATION},
* {@link RelType#CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION},
* {@link RelType#CLASSES_WITH_METHOD_PARAMETER_ANNOTATION}, or
* {@link RelType#CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION}.
* @return A list of classes that have a declared method with this annotation or meta-annotation, or the empty
* list if none.
*/
private ClassInfoList getClassesWithFieldOrMethodAnnotation(final RelType relType) {
final boolean isField = relType == RelType.CLASSES_WITH_FIELD_ANNOTATION
|| relType == RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION;
if (!(isField ? scanResult.scanSpec.enableFieldInfo : scanResult.scanSpec.enableMethodInfo)
|| !scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enable" + (isField ? "Field" : "Method")
+ "Info() and " + "#enableAnnotationInfo() before #scan()");
}
final ReachableAndDirectlyRelatedClasses classesWithDirectlyAnnotatedFieldsOrMethods = this
.filterClassInfo(relType, /* strictWhitelist = */ !isExternalClass);
final ReachableAndDirectlyRelatedClasses annotationsWithThisMetaAnnotation = this.filterClassInfo(
RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass, ClassType.ANNOTATION);
if (annotationsWithThisMetaAnnotation.reachableClasses.isEmpty()) {
// This annotation does not meta-annotate another annotation that annotates a method
return new ClassInfoList(classesWithDirectlyAnnotatedFieldsOrMethods, /* sortByName = */ true);
} else {
// Take the union of all classes with fields or methods directly annotated by this annotation,
// and classes with fields or methods meta-annotated by this annotation
final Set<ClassInfo> allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods = new LinkedHashSet<>(
classesWithDirectlyAnnotatedFieldsOrMethods.reachableClasses);
for (final ClassInfo metaAnnotatedAnnotation : annotationsWithThisMetaAnnotation.reachableClasses) {
allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods
.addAll(metaAnnotatedAnnotation.filterClassInfo(relType,
/* strictWhitelist = */ !metaAnnotatedAnnotation.isExternalClass).reachableClasses);
}
return new ClassInfoList(allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods,
classesWithDirectlyAnnotatedFieldsOrMethods.directlyRelatedClasses, /* sortByName = */ true);
}
}
/**
* Get a list of the annotations on this class, or the empty list if none.
*
* <p>
* Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of
* its subclasses.
*
* @return A list of {@link AnnotationInfo} objects for the annotations on this class, or the empty list if
* none.
*/
public AnnotationInfoList getAnnotationInfo() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
return AnnotationInfoList.getIndirectAnnotations(annotationInfo, this);
}
/**
* Get a the named non-{@link Repeatable} annotation on this class, or null if the class does not have the named
* annotation. (Use {@link #getAnnotationInfoRepeatable(String)} for {@link Repeatable} annotations.)
*
* <p>
* Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of
* its subclasses.
*
* <p>
* Note that if you need to get multiple named annotations, it is faster to call {@link #getAnnotationInfo()},
* and then get the named annotations from the returned {@link AnnotationInfoList}, so that the returned list
* doesn't have to be built multiple times.
*
* @param annotationName
* The annotation name.
* @return An {@link AnnotationInfo} object representing the named annotation on this class, or null if the
* class does not have the named annotation.
*/
public AnnotationInfo getAnnotationInfo(final String annotationName) {
return getAnnotationInfo().get(annotationName);
}
/**
* Get a the named {@link Repeatable} annotation on this class, or the empty list if the class does not have the
* named annotation.
*
* <p>
* Also handles the {@link Inherited} meta-annotation, which causes an annotation to annotate a class and all of
* its subclasses.
*
* <p>
* Note that if you need to get multiple named annotations, it is faster to call {@link #getAnnotationInfo()},
* and then get the named annotations from the returned {@link AnnotationInfoList}, so that the returned list
* doesn't have to be built multiple times.
*
* @param annotationName
* The annotation name.
* @return An {@link AnnotationInfoList} of all instances of the named annotation on this class, or the empty
* list if the class does not have the named annotation.
*/
public AnnotationInfoList getAnnotationInfoRepeatable(final String annotationName) {
return getAnnotationInfo().getRepeatable(annotationName);
}
/**
* Get the default parameter values for this annotation, if this is an annotation class.
*
* @return A list of {@link AnnotationParameterValue} objects for each of the default parameter values for this
* annotation, if this is an annotation class with default parameter values, otherwise the empty list.
*/
public AnnotationParameterValueList getAnnotationDefaultParameterValues() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
if (!isAnnotation()) {
throw new IllegalArgumentException("Class is not an annotation: " + getName());
}
if (annotationDefaultParamValues == null) {
return AnnotationParameterValueList.EMPTY_LIST;
}
if (!annotationDefaultParamValuesHasBeenConvertedToPrimitive) {
annotationDefaultParamValues.convertWrapperArraysToPrimitiveArrays(this);
annotationDefaultParamValuesHasBeenConvertedToPrimitive = true;
}
return annotationDefaultParamValues;
}
/**
* Get the classes that have this class as an annotation.
*
* @return A list of standard classes and non-annotation interfaces that are annotated by this class, if this is
* an annotation class, or the empty list if none. Also handles the {@link Inherited} meta-annotation,
* which causes an annotation on a class to be inherited by all of its subclasses.
*/
public ClassInfoList getClassesWithAnnotation() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
if (!isAnnotation()) {
throw new IllegalArgumentException("Class is not an annotation: " + getName());
}
// Get classes that have this annotation
final ReachableAndDirectlyRelatedClasses classesWithAnnotation = this
.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass);
if (isInherited) {
// If this is an inherited annotation, add into the result all subclasses of the annotated classes.
final Set<ClassInfo> classesWithAnnotationAndTheirSubclasses = new LinkedHashSet<>(
classesWithAnnotation.reachableClasses);
for (final ClassInfo classWithAnnotation : classesWithAnnotation.reachableClasses) {
classesWithAnnotationAndTheirSubclasses.addAll(classWithAnnotation.getSubclasses());
}
return new ClassInfoList(classesWithAnnotationAndTheirSubclasses,
classesWithAnnotation.directlyRelatedClasses, /* sortByName = */ true);
} else {
// If not inherited, only return the annotated classes
return new ClassInfoList(classesWithAnnotation, /* sortByName = */ true);
}
}
/**
* Get the classes that have this class as a direct annotation.
*
* @return The list of classes that are directly (i.e. are not meta-annotated) annotated with the requested
* annotation, or the empty list if none.
*/
ClassInfoList getClassesWithAnnotationDirectOnly() {
return new ClassInfoList(
this.filterClassInfo(RelType.CLASSES_WITH_ANNOTATION, /* strictWhitelist = */ !isExternalClass),
/* sortByName = */ true);
}
// -------------------------------------------------------------------------------------------------------------
// Methods
/**
* Get the declared methods, constructors, and/or static initializer methods of the class.
*
* @param methodName
* the method name
* @param getNormalMethods
* whether to get normal methods
* @param getConstructorMethods
* whether to get constructor methods
* @param getStaticInitializerMethods
* whether to get static initializer methods
* @return the declared method info
*/
private MethodInfoList getDeclaredMethodInfo(final String methodName, final boolean getNormalMethods,
final boolean getConstructorMethods, final boolean getStaticInitializerMethods) {
if (!scanResult.scanSpec.enableMethodInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableMethodInfo() before #scan()");
}
if (methodInfo == null) {
return MethodInfoList.EMPTY_LIST;
}
if (methodName == null) {
// If no method name is provided, filter for methods with the right type (normal method / constructor /
// static initializer)
final MethodInfoList methodInfoList = new MethodInfoList();
for (final MethodInfo mi : methodInfo) {
final String miName = mi.getName();
final boolean isConstructor = "<init>".equals(miName);
// (Currently static initializer methods are never returned by public methods)
final boolean isStaticInitializer = "<clinit>".equals(miName);
if ((isConstructor && getConstructorMethods) || (isStaticInitializer && getStaticInitializerMethods)
|| (!isConstructor && !isStaticInitializer && getNormalMethods)) {
methodInfoList.add(mi);
}
}
return methodInfoList;
} else {
// If method name is provided, filter for methods whose name matches, and ignore method type
boolean hasMethodWithName = false;
for (final MethodInfo f : methodInfo) {
if (f.getName().equals(methodName)) {
hasMethodWithName = true;
break;
}
}
if (!hasMethodWithName) {
return MethodInfoList.EMPTY_LIST;
}
final MethodInfoList methodInfoList = new MethodInfoList();
for (final MethodInfo mi : methodInfo) {
if (mi.getName().equals(methodName)) {
methodInfoList.add(mi);
}
}
return methodInfoList;
}
}
/**
* Get the methods, constructors, and/or static initializer methods of the class.
*
* @param methodName
* the method name
* @param getNormalMethods
* whether to get normal methods
* @param getConstructorMethods
* whether to get constructor methods
* @param getStaticInitializerMethods
* whether to get static initializer methods
* @return the method info
*/
private MethodInfoList getMethodInfo(final String methodName, final boolean getNormalMethods,
final boolean getConstructorMethods, final boolean getStaticInitializerMethods) {
if (!scanResult.scanSpec.enableMethodInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableMethodInfo() before #scan()");
}
// Implement method/constructor overriding
final MethodInfoList methodInfoList = new MethodInfoList();
final Set<Entry<String, String>> nameAndTypeDescriptorSet = new HashSet<>();
for (final ClassInfo ci : getOverrideOrder()) {
for (final MethodInfo mi : ci.getDeclaredMethodInfo(methodName, getNormalMethods, getConstructorMethods,
getStaticInitializerMethods)) {
// If method/constructor has not been overridden by method of same name and type descriptor
if (nameAndTypeDescriptorSet
.add(new SimpleEntry<>(mi.getName(), mi.getTypeDescriptor().toString()))) {
// Add method/constructor to output order
methodInfoList.add(mi);
}
}
}
return methodInfoList;
}
/**
* Returns information on visible methods declared by this class, but not by its interfaces or superclasses,
* that are not constructors. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one method of a given name with different type signatures, due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* @return the list of {@link MethodInfo} objects for visible methods declared by this class, or the empty list
* if no methods were found.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getDeclaredMethodInfo() {
return getDeclaredMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true,
/* getConstructorMethods = */ false, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on visible methods declared by this class, or by its interfaces or superclasses, that are
* not constructors. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one method of a given name with different type signatures, due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* @return the list of {@link MethodInfo} objects for visible methods of this class, its interfaces and
* superclasses, or the empty list if no methods were found.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getMethodInfo() {
return getMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true,
/* getConstructorMethods = */ false, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on visible constructors declared by this class, but not by its interfaces or
* superclasses. Constructors have the method name of {@code "<init>"}. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one constructor of a given name with different type signatures, due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public constructors, unless
* {@link ClassGraph#ignoreMethodVisibility()} was called before the scan.
*
* @return the list of {@link MethodInfo} objects for visible constructors declared by this class, or the empty
* list if no constructors were found or visible.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getDeclaredConstructorInfo() {
return getDeclaredMethodInfo(/* methodName = */ null, /* getNormalMethods = */ false,
/* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on visible constructors declared by this class, or by its interfaces or superclasses.
* Constructors have the method name of {@code "<init>"}. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one method of a given name with different type signatures, due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* @return the list of {@link MethodInfo} objects for visible constructors of this class and its superclasses,
* or the empty list if no methods were found.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getConstructorInfo() {
return getMethodInfo(/* methodName = */ null, /* getNormalMethods = */ false,
/* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on visible methods and constructors declared by this class, but not by its interfaces or
* superclasses. Constructors have the method name of {@code "<init>"} and static initializer blocks have the
* name of {@code "<clinit>"}. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one method or constructor or method of a given name with different type signatures,
* due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods and constructors, unless
* {@link ClassGraph#ignoreMethodVisibility()} was called before the scan. If method visibility is ignored, the
* result may include a reference to a private static class initializer block, with a method name of
* {@code "<clinit>"}.
*
* @return the list of {@link MethodInfo} objects for visible methods and constructors of this class, or the
* empty list if no methods or constructors were found or visible.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getDeclaredMethodAndConstructorInfo() {
return getDeclaredMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true,
/* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on visible constructors declared by this class, or by its interfaces or superclasses.
* Constructors have the method name of {@code "<init>"} and static initializer blocks have the name of
* {@code "<clinit>"}. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* There may be more than one method of a given name with different type signatures, due to overloading.
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* @return the list of {@link MethodInfo} objects for visible methods and constructors of this class, its
* interfaces and superclasses, or the empty list if no methods were found.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getMethodAndConstructorInfo() {
return getMethodInfo(/* methodName = */ null, /* getNormalMethods = */ true,
/* getConstructorMethods = */ true, /* getStaticInitializerMethods = */ false);
}
/**
* Returns information on the method(s) or constructor(s) of the given name declared by this class, but not by
* its interfaces or superclasses. Constructors have the method name of {@code "<init>"}. See also:
*
* <ul>
* <li>{@link #getMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* <p>
* May return info for multiple methods with the same name (with different type signatures).
*
* @param methodName
* The method name to query.
* @return a list of {@link MethodInfo} objects for the method(s) with the given name, or the empty list if the
* method was not found in this class (or is not visible).
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getDeclaredMethodInfo(final String methodName) {
return getDeclaredMethodInfo(methodName, /* ignored */ false, /* ignored */ false, /* ignored */ false);
}
/**
* Returns information on the method(s) or constructor(s) of the given name declared by this class, but not by
* its interfaces or superclasses. Constructors have the method name of {@code "<init>"}. See also:
*
* <ul>
* <li>{@link #getDeclaredMethodInfo(String)}
* <li>{@link #getMethodInfo()}
* <li>{@link #getDeclaredMethodInfo()}
* <li>{@link #getConstructorInfo()}
* <li>{@link #getDeclaredConstructorInfo()}
* <li>{@link #getMethodAndConstructorInfo()}
* <li>{@link #getDeclaredMethodAndConstructorInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableMethodInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreMethodVisibility()}
* was called before the scan.
*
* <p>
* May return info for multiple methods with the same name (with different type signatures).
*
* @param methodName
* The method name to query.
* @return a list of {@link MethodInfo} objects for the method(s) with the given name, or the empty list if the
* method was not found in this class (or is not visible).
* @throws IllegalArgumentException
* if {@link ClassGraph#enableMethodInfo()} was not called prior to initiating the scan.
*/
public MethodInfoList getMethodInfo(final String methodName) {
return getMethodInfo(methodName, /* ignored */ false, /* ignored */ false, /* ignored */ false);
}
/**
* Get all method annotations.
*
* @return A list of all annotations or meta-annotations on methods declared by the class, (not including
* methods declared by the interfaces or superclasses of this class), as a list of {@link ClassInfo}
* objects, or the empty list if none. N.B. these annotations do not contain specific annotation
* parameters -- call {@link MethodInfo#getAnnotationInfo()} to get details on specific method
* annotation instances.
*/
public ClassInfoList getMethodAnnotations() {
return getFieldOrMethodAnnotations(RelType.METHOD_ANNOTATIONS);
}
/**
* Get all method parameter annotations.
*
* @return A list of all annotations or meta-annotations on methods declared by the class, (not including
* methods declared by the interfaces or superclasses of this class), as a list of {@link ClassInfo}
* objects, or the empty list if none. N.B. these annotations do not contain specific annotation
* parameters -- call {@link MethodInfo#getAnnotationInfo()} to get details on specific method
* annotation instances.
*/
public ClassInfoList getMethodParameterAnnotations() {
return getFieldOrMethodAnnotations(RelType.METHOD_PARAMETER_ANNOTATIONS);
}
/**
* Get all classes that have this class as a method annotation, and their subclasses, if the method is
* non-private.
*
* @return A list of classes that have a declared method with this annotation or meta-annotation, or the empty
* list if none.
*/
public ClassInfoList getClassesWithMethodAnnotation() {
// Get all classes that have a method annotated or meta-annotated with this annotation
final Set<ClassInfo> classesWithMethodAnnotation = new HashSet<>(
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_METHOD_ANNOTATION));
// Add subclasses of all classes with a method that is non-privately annotated or meta-annotated with
// this annotation (non-private methods are inherited)
for (final ClassInfo classWithNonprivateMethodAnnotationOrMetaAnnotation : //
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_NONPRIVATE_METHOD_ANNOTATION)) {
classesWithMethodAnnotation.addAll(classWithNonprivateMethodAnnotationOrMetaAnnotation.getSubclasses());
}
return new ClassInfoList(classesWithMethodAnnotation,
new HashSet<>(getClassesWithMethodAnnotationDirectOnly()), /* sortByName = */ true);
}
/**
* Get all classes that have this class as a method parameter annotation, and their subclasses, if the method is
* non-private.
*
* @return A list of classes that have a declared method with a parameter that is annotated with this annotation
* or meta-annotation, or the empty list if none.
*/
public ClassInfoList getClassesWithMethodParameterAnnotation() {
// Get all classes that have a method annotated or meta-annotated with this annotation
final Set<ClassInfo> classesWithMethodParameterAnnotation = new HashSet<>(
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION));
// Add subclasses of all classes with a method that is non-privately annotated or meta-annotated with
// this annotation (non-private methods are inherited)
for (final ClassInfo classWithNonprivateMethodParameterAnnotationOrMetaAnnotation : //
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_NONPRIVATE_METHOD_PARAMETER_ANNOTATION)) {
classesWithMethodParameterAnnotation
.addAll(classWithNonprivateMethodParameterAnnotationOrMetaAnnotation.getSubclasses());
}
return new ClassInfoList(classesWithMethodParameterAnnotation,
new HashSet<>(getClassesWithMethodParameterAnnotationDirectOnly()), /* sortByName = */ true);
}
/**
* Get the classes that have this class as a direct method annotation.
*
* @return A list of classes that declare methods that are directly annotated (i.e. are not meta-annotated) with
* the requested method annotation, or the empty list if none.
*/
ClassInfoList getClassesWithMethodAnnotationDirectOnly() {
return new ClassInfoList(this.filterClassInfo(RelType.CLASSES_WITH_METHOD_ANNOTATION,
/* strictWhitelist = */ !isExternalClass), /* sortByName = */ true);
}
/**
* Get the classes that have this class as a direct method parameter annotation.
*
* @return A list of classes that declare methods with parameters that are directly annotated (i.e. are not
* meta-annotated) with the requested method annotation, or the empty list if none.
*/
ClassInfoList getClassesWithMethodParameterAnnotationDirectOnly() {
return new ClassInfoList(this.filterClassInfo(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,
/* strictWhitelist = */ !isExternalClass), /* sortByName = */ true);
}
// -------------------------------------------------------------------------------------------------------------
// Fields
/**
* Returns information on all visible fields declared by this class, but not by its superclasses. See also:
*
* <ul>
* <li>{@link #getFieldInfo(String)}
* <li>{@link #getDeclaredFieldInfo(String)}
* <li>{@link #getFieldInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableFieldInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreFieldVisibility()} was
* called before the scan.
*
* @return the list of FieldInfo objects for visible fields declared by this class, or the empty list if no
* fields were found or visible.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableFieldInfo()} was not called prior to initiating the scan.
*/
public FieldInfoList getDeclaredFieldInfo() {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
return fieldInfo == null ? FieldInfoList.EMPTY_LIST : fieldInfo;
}
/**
* Returns information on all visible fields declared by this class, or by its superclasses. See also:
*
* <ul>
* <li>{@link #getFieldInfo(String)}
* <li>{@link #getDeclaredFieldInfo(String)}
* <li>{@link #getDeclaredFieldInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableFieldInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreFieldVisibility()} was
* called before the scan.
*
* @return the list of FieldInfo objects for visible fields of this class or its superclases, or the empty list
* if no fields were found or visible.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableFieldInfo()} was not called prior to initiating the scan.
*/
public FieldInfoList getFieldInfo() {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
// Implement field overriding
final FieldInfoList fieldInfoList = new FieldInfoList();
final Set<String> fieldNameSet = new HashSet<>();
for (final ClassInfo ci : getOverrideOrder()) {
for (final FieldInfo fi : ci.getDeclaredFieldInfo()) {
// If field has not been overridden by field of same name
if (fieldNameSet.add(fi.getName())) {
// Add field to output order
fieldInfoList.add(fi);
}
}
}
return fieldInfoList;
}
/**
* Returns information on the named field declared by the class, but not by its superclasses. See also:
*
* <ul>
* <li>{@link #getFieldInfo(String)}
* <li>{@link #getFieldInfo()}
* <li>{@link #getDeclaredFieldInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableFieldInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public fields, unless {@link ClassGraph#ignoreFieldVisibility()} was
* called before the scan.
*
* @param fieldName
* The field name.
* @return the {@link FieldInfo} object for the named field declared by this class, or null if the field was not
* found in this class (or is not visible).
* @throws IllegalArgumentException
* if {@link ClassGraph#enableFieldInfo()} was not called prior to initiating the scan.
*/
public FieldInfo getDeclaredFieldInfo(final String fieldName) {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
if (fieldInfo == null) {
return null;
}
for (final FieldInfo fi : fieldInfo) {
if (fi.getName().equals(fieldName)) {
return fi;
}
}
return null;
}
/**
* Returns information on the named filed declared by this class, or by its superclasses. See also:
*
* <ul>
* <li>{@link #getDeclaredFieldInfo(String)}
* <li>{@link #getFieldInfo()}
* <li>{@link #getDeclaredFieldInfo()}
* </ul>
*
* <p>
* Requires that {@link ClassGraph#enableFieldInfo()} be called before scanning, otherwise throws
* {@link IllegalArgumentException}.
*
* <p>
* By default only returns information for public methods, unless {@link ClassGraph#ignoreFieldVisibility()} was
* called before the scan.
*
* @param fieldName
* The field name.
* @return the {@link FieldInfo} object for the named field of this class or its superclases, or the empty list
* if no fields were found or visible.
* @throws IllegalArgumentException
* if {@link ClassGraph#enableFieldInfo()} was not called prior to initiating the scan.
*/
public FieldInfo getFieldInfo(final String fieldName) {
if (!scanResult.scanSpec.enableFieldInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableFieldInfo() before #scan()");
}
// Implement field overriding
for (final ClassInfo ci : getOverrideOrder()) {
final FieldInfo fi = ci.getDeclaredFieldInfo(fieldName);
if (fi != null) {
return fi;
}
}
return null;
}
/**
* Get all field annotations.
*
* @return A list of all annotations on fields of this class, or the empty list if none. N.B. these annotations
* do not contain specific annotation parameters -- call {@link FieldInfo#getAnnotationInfo()} to get
* details on specific field annotation instances.
*/
public ClassInfoList getFieldAnnotations() {
return getFieldOrMethodAnnotations(RelType.FIELD_ANNOTATIONS);
}
/**
* Get the classes that have this class as a field annotation or meta-annotation.
*
* @return A list of classes that have a field with this annotation or meta-annotation, or the empty list if
* none.
*/
public ClassInfoList getClassesWithFieldAnnotation() {
// Get all classes that have a field annotated or meta-annotated with this annotation
final Set<ClassInfo> classesWithMethodAnnotation = new HashSet<>(
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_FIELD_ANNOTATION));
// Add subclasses of all classes with a field that is non-privately annotated or meta-annotated with
// this annotation (non-private fields are inherited)
for (final ClassInfo classWithNonprivateMethodAnnotationOrMetaAnnotation : //
getClassesWithFieldOrMethodAnnotation(RelType.CLASSES_WITH_NONPRIVATE_FIELD_ANNOTATION)) {
classesWithMethodAnnotation.addAll(classWithNonprivateMethodAnnotationOrMetaAnnotation.getSubclasses());
}
return new ClassInfoList(classesWithMethodAnnotation,
new HashSet<>(getClassesWithMethodAnnotationDirectOnly()), /* sortByName = */ true);
}
/**
* Get the classes that have this class as a direct field annotation.
*
* @return A list of classes that declare fields that are directly annotated (i.e. are not meta-annotated) with
* the requested method annotation, or the empty list if none.
*/
ClassInfoList getClassesWithFieldAnnotationDirectOnly() {
return new ClassInfoList(this.filterClassInfo(RelType.CLASSES_WITH_FIELD_ANNOTATION,
/* strictWhitelist = */ !isExternalClass), /* sortByName = */ true);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the parsed type signature for the class.
*
* @return The parsed type signature for the class, including any generic type parameters, or null if not
* available (probably indicating the class is not generic).
*/
public ClassTypeSignature getTypeSignature() {
if (typeSignatureStr == null) {
return null;
}
if (typeSignature == null) {
try {
typeSignature = ClassTypeSignature.parse(typeSignatureStr, this);
typeSignature.setScanResult(scanResult);
} catch (final ParseException e) {
throw new IllegalArgumentException(e);
}
}
return typeSignature;
}
/**
* Get the type signature string for the class.
*
* @return The type signature string for the class, including any generic type parameters, or null if not
* available (probably indicating the class is not generic).
*/
public String getTypeSignatureStr() {
return typeSignatureStr;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Get the {@link URI} of the classpath element that this class was found within.
*
* @return The {@link URI} of the classpath element that this class was found within.
* @throws IllegalArgumentException
* if the classpath element does not have a valid URI (e.g. for modules whose location URI is null).
*/
public URI getClasspathElementURI() {
if (classpathElement == null) {
throw new IllegalArgumentException("Classpath element is not known for this classpath element");
}
return classpathElement.getURI();
}
/**
* Get the {@link URL} of the classpath element or module that this class was found within. Use
* {@link #getClasspathElementURI()} instead if the resource may have come from a system module, or if this is a
* jlink'd runtime image, since "jrt:" URI schemes used by system modules and jlink'd runtime images are not
* suppored by {@link URL}, and this will cause {@link IllegalArgumentException} to be thrown.
*
* @return The {@link URL} of the classpath element that this class was found within.
* @throws IllegalArgumentException
* if the classpath element URI cannot be converted to a {@link URL} (in particular, if the URI has
* a {@code jrt:/} scheme).
*/
public URL getClasspathElementURL() {
if (classpathElement == null) {
throw new IllegalArgumentException("Classpath element is not known for this classpath element");
}
try {
return classpathElement.getURI().toURL();
} catch (final MalformedURLException e) {
throw new IllegalArgumentException("Could not get classpath element URL", e);
}
}
/**
* Get the {@link File} for the classpath element package root dir or jar that this class was found within, or
* null if this class was found in a module. (See also {@link #getModuleRef}.)
*
* @return The {@link File} for the classpath element package root dir or jar that this class was found within,
* or null if this class was found in a module (see {@link #getModuleRef}). May also return null if the
* classpath element was an http/https URL, and the jar was downloaded directly to RAM, rather than to a
* temp file on disk (e.g. if the temp dir is not writeable).
*/
public File getClasspathElementFile() {
if (classpathElement == null) {
throw new IllegalArgumentException("Classpath element is not known for this classpath element");
}
return classpathElement.getFile();
}
/**
* Get the module that this class was found within, as a {@link ModuleRef}, or null if this class was found in a
* directory or jar in the classpath. (See also {@link #getClasspathElementFile()}.)
*
* @return The module that this class was found within, as a {@link ModuleRef}, or null if this class was found
* in a directory or jar in the classpath. (See also {@link #getClasspathElementFile()}.)
*/
public ModuleRef getModuleRef() {
if (classpathElement == null) {
throw new IllegalArgumentException("Classpath element is not known for this classpath element");
}
return classpathElement instanceof ClasspathElementModule
? ((ClasspathElementModule) classpathElement).getModuleRef()
: null;
}
/**
* The {@link Resource} for the classfile of this class.
*
* @return The {@link Resource} for the classfile of this class. Returns null if the classfile for this class
* was not actually read during the scan, e.g. because this class was not itself whitelisted, but was
* referenced by a whitelisted class.
*/
public Resource getResource() {
return classfileResource;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Obtain a {@code Class<?>} reference for the class named by this {@link ClassInfo} object, casting it to the
* requested interface or superclass type. Causes the ClassLoader to load the class, if it is not already
* loaded.
*
* <p>
* <b>Important note:</b> since {@code superclassOrInterfaceType} is a class reference for an already-loaded
* class, it is critical that {@code superclassOrInterfaceType} is loaded by the same classloader as the class
* referred to by this {@code ClassInfo} object, otherwise the class cast will fail.
*
* @param <T>
* the superclass or interface type
* @param superclassOrInterfaceType
* The {@link Class} reference for the type to cast the loaded class to.
* @param ignoreExceptions
* If true, return null if any exceptions or errors thrown during classloading, or if attempting to
* cast the resulting {@code Class<?>} reference to the requested superclass or interface type fails.
* If false, {@link IllegalArgumentException} is thrown if the class could not be loaded or could not
* be cast to the requested type.
* @return The class reference, or null, if ignoreExceptions is true and there was an exception or error loading
* the class.
* @throws IllegalArgumentException
* if ignoreExceptions is false and there were problems loading the class, or casting it to the
* requested type.
*/
@Override
public <T> Class<T> loadClass(final Class<T> superclassOrInterfaceType, final boolean ignoreExceptions) {
return super.loadClass(superclassOrInterfaceType, ignoreExceptions);
}
/**
* Obtain a {@code Class<?>} reference for the class named by this {@link ClassInfo} object, casting it to the
* requested interface or superclass type. Causes the ClassLoader to load the class, if it is not already
* loaded.
*
* <p>
* <b>Important note:</b> since {@code superclassOrInterfaceType} is a class reference for an already-loaded
* class, it is critical that {@code superclassOrInterfaceType} is loaded by the same classloader as the class
* referred to by this {@code ClassInfo} object, otherwise the class cast will fail.
*
* @param <T>
* The superclass or interface type
* @param superclassOrInterfaceType
* The type to cast the loaded class to.
* @return The class reference.
* @throws IllegalArgumentException
* if there were problems loading the class or casting it to the requested type.
*/
@Override
public <T> Class<T> loadClass(final Class<T> superclassOrInterfaceType) {
return super.loadClass(superclassOrInterfaceType, /* ignoreExceptions = */ false);
}
/**
* Obtain a {@code Class<?>} reference for the class named by this {@link ClassInfo} object. Causes the
* ClassLoader to load the class, if it is not already loaded.
*
* @param ignoreExceptions
* Whether or not to ignore exceptions
* @return The class reference, or null, if ignoreExceptions is true and there was an exception or error loading
* the class.
* @throws IllegalArgumentException
* if ignoreExceptions is false and there were problems loading the class.
*/
@Override
public Class<?> loadClass(final boolean ignoreExceptions) {
return super.loadClass(ignoreExceptions);
}
/**
* Obtain a {@code Class<?>} reference for the class named by this {@link ClassInfo} object. Causes the
* ClassLoader to load the class, if it is not already loaded.
*
* @return The class reference.
* @throws IllegalArgumentException
* if there were problems loading the class.
*/
@Override
public Class<?> loadClass() {
return super.loadClass(/* ignoreExceptions = */ false);
}
// -------------------------------------------------------------------------------------------------------------
/* (non-Javadoc)
* @see io.github.classgraph.ScanResultObject#getClassName()
*/
@Override
protected String getClassName() {
return name;
}
/* (non-Javadoc)
* @see io.github.classgraph.ScanResultObject#getClassInfo()
*/
@Override
protected ClassInfo getClassInfo() {
return this;
}
/* (non-Javadoc)
* @see io.github.classgraph.ScanResultObject#setScanResult(io.github.classgraph.ScanResult)
*/
@Override
void setScanResult(final ScanResult scanResult) {
super.setScanResult(scanResult);
if (this.typeSignature != null) {
this.typeSignature.setScanResult(scanResult);
}
if (annotationInfo != null) {
for (final AnnotationInfo ai : annotationInfo) {
ai.setScanResult(scanResult);
}
}
if (fieldInfo != null) {
for (final FieldInfo fi : fieldInfo) {
fi.setScanResult(scanResult);
}
}
if (methodInfo != null) {
for (final MethodInfo mi : methodInfo) {
mi.setScanResult(scanResult);
}
}
if (annotationDefaultParamValues != null) {
for (final AnnotationParameterValue apv : annotationDefaultParamValues) {
apv.setScanResult(scanResult);
}
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Handle {@link Repeatable} annotations.
*
* @param allRepeatableAnnotationNames
* the names of all repeatable annotations
*/
void handleRepeatableAnnotations(final Set<String> allRepeatableAnnotationNames) {
if (annotationInfo != null) {
annotationInfo.handleRepeatableAnnotations(allRepeatableAnnotationNames, this,
RelType.CLASS_ANNOTATIONS, RelType.CLASSES_WITH_ANNOTATION, null);
}
if (fieldInfo != null) {
for (final FieldInfo fi : fieldInfo) {
fi.handleRepeatableAnnotations(allRepeatableAnnotationNames);
}
}
if (methodInfo != null) {
for (final MethodInfo mi : methodInfo) {
mi.handleRepeatableAnnotations(allRepeatableAnnotationNames);
}
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Add names of classes referenced by this class.
*
* @param refdClassNames
* the referenced class names
*/
void addReferencedClassNames(final Set<String> refdClassNames) {
if (this.referencedClassNames == null) {
this.referencedClassNames = refdClassNames;
} else {
this.referencedClassNames.addAll(refdClassNames);
}
}
/**
* Get {@link ClassInfo} objects for any classes referenced in this class' type descriptor, or the type
* descriptors of fields, methods or annotations.
*
* @param classNameToClassInfo
* the map from class name to {@link ClassInfo}.
* @param refdClassInfo
* the referenced class info
*/
@Override
protected void findReferencedClassInfo(final Map<String, ClassInfo> classNameToClassInfo,
final Set<ClassInfo> refdClassInfo) {
// Add this class to the set of references
super.findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
if (this.referencedClassNames != null) {
for (final String refdClassName : this.referencedClassNames) {
final ClassInfo classInfo = ClassInfo.getOrCreateClassInfo(refdClassName, classNameToClassInfo);
classInfo.setScanResult(scanResult);
refdClassInfo.add(classInfo);
}
}
getMethodInfo().findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
getFieldInfo().findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
getAnnotationInfo().findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
if (annotationDefaultParamValues != null) {
annotationDefaultParamValues.findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
}
final ClassTypeSignature classSig = getTypeSignature();
if (classSig != null) {
classSig.findReferencedClassInfo(classNameToClassInfo, refdClassInfo);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Set the list of ClassInfo objects for classes referenced by this class.
*
* @param refdClasses
* the referenced classes
*/
void setReferencedClasses(final ClassInfoList refdClasses) {
this.referencedClasses = refdClasses;
}
/**
* Get the class dependencies.
*
* @return A {@link ClassInfoList} of {@link ClassInfo} objects for all classes referenced by this class. Note
* that you need to call {@link ClassGraph#enableInterClassDependencies()} before
* {@link ClassGraph#scan()} for this method to work. You should also call
* {@link ClassGraph#enableExternalClasses()} before {@link ClassGraph#scan()} if you want
* non-whitelisted classes to appear in the result.
*/
public ClassInfoList getClassDependencies() {
if (!scanResult.scanSpec.enableInterClassDependencies) {
throw new IllegalArgumentException(
"Please call ClassGraph#enableInterClassDependencies() before #scan()");
}
return referencedClasses == null ? ClassInfoList.EMPTY_LIST : referencedClasses;
}
// -------------------------------------------------------------------------------------------------------------
/**
* Compare based on class name.
*
* @param o
* the other object
* @return the comparison result
*/
@Override
public int compareTo(final ClassInfo o) {
return this.name.compareTo(o.name);
}
/**
* Use class name for equals().
*
* @param obj
* the other object
* @return Whether the objects were equal.
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof ClassInfo)) {
return false;
}
final ClassInfo other = (ClassInfo) obj;
return name.equals(other.name);
}
/**
* Use hash code of class name.
*
* @return the hashcode
*/
@Override
public int hashCode() {
return name == null ? 0 : name.hashCode();
}
/**
* To string.
*
* @param typeNameOnly
* if true, convert type name to string only.
* @return the string
*/
protected String toString(final boolean typeNameOnly) {
final ClassTypeSignature typeSig = getTypeSignature();
if (typeSig != null) {
// Generic classes
return typeSig.toString(name, typeNameOnly, modifiers, isAnnotation(), isInterface());
} else {
// Non-generic classes
final StringBuilder buf = new StringBuilder();
if (typeNameOnly) {
buf.append(name);
} else {
TypeUtils.modifiersToString(modifiers, ModifierType.CLASS, /* ignored */ false, buf);
if (buf.length() > 0) {
buf.append(' ');
}
buf.append(isAnnotation() ? "@interface "
: isInterface() ? "interface " : (modifiers & 0x4000) != 0 ? "enum " : "class ");
buf.append(name);
final ClassInfo superclass = getSuperclass();
if (superclass != null && !superclass.getName().equals("java.lang.Object")) {
buf.append(" extends ").append(superclass.toString(/* typeNameOnly = */ true));
}
final Set<ClassInfo> interfaces = this.filterClassInfo(RelType.IMPLEMENTED_INTERFACES,
/* strictWhitelist = */ false).directlyRelatedClasses;
if (!interfaces.isEmpty()) {
buf.append(isInterface() ? " extends " : " implements ");
boolean first = true;
for (final ClassInfo iface : interfaces) {
if (first) {
first = false;
} else {
buf.append(", ");
}
buf.append(iface.toString(/* typeNameOnly = */ true));
}
}
}
return buf.toString();
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return toString(false);
}
}
| Use 'fields' instead of 'methods' in getXXXFieldInfo() JavaDoc.
| src/main/java/io/github/classgraph/ClassInfo.java | Use 'fields' instead of 'methods' in getXXXFieldInfo() JavaDoc. | <ide><path>rc/main/java/io/github/classgraph/ClassInfo.java
<ide> * {@link IllegalArgumentException}.
<ide> *
<ide> * <p>
<del> * By default only returns information for public methods, unless {@link ClassGraph#ignoreFieldVisibility()} was
<add> * By default only returns information for public fields, unless {@link ClassGraph#ignoreFieldVisibility()} was
<ide> * called before the scan.
<ide> *
<ide> * @return the list of FieldInfo objects for visible fields declared by this class, or the empty list if no
<ide> * {@link IllegalArgumentException}.
<ide> *
<ide> * <p>
<del> * By default only returns information for public methods, unless {@link ClassGraph#ignoreFieldVisibility()} was
<add> * By default only returns information for public fields, unless {@link ClassGraph#ignoreFieldVisibility()} was
<ide> * called before the scan.
<ide> *
<ide> * @return the list of FieldInfo objects for visible fields of this class or its superclases, or the empty list
<ide> * {@link IllegalArgumentException}.
<ide> *
<ide> * <p>
<del> * By default only returns information for public methods, unless {@link ClassGraph#ignoreFieldVisibility()} was
<add> * By default only returns information for public fields, unless {@link ClassGraph#ignoreFieldVisibility()} was
<ide> * called before the scan.
<ide> *
<ide> * @param fieldName |
|
Java | apache-2.0 | 5d4b7feb7a9db620af5f73ce9b102600d34e7f22 | 0 | strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,vroyer/elassandra | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.security.action.role;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.VersionUtils;
import org.elasticsearch.xpack.core.XPackClientPlugin;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor.ApplicationResourcePrivileges;
import org.elasticsearch.xpack.core.security.authz.privilege.ConditionalClusterPrivileges;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.iterableWithSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
public class PutRoleRequestTests extends ESTestCase {
public void testValidationOfApplicationPrivileges() {
assertSuccessfulValidation(buildRequestWithApplicationPrivilege("app", new String[]{"read"}, new String[]{"*"}));
assertSuccessfulValidation(buildRequestWithApplicationPrivilege("app", new String[]{"action:login"}, new String[]{"/"}));
assertSuccessfulValidation(buildRequestWithApplicationPrivilege("*", new String[]{"data/read:user"}, new String[]{"user/123"}));
// Fail
assertValidationError("privilege names and actions must match the pattern",
buildRequestWithApplicationPrivilege("app", new String[]{"in valid"}, new String[]{"*"}));
assertValidationError("An application name prefix must match the pattern",
buildRequestWithApplicationPrivilege("000", new String[]{"all"}, new String[]{"*"}));
assertValidationError("An application name prefix must match the pattern",
buildRequestWithApplicationPrivilege("%*", new String[]{"all"}, new String[]{"*"}));
}
public void testSerialization() throws IOException {
final PutRoleRequest original = buildRandomRequest();
final BytesStreamOutput out = new BytesStreamOutput();
original.writeTo(out);
final PutRoleRequest copy = new PutRoleRequest();
final NamedWriteableRegistry registry = new NamedWriteableRegistry(new XPackClientPlugin(Settings.EMPTY).getNamedWriteables());
StreamInput in = new NamedWriteableAwareStreamInput(ByteBufferStreamInput.wrap(BytesReference.toBytes(out.bytes())), registry);
copy.readFrom(in);
assertThat(copy.roleDescriptor(), equalTo(original.roleDescriptor()));
}
public void testSerializationBetweenV64AndV66() throws IOException {
final PutRoleRequest original = buildRandomRequest();
final BytesStreamOutput out = new BytesStreamOutput();
final Version version = VersionUtils.randomVersionBetween(random(), Version.V_6_4_0, Version.V_6_6_0);
out.setVersion(version);
original.writeTo(out);
final PutRoleRequest copy = new PutRoleRequest();
final NamedWriteableRegistry registry = new NamedWriteableRegistry(new XPackClientPlugin(Settings.EMPTY).getNamedWriteables());
StreamInput in = new NamedWriteableAwareStreamInput(ByteBufferStreamInput.wrap(BytesReference.toBytes(out.bytes())), registry);
in.setVersion(version);
copy.readFrom(in);
assertThat(copy.name(), equalTo(original.name()));
assertThat(copy.cluster(), equalTo(original.cluster()));
assertIndicesSerializedRestricted(copy.indices(), original.indices());
assertThat(copy.runAs(), equalTo(original.runAs()));
assertThat(copy.metadata(), equalTo(original.metadata()));
assertThat(copy.getRefreshPolicy(), equalTo(original.getRefreshPolicy()));
assertThat(copy.applicationPrivileges(), equalTo(original.applicationPrivileges()));
assertThat(copy.conditionalClusterPrivileges(), equalTo(original.conditionalClusterPrivileges()));
}
public void testSerializationV60AndV32() throws IOException {
final PutRoleRequest original = buildRandomRequest();
final BytesStreamOutput out = new BytesStreamOutput();
final Version version = VersionUtils.randomVersionBetween(random(), Version.V_5_6_0, Version.V_6_3_2);
out.setVersion(version);
original.writeTo(out);
final PutRoleRequest copy = new PutRoleRequest();
final StreamInput in = out.bytes().streamInput();
in.setVersion(version);
copy.readFrom(in);
assertThat(copy.name(), equalTo(original.name()));
assertThat(copy.cluster(), equalTo(original.cluster()));
assertIndicesSerializedRestricted(copy.indices(), original.indices());
assertThat(copy.runAs(), equalTo(original.runAs()));
assertThat(copy.metadata(), equalTo(original.metadata()));
assertThat(copy.getRefreshPolicy(), equalTo(original.getRefreshPolicy()));
assertThat(copy.applicationPrivileges(), iterableWithSize(0));
assertThat(copy.conditionalClusterPrivileges(), arrayWithSize(0));
}
private void assertIndicesSerializedRestricted(RoleDescriptor.IndicesPrivileges[] copy, RoleDescriptor.IndicesPrivileges[] original) {
assertThat(copy.length, equalTo(original.length));
for (int i = 0; i < copy.length; i++) {
assertThat(copy[i].allowRestrictedIndices(), equalTo(false));
assertThat(copy[i].getIndices(), equalTo(original[i].getIndices()));
assertThat(copy[i].getPrivileges(), equalTo(original[i].getPrivileges()));
assertThat(copy[i].getDeniedFields(), equalTo(original[i].getDeniedFields()));
assertThat(copy[i].getGrantedFields(), equalTo(original[i].getGrantedFields()));
assertThat(copy[i].getQuery(), equalTo(original[i].getQuery()));
}
}
private void assertSuccessfulValidation(PutRoleRequest request) {
final ActionRequestValidationException exception = request.validate();
assertThat(exception, nullValue());
}
private void assertValidationError(String message, PutRoleRequest request) {
final ActionRequestValidationException exception = request.validate();
assertThat(exception, notNullValue());
assertThat(exception.validationErrors(), hasItem(containsString(message)));
}
private PutRoleRequest buildRequestWithApplicationPrivilege(String appName, String[] privileges, String[] resources) {
final PutRoleRequest request = new PutRoleRequest();
request.name("test");
final ApplicationResourcePrivileges privilege = ApplicationResourcePrivileges.builder()
.application(appName)
.privileges(privileges)
.resources(resources)
.build();
request.addApplicationPrivileges(new ApplicationResourcePrivileges[]{privilege});
return request;
}
private PutRoleRequest buildRandomRequest() {
final PutRoleRequest request = new PutRoleRequest();
request.name(randomAlphaOfLengthBetween(4, 9));
request.cluster(randomSubsetOf(Arrays.asList("monitor", "manage", "all", "manage_security", "manage_ml", "monitor_watcher"))
.toArray(Strings.EMPTY_ARRAY));
for (int i = randomIntBetween(0, 4); i > 0; i--) {
request.addIndex(
generateRandomStringArray(randomIntBetween(1, 3), randomIntBetween(3, 8), false, false),
randomSubsetOf(randomIntBetween(1, 2), "read", "write", "index", "all").toArray(Strings.EMPTY_ARRAY),
generateRandomStringArray(randomIntBetween(1, 3), randomIntBetween(3, 8), true),
generateRandomStringArray(randomIntBetween(1, 3), randomIntBetween(3, 8), true),
null,
randomBoolean()
);
}
final Supplier<String> stringWithInitialLowercase = ()
-> randomAlphaOfLength(1).toLowerCase(Locale.ROOT) + randomAlphaOfLengthBetween(3, 12);
final ApplicationResourcePrivileges[] applicationPrivileges = new ApplicationResourcePrivileges[randomIntBetween(0, 5)];
for (int i = 0; i < applicationPrivileges.length; i++) {
applicationPrivileges[i] = ApplicationResourcePrivileges.builder()
.application(stringWithInitialLowercase.get())
.privileges(randomArray(1, 3, String[]::new, stringWithInitialLowercase))
.resources(generateRandomStringArray(5, randomIntBetween(3, 8), false, false))
.build();
}
request.addApplicationPrivileges(applicationPrivileges);
if (randomBoolean()) {
final String[] appNames = randomArray(1, 4, String[]::new, stringWithInitialLowercase);
request.conditionalCluster(new ConditionalClusterPrivileges.ManageApplicationPrivileges(Sets.newHashSet(appNames)));
}
request.runAs(generateRandomStringArray(4, 3, false, true));
final Map<String, Object> metadata = new HashMap<>();
for (String key : generateRandomStringArray(3, 5, false, true)) {
metadata.put(key, randomFrom(Boolean.TRUE, Boolean.FALSE, 1, 2, randomAlphaOfLengthBetween(2, 9)));
}
request.metadata(metadata);
request.setRefreshPolicy(randomFrom(WriteRequest.RefreshPolicy.values()));
return request;
}
}
| x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/action/role/PutRoleRequestTests.java | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.security.action.role;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.VersionUtils;
import org.elasticsearch.xpack.core.XPackClientPlugin;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor.ApplicationResourcePrivileges;
import org.elasticsearch.xpack.core.security.authz.privilege.ConditionalClusterPrivileges;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.iterableWithSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
public class PutRoleRequestTests extends ESTestCase {
public void testValidationOfApplicationPrivileges() {
assertSuccessfulValidation(buildRequestWithApplicationPrivilege("app", new String[]{"read"}, new String[]{"*"}));
assertSuccessfulValidation(buildRequestWithApplicationPrivilege("app", new String[]{"action:login"}, new String[]{"/"}));
assertSuccessfulValidation(buildRequestWithApplicationPrivilege("*", new String[]{"data/read:user"}, new String[]{"user/123"}));
// Fail
assertValidationError("privilege names and actions must match the pattern",
buildRequestWithApplicationPrivilege("app", new String[]{"in valid"}, new String[]{"*"}));
assertValidationError("An application name prefix must match the pattern",
buildRequestWithApplicationPrivilege("000", new String[]{"all"}, new String[]{"*"}));
assertValidationError("An application name prefix must match the pattern",
buildRequestWithApplicationPrivilege("%*", new String[]{"all"}, new String[]{"*"}));
}
public void testSerialization() throws IOException {
final PutRoleRequest original = buildRandomRequest();
final BytesStreamOutput out = new BytesStreamOutput();
original.writeTo(out);
final PutRoleRequest copy = new PutRoleRequest();
final NamedWriteableRegistry registry = new NamedWriteableRegistry(new XPackClientPlugin(Settings.EMPTY).getNamedWriteables());
StreamInput in = new NamedWriteableAwareStreamInput(ByteBufferStreamInput.wrap(BytesReference.toBytes(out.bytes())), registry);
copy.readFrom(in);
assertThat(copy.roleDescriptor(), equalTo(original.roleDescriptor()));
}
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/37662")
public void testSerializationBetweenV63AndV70() throws IOException {
final PutRoleRequest original = buildRandomRequest();
final BytesStreamOutput out = new BytesStreamOutput();
final Version version = VersionUtils.randomVersionBetween(random(), Version.V_6_3_2, Version.V_6_7_0);
out.setVersion(version);
original.writeTo(out);
final PutRoleRequest copy = new PutRoleRequest();
final StreamInput in = out.bytes().streamInput();
in.setVersion(version);
copy.readFrom(in);
assertThat(copy.name(), equalTo(original.name()));
assertThat(copy.cluster(), equalTo(original.cluster()));
assertIndicesSerializedRestricted(copy.indices(), original.indices());
assertThat(copy.runAs(), equalTo(original.runAs()));
assertThat(copy.metadata(), equalTo(original.metadata()));
assertThat(copy.getRefreshPolicy(), equalTo(original.getRefreshPolicy()));
assertThat(copy.applicationPrivileges(), equalTo(original.applicationPrivileges()));
assertThat(copy.conditionalClusterPrivileges(), equalTo(original.conditionalClusterPrivileges()));
}
public void testSerializationV63AndBefore() throws IOException {
final PutRoleRequest original = buildRandomRequest();
final BytesStreamOutput out = new BytesStreamOutput();
final Version version = VersionUtils.randomVersionBetween(random(), Version.V_5_6_0, Version.V_6_3_2);
out.setVersion(version);
original.writeTo(out);
final PutRoleRequest copy = new PutRoleRequest();
final StreamInput in = out.bytes().streamInput();
in.setVersion(version);
copy.readFrom(in);
assertThat(copy.name(), equalTo(original.name()));
assertThat(copy.cluster(), equalTo(original.cluster()));
assertIndicesSerializedRestricted(copy.indices(), original.indices());
assertThat(copy.runAs(), equalTo(original.runAs()));
assertThat(copy.metadata(), equalTo(original.metadata()));
assertThat(copy.getRefreshPolicy(), equalTo(original.getRefreshPolicy()));
assertThat(copy.applicationPrivileges(), iterableWithSize(0));
assertThat(copy.conditionalClusterPrivileges(), arrayWithSize(0));
}
private void assertIndicesSerializedRestricted(RoleDescriptor.IndicesPrivileges[] copy, RoleDescriptor.IndicesPrivileges[] original) {
assertThat(copy.length, equalTo(original.length));
for (int i = 0; i < copy.length; i++) {
assertThat(copy[i].allowRestrictedIndices(), equalTo(false));
assertThat(copy[i].getIndices(), equalTo(original[i].getIndices()));
assertThat(copy[i].getPrivileges(), equalTo(original[i].getPrivileges()));
assertThat(copy[i].getDeniedFields(), equalTo(original[i].getDeniedFields()));
assertThat(copy[i].getGrantedFields(), equalTo(original[i].getGrantedFields()));
assertThat(copy[i].getQuery(), equalTo(original[i].getQuery()));
}
}
private void assertSuccessfulValidation(PutRoleRequest request) {
final ActionRequestValidationException exception = request.validate();
assertThat(exception, nullValue());
}
private void assertValidationError(String message, PutRoleRequest request) {
final ActionRequestValidationException exception = request.validate();
assertThat(exception, notNullValue());
assertThat(exception.validationErrors(), hasItem(containsString(message)));
}
private PutRoleRequest buildRequestWithApplicationPrivilege(String appName, String[] privileges, String[] resources) {
final PutRoleRequest request = new PutRoleRequest();
request.name("test");
final ApplicationResourcePrivileges privilege = ApplicationResourcePrivileges.builder()
.application(appName)
.privileges(privileges)
.resources(resources)
.build();
request.addApplicationPrivileges(new ApplicationResourcePrivileges[]{privilege});
return request;
}
private PutRoleRequest buildRandomRequest() {
final PutRoleRequest request = new PutRoleRequest();
request.name(randomAlphaOfLengthBetween(4, 9));
request.cluster(randomSubsetOf(Arrays.asList("monitor", "manage", "all", "manage_security", "manage_ml", "monitor_watcher"))
.toArray(Strings.EMPTY_ARRAY));
for (int i = randomIntBetween(0, 4); i > 0; i--) {
request.addIndex(
generateRandomStringArray(randomIntBetween(1, 3), randomIntBetween(3, 8), false, false),
randomSubsetOf(randomIntBetween(1, 2), "read", "write", "index", "all").toArray(Strings.EMPTY_ARRAY),
generateRandomStringArray(randomIntBetween(1, 3), randomIntBetween(3, 8), true),
generateRandomStringArray(randomIntBetween(1, 3), randomIntBetween(3, 8), true),
null,
randomBoolean()
);
}
final Supplier<String> stringWithInitialLowercase = ()
-> randomAlphaOfLength(1).toLowerCase(Locale.ROOT) + randomAlphaOfLengthBetween(3, 12);
final ApplicationResourcePrivileges[] applicationPrivileges = new ApplicationResourcePrivileges[randomIntBetween(0, 5)];
for (int i = 0; i < applicationPrivileges.length; i++) {
applicationPrivileges[i] = ApplicationResourcePrivileges.builder()
.application(stringWithInitialLowercase.get())
.privileges(randomArray(1, 3, String[]::new, stringWithInitialLowercase))
.resources(generateRandomStringArray(5, randomIntBetween(3, 8), false, false))
.build();
}
request.addApplicationPrivileges(applicationPrivileges);
if (randomBoolean()) {
final String[] appNames = randomArray(1, 4, String[]::new, stringWithInitialLowercase);
request.conditionalCluster(new ConditionalClusterPrivileges.ManageApplicationPrivileges(Sets.newHashSet(appNames)));
}
request.runAs(generateRandomStringArray(4, 3, false, true));
final Map<String, Object> metadata = new HashMap<>();
for (String key : generateRandomStringArray(3, 5, false, true)) {
metadata.put(key, randomFrom(Boolean.TRUE, Boolean.FALSE, 1, 2, randomAlphaOfLengthBetween(2, 9)));
}
request.metadata(metadata);
request.setRefreshPolicy(randomFrom(WriteRequest.RefreshPolicy.values()));
return request;
}
}
| Fix PutRoleRequestTests
Closes #37662
| x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/action/role/PutRoleRequestTests.java | Fix PutRoleRequestTests | <ide><path>-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/action/role/PutRoleRequestTests.java
<ide> assertThat(copy.roleDescriptor(), equalTo(original.roleDescriptor()));
<ide> }
<ide>
<del> @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/37662")
<del> public void testSerializationBetweenV63AndV70() throws IOException {
<add> public void testSerializationBetweenV64AndV66() throws IOException {
<ide> final PutRoleRequest original = buildRandomRequest();
<ide>
<ide> final BytesStreamOutput out = new BytesStreamOutput();
<del> final Version version = VersionUtils.randomVersionBetween(random(), Version.V_6_3_2, Version.V_6_7_0);
<add> final Version version = VersionUtils.randomVersionBetween(random(), Version.V_6_4_0, Version.V_6_6_0);
<ide> out.setVersion(version);
<ide> original.writeTo(out);
<ide>
<ide> final PutRoleRequest copy = new PutRoleRequest();
<del> final StreamInput in = out.bytes().streamInput();
<add> final NamedWriteableRegistry registry = new NamedWriteableRegistry(new XPackClientPlugin(Settings.EMPTY).getNamedWriteables());
<add> StreamInput in = new NamedWriteableAwareStreamInput(ByteBufferStreamInput.wrap(BytesReference.toBytes(out.bytes())), registry);
<ide> in.setVersion(version);
<ide> copy.readFrom(in);
<ide>
<ide> assertThat(copy.conditionalClusterPrivileges(), equalTo(original.conditionalClusterPrivileges()));
<ide> }
<ide>
<del> public void testSerializationV63AndBefore() throws IOException {
<add> public void testSerializationV60AndV32() throws IOException {
<ide> final PutRoleRequest original = buildRandomRequest();
<ide>
<ide> final BytesStreamOutput out = new BytesStreamOutput(); |
|
Java | agpl-3.0 | a65be268b056ff13a3dd862fea37329d0240c347 | 0 | exomiser/Exomiser,exomiser/Exomiser | package de.charite.compbio.exomiser.core.prioritisers;
import de.charite.compbio.exomiser.core.model.Gene;
import de.charite.compbio.exomiser.core.prioritisers.util.ScoreDistribution;
import de.charite.compbio.exomiser.core.prioritisers.util.ScoreDistributionContainer;
import hpo.HPOutils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import ontologizer.go.OBOParser;
import ontologizer.go.OBOParserException;
import ontologizer.go.Ontology;
import ontologizer.go.Term;
import ontologizer.go.TermContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import similarity.SimilarityUtilities;
import similarity.concepts.ResnikSimilarity;
import similarity.objects.InformationContentObjectSimilarity;
import sonumina.math.graph.SlimDirectedGraphView;
/**
* Filter variants according to the phenotypic similarity of the specified
* disease to mouse models disrupting the same gene. We use semantic similarity
* calculations in the uberpheno.
*
* The files required for the constructor of this filter should be downloaded
* from: {@code http://purl.obolibrary.org/obo/hp/uberpheno/}
* (HSgenes_crossSpeciesPhenoAnnotation.txt, crossSpeciesPheno.obo)
*
* @author Sebastian Koehler
* @version 0.06 (6 December, 2013)
*/
public class PhenixPriority implements Priority {
private static final Logger logger = LoggerFactory.getLogger(PhenixPriority.class);
/**
* The HPO as Ontologizer-Ontology object
*/
private Ontology hpo;
/**
* The HPO as SlimDirectedGraph (fast access to ancestors etc.)
*/
private SlimDirectedGraphView<Term> hpoSlim;
/**
* A list of error-messages
*/
private ArrayList<String> error_record = null;
/**
* A list of messages that can be used to create a display in a HTML page or
* elsewhere.
*/
private ArrayList<String> messages = null;
/**
* The semantic similarity measure used to calculate phenotypic similarity
*/
private InformationContentObjectSimilarity similarityMeasure;
/**
* The HPO terms entered by the user describing the individual who is being
* sequenced by exome-sequencing or clinically relevant genome panel.
*/
private ArrayList<Term> hpoQueryTerms;
private float DEFAULT_SCORE = 0f;
private HashMap<String, ArrayList<Term>> geneId2annotations;
private HashMap<Term, HashSet<String>> annotationTerm2geneIds;
private HashMap<Term, Double> term2ic;
private final ScoreDistributionContainer scoredistributionContainer = new ScoreDistributionContainer();
private int numberQueryTerms;
/**
* A counter of the number of genes that could not be found in the database
* as being associated with a defined disease gene.
*/
private int offTargetGenes = 0;
/**
* Total number of genes used for the query, including genes with no
* associated disease.
*/
private int analysedGenes;
private boolean symmetric;
/**
* Path to the directory that has the files needed to calculate the score
* distribution.
*/
private String scoredistributionFolder;
/**
* Keeps track of the maximum semantic similarity score to date
*/
private double maxSemSim = 0d;
/**
* Keeps track of the maximum negative log of the p value to date
*/
private double maxNegLogP = 0d;
/**
* Create a new instance of the PhenixPriority.
*
* @param scoreDistributionFolder Folder which contains the score
* distributions (e.g. 3.out, 3_symmetric.out, 4.out, 4_symmetric.out). It
* must also contain the files hp.obo (obtained from
* {@code http://compbio.charite.de/hudson/job/hpo/}) and
* ALL_SOURCES_ALL_FREQUENCIES_genes_to_phenotype.txt-file (obtained from
* {@code http://compbio.charite.de/hudson/job/hpo.annotations.monthly/lastSuccessfulBuild/artifact/annotation/}).
* @param hpoQueryTermIds List of HPO terms
* @param symmetric Flag to indicate if the semantic similarity score should
* be calculated using the symmetrix formula.
* @throws ExomizerInitializationException
* @see <a href="http://purl.obolibrary.org/obo/hp/uberpheno/">Uberpheno
* Hudson page</a>
*/
public PhenixPriority(String scoreDistributionFolder, Set<String> hpoQueryTermIds, boolean symmetric) {
if (hpoQueryTermIds.isEmpty()) {
throw new PhenixException("Please supply some HPO terms. PhenIX is unable to prioritise genes without these.");
}
if (!scoreDistributionFolder.endsWith(File.separatorChar + "")) {
scoreDistributionFolder += File.separatorChar;
}
this.scoredistributionFolder = scoreDistributionFolder;
String hpoOboFile = String.format("%s%s", scoreDistributionFolder, "hp.obo");
String hpoAnnotationFile = String.format("%s%s", scoreDistributionFolder, "ALL_SOURCES_ALL_FREQUENCIES_genes_to_phenotype.txt");
parseData(hpoOboFile, hpoAnnotationFile);
HashSet<Term> hpoQueryTermsHS = new HashSet<Term>();
for (String termIdString : hpoQueryTermIds) {
Term t = hpo.getTermIncludingAlternatives(termIdString);
if (t != null) {
hpoQueryTermsHS.add(t);
} else {
logger.error("invalid term-id given: " + termIdString);
}
}
hpoQueryTerms = new ArrayList<Term>();
hpoQueryTerms.addAll(hpoQueryTermsHS);
this.symmetric = symmetric;
numberQueryTerms = hpoQueryTerms.size();
if (!scoredistributionContainer.didParseDistributions(symmetric, numberQueryTerms)) {
scoredistributionContainer.parseDistributions(symmetric, numberQueryTerms, scoreDistributionFolder);
}
ResnikSimilarity resnik = new ResnikSimilarity(hpo, term2ic);
similarityMeasure = new InformationContentObjectSimilarity(resnik, symmetric, false);
/* some logging stuff */
this.error_record = new ArrayList<String>();
this.messages = new ArrayList<String>();
}
private void parseData(String hpoOboFile, String hpoAnnotationFile) {
//The phenomizerData directory must contain the files "hp.obo", "ALL_SOURCES_ALL_FREQUENCIES_genes_to_phenotype.txt"
//as well as the score distribution files "*.out", all of which can be downloaded from the HPO hudson server.
try {
parseOntology(hpoOboFile);
} catch (OBOParserException e) {
logger.error("Error parsing ontology file {}", hpoOboFile, e);
} catch (IOException ioe) {
logger.error("I/O Error with ontology file{}", hpoOboFile, ioe);
}
try {
parseAnnotations(hpoAnnotationFile);
} catch (IOException e) {
logger.error("Error parsing annotation file {}", hpoAnnotationFile, e);
}
}
/**
* Parse the HPO phenotype annotation file (e.g., phenotype_annotation.tab).
* The point of this is to get the links between diseases and HPO phenotype
* terms. The hpoAnnotationFile is The
* ALL_SOURCES_ALL_FREQUENCIES_genes_to_phenotype.txt-file
*
* @param hpoAnnotationFile path to the file
*/
private void parseAnnotations(String hpoAnnotationFile) throws IOException {
geneId2annotations = new HashMap<String, ArrayList<Term>>();
BufferedReader in = new BufferedReader(new FileReader(hpoAnnotationFile));
String line = null;
while ((line = in.readLine()) != null) {
if (line.startsWith("#")) {
continue;
}
String[] split = line.split("\t");
String entrez = split[0];
Term t = null;
try {
/* split[4] is the HPO term field of an annotation line. */
t = hpo.getTermIncludingAlternatives(split[3]);
} catch (IllegalArgumentException e) {
logger.error("Unable to get term for line \n{}\n", line);
logger.error("The offending field was '{}'", split[3]);
for (int k = 0; k < split.length; ++k) {
logger.error("{} '{}'", k, split[k]);
}
t = null;
}
if (t == null) {
continue;
}
ArrayList<Term> annot;
if (geneId2annotations.containsKey(entrez)) {
annot = geneId2annotations.get(entrez);
} else {
annot = new ArrayList<>();
}
annot.add(t);
geneId2annotations.put(entrez, annot);
}
in.close();
// cleanup annotations
for (String entrez : geneId2annotations.keySet()) {
ArrayList<Term> terms = geneId2annotations.get(entrez);
HashSet<Term> uniqueTerms = new HashSet<Term>(terms);
ArrayList<Term> uniqueTermsAL = new ArrayList<Term>();
uniqueTermsAL.addAll(uniqueTerms);
ArrayList<Term> termsMostSpecific = HPOutils.cleanUpAssociation(uniqueTermsAL, hpoSlim, hpo.getRootTerm());
geneId2annotations.put(entrez, termsMostSpecific);
}
// prepare IC computation
annotationTerm2geneIds = new HashMap<Term, HashSet<String>>();
for (String oId : geneId2annotations.keySet()) {
ArrayList<Term> annotations = geneId2annotations.get(oId);
for (Term annot : annotations) {
ArrayList<Term> termAndAncestors = hpoSlim.getAncestors(annot);
for (Term t : termAndAncestors) {
HashSet<String> objectsAnnotatedByTerm; // here we store
// which objects
// have been
// annotated with
// this term
if (annotationTerm2geneIds.containsKey(t)) {
objectsAnnotatedByTerm = annotationTerm2geneIds.get(t);
} else {
objectsAnnotatedByTerm = new HashSet<String>();
}
objectsAnnotatedByTerm.add(oId); // add the current object
annotationTerm2geneIds.put(t, objectsAnnotatedByTerm);
}
}
}
term2ic = caclulateTermIC(hpo, annotationTerm2geneIds);
}
/**
* Parses the human-phenotype-ontology.obo file (or equivalently, the hp.obo
* file from our Hudosn server).
*
* @param hpoOboFile path to the hp.obo file.
*/
private Ontology parseOntology(String hpoOboFile) throws IOException, OBOParserException {
OBOParser oboParser = new OBOParser(hpoOboFile, OBOParser.PARSE_XREFS);
String parseInfo = oboParser.doParse();
logger.info(parseInfo);
TermContainer termContainer = new TermContainer(oboParser.getTermMap(), oboParser.getFormatVersion(), oboParser.getDate());
Ontology hpo = new Ontology(termContainer);
hpo.setRelevantSubontology(termContainer.get(HPOutils.organAbnormalityRootId).getName());
SlimDirectedGraphView<Term> hpoSlim = hpo.getSlimGraphView();
this.hpo = hpo;
this.hpoSlim = hpoSlim;
return hpo;
}
/**
* @see exomizer.priority.IPriority#getPriorityName()
*/
@Override
public String getPriorityName() {
return "HPO Phenomizer prioritizer";
}
/**
* Flag to output results of filtering against Uberpheno data.
*/
@Override
public PriorityType getPriorityType() {
return PriorityType.PHENIX_PRIORITY;
}
/**
* @return list of messages representing process, result, and if any, errors
* of score filtering.
*/
public ArrayList<String> getMessages() {
if (this.error_record.size() > 0) {
for (String s : error_record) {
this.messages.add("Error: " + s);
}
}
return this.messages;
}
/**
* Prioritize a list of candidate {@link exomizer.exome.Gene Gene} objects
* (the candidate genes have rare, potentially pathogenic variants).
*
* @param gene_list List of candidate genes.
* @see exomizer.filter.Filter#filter_list_of_variants(java.util.ArrayList)
*/
@Override
public void prioritizeGenes(List<Gene> gene_list) {
analysedGenes = gene_list.size();
for (Gene gene : gene_list) {
PhenixPriorityResult phenomizerRelScore = scoreVariantHPO(gene);
gene.addPriorityResult(phenomizerRelScore);
//System.out.println("Phenomizer Gene="+gene.getGeneSymbol()+" score=" +phenomizerRelScore.getScore());
}
String s = String.format("Data investigated in HPO for %d genes. No data for %d genes", analysedGenes, this.offTargetGenes);
//System.out.println(s);
normalizePhenomizerScores(gene_list);
this.messages.add(s);
}
/**
* The gene relevance scores are to be normalized to lie between zero and
* one. This function, which relies upon the variable {@link #maxSemSim}
* being set in {@link #scoreVariantHPO}, divides each score by
* {@link #maxSemSim}, which has the effect of putting the phenomizer scores
* in the range [0..1]. Note that for now we are using the semantic
* similarity scores, but we should also try the P value version (TODO).
* Note that this is not the same as rank normalization!
*/
private void normalizePhenomizerScores(List<Gene> gene_list) {
if (maxSemSim < 1) {
return;
}
PhenixPriorityResult.setNormalizationFactor(1d / maxSemSim);
/*for (Gene g : gene_list) {
float score = g.getRelevagetScorepe.PHENIX_PRIORITY);
score /= this.maxSemSim;
g.setScore(FilterType.PHENIX_PRIORITY, score);
}*/
}
/**
* @param g A {@link exomizer.exome.Gene Gene} whose score is to be
* determined.
*/
private PhenixPriorityResult scoreVariantHPO(Gene g) {
int entrezGeneId = g.getEntrezGeneID();
String entrezGeneIdString = entrezGeneId + "";
if (!geneId2annotations.containsKey(entrezGeneIdString)) {
//System.err.println("INVALID GENE GIVEN (will set to default-score): Entrez ID: " + g.getEntrezGeneID() + " / " + g.getGeneSymbol());
this.offTargetGenes++;
return new PhenixPriorityResult(DEFAULT_SCORE);
}
ArrayList<Term> annotationsOfGene = geneId2annotations.get(entrezGeneIdString);
double similarityScore = similarityMeasure.computeObjectSimilarity(hpoQueryTerms, annotationsOfGene);
if (similarityScore > maxSemSim) {
maxSemSim = similarityScore;
}
if (Double.isNaN(similarityScore)) {
error_record.add("score was NAN for gene:" + g + " : " + hpoQueryTerms + " <-> " + annotationsOfGene);
}
ScoreDistribution scoreDist = scoredistributionContainer.getDistribution(entrezGeneIdString, numberQueryTerms, symmetric,
scoredistributionFolder);
// get the pvalue
double rawPvalue;
if (scoreDist == null) {
return new PhenixPriorityResult(DEFAULT_SCORE);
} else {
rawPvalue = scoreDist.getPvalue(similarityScore, 1000.);
rawPvalue = Math.log(rawPvalue) * -1.0; /* Negative log of p value : most significant get highest score */
if (rawPvalue > maxNegLogP) {
maxNegLogP = rawPvalue;
}
}
return new PhenixPriorityResult(rawPvalue, similarityScore);
// // filter genes not associated with any disease
// if
// (!HPOutils.diseaseGeneMapper.entrezId2diseaseIds.containsKey(entrezGeneId))
// return new PhenixPriorityResult(DEFAULT_SCORE);
//
// double sum = 0; // sum of semantic similarity
// int num = 0; // required to make average
// for (DiseaseId diseaseId :
// HPOutils.diseaseGeneMapper.entrezId2diseaseIds.get(entrezGeneId)) {
//
// DiseaseEntry diseaseEntry = HPOutils.diseaseId2entry.get(diseaseId);
//
// if (diseaseEntry == null) {
// // System.out.println("diseaseID = " + diseaseId);
// // System.out.println("diseaseEntry = NULL " );
// // return new PhenixPriorityResult(DEFAULT_SCORE);
// continue;
// }
// ArrayList<Term> termsAL = diseaseEntry.getOrganAssociatedTerms();
// if (termsAL == null || termsAL.size() < 1) {
// continue;
// // return new PhenixPriorityResult(DEFAULT_SCORE);
// }
// double similarityScore =
// similarityMeasure.computeObjectSimilarity(hpoQueryTerms, termsAL);
// sum += similarityScore;
// ++num;
// }
// if (num == 0) {
// return new PhenixPriorityResult(DEFAULT_SCORE);
// }
//
// double avg = sum / num;
// return new PhenixPriorityResult(avg);
}
/**
* Flag to show results of this analysis in the HTML page.
*
* @return
*/
@Override
public boolean displayInHTML() {
return true;
}
/**
* @return an ul list with summary of phenomizer prioritization.
*/
@Override
public String getHTMLCode() {
String s = String.format("Phenomizer: %d genes were evaluated; no phenotype data available for %d of them",
this.analysedGenes, this.offTargetGenes);
String t = null;
if (symmetric) {
t = String.format("Symmetric Phenomizer query with %d terms was performed", this.numberQueryTerms);
} else {
t = String.format("Asymmetric Phenomizer query with %d terms was performed", this.numberQueryTerms);
}
String u = String.format("Maximum semantic similarity score: %.2f, maximum negative log. of p-value: %.2f",
this.maxSemSim, this.maxNegLogP);
return String.format("<ul><li>%s</li><li>%s</li><li>%s</li></ul>\n", s, t, u);
}
private HashMap<Term, Double> caclulateTermIC(Ontology ontology, HashMap<Term, HashSet<String>> term2objectIdsAnnotated) {
Term root = ontology.getRootTerm();
HashMap<Term, Integer> term2frequency = new HashMap<Term, Integer>();
for (Term t : term2objectIdsAnnotated.keySet()) {
term2frequency.put(t, term2objectIdsAnnotated.get(t).size());
}
int maxFreq = term2frequency.get(root);
HashMap<Term, Double> term2informationContent = SimilarityUtilities.caculateInformationContent(maxFreq, term2frequency);
int frequencyZeroCounter = 0;
double ICzeroCountTerms = -1 * (Math.log(1 / (double) maxFreq));
for (Term t : ontology) {
if (!term2frequency.containsKey(t)) {
++frequencyZeroCounter;
term2informationContent.put(t, ICzeroCountTerms);
}
}
logger.info("WARNING: Frequency of {} terms was zero!! Set IC of these to : {}", frequencyZeroCounter, ICzeroCountTerms);
return term2informationContent;
}
private static class PhenixException extends RuntimeException {
private PhenixException(String message) {
super(message);
}
}
}
| exomiser-core/src/main/java/de/charite/compbio/exomiser/core/prioritisers/PhenixPriority.java | package de.charite.compbio.exomiser.core.prioritisers;
import de.charite.compbio.exomiser.core.model.Gene;
import de.charite.compbio.exomiser.core.prioritisers.util.ScoreDistribution;
import de.charite.compbio.exomiser.core.prioritisers.util.ScoreDistributionContainer;
import hpo.HPOutils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import ontologizer.go.OBOParser;
import ontologizer.go.OBOParserException;
import ontologizer.go.Ontology;
import ontologizer.go.Term;
import ontologizer.go.TermContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import similarity.SimilarityUtilities;
import similarity.concepts.ResnikSimilarity;
import similarity.objects.InformationContentObjectSimilarity;
import sonumina.math.graph.SlimDirectedGraphView;
/**
* Filter variants according to the phenotypic similarity of the specified
* disease to mouse models disrupting the same gene. We use semantic similarity
* calculations in the uberpheno.
*
* The files required for the constructor of this filter should be downloaded
* from: {@code http://purl.obolibrary.org/obo/hp/uberpheno/}
* (HSgenes_crossSpeciesPhenoAnnotation.txt, crossSpeciesPheno.obo)
*
* @author Sebastian Koehler
* @version 0.06 (6 December, 2013)
*/
public class PhenixPriority implements Priority {
private static final Logger logger = LoggerFactory.getLogger(PhenixPriority.class);
/**
* The HPO as Ontologizer-Ontology object
*/
private Ontology hpo;
/**
* The HPO as SlimDirectedGraph (fast access to ancestors etc.)
*/
private SlimDirectedGraphView<Term> hpoSlim;
/**
* A list of error-messages
*/
private ArrayList<String> error_record = null;
/**
* A list of messages that can be used to create a display in a HTML page or
* elsewhere.
*/
private ArrayList<String> messages = null;
/**
* The semantic similarity measure used to calculate phenotypic similarity
*/
private InformationContentObjectSimilarity similarityMeasure;
/**
* The HPO terms entered by the user describing the individual who is being
* sequenced by exome-sequencing or clinically relevant genome panel.
*/
private ArrayList<Term> hpoQueryTerms;
private float DEFAULT_SCORE = 0f;
private HashMap<String, ArrayList<Term>> geneId2annotations;
private HashMap<Term, HashSet<String>> annotationTerm2geneIds;
private HashMap<Term, Double> term2ic;
private final ScoreDistributionContainer scoredistributionContainer = new ScoreDistributionContainer();
private int numberQueryTerms;
/**
* A counter of the number of genes that could not be found in the database
* as being associated with a defined disease gene.
*/
private int offTargetGenes = 0;
/**
* Total number of genes used for the query, including genes with no
* associated disease.
*/
private int analysedGenes;
private boolean symmetric;
/**
* Path to the directory that has the files needed to calculate the score
* distribution.
*/
private String scoredistributionFolder;
/**
* Keeps track of the maximum semantic similarity score to date
*/
private double maxSemSim = 0d;
/**
* Keeps track of the maximum negative log of the p value to date
*/
private double maxNegLogP = 0d;
/**
* Create a new instance of the PhenixPriority.
*
* @param scoreDistributionFolder Folder which contains the score
* distributions (e.g. 3.out, 3_symmetric.out, 4.out, 4_symmetric.out). It
* must also contain the files hp.obo (obtained from
* {@code http://compbio.charite.de/hudson/job/hpo/}) and
* ALL_SOURCES_ALL_FREQUENCIES_genes_to_phenotype.txt-file (obtained from
* {@code http://compbio.charite.de/hudson/job/hpo.annotations.monthly/lastSuccessfulBuild/artifact/annotation/}).
* @param hpoQueryTermIds List of HPO terms
* @param symmetric Flag to indicate if the semantic similarity score should
* be calculated using the symmetrix formula.
* @throws ExomizerInitializationException
* @see <a href="http://purl.obolibrary.org/obo/hp/uberpheno/">Uberpheno
* Hudson page</a>
*/
public PhenixPriority(String scoreDistributionFolder, Set<String> hpoQueryTermIds, boolean symmetric) {
if (!scoreDistributionFolder.endsWith(File.separatorChar + "")) {
scoreDistributionFolder += File.separatorChar;
}
this.scoredistributionFolder = scoreDistributionFolder;
String hpoOboFile = String.format("%s%s", scoreDistributionFolder, "hp.obo");
String hpoAnnotationFile = String.format("%s%s", scoreDistributionFolder, "ALL_SOURCES_ALL_FREQUENCIES_genes_to_phenotype.txt");
parseData(hpoOboFile, hpoAnnotationFile);
HashSet<Term> hpoQueryTermsHS = new HashSet<Term>();
for (String termIdString : hpoQueryTermIds) {
Term t = hpo.getTermIncludingAlternatives(termIdString);
if (t != null) {
hpoQueryTermsHS.add(t);
} else {
logger.error("invalid term-id given: " + termIdString);
}
}
hpoQueryTerms = new ArrayList<Term>();
hpoQueryTerms.addAll(hpoQueryTermsHS);
this.symmetric = symmetric;
numberQueryTerms = hpoQueryTerms.size();
if (!scoredistributionContainer.didParseDistributions(symmetric, numberQueryTerms)) {
scoredistributionContainer.parseDistributions(symmetric, numberQueryTerms, scoreDistributionFolder);
}
ResnikSimilarity resnik = new ResnikSimilarity(hpo, term2ic);
similarityMeasure = new InformationContentObjectSimilarity(resnik, symmetric, false);
/* some logging stuff */
this.error_record = new ArrayList<String>();
this.messages = new ArrayList<String>();
}
private void parseData(String hpoOboFile, String hpoAnnotationFile) {
//The phenomizerData directory must contain the files "hp.obo", "ALL_SOURCES_ALL_FREQUENCIES_genes_to_phenotype.txt"
//as well as the score distribution files "*.out", all of which can be downloaded from the HPO hudson server.
try {
parseOntology(hpoOboFile);
} catch (OBOParserException e) {
logger.error("Error parsing ontology file {}", hpoOboFile, e);
} catch (IOException ioe) {
logger.error("I/O Error with ontology file{}", hpoOboFile, ioe);
}
try {
parseAnnotations(hpoAnnotationFile);
} catch (IOException e) {
logger.error("Error parsing annotation file {}", hpoAnnotationFile, e);
}
}
/**
* Parse the HPO phenotype annotation file (e.g., phenotype_annotation.tab).
* The point of this is to get the links between diseases and HPO phenotype
* terms. The hpoAnnotationFile is The
* ALL_SOURCES_ALL_FREQUENCIES_genes_to_phenotype.txt-file
*
* @param hpoAnnotationFile path to the file
*/
private void parseAnnotations(String hpoAnnotationFile) throws IOException {
geneId2annotations = new HashMap<String, ArrayList<Term>>();
BufferedReader in = new BufferedReader(new FileReader(hpoAnnotationFile));
String line = null;
while ((line = in.readLine()) != null) {
if (line.startsWith("#")) {
continue;
}
String[] split = line.split("\t");
String entrez = split[0];
Term t = null;
try {
/* split[4] is the HPO term field of an annotation line. */
t = hpo.getTermIncludingAlternatives(split[3]);
} catch (IllegalArgumentException e) {
logger.error("Unable to get term for line \n{}\n", line);
logger.error("The offending field was '{}'", split[3]);
for (int k = 0; k < split.length; ++k) {
logger.error("{} '{}'", k, split[k]);
}
t = null;
}
if (t == null) {
continue;
}
ArrayList<Term> annot;
if (geneId2annotations.containsKey(entrez)) {
annot = geneId2annotations.get(entrez);
} else {
annot = new ArrayList<>();
}
annot.add(t);
geneId2annotations.put(entrez, annot);
}
in.close();
// cleanup annotations
for (String entrez : geneId2annotations.keySet()) {
ArrayList<Term> terms = geneId2annotations.get(entrez);
HashSet<Term> uniqueTerms = new HashSet<Term>(terms);
ArrayList<Term> uniqueTermsAL = new ArrayList<Term>();
uniqueTermsAL.addAll(uniqueTerms);
ArrayList<Term> termsMostSpecific = HPOutils.cleanUpAssociation(uniqueTermsAL, hpoSlim, hpo.getRootTerm());
geneId2annotations.put(entrez, termsMostSpecific);
}
// prepare IC computation
annotationTerm2geneIds = new HashMap<Term, HashSet<String>>();
for (String oId : geneId2annotations.keySet()) {
ArrayList<Term> annotations = geneId2annotations.get(oId);
for (Term annot : annotations) {
ArrayList<Term> termAndAncestors = hpoSlim.getAncestors(annot);
for (Term t : termAndAncestors) {
HashSet<String> objectsAnnotatedByTerm; // here we store
// which objects
// have been
// annotated with
// this term
if (annotationTerm2geneIds.containsKey(t)) {
objectsAnnotatedByTerm = annotationTerm2geneIds.get(t);
} else {
objectsAnnotatedByTerm = new HashSet<String>();
}
objectsAnnotatedByTerm.add(oId); // add the current object
annotationTerm2geneIds.put(t, objectsAnnotatedByTerm);
}
}
}
term2ic = caclulateTermIC(hpo, annotationTerm2geneIds);
}
/**
* Parses the human-phenotype-ontology.obo file (or equivalently, the hp.obo
* file from our Hudosn server).
*
* @param hpoOboFile path to the hp.obo file.
*/
private Ontology parseOntology(String hpoOboFile) throws IOException, OBOParserException {
OBOParser oboParser = new OBOParser(hpoOboFile, OBOParser.PARSE_XREFS);
String parseInfo = oboParser.doParse();
logger.info(parseInfo);
TermContainer termContainer = new TermContainer(oboParser.getTermMap(), oboParser.getFormatVersion(), oboParser.getDate());
Ontology hpo = new Ontology(termContainer);
hpo.setRelevantSubontology(termContainer.get(HPOutils.organAbnormalityRootId).getName());
SlimDirectedGraphView<Term> hpoSlim = hpo.getSlimGraphView();
this.hpo = hpo;
this.hpoSlim = hpoSlim;
return hpo;
}
/**
* @see exomizer.priority.IPriority#getPriorityName()
*/
@Override
public String getPriorityName() {
return "HPO Phenomizer prioritizer";
}
/**
* Flag to output results of filtering against Uberpheno data.
*/
@Override
public PriorityType getPriorityType() {
return PriorityType.PHENIX_PRIORITY;
}
/**
* @return list of messages representing process, result, and if any, errors
* of score filtering.
*/
public ArrayList<String> getMessages() {
if (this.error_record.size() > 0) {
for (String s : error_record) {
this.messages.add("Error: " + s);
}
}
return this.messages;
}
/**
* Prioritize a list of candidate {@link exomizer.exome.Gene Gene} objects
* (the candidate genes have rare, potentially pathogenic variants).
*
* @param gene_list List of candidate genes.
* @see exomizer.filter.Filter#filter_list_of_variants(java.util.ArrayList)
*/
@Override
public void prioritizeGenes(List<Gene> gene_list) {
analysedGenes = gene_list.size();
for (Gene gene : gene_list) {
PhenixPriorityResult phenomizerRelScore = scoreVariantHPO(gene);
gene.addPriorityResult(phenomizerRelScore);
//System.out.println("Phenomizer Gene="+gene.getGeneSymbol()+" score=" +phenomizerRelScore.getScore());
}
String s = String.format("Data investigated in HPO for %d genes. No data for %d genes", analysedGenes, this.offTargetGenes);
//System.out.println(s);
normalizePhenomizerScores(gene_list);
this.messages.add(s);
}
/**
* The gene relevance scores are to be normalized to lie between zero and
* one. This function, which relies upon the variable {@link #maxSemSim}
* being set in {@link #scoreVariantHPO}, divides each score by
* {@link #maxSemSim}, which has the effect of putting the phenomizer scores
* in the range [0..1]. Note that for now we are using the semantic
* similarity scores, but we should also try the P value version (TODO).
* Note that this is not the same as rank normalization!
*/
private void normalizePhenomizerScores(List<Gene> gene_list) {
if (maxSemSim < 1) {
return;
}
PhenixPriorityResult.setNormalizationFactor(1d / maxSemSim);
/*for (Gene g : gene_list) {
float score = g.getRelevagetScorepe.PHENIX_PRIORITY);
score /= this.maxSemSim;
g.setScore(FilterType.PHENIX_PRIORITY, score);
}*/
}
/**
* @param g A {@link exomizer.exome.Gene Gene} whose score is to be
* determined.
*/
private PhenixPriorityResult scoreVariantHPO(Gene g) {
int entrezGeneId = g.getEntrezGeneID();
String entrezGeneIdString = entrezGeneId + "";
if (!geneId2annotations.containsKey(entrezGeneIdString)) {
//System.err.println("INVALID GENE GIVEN (will set to default-score): Entrez ID: " + g.getEntrezGeneID() + " / " + g.getGeneSymbol());
this.offTargetGenes++;
return new PhenixPriorityResult(DEFAULT_SCORE);
}
ArrayList<Term> annotationsOfGene = geneId2annotations.get(entrezGeneIdString);
double similarityScore = similarityMeasure.computeObjectSimilarity(hpoQueryTerms, annotationsOfGene);
if (similarityScore > maxSemSim) {
maxSemSim = similarityScore;
}
if (Double.isNaN(similarityScore)) {
error_record.add("score was NAN for gene:" + g + " : " + hpoQueryTerms + " <-> " + annotationsOfGene);
}
ScoreDistribution scoreDist = scoredistributionContainer.getDistribution(entrezGeneIdString, numberQueryTerms, symmetric,
scoredistributionFolder);
// get the pvalue
double rawPvalue;
if (scoreDist == null) {
return new PhenixPriorityResult(DEFAULT_SCORE);
} else {
rawPvalue = scoreDist.getPvalue(similarityScore, 1000.);
rawPvalue = Math.log(rawPvalue) * -1.0; /* Negative log of p value : most significant get highest score */
if (rawPvalue > maxNegLogP) {
maxNegLogP = rawPvalue;
}
}
return new PhenixPriorityResult(rawPvalue, similarityScore);
// // filter genes not associated with any disease
// if
// (!HPOutils.diseaseGeneMapper.entrezId2diseaseIds.containsKey(entrezGeneId))
// return new PhenixPriorityResult(DEFAULT_SCORE);
//
// double sum = 0; // sum of semantic similarity
// int num = 0; // required to make average
// for (DiseaseId diseaseId :
// HPOutils.diseaseGeneMapper.entrezId2diseaseIds.get(entrezGeneId)) {
//
// DiseaseEntry diseaseEntry = HPOutils.diseaseId2entry.get(diseaseId);
//
// if (diseaseEntry == null) {
// // System.out.println("diseaseID = " + diseaseId);
// // System.out.println("diseaseEntry = NULL " );
// // return new PhenixPriorityResult(DEFAULT_SCORE);
// continue;
// }
// ArrayList<Term> termsAL = diseaseEntry.getOrganAssociatedTerms();
// if (termsAL == null || termsAL.size() < 1) {
// continue;
// // return new PhenixPriorityResult(DEFAULT_SCORE);
// }
// double similarityScore =
// similarityMeasure.computeObjectSimilarity(hpoQueryTerms, termsAL);
// sum += similarityScore;
// ++num;
// }
// if (num == 0) {
// return new PhenixPriorityResult(DEFAULT_SCORE);
// }
//
// double avg = sum / num;
// return new PhenixPriorityResult(avg);
}
/**
* Flag to show results of this analysis in the HTML page.
*
* @return
*/
@Override
public boolean displayInHTML() {
return true;
}
/**
* @return an ul list with summary of phenomizer prioritization.
*/
@Override
public String getHTMLCode() {
String s = String.format("Phenomizer: %d genes were evaluated; no phenotype data available for %d of them",
this.analysedGenes, this.offTargetGenes);
String t = null;
if (symmetric) {
t = String.format("Symmetric Phenomizer query with %d terms was performed", this.numberQueryTerms);
} else {
t = String.format("Asymmetric Phenomizer query with %d terms was performed", this.numberQueryTerms);
}
String u = String.format("Maximum semantic similarity score: %.2f, maximum negative log. of p-value: %.2f",
this.maxSemSim, this.maxNegLogP);
return String.format("<ul><li>%s</li><li>%s</li><li>%s</li></ul>\n", s, t, u);
}
private HashMap<Term, Double> caclulateTermIC(Ontology ontology, HashMap<Term, HashSet<String>> term2objectIdsAnnotated) {
Term root = ontology.getRootTerm();
HashMap<Term, Integer> term2frequency = new HashMap<Term, Integer>();
for (Term t : term2objectIdsAnnotated.keySet()) {
term2frequency.put(t, term2objectIdsAnnotated.get(t).size());
}
int maxFreq = term2frequency.get(root);
HashMap<Term, Double> term2informationContent = SimilarityUtilities.caculateInformationContent(maxFreq, term2frequency);
int frequencyZeroCounter = 0;
double ICzeroCountTerms = -1 * (Math.log(1 / (double) maxFreq));
for (Term t : ontology) {
if (!term2frequency.containsKey(t)) {
++frequencyZeroCounter;
term2informationContent.put(t, ICzeroCountTerms);
}
}
logger.info("WARNING: Frequency of {} terms was zero!! Set IC of these to : {}", frequencyZeroCounter, ICzeroCountTerms);
return term2informationContent;
}
}
| Commit for issue #49 PhenixPriority now dies immediately and with an informative message if no HPO terms are supplied. | exomiser-core/src/main/java/de/charite/compbio/exomiser/core/prioritisers/PhenixPriority.java | Commit for issue #49 PhenixPriority now dies immediately and with an informative message if no HPO terms are supplied. | <ide><path>xomiser-core/src/main/java/de/charite/compbio/exomiser/core/prioritisers/PhenixPriority.java
<ide> */
<ide> public PhenixPriority(String scoreDistributionFolder, Set<String> hpoQueryTermIds, boolean symmetric) {
<ide>
<add> if (hpoQueryTermIds.isEmpty()) {
<add> throw new PhenixException("Please supply some HPO terms. PhenIX is unable to prioritise genes without these.");
<add> }
<add>
<ide> if (!scoreDistributionFolder.endsWith(File.separatorChar + "")) {
<ide> scoreDistributionFolder += File.separatorChar;
<ide> }
<ide> String hpoAnnotationFile = String.format("%s%s", scoreDistributionFolder, "ALL_SOURCES_ALL_FREQUENCIES_genes_to_phenotype.txt");
<ide> parseData(hpoOboFile, hpoAnnotationFile);
<ide>
<del> HashSet<Term> hpoQueryTermsHS = new HashSet<Term>();
<add> HashSet<Term> hpoQueryTermsHS = new HashSet<Term>();
<ide> for (String termIdString : hpoQueryTermIds) {
<ide> Term t = hpo.getTermIncludingAlternatives(termIdString);
<ide> if (t != null) {
<ide> return term2informationContent;
<ide> }
<ide>
<add> private static class PhenixException extends RuntimeException {
<add>
<add> private PhenixException(String message) {
<add> super(message);
<add> }
<add> }
<add>
<ide> } |
|
Java | mit | 010745c413cd5f61dc89e239b0738b3e9b53eb47 | 0 | int02h/tellon,praetoriandroid/tellon,int02h/tellon,praetoriandroid/tellon | package com.dpforge.tellon.core.parser;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class WatcherConstantParserTest {
@Test
public void singleLiteral() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String A = \"Hello\";",
"}");
assertEquals("Hello", map.get("A").get(0));
}
@Test
public void multipleLiteralInitializer() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String[] A = {\"Hello\", \"World\"};",
"}");
assertEquals("Hello", map.get("A").get(0));
assertEquals("World", map.get("A").get(1));
}
@Test
public void multipleLiteralCreation() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String[] A = new String[] {\"Hello\", \"World\"};",
"}");
assertEquals("Hello", map.get("A").get(0));
assertEquals("World", map.get("A").get(1));
}
@Test
public void singleReference() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String A = \"Hello\";",
" static final String B = A;",
"}");
assertEquals("Hello", map.get("A").get(0));
assertEquals("Hello", map.get("B").get(0));
}
@Test
public void referenceToMultiple() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String A = {\"Hello\", \"World\"};",
" static final String B = A;",
"}");
assertEquals("Hello", map.get("A").get(0));
assertEquals("World", map.get("A").get(1));
assertEquals("Hello", map.get("B").get(0));
assertEquals("World", map.get("B").get(1));
}
@Test
public void multipleReferenceInitializer() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String A = \"Hello\";",
" static final String B = \"World\";",
" static final String[] C = {A, B};",
"}");
assertEquals("Hello", map.get("C").get(0));
assertEquals("World", map.get("C").get(1));
}
@Test
public void multipleReferenceCreation() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String A = \"Hello\";",
" static final String B = \"World\";",
" static final String C[] = new String[] {A, B};",
"}");
assertEquals("Hello", map.get("C").get(0));
assertEquals("World", map.get("C").get(1));
}
@Test
public void nonStatic() {
try {
parse("class Foo {",
" final String A = \"Hello\";",
"}");
fail("No exception thrown");
} catch (Exception e) {
assertEquals("Field not static", e.getMessage());
}
}
@Test
public void nonFinal() {
try {
parse("class Foo {",
" static String A = \"Hello\";",
"}");
fail("No exception thrown");
} catch (Exception e) {
assertEquals("Field not final", e.getMessage());
}
}
@Test
public void wrongType() {
try {
parse("class Foo {",
" static final Integer A = 1;",
"}");
fail("No exception thrown");
} catch (Exception e) {
assertEquals("Field must be of type String", e.getMessage());
}
}
private static Map<String, List<String>> parse(final String... code) {
return new WatcherConstantParser().parse(SourceCode.createFromContent(code));
}
} | tellon-core/src/test/java/com/dpforge/tellon/core/parser/WatcherConstantParserTest.java | package com.dpforge.tellon.core.parser;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class WatcherConstantParserTest {
@Test
public void singleLiteral() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String A = \"Hello\";",
"}");
assertEquals("Hello", map.get("A").get(0));
}
@Test
public void multipleLiteralInitializer() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String[] A = {\"Hello\", \"World\"};",
"}");
assertEquals("Hello", map.get("A").get(0));
assertEquals("World", map.get("A").get(1));
}
@Test
public void multipleLiteralCreation() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String[] A = new String[] {\"Hello\", \"World\"};",
"}");
assertEquals("Hello", map.get("A").get(0));
assertEquals("World", map.get("A").get(1));
}
@Test
public void singleReference() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String A = \"Hello\";",
" static final String B = A;",
"}");
assertEquals("Hello", map.get("A").get(0));
assertEquals("Hello", map.get("B").get(0));
}
@Test
public void multipleReferenceInitializer() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String A = \"Hello\";",
" static final String B = \"World\";",
" static final String[] C = {A, B};",
"}");
assertEquals("Hello", map.get("C").get(0));
assertEquals("World", map.get("C").get(1));
}
@Test
public void multipleReferenceCreation() {
Map<String, List<String>> map = parse(
"class Foo {",
" static final String A = \"Hello\";",
" static final String B = \"World\";",
" static final String C[] = new String[] {A, B};",
"}");
assertEquals("Hello", map.get("C").get(0));
assertEquals("World", map.get("C").get(1));
}
@Test
public void nonStatic() {
try {
parse("class Foo {",
" final String A = \"Hello\";",
"}");
fail("No exception thrown");
} catch (Exception e) {
assertEquals("Field not static", e.getMessage());
}
}
@Test
public void nonFinal() {
try {
parse("class Foo {",
" static String A = \"Hello\";",
"}");
fail("No exception thrown");
} catch (Exception e) {
assertEquals("Field not final", e.getMessage());
}
}
@Test
public void wrongType() {
try {
parse("class Foo {",
" static final Integer A = 1;",
"}");
fail("No exception thrown");
} catch (Exception e) {
assertEquals("Field must be of type String", e.getMessage());
}
}
private static Map<String, List<String>> parse(final String... code) {
return new WatcherConstantParser().parse(SourceCode.createFromContent(code));
}
} | unit test
| tellon-core/src/test/java/com/dpforge/tellon/core/parser/WatcherConstantParserTest.java | unit test | <ide><path>ellon-core/src/test/java/com/dpforge/tellon/core/parser/WatcherConstantParserTest.java
<ide> "}");
<ide> assertEquals("Hello", map.get("A").get(0));
<ide> assertEquals("Hello", map.get("B").get(0));
<add> }
<add>
<add> @Test
<add> public void referenceToMultiple() {
<add> Map<String, List<String>> map = parse(
<add> "class Foo {",
<add> " static final String A = {\"Hello\", \"World\"};",
<add> " static final String B = A;",
<add> "}");
<add> assertEquals("Hello", map.get("A").get(0));
<add> assertEquals("World", map.get("A").get(1));
<add> assertEquals("Hello", map.get("B").get(0));
<add> assertEquals("World", map.get("B").get(1));
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | error: pathspec 'com/planet_ink/coffee_mud/Abilities/Traps/Trap_Needle.java' did not match any file(s) known to git
| d7c636a094caaab217b5ebe5909c75bd1d74a75e | 1 | Tycheo/coffeemud,sfunk1x/CoffeeMud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,MaxRau/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud | package com.planet_ink.coffee_mud.Abilities.Traps;
public class Trap_Needle
{
}
| com/planet_ink/coffee_mud/Abilities/Traps/Trap_Needle.java |
git-svn-id: svn://192.168.1.10/public/CoffeeMud@2233 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/Abilities/Traps/Trap_Needle.java | <ide><path>om/planet_ink/coffee_mud/Abilities/Traps/Trap_Needle.java
<add>package com.planet_ink.coffee_mud.Abilities.Traps;
<add>
<add>public class Trap_Needle
<add>{
<add>} |
||
JavaScript | apache-2.0 | c8895b2bea8b95bf811ce0455bf8b39982ebefe2 | 0 | bryce-richards/dot-planner,bryce-richards/dot-planner,bryce-richards/dot-planner,bryce-richards/dot-planner | $("#project-details").hide();
//Global variable which will become the geoJSON layer
var geoJSON;
//Global variable which will represent the layer at the top of the map(layer that has been clicked on) so that it can be hidden
var layerID;
//Creating the map with mapbox (view coordinates are downtown Los Angeles)
// var map = L.mapbox.map('map');
var colors = {
red: "#FF355E",
// safety / police
watermelon: "#FD5B78",
// srts / triangle
orange: "#FF9933",
// else / marker
sun: "#FFCC33",
// bike / bicycle
rose: "#EE34D2",
// ped & bike / entrance
lime: "#CCFF00",
// first & last / hospital
green: "#66FF66",
// people / city
mint: "#AAF0D1",
// ped / toilets
blue: "#50BFE6"
// transit / rail
};
function getMarkerStyle(type) {
var newMarker = {
"marker-color": "",
"marker-symbol": ""
};
var projectType;
if (type) {
projectType = type.trim();
} else {
projectType = type;
}
if (projectType === "Ped and Bike" || projectType === "Bike/ped") {
newMarker["marker-color"] = colors.rose;
newMarker["marker-symbol"] = "pitch";
}
else if (projectType === "Bike Only") {
newMarker["marker-color"] = colors.sun;
newMarker["marker-symbol"] = "bicycle";
}
else if (projectType === "Ped Only") {
newMarker["marker-color"] = colors.mint;
newMarker["marker-symbol"] = "toilets";
}
else if (projectType === "First and Last Mile" || projectType === "First mile and last mile") {
newMarker["marker-color"] = colors.lime;
newMarker["marker-symbol"] = "hospital";
}
else if (projectType === "Safety") {
newMarker["marker-color"] = colors.red;
newMarker["marker-symbol"] = "police";
}
else if (projectType === "SRTS") {
newMarker["marker-color"] = colors.watermelon;
newMarker["marker-symbol"] = "triangle-stroked";
}
else if (projectType === "People St") {
newMarker["marker-color"] = colors.green;
newMarker["marker-symbol"] = "city";
}
else if (projectType === "Transit") {
newMarker["marker-color"] = colors.blue;
newMarker["marker-symbol"] = "bus";
}
else {
newMarker["marker-color"] = colors.orange;
newMarker["marker-symbol"] = "marker";
}
return newMarker;
}
// TODO: Does mapbox API token expire? We probably need the city to make their own account and create a map. This is currently using Spencer's account.
// Creating the map with mapbox (view coordinates are downtown Los Angeles)
var map = L.mapbox.map('map', {
layers: [imageryLayer]
});
var imageryLayer = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
id: 'SATELLITE',
//attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
detectRetina: true
});
var overlayMaps = {
'SATELLITE': imageryLayer
};
L.control.layers({}, overlayMaps).addTo(map);
L.tileLayer("https://api.mapbox.com/styles/v1/spencerc77/ciw30fzgs00ap2jpg6sj6ubnn/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic3BlbmNlcmM3NyIsImEiOiJjaXczMDZ6NWwwMTgzMm9tbXR4dGRtOXlwIn0.TPfrEq5h7Iuain1LsBsC8Q", {
detectRetina: true
}, {}).addTo(map);
//Adding a feature group to the map
var featureGroup = L.featureGroup().addTo(map);
//Defining the bounds for all Google autocomplete inputs
//This means autocomplete search will start here and expand outwards
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(34.0522, -118.2437)
);
//Options for the google autocomplete inputs
var googleOptions = {
location: defaultBounds,
types: ['address']
};
//Create the autocomplete input
var input = document.getElementById("google-search-input");
var autocomplete = new google.maps.places.Autocomplete(input, googleOptions);
//Add an event listener that changes the map view when an autocomplete address is selected
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
map.setView([lat, lng], 15);
$('#google-search-input').val('');
});
// Create radius to add to map
var circleRadius = L.circle([34.0522, -118.2437], 100).addTo(map);
var circle_lat_long = circleRadius.getLatLng();
var globalRadius;
// Add circle radius to map when slider value changes
var updateCircle = function (latlng, radius) {
//
// if (!isFunded) {
// filterProjectTypes(true);
// } else {
// filterProjectTypes();
// }
globalRadius = radius;
circleRadius = L.circle([latlng.lat, latlng.lng], globalRadius).addTo(map);
// add move radius functionality
moveRadius();
};
var moveRadius = function () {
circleRadius.on({
mousedown: function () {
map.on('mousemove', function (e) {
circleRadius.setLatLng(e.latlng);
});
}
});
map.on('mouseup', function (e) {
map.removeEventListener('mousemove');
map.featuresAt(e.point, {
radius: globalRadius,
includeGeometry: true
}, function(err, features) {
if (err || !features.length) {
popup.remove();
return;
}
displayResults(features);
});
// if (!isFunded) {
// filterProjectTypes(true);
// } else {
// filterProjectTypes();
// }
});
};
moveRadius();
// Grab the radius value from the slider
$('#radiusSlider').slider({
formatter: function (value) {
var latlng;
map.removeLayer(circleRadius);
latlng = circleRadius._latlng;
var valueInMiles = Math.round(value * 0.000621371);
// console.log(latlng);
updateCircle(latlng, value);
globalRadius = valueInMiles;
return valueInMiles;
}
});
//AJAX request to the PostgreSQL database to get all projects and render them on the map
function renderAllProjects(zoom) {
$("#edit-button").attr("disabled", "true");
$.ajax({
type: 'GET',
url: '/projects/all',
datatype: 'JSON',
success: function (data) {
if (data) {
displayResults(data);
// var features = data.features;
// for (var i = 0; i < features.length; i++) {
//
// var projectFeatures = features[i].properties;
//
// var projectType = projectFeatures.Proj_Ty;
//
// var markerStyle = getMarkerStyle(projectType);
//
//
// projectFeatures["marker-color"] = markerStyle["marker-color"];
// projectFeatures["marker-symbol"] = markerStyle["marker-symbol"];
// projectFeatures["marker-size"] = "small";
// }
//
// if (geoJSON) {
// geoJSON.clearLayers();
// }
// geoJSON = L.geoJson(data, {
// style: {
// color: "#004EB9"
// },
// onEachFeature: function(feature, layer) {
// onEachFeature(feature, layer);
// },
// pointToLayer: L.mapbox.marker.style
// }).addTo(map);
// if (zoom) {
// checkZoom();
// }
}
}
});
}
renderAllProjects(true);
// filterProjectTypes(true);
//Function to check if a project should be zoomed in on
function checkZoom() {
var url = window.location.href;
if (url.includes('?id=')) {
url = url.split('?id=');
var id = url[url.length - 1];
$.ajax({
method: "GET",
url: "/projects/id/" + id,
dataType: "json",
success: function (data) {
if (data) {
geoJSON.eachLayer(function (l) {
if (l.feature.properties.id === data[0].id) {
l.fireEvent('click');
}
});
}
}
});
} else {
map.setView([
34.0522, -118.2437
], 10);
}
}
// Global variable to know if we're looking for funded or unfunded
var isFunded;
// Give me funded projects
$('#fundedTab').on('click', function () {
isFunded = "funded";
$('#project-details').hide();
$('#main-info').empty();
filterProjectTypes();
});
//Give me unfunded projects
$('#unfundedTab').on('click', function () {
isFunded = "unfunded";
$('#project-details').hide();
$('#main-info').empty();
filterProjectTypes();
});
$(".filter-check").change(function () {
if (!isFunded) {
filterProjectTypes(true);
} else {
filterProjectTypes();
}
});
/* FILTER PROJECT TYPES FUNCTION */
function filterProjectTypes(type) {
// reset map view
// var fundingType = $('#fundedTab').getAttribute('value');
// var fundingType = $('#fundedTab').text().toLowerCase();
// console.log(fundingType);
var projectTypes = $('.project-type input[type="checkbox"]:checked').map(function (_, el) {
return $(el).val();
}).get();
if (projectTypes.length >= 1) {
for (var i = 0; i < projectTypes.length; i++) {
projectTypes[i] = projectTypes[i].split(' ').join('%20');
}
var fundingQuery = isFunded;
var typeQuery = projectTypes.join('&');
if (type) {
$.ajax({
type: 'GET',
url: '/projects/type/' + typeQuery,
datatype: 'JSON',
success: function (data) {
displayResults(data);
// filterByRadius(data);
}
});
} else {
$.ajax({
type: 'GET',
url: '/projects/funding/' + fundingQuery + '/type/' + typeQuery,
datatype: 'JSON',
success: function (data) {
displayResults(data);
// filterByRadius(data);
}
});
}
} else {
geoJSON.clearLayers();
}
}
// function filterByRadius(data) {
//
// var finalResults = {};
// finalResults.features = [];
//
// var features = data.features;
// // check if data meets radius requirements
// for (var i = 0; i < features.length; i++) {
//
// var projectGeometry = features[i].geometry;
//
// if (projectGeometry.type === "Point") {
//
// // Single point
// var coordinates = projectGeometry.coordinates;
//
// var latlng = L.latLng(coordinates.reverse());
//
// var distance = latlng.distanceTo(circle_lat_long);
// // Convert meters to feet
// var distanceInMiles = distance * 0.000621371192;
//
// latlng = L.latLng(coordinates.reverse());
//
// if (distanceInMiles <= globalRadius) {
// finalResults.features.push(features[i]);
// }
//
//
// }
// if (projectGeometry.type === "MultiLineString" || projectGeometry.type === "Polygon") {
//
// var outsideCoordinates = projectGeometry.coordinates;
//
// var isMatch = false;
//
// for (var k = 0; k < outsideCoordinates.length; k++) {
//
// if (isMatch) {
// break;
// }
// var insideCoordinates = outsideCoordinates[k];
// for (l = 0; l < insideCoordinates.length; l++) {
//
// var coordinates = insideCoordinates[l];
// var latlng = L.latLng(coordinates.reverse());
// var distance = (latlng).distanceTo(circle_lat_long);
// // Convert meters to feet
// var distanceInMiles = distance * 0.000621371192;
// latlng = L.latLng(coordinates.reverse());
//
// if (distanceInMiles <= globalRadius && !isMatch) {
// finalResults.features.push(features[i]);
// isMatch = true;
// break;
// }
// }
// }
// }
// if (projectGeometry.type === "MultiPoint" || projectGeometry.type === "LineString") {
//
// var coordinatesArray = projectGeometry.coordinates;
//
//
// for (var j = 0; j < coordinatesArray.length; j++) {
//
//
// var coordinates = coordinatesArray[j];
//
// var latlng = L.latLng(coordinates.reverse());
//
//
// var distance = (latlng).distanceTo(circle_lat_long);
// // Convert meters to feet
// var distanceInMiles = distance * 0.000621371192;
// latlng = L.latLng(coordinates.reverse());
//
// if (distanceInMiles <= globalRadius) {
// finalResults.features.push(features[i]);
// break;
// }
//
// }
//
// }
// }
// displayResults(finalResults);
// }
function displayResults(results) {
checkZoom();
$('#main-info').empty();
// show main info div
$('#main-info').show();
// hide project details div
$("#project-details").hide();
var panelGroup = $("<div>");
panelGroup
.addClass("panel-group")
.attr("id", "project-accordian")
.attr("role", "tablist")
// .attr("aria-multiselectable", "true");
$("#main-info").append(panelGroup);
var count = 0;
var features = results.features;
for (var i = 0; i < features.length; i++) {
var projectFeatures = features[i].properties;
var projectType = projectFeatures.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
projectFeatures["marker-color"] = markerStyle["marker-color"];
projectFeatures["marker-symbol"] = markerStyle["marker-symbol"];
projectFeatures["marker-size"] = "small";
// build accordian panel
var panel = $("<div>");
panel
.addClass("row panel projects-list-item");
var panelHeading = $("<div>");
panelHeading
.addClass("col-sm-12 panel-heading project-heading")
.attr("id", "heading_" + i)
.attr("role", "tab");
var panelTitle = $("<h3>");
panelTitle
.addClass("panel-title project-title");
var panelLink = $("<a>");
panelLink
.addClass("project-heading-data")
.attr("role", "button")
.attr("data-parent", "#project-accordian")
.attr("data-toggle", "collapse")
.attr("href", "#collapse_" + i)
// .attr("aria-expanded", "true")
// .attr("aria-controls", "collapse_" + i)
.text(projectFeatures.Proj_Title);
panelTitle
.append(panelLink);
var panelHeaderData = $("<div>");
panelHeaderData
.addClass("row");
var panelHeaderColumn1 = $("<div>");
panelHeaderColumn1
.addClass("col-sm-9");
var panelMiles = $("<h6>");
var panelCompletion = $("<h6>");
var panelId = $("<h6>");
panelMiles
.addClass("project-heading-data")
.text("MILES: ");
var completionDate = projectFeatures.ProjectProjectedCompletionDate;
if (completionDate) {
completionDate = completionDate;
} else {
completionDate = "TBD";
}
panelCompletion
.addClass("project-heading-data")
.text("COMPLETION DATE: " + completionDate);
panelId
.addClass("project-heading-data")
.text("ID: " + projectFeatures.id);
panelHeaderColumn1
.append(panelMiles)
.append(panelCompletion)
.append(panelId);
var panelHeaderColumn2 = $("<div>");
panelHeaderColumn2
.addClass("col-sm-2");
var projectColor = markerStyle["marker-color"];
var panelIcon = $("<i>");
panelIcon
.addClass("fa fa-circle fa-3x panel-icon")
// .attr("aria-hidden", "true")
.css("color", projectColor);
var panelSvg = $("<img>");
var projectIcon = markerStyle["marker-symbol"];
panelSvg
.attr("src", "/images/icons/" + projectIcon + ".svg")
.addClass("panel-svg");
panelIcon
.append(panelSvg);
panelHeaderColumn2
.append(panelIcon);
panelHeaderData
.append(panelHeaderColumn1)
.append(panelHeaderColumn2);
panelHeading
.append(panelTitle)
.append(panelHeaderData);
panel
.append(panelHeading);
var panelBodyCollapse = $("<div>");
panelBodyCollapse
.addClass("panel-collapse collapse")
.attr("id", "collapse_" + i)
.attr("role", "tabpanel")
// .attr("aria-labelledby", "heading_" + i);
var panelBody = $("<div>");
panelBody
.addClass("project-body panel-body");
var projTitle = $("<p>");
projTitle
.text("Title: " + projectFeatures.Proj_Title);
var projDesc = $("<p>");
projDesc
.text("Description: " + projectFeatures.Proj_Desc);
var legacyId = $("<p>");
legacyId
.text("Legacy ID: " + projectFeatures.Legacy_ID);
var leadAg = $("<p>");
leadAg
.text("Lead Agency: " + projectFeatures.Lead_Ag);
var fundSt = $("<p>");
fundSt
.text("Funding Status: " + projectFeatures.Fund_St);
var projTy = $("<p>");
projTy
.text("Project Type: " + projectFeatures.Proj_Ty);
var contactName = $("<p>");
contactName
.text("Contact Name: " + projectFeatures.Contact_info.Contact_info_name);
var contactPhone = $("<p>");
contactPhone
.text("Contact Phone: " + projectFeatures.Contact_info.Contact_info_phone);
var contactEmail = $("<p>");
contactEmail
.text("Contact Email: " + projectFeatures.Contact_info.Contact_info_email);
panelBody
.append(projTitle)
.append(projDesc)
.append(legacyId)
.append(leadAg)
.append(fundSt)
.append(projTy)
.append(contactName)
.append(contactPhone)
.append(contactEmail);
panelBodyCollapse
.append(panelBody);
panel
.append(panelBodyCollapse);
var panelButton = $("<button>");
panelButton
.addClass("btn project-body-button")
.attr("type", "button")
.attr("data-toggle", "collapse")
.attr("data-target", "#collapseMore_" + i)
// .attr("aria-expanded", "false")
// .attr("aria-controls", "collapseMore_" + i)
.text("More Info");
var viewButton = $("<a>");
viewButton
.addClass("btn project-body-button")
.attr("type", "button")
.attr("data-id", projectFeatures.id)
.text("View Project");
panelBodyCollapse
.append(panelButton)
.append(viewButton);
var moreData = $("<div>");
moreData
.addClass("collapse").attr("id", "collapseMore_" + i);
var moreDataWell = $("<div>");
moreDataWell
.addClass("project-more-data well");
if (isFunded === "funded") {
// funded project marker color
var deptProjId = $("<p>");
deptProjId.text("Dept Project ID: " + projectFeatures.Dept_Proj_ID);
moreDataWell.append(deptProjId);
var otherId = $("<p>");
otherId.text("Other ID: " + projectFeatures.Other_ID);
moreDataWell.append(otherId);
if (projectFeatures.Total_bgt) {
var totalBgt = $("<p>");
totalBgt.text("Total Budget: $" + projectFeatures.Total_bgt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(totalBgt);
}
if (projectFeatures.Grant) {
var grant = $("<p>");
grant.text("Grant: $" + projectFeatures.Grant.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(grant);
}
if (projectFeatures.Other_funds) {
var otherFunds = $("<p>");
otherFunds.text("Other Funds: $" + projectFeatures.Other_funds.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(otherFunds);
}
if (projectFeatures.Prop_c) {
var propC = $("<p>");
propC.text("Prop C: $" + projectFeatures.Prop_c.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(propC);
}
if (projectFeatures.Measure_r) {
var measureR = $("<p>");
measureR.text("Measure R: $" + projectFeatures.Measure_r.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(measureR);
}
if (projectFeatures.Gas_Tax) {
var gasTax = $("<p>");
gasTax.text("Gas Tax: $" + projectFeatures.Gas_Tax.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(gasTax);
}
if (projectFeatures.General_fund) {
var generalFund = $("<p>");
generalFund.text("General Fund: $" + projectFeatures.General_fund.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(generalFund);
}
var authorization = $("<p>");
authorization.text("Authorization: " + projectFeatures.Authorization);
var issues = $("<p>");
issues.text("Issues: " + projectFeatures.Issues);
var deobligation = $("<p>");
deobligation.text("Deobligation: " + projectFeatures.Deobligation);
var explanation = $("<p>");
explanation.text("Explanation: " + projectFeatures.Explanation);
var constrBy = $("<p>");
constrBy.text("Constructed By: " + projectFeatures.Constr_by);
var infoSource = $("<p>");
infoSource.text("Info Source: " + projectFeatures.Info_source);
var access = $("<p>");
access.text("Access: " + projectFeatures.Access);
moreDataWell
.append(authorization)
.append(issues)
.append(deobligation)
.append(explanation)
.append(constrBy)
.append(infoSource)
.append(access);
}
if (isFunded === "unfunded") {
// unfunded project marker color
var unfundedMoreInfo = $("<p>");
unfundedMoreInfo.text("Unfunded More Info: " + projectFeatures.More_info);
var unfundedCD = $("<p>");
unfundedCD.text("Unfunded CD: " + projectFeatures.CD);
var grantCat = $("<p>");
grantCat.text("Grant Category: " + projectFeatures.Grant_Cat);
var grantCycle = $("<p>");
grantCycle.text(projectFeatures.Grant_Cycle);
moreDataWell.append(unfundedMoreInfo).append(unfundedCD).append(grantCat).append(grantCycle);
if (projectFeatures.Est_Cost) {
var estCost = $("<p>");
estCost.text("Estimated Cost: $" + projectFeatures.Est_Cost.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(estCost);
}
if (projectFeatures.Fund_Rq) {
var fundRq = $("<p>");
fundRq.text("Fund Request: " + projectFeatures.Fund_Rq.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(fundRq);
}
if (projectFeatures.Lc_match) {
var LcMatch = $("<p>");
LcMatch.text("Lc Match: $ " + projectFeatures.Lc_match.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(LcMatch);
}
var matchPt = $("<p>");
matchPt.text("Match Percentage: " + projectFeatures.Match_Pt + "%");
moreDataWell.append(matchPt);
}
moreData
.append(moreDataWell);
panelBodyCollapse
.append(moreData);
panelGroup
.append(panel);
count++;
}
$("#count-info").empty();
$('#count-info').append("<p><strong>Projects Listed: " + count + "</strong></p>");
if (geoJSON) {
geoJSON.clearLayers();
}
geoJSON = L.geoJson(results, {
style: {
color: "#004EB9"
},
onEachFeature: function (feature, layer) {
onEachFeature(feature, layer);
},
pointToLayer: L
.mapbox.marker.style
}).addTo(map);
checkZoom();
}
$(document).on("click", ".project-body-button", function () {
var id = $(this).data("id");
$.ajax({
method: "GET",
url: "/projects/id/" + id,
datatype: 'JSON',
success: function (data) {
if (data) {
geoJSON.eachLayer(function (l) {
if (l.feature.properties.id === data[0].id) {
l.fireEvent('click');
}
});
}
}
});
});
$('#hide-button').on('click', function () {
geoJSON.eachLayer(function (l) {
if (l._leaflet_id === layerID) {
map.removeLayer(l);
}
});
});
$('#unhide-button').on('click', function () {
renderAllProjects(false);
});
/* ZOOM TO FEATURE FUNCTION */
//Function that sets the map bounds to a project
//This essentially "zooms in" on a project
function zoomToFeature(e) {
if (e.target.feature.geometry.type === 'Point') {
var coordinates = e.target.feature.geometry.coordinates.slice().reverse();
map.setView(coordinates, 16);
} else {
map.fitBounds(e.target.getBounds());
}
}
/* ON EACH FEATURE FUNCTION */
function onEachFeature(feature, layer) {
layer.on('click', function (e) {
$("#project-details").show();
$("#main-info").hide();
//Empty the cross streets since we are using .append()
$('#Cross_Streets').empty();
layerID = layer._leaflet_id;
zoomToFeature(e);
geoJSON.eachLayer(function (l) {
geoJSON.resetStyle(l);
if (l.feature.geometry.type === 'MultiPoint') {
l.eachLayer(function (MultiPointLayer) {
var projectType = l.feature.properties.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
MultiPointLayer.setIcon(L.mapbox.marker.icon({
"marker-color": markerStyle["marker-color"],
"marker-symbol": markerStyle["marker-symbol"],
"marker-size": "small"
}));
});
}
if (l.feature.geometry.type === 'Point') {
var projectType = l.feature.properties.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
l.setIcon(L.mapbox.marker.icon({
"marker-color": markerStyle["marker-color"],
"marker-symbol": markerStyle["marker-symbol"],
"marker-size": "small"
}));
}
});
if (e.target.feature.geometry.type === 'MultiPoint') {
layer.eachLayer(function (l) {
var projectType = e.target.feature.properties.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
l.setIcon(
L.mapbox.marker.icon({
"marker-color": markerStyle["marker-color"],
"marker-symbol": "star",
"marker-size": "large"
})
);
});
}
if (e.target.feature.geometry.type === 'Point') {
var projectType = e.target.feature.properties.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
layer.setIcon(
L.mapbox.marker.icon({
"marker-color": markerStyle["marker-color"],
"marker-symbol": "star",
"marker-size": "large"
})
);
}
if (e.target.feature.geometry.type != 'Point') {
layer.bringToFront();
var projectType = e.target.feature.properties.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
layer.setStyle({
color: markerStyle["marker-color"]
});
}
var fundStatus = feature.properties.Fund_St;
$('#sidebar-fundedAndUnfunded').hide();
$('#sidebar-funded-attributes').hide();
$('#sidebar-unfunded-attributes').hide();
$('#sidebar-more-info').hide();
$('#show-info').remove();
$('#hide-info').remove();
$('#edit-button').show();
$(document).on('click', '#show-info', function () {
$('#show-info').remove();
$('#hide-info').remove();
var button = $('<button id="hide-info" type="button" name="button" class="btn">Less Info</button>');
$('#project-details').append(button);
$('#sidebar-more-info').show();
if (fundStatus === 'Funded') {
$('#sidebar-funded-attributes').show();
$('#sidebar-unfunded-attributes').hide();
} else if (fundStatus === 'Unfunded') {
$('#sidebar-unfunded-attributes').show();
$('#sidebar-funded-attributes').hide();
}
});
$(document).on('click', '#hide-info', function () {
$('#show-info').remove();
$('#hide-info').remove();
var button = $('<button id="show-info" type="button" name="button" class="btn">More Info</button>');
$('#project-details').append(button);
$('#sidebar-more-info').hide();
if (fundStatus === 'Funded') {
$('#sidebar-funded-attributes').hide();
} else if (fundStatus === 'Unfunded') {
$('#sidebar-unfunded-attributes').hide();
}
});
$("#edit-button").removeAttr("disabled");
//Common attributes
$('#Proj_Title').text(feature.properties.Proj_Title);
$('#Proj_Desc').text(feature.properties.Proj_Desc);
$('#Legacy_ID').text(feature.properties.Legacy_ID);
$('#Lead_Ag').text(feature.properties.Lead_Ag);
$('#Fund_St').text(feature.properties.Fund_St);
$('#Proj_Ty').text(feature.properties.Proj_Ty);
$('#Contact_info_name').text(feature.properties.Contact_info.Contact_info_name);
$('#Contact_info_phone').text(feature.properties.Contact_info.Contact_info_phone);
$('#Contact_info_email').text(feature.properties.Contact_info.Contact_info_email);
if (fundStatus != 'Idea Project') {
$('#Proj_Man').text(feature.properties.Proj_Man);
$('#Current_Status').text(feature.properties.Proj_Status);
$('#More_info').text(feature.properties.More_info);
$('#CD').text(feature.properties.CD);
$('#Primary_Street').text(feature.properties.Primary_Street);
if (feature.properties.Cross_Streets && feature.properties.Cross_Streets.Intersections) {
var streets = feature.properties.Cross_Streets.Intersections;
streetsString = '';
for (var i = 0; i < streets.length; i++) {
streetsString += '<p>' + streets[i] + '</p><br>';
}
$('#Cross_Streets').append(streetsString);
}
// $('#sidebar-fundedAndUnfunded').show();
// var button = $('<button id="show-info" class="btn" type="button" name="button">More Info</button>');
// $('#project-details').append(button);
}
//Separate section for funded attributes
if (fundStatus === 'Funded') {
$('#Dept_Proj_ID').text(feature.properties.Dept_Proj_ID);
$('#Other_ID').text(feature.properties.Other_ID);
if (feature.properties.Total_bgt) {
$('#Total_bgt').text('$' + feature.properties.Total_bgt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Grant) {
$('#Grant').text('$' + feature.properties.Grant.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Other_funds) {
$('#Other_funds').text('$' + feature.properties.Other_funds.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Prop_c) {
$('#Prop_c').text('$' + feature.properties.Prop_c.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Measure_r) {
$('#Measure_r').text('$' + feature.properties.Measure_r.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Gas_Tax) {
$('#Gas_Tax').text('$' + feature.properties.Gas_Tax.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.General_fund) {
$('#General_fund').text('$' + feature.properties.General_fund.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
$('#Authorization').text(feature.properties.Authorization);
$('#Issues').text(feature.properties.Issues);
$('#Deobligation').text(feature.properties.Deobligation);
$('#Explanation').text(feature.properties.Explanation);
$('#Constr_by').text(feature.properties.Constr_by);
$('#Info_source').text(feature.properties.Info_source);
$('#Access').text(feature.properties.Access);
} else if (fundStatus === 'Unfunded') {
//Unfunded
$('#Unfunded-More_info').text(feature.properties.More_info);
$('#Unfunded-CD').text(feature.properties.CD);
$('#Grant_Cat').text(feature.properties.Grant_Cat);
$('#Grant_Cycle').text(feature.properties.Grant_Cycle);
if (feature.properties.Est_Cost) {
$('#Est_Cost').text('$' + feature.properties.Est_Cost.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Fund_Rq) {
$('#Fund_Rq').text('$' + feature.properties.Fund_Rq.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Lc_match) {
$('#Lc_match').text('$' + feature.properties.Lc_match.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
$('#Match_Pt').text(feature.properties.Match_Pt + '%');
}
$('#edit-button').attr('data-href', "/projects/edit/" + feature.properties.id);
});
}
//When the edit button is clicked redirect to the edit page which is defined in data-href
$(document).on('click', '#edit-button', function () {
window.location = $('#edit-button').attr('data-href');
});
$('#export-csv').on('click', function () {
exportCSV();
});
$('#export-shapefiles').on('click', function () {
separateShapes();
});
function exportCSV() {
var searchIDs = [];
var bounds = map.getBounds();
geoJSON.eachLayer(function (layer) {
if (layer.feature.geometry.type === 'Point') {
if (bounds.contains(layer.getLatLng())) {
searchIDs.push(layer.feature.properties.id);
}
} else if (layer.feature.geometry.type === 'MultiPoint') {
if (bounds.contains(layer.getBounds())) {
searchIDs.push(layer.feature.properties.id);
}
} else {
if (bounds.contains(layer.getLatLngs())) {
searchIDs.push(layer.feature.properties.id);
}
}
});
var queryString = searchIDs.join('&');
$.ajax({
method: "GET",
url: "/projects/ids/" + queryString,
dataType: "json",
success: function (data) {
var geoJSON = JSON.stringify(data);
$.post('https://ogre.adc4gis.com/convertJson', {
json: geoJSON,
format: "csv"
},
function (csv) {
a = document.createElement('a');
a.download = "projects.csv";
a.href = 'data:text/csv;charset=utf-8,' + escape(csv);
document.body.appendChild(a);
a.click();
a.remove();
});
}
});
}
function separateShapes() {
var bounds = map.getBounds();
var points = {
name: 'points',
features: []
};
var lines = {
name: 'lines',
features: []
};
var multilines = {
name: 'multilinestrings',
features: []
};
var polygons = {
name: 'polygons',
features: []
};
var multipoints = {
name: 'multipoints',
features: []
};
geoJSON.eachLayer(function (layer) {
switch (layer.feature.geometry.type) {
case 'Point':
if (bounds.contains(layer.getLatLng())) {
points.features.push(layer.feature.properties.id);
}
break;
case 'MultiPoint':
if (bounds.contains(layer.getBounds())) {
multipoints.features.push(layer.feature.properties.id);
}
break;
case 'LineString':
if (bounds.contains(layer.getLatLngs())) {
lines.features.push(layer.feature.properties.id);
}
break;
case 'MultiLineString':
if (bounds.contains(layer.getLatLngs())) {
multilines.features.push(layer.feature.properties.id);
}
break;
case 'Polygon':
if (bounds.contains(layer.getLatLngs())) {
polygons.features.push(layer.feature.properties.id);
}
break;
}
});
var shapeFilesArr = [points, lines, polygons, multilines, multipoints];
for (var i = shapeFilesArr.length - 1; i >= 0; i--) {
if (shapeFilesArr[i].features.length < 1) {
shapeFilesArr.splice(i, 1);
}
}
for (var j = 0; j < shapeFilesArr.length; j++) {
downloadShapeFiles(shapeFilesArr[j], j + 1, shapeFilesArr.length);
}
}
function downloadShapeFiles(geoTypeObj) {
var queryString = geoTypeObj.features.join('&');
$.ajax({
method: "GET",
url: "/projects/ids/" + queryString,
dataType: "json",
success: function (data) {
var geoJSON = JSON.stringify(data);
// XHR Request Working
var formData = new FormData();
formData.append('json', geoJSON);
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://ogre.adc4gis.com/convertJson");
xhr.responseType = "arraybuffer"; // ask for a binary result
xhr.onreadystatechange = function (evt) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
JSZip.loadAsync(xhr.response).then(function (zip) {
zip.generateAsync({
type: "blob"
})
.then(function (blob) {
saveAs(blob, geoTypeObj.name + '.zip');
});
});
} else {
console.log("http call error");
}
}
};
xhr.send(formData);
}
});
} | public/javascripts/map.js | $("#project-details").hide();
//Global variable which will become the geoJSON layer
var geoJSON;
//Global variable which will represent the layer at the top of the map(layer that has been clicked on) so that it can be hidden
var layerID;
//Creating the map with mapbox (view coordinates are downtown Los Angeles)
// var map = L.mapbox.map('map');
var colors = {
red: "#FF355E",
// safety / police
watermelon: "#FD5B78",
// srts / triangle
orange: "#FF9933",
// else / marker
sun: "#FFCC33",
// bike / bicycle
rose: "#EE34D2",
// ped & bike / entrance
lime: "#CCFF00",
// first & last / hospital
green: "#66FF66",
// people / city
mint: "#AAF0D1",
// ped / toilets
blue: "#50BFE6"
// transit / rail
};
function getMarkerStyle(type) {
var newMarker = {
"marker-color": "",
"marker-symbol": ""
};
var projectType;
if (type) {
projectType = type.trim();
} else {
projectType = type;
}
if (projectType === "Ped and Bike" || projectType === "Bike/ped") {
newMarker["marker-color"] = colors.rose;
newMarker["marker-symbol"] = "pitch";
}
else if (projectType === "Bike Only") {
newMarker["marker-color"] = colors.sun;
newMarker["marker-symbol"] = "bicycle";
}
else if (projectType === "Ped Only") {
newMarker["marker-color"] = colors.mint;
newMarker["marker-symbol"] = "toilets";
}
else if (projectType === "First and Last Mile" || projectType === "First mile and last mile") {
newMarker["marker-color"] = colors.lime;
newMarker["marker-symbol"] = "hospital";
}
else if (projectType === "Safety") {
newMarker["marker-color"] = colors.red;
newMarker["marker-symbol"] = "police";
}
else if (projectType === "SRTS") {
newMarker["marker-color"] = colors.watermelon;
newMarker["marker-symbol"] = "triangle-stroked";
}
else if (projectType === "People St") {
newMarker["marker-color"] = colors.green;
newMarker["marker-symbol"] = "city";
}
else if (projectType === "Transit") {
newMarker["marker-color"] = colors.blue;
newMarker["marker-symbol"] = "bus";
}
else {
newMarker["marker-color"] = colors.orange;
newMarker["marker-symbol"] = "marker";
}
return newMarker;
}
// TODO: Does mapbox API token expire? We probably need the city to make their own account and create a map. This is currently using Spencer's account.
// Creating the map with mapbox (view coordinates are downtown Los Angeles)
var map = L.mapbox.map('map', {
layers: [imageryLayer]
});
var imageryLayer = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
id: 'SATELLITE',
//attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
detectRetina: true
});
var overlayMaps = {
'SATELLITE': imageryLayer
};
L.control.layers({}, overlayMaps).addTo(map);
L.tileLayer("https://api.mapbox.com/styles/v1/spencerc77/ciw30fzgs00ap2jpg6sj6ubnn/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoic3BlbmNlcmM3NyIsImEiOiJjaXczMDZ6NWwwMTgzMm9tbXR4dGRtOXlwIn0.TPfrEq5h7Iuain1LsBsC8Q", {
detectRetina: true
}, {}).addTo(map);
//Adding a feature group to the map
var featureGroup = L.featureGroup().addTo(map);
//Defining the bounds for all Google autocomplete inputs
//This means autocomplete search will start here and expand outwards
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(34.0522, -118.2437)
);
//Options for the google autocomplete inputs
var googleOptions = {
location: defaultBounds,
types: ['address']
};
//Create the autocomplete input
var input = document.getElementById("google-search-input");
var autocomplete = new google.maps.places.Autocomplete(input, googleOptions);
//Add an event listener that changes the map view when an autocomplete address is selected
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
map.setView([lat, lng], 15);
$('#google-search-input').val('');
});
// Create radius to add to map
var circleRadius = L.circle([34.0522, -118.2437], 100).addTo(map);
var circle_lat_long = circleRadius.getLatLng();
var globalRadius;
// Add circle radius to map when slider value changes
var updateCircle = function (latlng, radius) {
if (!isFunded) {
filterProjectTypes(true);
} else {
filterProjectTypes();
}
globalRadius = radius;
circleRadius = L.circle([latlng.lat, latlng.lng], globalRadius).addTo(map);
// add move radius functionality
moveRadius();
};
var moveRadius = function () {
circleRadius.on({
mousedown: function () {
map.on('mousemove', function (e) {
circleRadius.setLatLng(e.latlng);
});
}
});
map.on('mouseup', function (e) {
map.removeEventListener('mousemove');
if (!isFunded) {
filterProjectTypes(true);
} else {
filterProjectTypes();
}
});
};
moveRadius();
// Grab the radius value from the slider
$('#radiusSlider').slider({
formatter: function (value) {
var latlng;
map.removeLayer(circleRadius);
latlng = circleRadius._latlng;
var valueInMiles = Math.round(value * 0.000621371);
// console.log(latlng);
updateCircle(latlng, value);
globalRadius = valueInMiles;
return valueInMiles;
}
});
//AJAX request to the PostgreSQL database to get all projects and render them on the map
function renderAllProjects(zoom) {
$("#edit-button").attr("disabled", "true");
$.ajax({
type: 'GET',
url: '/projects/all',
datatype: 'JSON',
success: function (data) {
if (data) {
displayResults(data);
// var features = data.features;
// for (var i = 0; i < features.length; i++) {
//
// var projectFeatures = features[i].properties;
//
// var projectType = projectFeatures.Proj_Ty;
//
// var markerStyle = getMarkerStyle(projectType);
//
//
// projectFeatures["marker-color"] = markerStyle["marker-color"];
// projectFeatures["marker-symbol"] = markerStyle["marker-symbol"];
// projectFeatures["marker-size"] = "small";
// }
//
// if (geoJSON) {
// geoJSON.clearLayers();
// }
// geoJSON = L.geoJson(data, {
// style: {
// color: "#004EB9"
// },
// onEachFeature: function(feature, layer) {
// onEachFeature(feature, layer);
// },
// pointToLayer: L.mapbox.marker.style
// }).addTo(map);
// if (zoom) {
// checkZoom();
// }
}
}
});
}
renderAllProjects(true);
// filterProjectTypes(true);
//Function to check if a project should be zoomed in on
function checkZoom() {
var url = window.location.href;
if (url.includes('?id=')) {
url = url.split('?id=');
var id = url[url.length - 1];
$.ajax({
method: "GET",
url: "/projects/id/" + id,
dataType: "json",
success: function (data) {
if (data) {
geoJSON.eachLayer(function (l) {
if (l.feature.properties.id === data[0].id) {
l.fireEvent('click');
}
});
}
}
});
} else {
map.setView([
34.0522, -118.2437
], 10);
}
}
// Global variable to know if we're looking for funded or unfunded
var isFunded;
// Give me funded projects
$('#fundedTab').on('click', function () {
isFunded = "funded";
$('#project-details').hide();
$('#main-info').empty();
filterProjectTypes();
});
//Give me unfunded projects
$('#unfundedTab').on('click', function () {
isFunded = "unfunded";
$('#project-details').hide();
$('#main-info').empty();
filterProjectTypes();
});
$(".filter-check").change(function () {
if (!isFunded) {
filterProjectTypes(true);
} else {
filterProjectTypes();
}
});
/* FILTER PROJECT TYPES FUNCTION */
function filterProjectTypes(type) {
// reset map view
// var fundingType = $('#fundedTab').getAttribute('value');
// var fundingType = $('#fundedTab').text().toLowerCase();
// console.log(fundingType);
var projectTypes = $('.project-type input[type="checkbox"]:checked').map(function (_, el) {
return $(el).val();
}).get();
if (projectTypes.length >= 1) {
for (var i = 0; i < projectTypes.length; i++) {
projectTypes[i] = projectTypes[i].split(' ').join('%20');
}
var fundingQuery = isFunded;
var typeQuery = projectTypes.join('&');
if (type) {
$.ajax({
type: 'GET',
url: '/projects/type/' + typeQuery,
datatype: 'JSON',
success: function (data) {
displayResults(data);
// filterByRadius(data);
}
});
} else {
$.ajax({
type: 'GET',
url: '/projects/funding/' + fundingQuery + '/type/' + typeQuery,
datatype: 'JSON',
success: function (data) {
displayResults(data);
// filterByRadius(data);
}
});
}
} else {
geoJSON.clearLayers();
}
}
// function filterByRadius(data) {
//
// var finalResults = {};
// finalResults.features = [];
//
// var features = data.features;
// // check if data meets radius requirements
// for (var i = 0; i < features.length; i++) {
//
// var projectGeometry = features[i].geometry;
//
// if (projectGeometry.type === "Point") {
//
// // Single point
// var coordinates = projectGeometry.coordinates;
//
// var latlng = L.latLng(coordinates.reverse());
//
// var distance = latlng.distanceTo(circle_lat_long);
// // Convert meters to feet
// var distanceInMiles = distance * 0.000621371192;
//
// latlng = L.latLng(coordinates.reverse());
//
// if (distanceInMiles <= globalRadius) {
// finalResults.features.push(features[i]);
// }
//
//
// }
// if (projectGeometry.type === "MultiLineString" || projectGeometry.type === "Polygon") {
//
// var outsideCoordinates = projectGeometry.coordinates;
//
// var isMatch = false;
//
// for (var k = 0; k < outsideCoordinates.length; k++) {
//
// if (isMatch) {
// break;
// }
// var insideCoordinates = outsideCoordinates[k];
// for (l = 0; l < insideCoordinates.length; l++) {
//
// var coordinates = insideCoordinates[l];
// var latlng = L.latLng(coordinates.reverse());
// var distance = (latlng).distanceTo(circle_lat_long);
// // Convert meters to feet
// var distanceInMiles = distance * 0.000621371192;
// latlng = L.latLng(coordinates.reverse());
//
// if (distanceInMiles <= globalRadius && !isMatch) {
// finalResults.features.push(features[i]);
// isMatch = true;
// break;
// }
// }
// }
// }
// if (projectGeometry.type === "MultiPoint" || projectGeometry.type === "LineString") {
//
// var coordinatesArray = projectGeometry.coordinates;
//
//
// for (var j = 0; j < coordinatesArray.length; j++) {
//
//
// var coordinates = coordinatesArray[j];
//
// var latlng = L.latLng(coordinates.reverse());
//
//
// var distance = (latlng).distanceTo(circle_lat_long);
// // Convert meters to feet
// var distanceInMiles = distance * 0.000621371192;
// latlng = L.latLng(coordinates.reverse());
//
// if (distanceInMiles <= globalRadius) {
// finalResults.features.push(features[i]);
// break;
// }
//
// }
//
// }
// }
// displayResults(finalResults);
// }
function displayResults(results) {
checkZoom();
$('#main-info').empty();
// show main info div
$('#main-info').show();
// hide project details div
$("#project-details").hide();
var panelGroup = $("<div>");
panelGroup
.addClass("panel-group")
.attr("id", "project-accordian")
.attr("role", "tablist")
.attr("aria-multiselectable", "true");
$("#main-info").append(panelGroup);
var count = 0;
var features = results.features;
for (var i = 0; i < features.length; i++) {
var projectFeatures = features[i].properties;
var projectType = projectFeatures.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
projectFeatures["marker-color"] = markerStyle["marker-color"];
projectFeatures["marker-symbol"] = markerStyle["marker-symbol"];
projectFeatures["marker-size"] = "small";
// build accordian panel
var panel = $("<div>");
panel
.addClass("row panel projects-list-item");
var panelHeading = $("<div>");
panelHeading
.addClass("col-sm-12 panel-heading project-heading")
.attr("id", "heading_" + i)
.attr("role", "tab");
var panelTitle = $("<h3>");
panelTitle
.addClass("panel-title project-title");
var panelLink = $("<a>");
panelLink
.addClass("project-heading-data")
.attr("role", "button")
.attr("data-toggle", "collapse")
.attr("data-parent", "#project-accordian")
.attr("href", "#collapse_" + i)
.attr("aria-expanded", "true")
.attr("aria-controls", "collapse_" + i)
.text(projectFeatures.Proj_Title);
panelTitle
.append(panelLink);
var panelHeaderData = $("<div>");
panelHeaderData
.addClass("row");
var panelHeaderColumn1 = $("<div>");
panelHeaderColumn1
.addClass("col-sm-9");
var panelMiles = $("<h6>");
var panelCompletion = $("<h6>");
var panelId = $("<h6>");
panelMiles
.addClass("project-heading-data")
.text("MILES: ");
var completionDate = projectFeatures.ProjectProjectedCompletionDate;
if (completionDate) {
completionDate = completionDate;
} else {
completionDate = "TBD";
}
panelCompletion
.addClass("project-heading-data")
.text("COMPLETION DATE: " + completionDate);
panelId
.addClass("project-heading-data")
.text("ID: " + projectFeatures.id);
panelHeaderColumn1
.append(panelMiles)
.append(panelCompletion)
.append(panelId);
var panelHeaderColumn2 = $("<div>");
panelHeaderColumn2
.addClass("col-sm-2");
var projectColor = markerStyle["marker-color"];
var panelIcon = $("<i>");
panelIcon
.addClass("fa fa-circle fa-3x panel-icon")
.attr("aria-hidden", "true")
.css("color", projectColor);
var panelSvg = $("<img>");
var projectIcon = markerStyle["marker-symbol"];
panelSvg
.attr("src", "/images/icons/" + projectIcon + ".svg")
.addClass("panel-svg");
panelIcon
.append(panelSvg);
panelHeaderColumn2
.append(panelIcon);
panelHeaderData
.append(panelHeaderColumn1)
.append(panelHeaderColumn2);
panelHeading
.append(panelTitle)
.append(panelHeaderData);
panel
.append(panelHeading);
var panelBodyCollapse = $("<div>");
panelBodyCollapse
.addClass("panel-collapse collapse")
.attr("id", "collapse_" + i)
.attr("role", "tabpanel")
.attr("aria-labelledby", "heading_" + i);
var panelBody = $("<div>");
panelBody
.addClass("project-body panel-body");
var projTitle = $("<p>");
projTitle
.text("Title: " + projectFeatures.Proj_Title);
var projDesc = $("<p>");
projDesc
.text("Description: " + projectFeatures.Proj_Desc);
var legacyId = $("<p>");
legacyId
.text("Legacy ID: " + projectFeatures.Legacy_ID);
var leadAg = $("<p>");
leadAg
.text("Lead Agency: " + projectFeatures.Lead_Ag);
var fundSt = $("<p>");
fundSt
.text("Funding Status: " + projectFeatures.Fund_St);
var projTy = $("<p>");
projTy
.text("Project Type: " + projectFeatures.Proj_Ty);
var contactName = $("<p>");
contactName
.text("Contact Name: " + projectFeatures.Contact_info.Contact_info_name);
var contactPhone = $("<p>");
contactPhone
.text("Contact Phone: " + projectFeatures.Contact_info.Contact_info_phone);
var contactEmail = $("<p>");
contactEmail
.text("Contact Email: " + projectFeatures.Contact_info.Contact_info_email);
panelBody
.append(projTitle)
.append(projDesc)
.append(legacyId)
.append(leadAg)
.append(fundSt)
.append(projTy)
.append(contactName)
.append(contactPhone)
.append(contactEmail);
panelBodyCollapse
.append(panelBody);
panel
.append(panelBodyCollapse);
var panelButton = $("<button>");
panelButton
.addClass("btn project-body-button")
.attr("type", "button")
.attr("data-toggle", "collapse")
.attr("data-target", "#collapseMore_" + i)
.attr("aria-expanded", "false")
.attr("aria-controls", "collapseMore_" + i)
.text("More Info");
var viewButton = $("<a>");
viewButton
.addClass("btn project-body-button")
.attr("type", "button")
.attr("data-id", projectFeatures.id)
.text("View Project");
panelBodyCollapse
.append(panelButton)
.append(viewButton);
var moreData = $("<div>");
moreData
.addClass("collapse").attr("id", "collapseMore_" + i);
var moreDataWell = $("<div>");
moreDataWell
.addClass("project-more-data well");
if (isFunded === "funded") {
// funded project marker color
var deptProjId = $("<p>");
deptProjId.text("Dept Project ID: " + projectFeatures.Dept_Proj_ID);
moreDataWell.append(deptProjId);
var otherId = $("<p>");
otherId.text("Other ID: " + projectFeatures.Other_ID);
moreDataWell.append(otherId);
if (projectFeatures.Total_bgt) {
var totalBgt = $("<p>");
totalBgt.text("Total Budget: $" + projectFeatures.Total_bgt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(totalBgt);
}
if (projectFeatures.Grant) {
var grant = $("<p>");
grant.text("Grant: $" + projectFeatures.Grant.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(grant);
}
if (projectFeatures.Other_funds) {
var otherFunds = $("<p>");
otherFunds.text("Other Funds: $" + projectFeatures.Other_funds.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(otherFunds);
}
if (projectFeatures.Prop_c) {
var propC = $("<p>");
propC.text("Prop C: $" + projectFeatures.Prop_c.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(propC);
}
if (projectFeatures.Measure_r) {
var measureR = $("<p>");
measureR.text("Measure R: $" + projectFeatures.Measure_r.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(measureR);
}
if (projectFeatures.Gas_Tax) {
var gasTax = $("<p>");
gasTax.text("Gas Tax: $" + projectFeatures.Gas_Tax.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(gasTax);
}
if (projectFeatures.General_fund) {
var generalFund = $("<p>");
generalFund.text("General Fund: $" + projectFeatures.General_fund.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(generalFund);
}
var authorization = $("<p>");
authorization.text("Authorization: " + projectFeatures.Authorization);
var issues = $("<p>");
issues.text("Issues: " + projectFeatures.Issues);
var deobligation = $("<p>");
deobligation.text("Deobligation: " + projectFeatures.Deobligation);
var explanation = $("<p>");
explanation.text("Explanation: " + projectFeatures.Explanation);
var constrBy = $("<p>");
constrBy.text("Constructed By: " + projectFeatures.Constr_by);
var infoSource = $("<p>");
infoSource.text("Info Source: " + projectFeatures.Info_source);
var access = $("<p>");
access.text("Access: " + projectFeatures.Access);
moreDataWell
.append(authorization)
.append(issues)
.append(deobligation)
.append(explanation)
.append(constrBy)
.append(infoSource)
.append(access);
}
if (isFunded === "unfunded") {
// unfunded project marker color
var unfundedMoreInfo = $("<p>");
unfundedMoreInfo.text("Unfunded More Info: " + projectFeatures.More_info);
var unfundedCD = $("<p>");
unfundedCD.text("Unfunded CD: " + projectFeatures.CD);
var grantCat = $("<p>");
grantCat.text("Grant Category: " + projectFeatures.Grant_Cat);
var grantCycle = $("<p>");
grantCycle.text(projectFeatures.Grant_Cycle);
moreDataWell.append(unfundedMoreInfo).append(unfundedCD).append(grantCat).append(grantCycle);
if (projectFeatures.Est_Cost) {
var estCost = $("<p>");
estCost.text("Estimated Cost: $" + projectFeatures.Est_Cost.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(estCost);
}
if (projectFeatures.Fund_Rq) {
var fundRq = $("<p>");
fundRq.text("Fund Request: " + projectFeatures.Fund_Rq.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(fundRq);
}
if (projectFeatures.Lc_match) {
var LcMatch = $("<p>");
LcMatch.text("Lc Match: $ " + projectFeatures.Lc_match.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
moreDataWell.append(LcMatch);
}
var matchPt = $("<p>");
matchPt.text("Match Percentage: " + projectFeatures.Match_Pt + "%");
moreDataWell.append(matchPt);
}
moreData
.append(moreDataWell);
panelBodyCollapse
.append(moreData);
panelGroup
.append(panel);
count++;
}
$("#count-info").empty();
$('#count-info').append("<p><strong>Projects Listed: " + count + "</strong></p>");
if (geoJSON) {
geoJSON.clearLayers();
}
geoJSON = L.geoJson(results, {
style: {
color: "#004EB9"
},
onEachFeature: function (feature, layer) {
onEachFeature(feature, layer);
},
pointToLayer: L
.mapbox.marker.style
}).addTo(map);
checkZoom();
}
$(document).on("click", ".project-body-button", function () {
var id = $(this).data("id");
$.ajax({
method: "GET",
url: "/projects/id/" + id,
datatype: 'JSON',
success: function (data) {
if (data) {
geoJSON.eachLayer(function (l) {
if (l.feature.properties.id === data[0].id) {
l.fireEvent('click');
}
});
}
}
});
});
$('#hide-button').on('click', function () {
geoJSON.eachLayer(function (l) {
if (l._leaflet_id === layerID) {
map.removeLayer(l);
}
});
});
$('#unhide-button').on('click', function () {
renderAllProjects(false);
});
/* ZOOM TO FEATURE FUNCTION */
//Function that sets the map bounds to a project
//This essentially "zooms in" on a project
function zoomToFeature(e) {
if (e.target.feature.geometry.type === 'Point') {
var coordinates = e.target.feature.geometry.coordinates.slice().reverse();
map.setView(coordinates, 16);
} else {
map.fitBounds(e.target.getBounds());
}
}
/* ON EACH FEATURE FUNCTION */
function onEachFeature(feature, layer) {
layer.on('click', function (e) {
$("#project-details").show();
$("#main-info").hide();
//Empty the cross streets since we are using .append()
$('#Cross_Streets').empty();
layerID = layer._leaflet_id;
zoomToFeature(e);
geoJSON.eachLayer(function (l) {
geoJSON.resetStyle(l);
if (l.feature.geometry.type === 'MultiPoint') {
l.eachLayer(function (MultiPointLayer) {
var projectType = l.feature.properties.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
MultiPointLayer.setIcon(L.mapbox.marker.icon({
"marker-color": markerStyle["marker-color"],
"marker-symbol": markerStyle["marker-symbol"],
"marker-size": "small"
}));
});
}
if (l.feature.geometry.type === 'Point') {
var projectType = l.feature.properties.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
l.setIcon(L.mapbox.marker.icon({
"marker-color": markerStyle["marker-color"],
"marker-symbol": markerStyle["marker-symbol"],
"marker-size": "small"
}));
}
});
if (e.target.feature.geometry.type === 'MultiPoint') {
layer.eachLayer(function (l) {
var projectType = e.target.feature.properties.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
l.setIcon(
L.mapbox.marker.icon({
"marker-color": markerStyle["marker-color"],
"marker-symbol": "star",
"marker-size": "large"
})
);
});
}
if (e.target.feature.geometry.type === 'Point') {
var projectType = e.target.feature.properties.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
layer.setIcon(
L.mapbox.marker.icon({
"marker-color": markerStyle["marker-color"],
"marker-symbol": "star",
"marker-size": "large"
})
);
}
if (e.target.feature.geometry.type != 'Point') {
layer.bringToFront();
var projectType = e.target.feature.properties.Proj_Ty;
var markerStyle = getMarkerStyle(projectType);
layer.setStyle({
color: markerStyle["marker-color"]
});
}
var fundStatus = feature.properties.Fund_St;
$('#sidebar-fundedAndUnfunded').hide();
$('#sidebar-funded-attributes').hide();
$('#sidebar-unfunded-attributes').hide();
$('#sidebar-more-info').hide();
$('#show-info').remove();
$('#hide-info').remove();
$('#edit-button').show();
$(document).on('click', '#show-info', function () {
$('#show-info').remove();
$('#hide-info').remove();
var button = $('<button id="hide-info" type="button" name="button" class="btn">Less Info</button>');
$('#project-details').append(button);
$('#sidebar-more-info').show();
if (fundStatus === 'Funded') {
$('#sidebar-funded-attributes').show();
$('#sidebar-unfunded-attributes').hide();
} else if (fundStatus === 'Unfunded') {
$('#sidebar-unfunded-attributes').show();
$('#sidebar-funded-attributes').hide();
}
});
$(document).on('click', '#hide-info', function () {
$('#show-info').remove();
$('#hide-info').remove();
var button = $('<button id="show-info" type="button" name="button" class="btn">More Info</button>');
$('#project-details').append(button);
$('#sidebar-more-info').hide();
if (fundStatus === 'Funded') {
$('#sidebar-funded-attributes').hide();
} else if (fundStatus === 'Unfunded') {
$('#sidebar-unfunded-attributes').hide();
}
});
$("#edit-button").removeAttr("disabled");
//Common attributes
$('#Proj_Title').text(feature.properties.Proj_Title);
$('#Proj_Desc').text(feature.properties.Proj_Desc);
$('#Legacy_ID').text(feature.properties.Legacy_ID);
$('#Lead_Ag').text(feature.properties.Lead_Ag);
$('#Fund_St').text(feature.properties.Fund_St);
$('#Proj_Ty').text(feature.properties.Proj_Ty);
$('#Contact_info_name').text(feature.properties.Contact_info.Contact_info_name);
$('#Contact_info_phone').text(feature.properties.Contact_info.Contact_info_phone);
$('#Contact_info_email').text(feature.properties.Contact_info.Contact_info_email);
if (fundStatus != 'Idea Project') {
$('#Proj_Man').text(feature.properties.Proj_Man);
$('#Current_Status').text(feature.properties.Proj_Status);
$('#More_info').text(feature.properties.More_info);
$('#CD').text(feature.properties.CD);
$('#Primary_Street').text(feature.properties.Primary_Street);
if (feature.properties.Cross_Streets && feature.properties.Cross_Streets.Intersections) {
var streets = feature.properties.Cross_Streets.Intersections;
streetsString = '';
for (var i = 0; i < streets.length; i++) {
streetsString += '<p>' + streets[i] + '</p><br>';
}
$('#Cross_Streets').append(streetsString);
}
// $('#sidebar-fundedAndUnfunded').show();
// var button = $('<button id="show-info" class="btn" type="button" name="button">More Info</button>');
// $('#project-details').append(button);
}
//Separate section for funded attributes
if (fundStatus === 'Funded') {
$('#Dept_Proj_ID').text(feature.properties.Dept_Proj_ID);
$('#Other_ID').text(feature.properties.Other_ID);
if (feature.properties.Total_bgt) {
$('#Total_bgt').text('$' + feature.properties.Total_bgt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Grant) {
$('#Grant').text('$' + feature.properties.Grant.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Other_funds) {
$('#Other_funds').text('$' + feature.properties.Other_funds.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Prop_c) {
$('#Prop_c').text('$' + feature.properties.Prop_c.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Measure_r) {
$('#Measure_r').text('$' + feature.properties.Measure_r.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Gas_Tax) {
$('#Gas_Tax').text('$' + feature.properties.Gas_Tax.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.General_fund) {
$('#General_fund').text('$' + feature.properties.General_fund.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
$('#Authorization').text(feature.properties.Authorization);
$('#Issues').text(feature.properties.Issues);
$('#Deobligation').text(feature.properties.Deobligation);
$('#Explanation').text(feature.properties.Explanation);
$('#Constr_by').text(feature.properties.Constr_by);
$('#Info_source').text(feature.properties.Info_source);
$('#Access').text(feature.properties.Access);
} else if (fundStatus === 'Unfunded') {
//Unfunded
$('#Unfunded-More_info').text(feature.properties.More_info);
$('#Unfunded-CD').text(feature.properties.CD);
$('#Grant_Cat').text(feature.properties.Grant_Cat);
$('#Grant_Cycle').text(feature.properties.Grant_Cycle);
if (feature.properties.Est_Cost) {
$('#Est_Cost').text('$' + feature.properties.Est_Cost.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Fund_Rq) {
$('#Fund_Rq').text('$' + feature.properties.Fund_Rq.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
if (feature.properties.Lc_match) {
$('#Lc_match').text('$' + feature.properties.Lc_match.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
}
$('#Match_Pt').text(feature.properties.Match_Pt + '%');
}
$('#edit-button').attr('data-href', "/projects/edit/" + feature.properties.id);
});
}
//When the edit button is clicked redirect to the edit page which is defined in data-href
$(document).on('click', '#edit-button', function () {
window.location = $('#edit-button').attr('data-href');
});
$('#export-csv').on('click', function () {
exportCSV();
});
$('#export-shapefiles').on('click', function () {
separateShapes();
});
function exportCSV() {
var searchIDs = [];
var bounds = map.getBounds();
geoJSON.eachLayer(function (layer) {
if (layer.feature.geometry.type === 'Point') {
if (bounds.contains(layer.getLatLng())) {
searchIDs.push(layer.feature.properties.id);
}
} else if (layer.feature.geometry.type === 'MultiPoint') {
if (bounds.contains(layer.getBounds())) {
searchIDs.push(layer.feature.properties.id);
}
} else {
if (bounds.contains(layer.getLatLngs())) {
searchIDs.push(layer.feature.properties.id);
}
}
});
var queryString = searchIDs.join('&');
$.ajax({
method: "GET",
url: "/projects/ids/" + queryString,
dataType: "json",
success: function (data) {
var geoJSON = JSON.stringify(data);
$.post('https://ogre.adc4gis.com/convertJson', {
json: geoJSON,
format: "csv"
},
function (csv) {
a = document.createElement('a');
a.download = "projects.csv";
a.href = 'data:text/csv;charset=utf-8,' + escape(csv);
document.body.appendChild(a);
a.click();
a.remove();
});
}
});
}
function separateShapes() {
var bounds = map.getBounds();
var points = {
name: 'points',
features: []
};
var lines = {
name: 'lines',
features: []
};
var multilines = {
name: 'multilinestrings',
features: []
};
var polygons = {
name: 'polygons',
features: []
};
var multipoints = {
name: 'multipoints',
features: []
};
geoJSON.eachLayer(function (layer) {
switch (layer.feature.geometry.type) {
case 'Point':
if (bounds.contains(layer.getLatLng())) {
points.features.push(layer.feature.properties.id);
}
break;
case 'MultiPoint':
if (bounds.contains(layer.getBounds())) {
multipoints.features.push(layer.feature.properties.id);
}
break;
case 'LineString':
if (bounds.contains(layer.getLatLngs())) {
lines.features.push(layer.feature.properties.id);
}
break;
case 'MultiLineString':
if (bounds.contains(layer.getLatLngs())) {
multilines.features.push(layer.feature.properties.id);
}
break;
case 'Polygon':
if (bounds.contains(layer.getLatLngs())) {
polygons.features.push(layer.feature.properties.id);
}
break;
}
});
var shapeFilesArr = [points, lines, polygons, multilines, multipoints];
for (var i = shapeFilesArr.length - 1; i >= 0; i--) {
if (shapeFilesArr[i].features.length < 1) {
shapeFilesArr.splice(i, 1);
}
}
for (var j = 0; j < shapeFilesArr.length; j++) {
downloadShapeFiles(shapeFilesArr[j], j + 1, shapeFilesArr.length);
}
}
function downloadShapeFiles(geoTypeObj) {
var queryString = geoTypeObj.features.join('&');
$.ajax({
method: "GET",
url: "/projects/ids/" + queryString,
dataType: "json",
success: function (data) {
var geoJSON = JSON.stringify(data);
// XHR Request Working
var formData = new FormData();
formData.append('json', geoJSON);
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://ogre.adc4gis.com/convertJson");
xhr.responseType = "arraybuffer"; // ask for a binary result
xhr.onreadystatechange = function (evt) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
JSZip.loadAsync(xhr.response).then(function (zip) {
zip.generateAsync({
type: "blob"
})
.then(function (blob) {
saveAs(blob, geoTypeObj.name + '.zip');
});
});
} else {
console.log("http call error");
}
}
};
xhr.send(formData);
}
});
} | working on radius tool
| public/javascripts/map.js | working on radius tool | <ide><path>ublic/javascripts/map.js
<ide>
<ide> // Creating the map with mapbox (view coordinates are downtown Los Angeles)
<ide> var map = L.mapbox.map('map', {
<del>
<ide> layers: [imageryLayer]
<ide> });
<ide> var imageryLayer = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
<ide>
<ide> // Add circle radius to map when slider value changes
<ide> var updateCircle = function (latlng, radius) {
<del> if (!isFunded) {
<del> filterProjectTypes(true);
<del> } else {
<del> filterProjectTypes();
<del> }
<add> //
<add> // if (!isFunded) {
<add> // filterProjectTypes(true);
<add> // } else {
<add> // filterProjectTypes();
<add> // }
<ide> globalRadius = radius;
<ide> circleRadius = L.circle([latlng.lat, latlng.lng], globalRadius).addTo(map);
<del>
<ide> // add move radius functionality
<ide> moveRadius();
<ide>
<ide> });
<ide> map.on('mouseup', function (e) {
<ide> map.removeEventListener('mousemove');
<del> if (!isFunded) {
<del> filterProjectTypes(true);
<del> } else {
<del> filterProjectTypes();
<del> }
<add> map.featuresAt(e.point, {
<add> radius: globalRadius,
<add> includeGeometry: true
<add> }, function(err, features) {
<add> if (err || !features.length) {
<add> popup.remove();
<add> return;
<add> }
<add>
<add> displayResults(features);
<add> });
<add>
<add> // if (!isFunded) {
<add> // filterProjectTypes(true);
<add> // } else {
<add> // filterProjectTypes();
<add> // }
<ide> });
<ide> };
<ide>
<ide> url: '/projects/type/' + typeQuery,
<ide> datatype: 'JSON',
<ide> success: function (data) {
<add>
<ide> displayResults(data);
<ide> // filterByRadius(data);
<ide> }
<ide> .addClass("panel-group")
<ide> .attr("id", "project-accordian")
<ide> .attr("role", "tablist")
<del> .attr("aria-multiselectable", "true");
<add> // .attr("aria-multiselectable", "true");
<ide>
<ide> $("#main-info").append(panelGroup);
<ide>
<ide> panelLink
<ide> .addClass("project-heading-data")
<ide> .attr("role", "button")
<add> .attr("data-parent", "#project-accordian")
<ide> .attr("data-toggle", "collapse")
<del> .attr("data-parent", "#project-accordian")
<ide> .attr("href", "#collapse_" + i)
<del> .attr("aria-expanded", "true")
<del> .attr("aria-controls", "collapse_" + i)
<add> // .attr("aria-expanded", "true")
<add> // .attr("aria-controls", "collapse_" + i)
<ide> .text(projectFeatures.Proj_Title);
<ide>
<ide> panelTitle
<ide> var panelIcon = $("<i>");
<ide> panelIcon
<ide> .addClass("fa fa-circle fa-3x panel-icon")
<del> .attr("aria-hidden", "true")
<add> // .attr("aria-hidden", "true")
<ide> .css("color", projectColor);
<ide>
<ide> var panelSvg = $("<img>");
<ide> .addClass("panel-collapse collapse")
<ide> .attr("id", "collapse_" + i)
<ide> .attr("role", "tabpanel")
<del> .attr("aria-labelledby", "heading_" + i);
<add> // .attr("aria-labelledby", "heading_" + i);
<ide>
<ide> var panelBody = $("<div>");
<ide> panelBody
<ide> .append(contactPhone)
<ide> .append(contactEmail);
<ide>
<del>
<ide> panelBodyCollapse
<ide> .append(panelBody);
<ide>
<ide> .attr("type", "button")
<ide> .attr("data-toggle", "collapse")
<ide> .attr("data-target", "#collapseMore_" + i)
<del> .attr("aria-expanded", "false")
<del> .attr("aria-controls", "collapseMore_" + i)
<add> // .attr("aria-expanded", "false")
<add> // .attr("aria-controls", "collapseMore_" + i)
<ide> .text("More Info");
<ide>
<ide> var viewButton = $("<a>"); |
|
Java | mit | ceaf1805524ed56147458c68d042455ae549175e | 0 | PrinceOfAmber/inventory-tweaks,Kobata/inventory-tweaks,mrammy/inventory-tweaks,PrinceOfAmber/inventory-tweaks,mrammy/inventory-tweaks | package invtweaks;
import invtweaks.api.IItemTreeItem;
import invtweaks.api.SortingMethod;
import invtweaks.api.container.ContainerSection;
import invtweaks.container.IContainerManager;
import invtweaks.container.ContainerSectionManager;
import net.minecraft.client.Minecraft;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.Logger;
import java.util.*;
import java.util.Map.Entry;
/**
* Core of the sorting behaviour. Allows to move items in a container (inventory or chest) with respect to the mod's
* configuration.
*
* @author Jimeo Wan
*/
public class InvTweaksHandlerSorting extends InvTweaksObfuscation {
private static final Logger log = InvTweaks.log;
private static final int MAX_CONTAINER_SIZE = 999;
private static int[] DEFAULT_LOCK_PRIORITIES = null;
private static boolean[] DEFAULT_FROZEN_SLOTS = null;
private ContainerSectionManager containerMgr;
private SortingMethod algorithm;
private int size;
private boolean sortArmorParts;
private InvTweaksItemTree tree;
private List<InvTweaksConfigSortingRule> rules;
private int[] rulePriority;
private int[] keywordOrder;
private int[] lockPriorities;
private boolean[] frozenSlots;
public InvTweaksHandlerSorting(Minecraft mc_, InvTweaksConfig config, ContainerSection section, SortingMethod algorithm_,
int rowSize) throws Exception {
super(mc_);
// Init constants
if(DEFAULT_LOCK_PRIORITIES == null) {
DEFAULT_LOCK_PRIORITIES = new int[MAX_CONTAINER_SIZE];
for(int i = 0; i < MAX_CONTAINER_SIZE; i++) {
DEFAULT_LOCK_PRIORITIES[i] = 0;
}
}
if(DEFAULT_FROZEN_SLOTS == null) {
DEFAULT_FROZEN_SLOTS = new boolean[MAX_CONTAINER_SIZE];
for(int i = 0; i < MAX_CONTAINER_SIZE; i++) {
DEFAULT_FROZEN_SLOTS[i] = false;
}
}
// Init attributes
containerMgr = new ContainerSectionManager(section);
size = containerMgr.getSize();
sortArmorParts = config.getProperty(InvTweaksConfig.PROP_ENABLE_AUTO_EQUIP_ARMOR)
.equals(InvTweaksConfig.VALUE_TRUE) && !isGuiInventoryCreative(
getCurrentScreen()); // FIXME Armor parts disappear when sorting in creative mode while holding an item
rules = config.getRules();
tree = config.getTree();
if(section == ContainerSection.INVENTORY) {
lockPriorities = config.getLockPriorities();
frozenSlots = config.getFrozenSlots();
algorithm = SortingMethod.INVENTORY;
} else {
lockPriorities = DEFAULT_LOCK_PRIORITIES;
frozenSlots = DEFAULT_FROZEN_SLOTS;
algorithm = algorithm_;
if(algorithm != SortingMethod.DEFAULT) {
computeLineSortingRules(rowSize, algorithm == SortingMethod.HORIZONTAL);
}
}
rulePriority = new int[size];
keywordOrder = new int[size];
for(int i = 0; i < size; i++) {
rulePriority[i] = -1;
ItemStack stack = containerMgr.getItemStack(i);
if(stack != null) {
keywordOrder[i] = getItemOrder(stack);
} else {
keywordOrder[i] = -1;
}
}
// Initialize rule priority for currently matching items
// TODO: J1.8 streams?
rules.stream().filter(rule -> rule.getContainerSize() == size).forEach(rule -> {
int priority = rule.getPriority();
for(int slot : rule.getPreferredSlots()) {
ItemStack stack = containerMgr.getItemStack(slot);
if(stack != null) {
List<IItemTreeItem> items = tree
.getItems(Item.itemRegistry.getNameForObject(stack.getItem()).toString(), stack.getItemDamage());
if(rulePriority[slot] < priority && tree.matches(items, rule.getKeyword())) {
rulePriority[slot] = priority;
}
}
}
});
}
public void sort() {
long timer = System.nanoTime();
IContainerManager globalContainer = InvTweaks.getCurrentContainerManager();
// Put hold item down
if(getHeldStack() != null) {
int emptySlot = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY);
if(emptySlot != -1) {
globalContainer.putHoldItemDown(ContainerSection.INVENTORY, emptySlot);
} else {
return; // Not enough room to work, abort
}
}
if(algorithm != SortingMethod.DEFAULT) {
if(algorithm == SortingMethod.EVEN_STACKS) {
sortEvenStacks();
} else if(algorithm == SortingMethod.INVENTORY) {
sortInventory(globalContainer);
}
sortWithRules();
}
//// Sort remaining
defaultSorting();
if(log.isEnabled(InvTweaksConst.DEBUG)) {
timer = System.nanoTime() - timer;
log.info("Sorting done in " + timer + "ns");
}
//// Put hold item down, just in case
if(getHeldStack() != null) {
int emptySlot = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY);
if(emptySlot != -1) {
globalContainer.putHoldItemDown(ContainerSection.INVENTORY, emptySlot);
}
}
globalContainer.applyChanges();
}
private void sortWithRules() {
//// Apply rules
log.info("Applying rules.");
// Sorts rule by rule, themselves being already sorted by decreasing priority
for(InvTweaksConfigSortingRule rule : rules) {
int priority = rule.getPriority();
if(log.isEnabled(InvTweaksConst.DEBUG)) {
log.info("Rule : " + rule.getKeyword() + "(" + priority + ")");
}
// For every item in the inventory
for(int i = 0; i < size; i++) {
ItemStack from = containerMgr.getItemStack(i);
// If the rule is strong enough to move the item and it matches the item, move it
if(hasToBeMoved(i, priority) && lockPriorities[i] < priority) {
// TODO: It looks like Mojang changed the internal name type to ResourceLocation. Evaluate how much of a pain that will be.
List<IItemTreeItem> fromItems = tree
.getItems(Item.itemRegistry.getNameForObject(from.getItem()).toString(), from.getItemDamage());
if(tree.matches(fromItems, rule.getKeyword())) {
// Test preferred slots
int[] preferredSlots = rule.getPreferredSlots();
int stackToMove = i;
for(int k : preferredSlots) {
// Move the stack!
int moveResult = move(stackToMove, k, priority);
if(moveResult != -1) {
if(moveResult == k) {
break;
} else {
from = containerMgr.getItemStack(moveResult);
// TODO: It looks like Mojang changed the internal name type to ResourceLocation. Evaluate how much of a pain that will be.
fromItems = tree.getItems(Item.itemRegistry.getNameForObject(from.getItem()).toString(), from.getItemDamage());
if(tree.matches(fromItems, rule.getKeyword())) {
if(i >= moveResult) {
// Current or already-processed slot.
stackToMove = moveResult;
//j = -1; // POSSIBLE INFINITE LOOP. But having this missing may cause sorting to take a few tries to stabilize in specific situations.
} else {
// The item will be processed later
break;
}
} else {
break;
}
}
}
}
}
}
}
}
//// Don't move locked stacks
log.info("Locking stacks.");
for(int i = 0; i < size; i++) {
if(hasToBeMoved(i, 1) && lockPriorities[i] > 0) {
markAsMoved(i, 1);
}
}
}
private void sortInventory(IContainerManager globalContainer) {
//// Move items out of the crafting slots
log.info("Handling crafting slots.");
if(globalContainer.hasSection(ContainerSection.CRAFTING_IN)) {
List<Slot> craftingSlots = globalContainer.getSlots(ContainerSection.CRAFTING_IN);
int emptyIndex = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY);
if(emptyIndex != -1) {
for(Slot craftingSlot : craftingSlots) {
if(craftingSlot.getHasStack()) {
globalContainer.move(ContainerSection.CRAFTING_IN,
globalContainer.getSlotIndex(getSlotNumber(craftingSlot)),
ContainerSection.INVENTORY, emptyIndex);
emptyIndex = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY);
if(emptyIndex == -1) {
break;
}
}
}
}
}
sortMergeArmor(globalContainer);
}
private void sortMergeArmor(IContainerManager globalContainer) {
//// Merge stacks to fill the ones in locked slots
//// + Move armor parts to the armor slots
log.info("Merging stacks.");
for(int i = size - 1; i >= 0; i--) {
ItemStack from = containerMgr.getItemStack(i);
if(from != null) {
// Move armor parts
// Item
Item fromItem = from.getItem();
if(fromItem.isDamageable()) {
moveArmor(globalContainer, i, from, fromItem);
}
// Stackable objects are never damageable
else {
mergeItem(i, from);
}
}
}
}
private void mergeItem(int i, ItemStack from) {
int j = 0;
for(Integer lockPriority : lockPriorities) {
if(lockPriority > 0) {
ItemStack to = containerMgr.getItemStack(j);
if(to != null && areItemsStackable(from, to)) {
move(i, j, Integer.MAX_VALUE);
markAsNotMoved(j);
if(containerMgr.getItemStack(i) == null) {
break;
}
}
}
j++;
}
}
private void moveArmor(IContainerManager globalContainer, int i, ItemStack from, Item fromItem) {
if(sortArmorParts) {
if(isItemArmor(fromItem)) {
// ItemArmor
ItemArmor fromItemArmor = (ItemArmor) fromItem;
if(globalContainer.hasSection(ContainerSection.ARMOR)) {
List<Slot> armorSlots = globalContainer.getSlots(ContainerSection.ARMOR);
for(Slot slot : armorSlots) {
boolean move = false;
if(!slot.getHasStack()) {
move = true;
} else {
// Item
Item currentArmor = slot.getStack().getItem();
if(isItemArmor(currentArmor)) {
// ItemArmor
// ItemArmor
int armorLevel = ((ItemArmor) currentArmor).damageReduceAmount;
// ItemArmor
// ItemArmor
if(armorLevel < fromItemArmor.damageReduceAmount || (armorLevel == fromItemArmor.damageReduceAmount && slot
.getStack().getItemDamage() < from.getItemDamage())) {
move = true;
}
} else {
move = true;
}
}
if(slot.isItemValid(from) && move) {
globalContainer.move(ContainerSection.INVENTORY, i, ContainerSection.ARMOR,
globalContainer.getSlotIndex(getSlotNumber(slot)));
}
}
}
}
}
}
private void sortEvenStacks() {
log.info("Distributing items.");
//item and slot counts for each unique item
HashMap<Pair<String, Integer>, int[]> itemCounts = new HashMap<>();
for(int i = 0; i < size; i++) {
ItemStack stack = containerMgr.getItemStack(i);
if(stack != null) {
// TODO: It looks like Mojang changed the internal name type to ResourceLocation. Evaluate how much of a pain that will be.
Pair<String, Integer> item = Pair.of(Item.itemRegistry.getNameForObject(stack.getItem()).toString(), stack.getItemDamage());
int[] count = itemCounts.get(item);
if(count == null) {
int[] newCount = {stack.stackSize, 1};
itemCounts.put(item, newCount);
} else {
count[0] += stack.stackSize; //amount of item
count[1]++; //slots with item
}
}
}
//handle each unique item separately
for(Entry<Pair<String, Integer>, int[]> entry : itemCounts.entrySet()) {
Pair<String, Integer> item = entry.getKey();
int[] count = entry.getValue();
int numPerSlot = count[0] / count[1]; //totalNumber/numberOfSlots
//skip hacked itemstacks that are larger than their max size
//no idea why they would be here, but may as well account for them anyway
if(numPerSlot <= new ItemStack((Item) Item.itemRegistry.getObject(item.getLeft()), 1, 0).getMaxStackSize()) {
//linkedlists to store which stacks have too many/few items
LinkedList<Integer> smallStacks = new LinkedList<>();
LinkedList<Integer> largeStacks = new LinkedList<>();
for(int i = 0; i < size; i++) {
ItemStack stack = containerMgr.getItemStack(i);
if(stack != null && Pair.of(Item.itemRegistry.getNameForObject(stack.getItem()), stack.getItemDamage())
.equals(item)) {
int stackSize = stack.stackSize;
if(stackSize > numPerSlot) {
largeStacks.offer(i);
} else if(stackSize < numPerSlot) {
smallStacks.offer(i);
}
}
}
//move items from stacks with too many to those with too little
while((!smallStacks.isEmpty())) {
int largeIndex = largeStacks.peek();
int largeSize = containerMgr.getItemStack(largeIndex).stackSize;
int smallIndex = smallStacks.peek();
int smallSize = containerMgr.getItemStack(smallIndex).stackSize;
containerMgr
.moveSome(largeIndex, smallIndex, Math.min(numPerSlot - smallSize, largeSize - numPerSlot));
//update stack lists
largeSize = containerMgr.getItemStack(largeIndex).stackSize;
smallSize = containerMgr.getItemStack(smallIndex).stackSize;
if(largeSize == numPerSlot) {
largeStacks.remove();
}
if(smallSize == numPerSlot) {
smallStacks.remove();
}
}
//put all leftover into one stack for easy removal
while(largeStacks.size() > 1) {
int largeIndex = largeStacks.poll();
int largeSize = containerMgr.getItemStack(largeIndex).stackSize;
containerMgr.moveSome(largeIndex, largeStacks.peek(), largeSize - numPerSlot);
}
}
}
//mark all items as moved. (is there a better way?)
for(int i = 0; i < size; i++) {
markAsMoved(i, 1);
}
}
private void defaultSorting() {
log.info("Default sorting.");
ArrayList<Integer> remaining = new ArrayList<>(), nextRemaining = new ArrayList<>();
for(int i = 0; i < size; i++) {
if(hasToBeMoved(i, 1)) {
remaining.add(i);
nextRemaining.add(i);
}
}
int iterations = 0;
while(remaining.size() > 0 && iterations++ < 50) {
for(int i : remaining) {
if(hasToBeMoved(i, 1)) {
for(int j = 0; j < size; j++) {
if(move(i, j, 1) != -1) {
nextRemaining.remove((Integer) j);
break;
}
}
} else {
nextRemaining.remove((Integer) i);
}
}
remaining.clear();
remaining.addAll(nextRemaining);
}
if(iterations == 100) {
log.warn("Sorting takes too long, aborting.");
}
}
private static boolean canMergeStacks(ItemStack from, ItemStack to) {
if(areItemsStackable(from, to)) {
if(from.stackSize > from.getMaxStackSize()) {
return false;
}
if(to.stackSize < to.getMaxStackSize()) {
return true;
}
}
return false;
}
private boolean canSwapSlots(int i, int j, int priority) {
return lockPriorities[j] <= priority && (rulePriority[j] < priority || (rulePriority[j] == priority && isOrderedBefore(
i, j)));
}
/**
* Tries to move a stack from i to j, and swaps them if j is already occupied but i is of greater priority (even if
* they are of same ID).
*
* @param i from slot
* @param j to slot
* @param priority The rule priority. Use 1 if the stack was not moved using a rule.
* @return -1 if it failed, j if the stacks were merged into one, n if the j stack has been moved to the n slot.
*/
private int move(int i, int j, int priority) {
ItemStack from = containerMgr.getItemStack(i), to = containerMgr.getItemStack(j);
if(from == null || frozenSlots[j] || frozenSlots[i]) {
return -1;
}
//log.info("Moving " + i + " (" + from + ") to " + j + " (" + to + ") ");
if(lockPriorities[i] <= priority) {
if(i == j) {
markAsMoved(i, priority);
return j;
}
// Move to empty slot
if(to == null && lockPriorities[j] <= priority && !frozenSlots[j]) {
rulePriority[i] = -1;
keywordOrder[i] = -1;
rulePriority[j] = priority;
keywordOrder[j] = getItemOrder(from);
if(containerMgr.move(i, j)) {
return j;
} else {
return -1;
}
}
// Try to swap/merge
else if(to != null) {
if(canSwapSlots(i, j, priority) || canMergeStacks(from, to)) {
keywordOrder[j] = keywordOrder[i];
rulePriority[j] = priority;
rulePriority[i] = -1;
boolean success = containerMgr.move(i, j);
if(success) {
ItemStack remains = containerMgr.getItemStack(i);
if(remains != null) {
int dropSlot = i;
if(lockPriorities[j] > lockPriorities[i]) {
for(int k = 0; k < size; k++) {
if(containerMgr.getItemStack(k) == null && lockPriorities[k] == 0) {
dropSlot = k;
break;
}
}
}
if(dropSlot != i) {
if(!containerMgr.move(i, dropSlot)) {
// TODO: This is a potentially bad situation: One move succeeded, then the rest failed.
return -1;
}
}
rulePriority[dropSlot] = -1;
keywordOrder[dropSlot] = getItemOrder(remains);
return dropSlot;
} else {
return j;
}
} else {
return -1;
}
}
}
}
return -1;
}
private void markAsMoved(int i, int priority) {
rulePriority[i] = priority;
}
private void markAsNotMoved(int i) {
rulePriority[i] = -1;
}
private boolean hasToBeMoved(int slot, int priority) {
return containerMgr.getItemStack(slot) != null && rulePriority[slot] <= priority;
}
private boolean isOrderedBefore(int i, int j) {
ItemStack iStack = containerMgr.getItemStack(i), jStack = containerMgr.getItemStack(j);
return InvTweaks.getInstance().compareItems(iStack, jStack, keywordOrder[i], keywordOrder[j]) < 0;
}
private int getItemOrder(ItemStack itemStack) {
// TODO: It looks like Mojang changed the internal name type to ResourceLocation. Evaluate how much of a pain that will be.
List<IItemTreeItem> items = tree.getItems(Item.itemRegistry.getNameForObject(itemStack.getItem()).toString(), itemStack.getItemDamage());
return (items != null && items.size() > 0) ? items.get(0).getOrder() : Integer.MAX_VALUE;
}
private void computeLineSortingRules(int rowSize, boolean horizontal) {
rules = new ArrayList<>();
Map<IItemTreeItem, Integer> stats = computeContainerStats();
List<IItemTreeItem> itemOrder = new ArrayList<>();
int distinctItems = stats.size();
int columnSize = getContainerColumnSize(rowSize);
int spaceWidth;
int spaceHeight;
int availableSlots = size;
int remainingStacks = 0;
for(Integer stacks : stats.values()) {
remainingStacks += stacks;
}
// No need to compute rules for an empty chest
if(distinctItems == 0) {
return;
}
// (Partially) sort stats by decreasing item stack count
List<IItemTreeItem> unorderedItems = new ArrayList<>(stats.keySet());
boolean hasStacksToOrderFirst = true;
while(hasStacksToOrderFirst) {
hasStacksToOrderFirst = false;
for(IItemTreeItem item : unorderedItems) {
Integer value = stats.get(item);
if(value > ((horizontal) ? rowSize : columnSize) && !itemOrder.contains(item)) {
hasStacksToOrderFirst = true;
itemOrder.add(item);
unorderedItems.remove(item);
break;
}
}
}
Collections.sort(unorderedItems, Collections.reverseOrder());
itemOrder.addAll(unorderedItems);
// Define space size used for each item type.
if(horizontal) {
spaceHeight = 1;
spaceWidth = rowSize / ((distinctItems + columnSize - 1) / columnSize);
} else {
spaceWidth = 1;
spaceHeight = columnSize / ((distinctItems + rowSize - 1) / rowSize);
}
char row = 'a', maxRow = (char) (row - 1 + columnSize);
char column = '1', maxColumn = (char) (column - 1 + rowSize);
// Create rules
for(IItemTreeItem item : itemOrder) {
// Adapt rule dimensions to fit the amount
int thisSpaceWidth = spaceWidth,
thisSpaceHeight = spaceHeight;
while(stats.get(item) > thisSpaceHeight * thisSpaceWidth) {
if(horizontal) {
if(column + thisSpaceWidth < maxColumn) {
thisSpaceWidth = maxColumn - column + 1;
} else if(row + thisSpaceHeight < maxRow) {
thisSpaceHeight++;
} else {
break;
}
} else {
if(row + thisSpaceHeight < maxRow) {
thisSpaceHeight = maxRow - row + 1;
} else if(column + thisSpaceWidth < maxColumn) {
thisSpaceWidth++;
} else {
break;
}
}
}
// Adjust line/column ends to fill empty space
if(horizontal && (column + thisSpaceWidth == maxColumn)) {
thisSpaceWidth++;
} else if(!horizontal && row + thisSpaceHeight == maxRow) {
thisSpaceHeight++;
}
// Create rule
String constraint = String.format("%c%c-%c%c", row, column, (char) (row - 1 + thisSpaceHeight), (char) (column - 1 + thisSpaceWidth));
if(!horizontal) {
constraint += 'v';
}
rules.add(new InvTweaksConfigSortingRule(tree, constraint, item.getName(), size, rowSize));
// Check if ther's still room for more rules
availableSlots -= thisSpaceHeight * thisSpaceWidth;
remainingStacks -= stats.get(item);
if(availableSlots >= remainingStacks) {
// Move origin for next rule
if(horizontal) {
if(column + thisSpaceWidth + spaceWidth <= maxColumn + 1) {
column += thisSpaceWidth;
} else {
column = '1';
row += thisSpaceHeight;
}
} else {
if(row + thisSpaceHeight + spaceHeight <= maxRow + 1) {
row += thisSpaceHeight;
} else {
row = 'a';
column += thisSpaceWidth;
}
}
if(row > maxRow || column > maxColumn) {
break;
}
} else {
break;
}
}
String defaultRule;
if(horizontal) {
defaultRule = maxRow + "1-a" + maxColumn;
} else {
defaultRule = "a" + maxColumn + "-" + maxRow + "1v";
}
rules.add(new InvTweaksConfigSortingRule(tree, defaultRule, tree.getRootCategory().getName(), size, rowSize));
}
private Map<IItemTreeItem, Integer> computeContainerStats() {
Map<IItemTreeItem, Integer> stats = new HashMap<>();
Map<Integer, IItemTreeItem> itemSearch = new HashMap<>();
for(int i = 0; i < size; i++) {
ItemStack stack = containerMgr.getItemStack(i);
if(stack != null) {
// TODO: ID Changes (Leaving as-is for now because WHY)
int itemSearchKey = Item.getIdFromItem(stack.getItem()) * 100000 + ((stack
.getMaxStackSize() != 1) ? stack.getItemDamage() : 0);
IItemTreeItem item = itemSearch.get(itemSearchKey);
if(item == null) {
// TODO: It looks like Mojang changed the internal name type to ResourceLocation. Evaluate how much of a pain that will be.
item = tree.getItems(Item.itemRegistry.getNameForObject(stack.getItem()).toString(), stack.getItemDamage()).get(0);
itemSearch.put(itemSearchKey, item);
stats.put(item, 1);
} else {
stats.put(item, stats.get(item) + 1);
}
}
}
return stats;
}
private int getContainerColumnSize(int rowSize) {
return size / rowSize;
}
}
| src/main/java/invtweaks/InvTweaksHandlerSorting.java | package invtweaks;
import invtweaks.api.IItemTreeItem;
import invtweaks.api.SortingMethod;
import invtweaks.api.container.ContainerSection;
import invtweaks.container.IContainerManager;
import invtweaks.container.ContainerSectionManager;
import net.minecraft.client.Minecraft;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.Logger;
import java.util.*;
import java.util.Map.Entry;
/**
* Core of the sorting behaviour. Allows to move items in a container (inventory or chest) with respect to the mod's
* configuration.
*
* @author Jimeo Wan
*/
public class InvTweaksHandlerSorting extends InvTweaksObfuscation {
private static final Logger log = InvTweaks.log;
private static final int MAX_CONTAINER_SIZE = 999;
private static int[] DEFAULT_LOCK_PRIORITIES = null;
private static boolean[] DEFAULT_FROZEN_SLOTS = null;
private ContainerSectionManager containerMgr;
private SortingMethod algorithm;
private int size;
private boolean sortArmorParts;
private InvTweaksItemTree tree;
private List<InvTweaksConfigSortingRule> rules;
private int[] rulePriority;
private int[] keywordOrder;
private int[] lockPriorities;
private boolean[] frozenSlots;
public InvTweaksHandlerSorting(Minecraft mc_, InvTweaksConfig config, ContainerSection section, SortingMethod algorithm_,
int rowSize) throws Exception {
super(mc_);
// Init constants
if(DEFAULT_LOCK_PRIORITIES == null) {
DEFAULT_LOCK_PRIORITIES = new int[MAX_CONTAINER_SIZE];
for(int i = 0; i < MAX_CONTAINER_SIZE; i++) {
DEFAULT_LOCK_PRIORITIES[i] = 0;
}
}
if(DEFAULT_FROZEN_SLOTS == null) {
DEFAULT_FROZEN_SLOTS = new boolean[MAX_CONTAINER_SIZE];
for(int i = 0; i < MAX_CONTAINER_SIZE; i++) {
DEFAULT_FROZEN_SLOTS[i] = false;
}
}
// Init attributes
containerMgr = new ContainerSectionManager(section);
size = containerMgr.getSize();
sortArmorParts = config.getProperty(InvTweaksConfig.PROP_ENABLE_AUTO_EQUIP_ARMOR)
.equals(InvTweaksConfig.VALUE_TRUE) && !isGuiInventoryCreative(
getCurrentScreen()); // FIXME Armor parts disappear when sorting in creative mode while holding an item
rules = config.getRules();
tree = config.getTree();
if(section == ContainerSection.INVENTORY) {
lockPriorities = config.getLockPriorities();
frozenSlots = config.getFrozenSlots();
algorithm = SortingMethod.INVENTORY;
} else {
lockPriorities = DEFAULT_LOCK_PRIORITIES;
frozenSlots = DEFAULT_FROZEN_SLOTS;
algorithm = algorithm_;
if(algorithm != SortingMethod.DEFAULT) {
computeLineSortingRules(rowSize, algorithm == SortingMethod.HORIZONTAL);
}
}
rulePriority = new int[size];
keywordOrder = new int[size];
for(int i = 0; i < size; i++) {
rulePriority[i] = -1;
ItemStack stack = containerMgr.getItemStack(i);
if(stack != null) {
keywordOrder[i] = getItemOrder(stack);
} else {
keywordOrder[i] = -1;
}
}
// Initialize rule priority for currently matching items
// TODO: J1.8 streams?
rules.stream().filter(rule -> rule.getContainerSize() == size).forEach(rule -> {
int priority = rule.getPriority();
for(int slot : rule.getPreferredSlots()) {
ItemStack stack = containerMgr.getItemStack(slot);
if(stack != null) {
List<IItemTreeItem> items = tree
.getItems(Item.itemRegistry.getNameForObject(stack.getItem()).toString(), stack.getItemDamage());
if(rulePriority[slot] < priority && tree.matches(items, rule.getKeyword())) {
rulePriority[slot] = priority;
}
}
}
});
}
public void sort() {
long timer = System.nanoTime();
IContainerManager globalContainer = InvTweaks.getCurrentContainerManager();
// Put hold item down
if(getHeldStack() != null) {
int emptySlot = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY);
if(emptySlot != -1) {
globalContainer.putHoldItemDown(ContainerSection.INVENTORY, emptySlot);
} else {
return; // Not enough room to work, abort
}
}
if(algorithm != SortingMethod.DEFAULT) {
if(algorithm == SortingMethod.EVEN_STACKS) {
sortEvenStacks();
} else if(algorithm == SortingMethod.INVENTORY) {
sortInventory(globalContainer);
}
sortWithRules();
}
//// Sort remaining
defaultSorting();
if(log.isEnabled(InvTweaksConst.DEBUG)) {
timer = System.nanoTime() - timer;
log.info("Sorting done in " + timer + "ns");
}
//// Put hold item down, just in case
if(getHeldStack() != null) {
int emptySlot = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY);
if(emptySlot != -1) {
globalContainer.putHoldItemDown(ContainerSection.INVENTORY, emptySlot);
}
}
globalContainer.applyChanges();
}
private void sortWithRules() {
//// Apply rules
log.info("Applying rules.");
// Sorts rule by rule, themselves being already sorted by decreasing priority
for(InvTweaksConfigSortingRule rule : rules) {
int priority = rule.getPriority();
if(log.isEnabled(InvTweaksConst.DEBUG)) {
log.info("Rule : " + rule.getKeyword() + "(" + priority + ")");
}
// For every item in the inventory
for(int i = 0; i < size; i++) {
ItemStack from = containerMgr.getItemStack(i);
// If the rule is strong enough to move the item and it matches the item, move it
if(hasToBeMoved(i, priority) && lockPriorities[i] < priority) {
// TODO: It looks like Mojang changed the internal name type to ResourceLocation. Evaluate how much of a pain that will be.
List<IItemTreeItem> fromItems = tree
.getItems(Item.itemRegistry.getNameForObject(from.getItem()).toString(), from.getItemDamage());
if(tree.matches(fromItems, rule.getKeyword())) {
// Test preferred slots
int[] preferredSlots = rule.getPreferredSlots();
int stackToMove = i;
for(int k : preferredSlots) {
// Move the stack!
int moveResult = move(stackToMove, k, priority);
if(moveResult != -1) {
if(moveResult == k) {
break;
} else {
from = containerMgr.getItemStack(moveResult);
// TODO: It looks like Mojang changed the internal name type to ResourceLocation. Evaluate how much of a pain that will be.
fromItems = tree.getItems(Item.itemRegistry.getNameForObject(from.getItem()).toString(), from.getItemDamage());
if(tree.matches(fromItems, rule.getKeyword())) {
if(i >= moveResult) {
// Current or already-processed slot.
stackToMove = moveResult;
//j = -1; // POSSIBLE INFINITE LOOP. But having this missing may cause sorting to take a few tries to stabilize in specific situations.
} else {
// The item will be processed later
break;
}
} else {
break;
}
}
}
}
}
}
}
}
//// Don't move locked stacks
log.info("Locking stacks.");
for(int i = 0; i < size; i++) {
if(hasToBeMoved(i, 1) && lockPriorities[i] > 0) {
markAsMoved(i, 1);
}
}
}
private void sortInventory(IContainerManager globalContainer) {
//// Move items out of the crafting slots
log.info("Handling crafting slots.");
if(globalContainer.hasSection(ContainerSection.CRAFTING_IN)) {
List<Slot> craftingSlots = globalContainer.getSlots(ContainerSection.CRAFTING_IN);
int emptyIndex = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY);
if(emptyIndex != -1) {
for(Slot craftingSlot : craftingSlots) {
if(craftingSlot.getHasStack()) {
globalContainer.move(ContainerSection.CRAFTING_IN,
globalContainer.getSlotIndex(getSlotNumber(craftingSlot)),
ContainerSection.INVENTORY, emptyIndex);
emptyIndex = globalContainer.getFirstEmptyIndex(ContainerSection.INVENTORY);
if(emptyIndex == -1) {
break;
}
}
}
}
}
sortMergeArmor(globalContainer);
}
private void sortMergeArmor(IContainerManager globalContainer) {
//// Merge stacks to fill the ones in locked slots
//// + Move armor parts to the armor slots
log.info("Merging stacks.");
for(int i = size - 1; i >= 0; i--) {
ItemStack from = containerMgr.getItemStack(i);
if(from != null) {
// Move armor parts
// Item
Item fromItem = from.getItem();
if(fromItem.isDamageable()) {
moveArmor(globalContainer, i, from, fromItem);
}
// Stackable objects are never damageable
else {
mergeItem(i, from);
}
}
}
}
private void mergeItem(int i, ItemStack from) {
int j = 0;
for(Integer lockPriority : lockPriorities) {
if(lockPriority > 0) {
ItemStack to = containerMgr.getItemStack(j);
if(to != null && areItemsStackable(from, to)) {
move(i, j, Integer.MAX_VALUE);
markAsNotMoved(j);
if(containerMgr.getItemStack(i) == null) {
break;
}
}
}
j++;
}
}
private void moveArmor(IContainerManager globalContainer, int i, ItemStack from, Item fromItem) {
if(sortArmorParts) {
if(isItemArmor(fromItem)) {
// ItemArmor
ItemArmor fromItemArmor = (ItemArmor) fromItem;
if(globalContainer.hasSection(ContainerSection.ARMOR)) {
List<Slot> armorSlots = globalContainer.getSlots(ContainerSection.ARMOR);
for(Slot slot : armorSlots) {
boolean move = false;
if(!slot.getHasStack()) {
move = true;
} else {
// Item
Item currentArmor = slot.getStack().getItem();
if(isItemArmor(currentArmor)) {
// ItemArmor
// ItemArmor
int armorLevel = ((ItemArmor) currentArmor).damageReduceAmount;
// ItemArmor
// ItemArmor
if(armorLevel < fromItemArmor.damageReduceAmount || (armorLevel == fromItemArmor.damageReduceAmount && slot
.getStack().getItemDamage() < from.getItemDamage())) {
move = true;
}
} else {
move = true;
}
}
if(slot.isItemValid(from) && move) {
globalContainer.move(ContainerSection.INVENTORY, i, ContainerSection.ARMOR,
globalContainer.getSlotIndex(getSlotNumber(slot)));
}
}
}
}
}
}
private void sortEvenStacks() {
log.info("Distributing items.");
//item and slot counts for each unique item
HashMap<Pair<String, Integer>, int[]> itemCounts = new HashMap<>();
for(int i = 0; i < size; i++) {
ItemStack stack = containerMgr.getItemStack(i);
if(stack != null) {
// TODO: It looks like Mojang changed the internal name type to ResourceLocation. Evaluate how much of a pain that will be.
Pair<String, Integer> item = Pair.of(Item.itemRegistry.getNameForObject(stack.getItem()).toString(), stack.getItemDamage());
int[] count = itemCounts.get(item);
if(count == null) {
int[] newCount = {stack.stackSize, 1};
itemCounts.put(item, newCount);
} else {
count[0] += stack.stackSize; //amount of item
count[1]++; //slots with item
}
}
}
//handle each unique item separately
for(Entry<Pair<String, Integer>, int[]> entry : itemCounts.entrySet()) {
Pair<String, Integer> item = entry.getKey();
int[] count = entry.getValue();
int numPerSlot = count[0] / count[1]; //totalNumber/numberOfSlots
//skip hacked itemstacks that are larger than their max size
//no idea why they would be here, but may as well account for them anyway
if(numPerSlot <= new ItemStack((Item) Item.itemRegistry.getObject(item.getLeft()), 1, 0).getMaxStackSize()) {
//linkedlists to store which stacks have too many/few items
LinkedList<Integer> smallStacks = new LinkedList<>();
LinkedList<Integer> largeStacks = new LinkedList<>();
for(int i = 0; i < size; i++) {
ItemStack stack = containerMgr.getItemStack(i);
if(stack != null && Pair.of(Item.itemRegistry.getNameForObject(stack.getItem()), stack.getItemDamage())
.equals(item)) {
int stackSize = stack.stackSize;
if(stackSize > numPerSlot) {
largeStacks.offer(i);
} else if(stackSize < numPerSlot) {
smallStacks.offer(i);
}
}
}
//move items from stacks with too many to those with too little
while((!smallStacks.isEmpty())) {
int largeIndex = largeStacks.peek();
int largeSize = containerMgr.getItemStack(largeIndex).stackSize;
int smallIndex = smallStacks.peek();
int smallSize = containerMgr.getItemStack(smallIndex).stackSize;
containerMgr
.moveSome(largeIndex, smallIndex, Math.min(numPerSlot - smallSize, largeSize - numPerSlot));
//update stack lists
largeSize = containerMgr.getItemStack(largeIndex).stackSize;
smallSize = containerMgr.getItemStack(smallIndex).stackSize;
if(largeSize == numPerSlot) {
largeStacks.remove();
}
if(smallSize == numPerSlot) {
smallStacks.remove();
}
}
//put all leftover into one stack for easy removal
while(largeStacks.size() > 1) {
int largeIndex = largeStacks.poll();
int largeSize = containerMgr.getItemStack(largeIndex).stackSize;
containerMgr.moveSome(largeIndex, largeStacks.peek(), largeSize - numPerSlot);
}
}
}
//mark all items as moved. (is there a better way?)
for(int i = 0; i < size; i++) {
markAsMoved(i, 1);
}
}
private void defaultSorting() {
log.info("Default sorting.");
ArrayList<Integer> remaining = new ArrayList<>(), nextRemaining = new ArrayList<>();
for(int i = 0; i < size; i++) {
if(hasToBeMoved(i, 1)) {
remaining.add(i);
nextRemaining.add(i);
}
}
int iterations = 0;
while(remaining.size() > 0 && iterations++ < 50) {
for(int i : remaining) {
if(hasToBeMoved(i, 1)) {
for(int j = 0; j < size; j++) {
if(move(i, j, 1) != -1) {
nextRemaining.remove((Integer) j);
break;
}
}
} else {
nextRemaining.remove((Integer) i);
}
}
remaining.clear();
remaining.addAll(nextRemaining);
}
if(iterations == 100) {
log.warn("Sorting takes too long, aborting.");
}
}
private static boolean canMergeStacks(ItemStack from, ItemStack to) {
if(areItemsStackable(from, to)) {
if(from.stackSize > from.getMaxStackSize()) {
return false;
}
if(to.stackSize < to.getMaxStackSize()) {
return true;
}
}
return false;
}
private boolean canSwapSlots(int i, int j, int priority) {
return lockPriorities[j] <= priority && (rulePriority[j] < priority || (rulePriority[j] == priority && isOrderedBefore(
i, j)));
}
/**
* Tries to move a stack from i to j, and swaps them if j is already occupied but i is of greater priority (even if
* they are of same ID).
*
* @param i from slot
* @param j to slot
* @param priority The rule priority. Use 1 if the stack was not moved using a rule.
* @return -1 if it failed, j if the stacks were merged into one, n if the j stack has been moved to the n slot.
*/
private int move(int i, int j, int priority) {
ItemStack from = containerMgr.getItemStack(i), to = containerMgr.getItemStack(j);
if(from == null || frozenSlots[j] || frozenSlots[i]) {
return -1;
}
//log.info("Moving " + i + " (" + from + ") to " + j + " (" + to + ") ");
if(lockPriorities[i] <= priority) {
if(i == j) {
markAsMoved(i, priority);
return j;
}
// Move to empty slot
if(to == null && lockPriorities[j] <= priority && !frozenSlots[j]) {
rulePriority[i] = -1;
keywordOrder[i] = -1;
rulePriority[j] = priority;
keywordOrder[j] = getItemOrder(from);
if(containerMgr.move(i, j)) {
return j;
} else {
return -1;
}
}
// Try to swap/merge
else if(to != null) {
if(canSwapSlots(i, j, priority) || canMergeStacks(from, to)) {
keywordOrder[j] = keywordOrder[i];
rulePriority[j] = priority;
rulePriority[i] = -1;
boolean success = containerMgr.move(i, j);
if(success) {
ItemStack remains = containerMgr.getItemStack(i);
if(remains != null) {
int dropSlot = i;
if(lockPriorities[j] > lockPriorities[i]) {
for(int k = 0; k < size; k++) {
if(containerMgr.getItemStack(k) == null && lockPriorities[k] == 0) {
dropSlot = k;
break;
}
}
}
if(dropSlot != i) {
if(!containerMgr.move(i, dropSlot)) {
// TODO: This is a potentially bad situation: One move succeeded, then the rest failed.
return -1;
}
}
rulePriority[dropSlot] = -1;
keywordOrder[dropSlot] = getItemOrder(remains);
return dropSlot;
} else {
return j;
}
} else {
return -1;
}
}
}
}
return -1;
}
private void markAsMoved(int i, int priority) {
rulePriority[i] = priority;
}
private void markAsNotMoved(int i) {
rulePriority[i] = -1;
}
private boolean hasToBeMoved(int slot, int priority) {
return containerMgr.getItemStack(slot) != null && rulePriority[slot] <= priority;
}
private boolean isOrderedBefore(int i, int j) {
ItemStack iStack = containerMgr.getItemStack(i), jStack = containerMgr.getItemStack(j);
return InvTweaks.getInstance().compareItems(iStack, jStack, keywordOrder[i], keywordOrder[j]) < 0;
}
private int getItemOrder(ItemStack itemStack) {
// TODO: It looks like Mojang changed the internal name type to ResourceLocation. Evaluate how much of a pain that will be.
List<IItemTreeItem> items = tree.getItems(Item.itemRegistry.getNameForObject(itemStack.getItem()).toString(), itemStack.getItemDamage());
return (items != null && items.size() > 0) ? items.get(0).getOrder() : Integer.MAX_VALUE;
}
private void computeLineSortingRules(int rowSize, boolean horizontal) {
rules = new ArrayList<>();
Map<IItemTreeItem, Integer> stats = computeContainerStats();
List<IItemTreeItem> itemOrder = new ArrayList<>();
int distinctItems = stats.size();
int columnSize = getContainerColumnSize(rowSize);
int spaceWidth;
int spaceHeight;
int availableSlots = size;
int remainingStacks = 0;
for(Integer stacks : stats.values()) {
remainingStacks += stacks;
}
// No need to compute rules for an empty chest
if(distinctItems == 0) {
return;
}
// (Partially) sort stats by decreasing item stack count
List<IItemTreeItem> unorderedItems = new ArrayList<>(stats.keySet());
boolean hasStacksToOrderFirst = true;
while(hasStacksToOrderFirst) {
hasStacksToOrderFirst = false;
for(IItemTreeItem item : unorderedItems) {
Integer value = stats.get(item);
if(value > ((horizontal) ? rowSize : columnSize) && !itemOrder.contains(item)) {
hasStacksToOrderFirst = true;
itemOrder.add(item);
unorderedItems.remove(item);
break;
}
}
}
Collections.sort(unorderedItems, Collections.reverseOrder());
itemOrder.addAll(unorderedItems);
// Define space size used for each item type.
if(horizontal) {
spaceHeight = 1;
spaceWidth = rowSize / ((distinctItems + columnSize - 1) / columnSize);
} else {
spaceWidth = 1;
spaceHeight = columnSize / ((distinctItems + rowSize - 1) / rowSize);
}
char row = 'a', maxRow = (char) (row - 1 + columnSize);
char column = '1', maxColumn = (char) (column - 1 + rowSize);
// Create rules
for(IItemTreeItem item : itemOrder) {
// Adapt rule dimensions to fit the amount
int thisSpaceWidth = spaceWidth,
thisSpaceHeight = spaceHeight;
while(stats.get(item) > thisSpaceHeight * thisSpaceWidth) {
if(horizontal) {
if(column + thisSpaceWidth < maxColumn) {
thisSpaceWidth = maxColumn - column + 1;
} else if(row + thisSpaceHeight < maxRow) {
thisSpaceHeight++;
} else {
break;
}
} else {
if(row + thisSpaceHeight < maxRow) {
thisSpaceHeight = maxRow - row + 1;
} else if(column + thisSpaceWidth < maxColumn) {
thisSpaceWidth++;
} else {
break;
}
}
}
// Adjust line/column ends to fill empty space
if(horizontal && (column + thisSpaceWidth == maxColumn)) {
thisSpaceWidth++;
} else if(!horizontal && row + thisSpaceHeight == maxRow) {
thisSpaceHeight++;
}
// Create rule
String constraint = row + column + "-" + (char) (row - 1 + thisSpaceHeight) + (char) (column - 1 + thisSpaceWidth);
if(!horizontal) {
constraint += 'v';
}
rules.add(new InvTweaksConfigSortingRule(tree, constraint, item.getName(), size, rowSize));
// Check if ther's still room for more rules
availableSlots -= thisSpaceHeight * thisSpaceWidth;
remainingStacks -= stats.get(item);
if(availableSlots >= remainingStacks) {
// Move origin for next rule
if(horizontal) {
if(column + thisSpaceWidth + spaceWidth <= maxColumn + 1) {
column += thisSpaceWidth;
} else {
column = '1';
row += thisSpaceHeight;
}
} else {
if(row + thisSpaceHeight + spaceHeight <= maxRow + 1) {
row += thisSpaceHeight;
} else {
row = 'a';
column += thisSpaceWidth;
}
}
if(row > maxRow || column > maxColumn) {
break;
}
} else {
break;
}
}
String defaultRule;
if(horizontal) {
defaultRule = maxRow + "1-a" + maxColumn;
} else {
defaultRule = "a" + maxColumn + "-" + maxRow + "1v";
}
rules.add(new InvTweaksConfigSortingRule(tree, defaultRule, tree.getRootCategory().getName(), size, rowSize));
}
private Map<IItemTreeItem, Integer> computeContainerStats() {
Map<IItemTreeItem, Integer> stats = new HashMap<>();
Map<Integer, IItemTreeItem> itemSearch = new HashMap<>();
for(int i = 0; i < size; i++) {
ItemStack stack = containerMgr.getItemStack(i);
if(stack != null) {
// TODO: ID Changes (Leaving as-is for now because WHY)
int itemSearchKey = Item.getIdFromItem(stack.getItem()) * 100000 + ((stack
.getMaxStackSize() != 1) ? stack.getItemDamage() : 0);
IItemTreeItem item = itemSearch.get(itemSearchKey);
if(item == null) {
// TODO: It looks like Mojang changed the internal name type to ResourceLocation. Evaluate how much of a pain that will be.
item = tree.getItems(Item.itemRegistry.getNameForObject(stack.getItem()).toString(), stack.getItemDamage()).get(0);
itemSearch.put(itemSearchKey, item);
stats.put(item, 1);
} else {
stats.put(item, stats.get(item) + 1);
}
}
}
return stats;
}
private int getContainerColumnSize(int rowSize) {
return size / rowSize;
}
}
| Fix error in building rules for horiz/vert mode.
| src/main/java/invtweaks/InvTweaksHandlerSorting.java | Fix error in building rules for horiz/vert mode. | <ide><path>rc/main/java/invtweaks/InvTweaksHandlerSorting.java
<ide> }
<ide>
<ide> // Create rule
<del> String constraint = row + column + "-" + (char) (row - 1 + thisSpaceHeight) + (char) (column - 1 + thisSpaceWidth);
<add> String constraint = String.format("%c%c-%c%c", row, column, (char) (row - 1 + thisSpaceHeight), (char) (column - 1 + thisSpaceWidth));
<ide> if(!horizontal) {
<ide> constraint += 'v';
<ide> } |
|
Java | epl-1.0 | b0aea307301907059ea1d82ca39d7d257d28e1c6 | 0 | opendaylight/yangtools,opendaylight/yangtools | /*
* Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.parser.stmt.reactor;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Verify.verify;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.VerifyException;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.common.YangVersion;
import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStatementState;
import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Parent;
import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.ExecutionOrder;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Real "core" reactor statement implementation of {@link Mutable}, supporting basic reactor lifecycle.
*
* @param <A> Argument type
* @param <D> Declared Statement representation
* @param <E> Effective Statement representation
*/
abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
extends NamespaceStorageSupport implements Mutable<A, D, E>, Current<A, D> {
private static final Logger LOG = LoggerFactory.getLogger(ReactorStmtCtx.class);
/**
* Substatement refcount tracking. This mechanics deals with retaining substatements for the purposes of
* instantiating their lazy copies in InferredStatementContext. It works in concert with {@link #buildEffective()}
* and {@link #declared()}: declared/effective statement views hold an implicit reference and refcount-based
* sweep is not activated until they are done (or this statement is not {@link #isSupportedToBuildEffective}).
*
* <p>
* Reference count is hierarchical in that parent references also pin down their child statements and do not allow
* them to be swept.
*
* <p>
* The counter's positive values are tracking incoming references via {@link #incRef()}/{@link #decRef()} methods.
* Once we transition to sweeping, this value becomes negative counting upwards to {@link #REFCOUNT_NONE} based on
* {@link #sweepOnChildDone()}. Once we reach that, we transition to {@link #REFCOUNT_SWEPT}.
*/
private int refcount = REFCOUNT_NONE;
/**
* No outstanding references, this statement is a potential candidate for sweeping, provided it has populated its
* declared and effective views and {@link #parentRef} is known to be absent.
*/
private static final int REFCOUNT_NONE = 0;
/**
* Reference count overflow or some other recoverable logic error. Do not rely on refcounts and do not sweep
* anything.
*
* <p>
* Note on value assignment:
* This allow our incRef() to naturally progress to being saturated. Others jump there directly.
* It also makes it it impossible to observe {@code Interger.MAX_VALUE} children, which we take advantage of for
* {@link #REFCOUNT_SWEEPING}.
*/
private static final int REFCOUNT_DEFUNCT = Integer.MAX_VALUE;
/**
* This statement is being actively swept. This is a transient value set when we are sweeping our children, so that
* we prevent re-entering this statement.
*
* <p>
* Note on value assignment:
* The value is lower than any legal child refcount due to {@link #REFCOUNT_DEFUNCT} while still being higher than
* {@link #REFCOUNT_SWEPT}.
*/
private static final int REFCOUNT_SWEEPING = -Integer.MAX_VALUE;
/**
* This statement, along with its entire subtree has been swept and we positively know all our children have reached
* this state. We {@link #sweepNamespaces()} upon reaching this state.
*
* <p>
* Note on value assignment:
* This is the lowest value observable, making it easier on checking others on equality.
*/
private static final int REFCOUNT_SWEPT = Integer.MIN_VALUE;
/**
* Effective instance built from this context. This field as dual types. Under normal circumstances in matches the
* {@link #buildEffective()} instance. If this context is reused, it can be inflated to {@link EffectiveInstances}
* and also act as a common instance reuse site.
*/
private @Nullable Object effectiveInstance;
// Master flag controlling whether this context can yield an effective statement
// FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
// of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
private boolean isSupportedToBuildEffective = true;
// EffectiveConfig mapping
private static final int MASK_CONFIG = 0x03;
private static final int HAVE_CONFIG = 0x04;
// Effective instantiation mechanics for StatementContextBase: if this flag is set all substatements are known not
// change when instantiated. This includes context-independent statements as well as any statements which are
// ignored during copy instantiation.
private static final int ALL_INDEPENDENT = 0x08;
// Flag bit assignments
private static final int IS_SUPPORTED_BY_FEATURES = 0x10;
private static final int HAVE_SUPPORTED_BY_FEATURES = 0x20;
private static final int IS_IGNORE_IF_FEATURE = 0x40;
private static final int HAVE_IGNORE_IF_FEATURE = 0x80;
// Have-and-set flag constants, also used as masks
private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
private static final EffectiveConfig[] EFFECTIVE_CONFIGS;
static {
final EffectiveConfig[] values = EffectiveConfig.values();
final int length = values.length;
verify(length == 4, "Unexpected EffectiveConfig cardinality %s", length);
EFFECTIVE_CONFIGS = values;
}
// Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
// hence improve memory layout.
private byte flags;
// Flag for use by AbstractResumedStatement, ReplicaStatementContext and InferredStatementContext. Each of them
// uses it to indicated a different condition. This is hiding in the alignment shadow created by
// 'isSupportedToBuildEffective'.
// FIXME: move this out once we have JDK15+
private boolean boolFlag;
ReactorStmtCtx() {
// Empty on purpose
}
ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
isSupportedToBuildEffective = original.isSupportedToBuildEffective;
boolFlag = original.boolFlag;
flags = original.flags;
}
// Used by ReplicaStatementContext only
ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original, final Void dummy) {
boolFlag = isSupportedToBuildEffective = original.isSupportedToBuildEffective;
flags = original.flags;
}
//
//
// Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
// up mixing concerns and simple details with more complex logic.
//
//
@Override
public abstract StatementContextBase<?, ?, ?> getParentContext();
@Override
public abstract RootStatementContext<?, ?, ?> getRoot();
@Override
public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
@Override
public final @NonNull Registry getBehaviourRegistry() {
return getRoot().getBehaviourRegistryImpl();
}
@Override
public final YangVersion yangVersion() {
return getRoot().getRootVersionImpl();
}
@Override
public final void setRootVersion(final YangVersion version) {
getRoot().setRootVersionImpl(version);
}
@Override
public final void addRequiredSource(final SourceIdentifier dependency) {
getRoot().addRequiredSourceImpl(dependency);
}
@Override
public final void setRootIdentifier(final SourceIdentifier identifier) {
getRoot().setRootIdentifierImpl(identifier);
}
@Override
public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
return getRoot().getSourceContext().newInferenceAction(phase);
}
@Override
public final StatementDefinition publicDefinition() {
return definition().getPublicView();
}
@Override
public final Parent effectiveParent() {
return getParentContext();
}
@Override
public final QName moduleName() {
final RootStatementContext<?, ?, ?> root = getRoot();
return QName.create(StmtContextUtils.getRootModuleQName(root), root.getRawArgument());
}
@Override
@Deprecated(since = "7.0.9", forRemoval = true)
public final EffectiveStatement<?, ?> original() {
return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
}
//
// In the next two methods we are looking for an effective statement. If we already have an effective instance,
// defer to it's implementation of the equivalent search. Otherwise we search our substatement contexts.
//
// Note that the search function is split, so as to allow InferredStatementContext to do its own thing first.
//
@Override
public final <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
final @NonNull Class<Z> type) {
final E existing = effectiveInstance();
return existing != null ? existing.findFirstEffectiveSubstatementArgument(type)
: findSubstatementArgumentImpl(type);
}
@Override
public final boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
final E existing = effectiveInstance();
return existing != null ? existing.findFirstEffectiveSubstatement(type).isPresent() : hasSubstatementImpl(type);
}
private E effectiveInstance() {
final Object existing = effectiveInstance;
return existing != null ? EffectiveInstances.local(existing) : null;
}
// Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
<X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
final @NonNull Class<Z> type) {
return allSubstatementsStream()
.filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
.findAny()
.map(ctx -> (X) ctx.getArgument());
}
// Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
return allSubstatementsStream()
.anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
}
@Override
@Deprecated
@SuppressWarnings("unchecked")
public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
return (StmtContext<A, D, Z>) this;
}
@Override
public final String toString() {
return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
}
protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
return toStringHelper.add("definition", definition()).add("argument", argument()).add("refCount", refString());
}
private String refString() {
final int current = refcount;
switch (current) {
case REFCOUNT_DEFUNCT:
return "DEFUNCT";
case REFCOUNT_SWEEPING:
return "SWEEPING";
case REFCOUNT_SWEPT:
return "SWEPT";
default:
return String.valueOf(refcount);
}
}
/**
* Return the context in which this statement was defined.
*
* @return statement definition
*/
abstract @NonNull StatementDefinitionContext<A, D, E> definition();
//
//
// NamespaceStorageSupport/Mutable integration methods. Keep these together.
//
//
@Override
public final <K, V, T extends K, N extends ParserNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
final T key) {
return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
}
@Override
public final <K, V, N extends ParserNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
return getNamespace(type);
}
@Override
public final <K, V, N extends ParserNamespace<K, V>>
Map<K, V> localNamespacePortion(final Class<@NonNull N> type) {
return getLocalNamespace(type);
}
@Override
protected <K, V, N extends ParserNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
final V value) {
// definition().onNamespaceElementAdded(this, type, key, value);
}
/**
* Return the effective statement view of a copy operation. This method may return one of:
* <ul>
* <li>{@code this}, when the effective view did not change</li>
* <li>an InferredStatementContext, when there is a need for inference-equivalent copy</li>
* <li>{@code null}, when the statement failed to materialize</li>
* </ul>
*
* @param parent Proposed new parent
* @param type Copy operation type
* @param targetModule New target module
* @return {@link ReactorStmtCtx} holding effective view
*/
abstract @Nullable ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(StatementContextBase<?, ?, ?> parent, CopyType type,
QNameModule targetModule);
@Override
public final ReplicaStatementContext<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
final var ret = replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
definition().onStatementAdded(ret);
return ret;
}
abstract @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(@NonNull StatementContextBase<?, ?, ?> parent);
//
//
// Statement build entry points -- both public and package-private.
//
//
@Override
public final E buildEffective() {
final Object existing;
return (existing = effectiveInstance) != null ? EffectiveInstances.local(existing) : loadEffective();
}
private @NonNull E loadEffective() {
final E ret = createEffective();
effectiveInstance = ret;
// we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
// some residue.
if (refcount == REFCOUNT_NONE) {
sweepOnDecrement();
}
return ret;
}
abstract @NonNull E createEffective();
/**
* Attach an effective copy of this statement. This essentially acts as a map, where we make a few assumptions:
* <ul>
* <li>{@code copy} and {@code this} statement share {@link #getOriginalCtx()} if it exists</li>
* <li>{@code copy} did not modify any statements relative to {@code this}</li>
* </ul>
*
* @param state effective statement state, acting as a lookup key
* @param stmt New copy to append
* @return {@code stmt} or a previously-created instances with the same {@code state}
*/
@SuppressWarnings("unchecked")
final @NonNull E attachEffectiveCopy(final @NonNull EffectiveStatementState state, final @NonNull E stmt) {
final Object local = effectiveInstance;
final EffectiveInstances<E> instances;
if (local instanceof EffectiveInstances) {
instances = (EffectiveInstances<E>) local;
} else {
effectiveInstance = instances = new EffectiveInstances<>((E) local);
}
return instances.attachCopy(state, stmt);
}
/**
* Walk this statement's copy history and return the statement closest to original which has not had its effective
* statements modified. This statement and returned substatement logically have the same set of substatements, hence
* share substatement-derived state.
*
* @return Closest {@link ReactorStmtCtx} with equivalent effective substatements
*/
abstract @NonNull ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource();
@Override
public final ModelProcessingPhase getCompletedPhase() {
return ModelProcessingPhase.ofExecutionOrder(executionOrder());
}
abstract byte executionOrder();
/**
* Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
* this method does nothing. This must not be called with {@link ExecutionOrder#NULL}.
*
* @param phase to be executed (completed)
* @return true if phase was successfully completed
* @throws SourceException when an error occurred in source parsing
*/
final boolean tryToCompletePhase(final byte executionOrder) {
return executionOrder() >= executionOrder || doTryToCompletePhase(executionOrder);
}
abstract boolean doTryToCompletePhase(byte targetOrder);
//
//
// Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
// shadow.
//
//
@Override
public final boolean isSupportedToBuildEffective() {
return isSupportedToBuildEffective;
}
@Override
public final void setUnsupported() {
this.isSupportedToBuildEffective = false;
}
@Override
public final boolean isSupportedByFeatures() {
final int fl = flags & SET_SUPPORTED_BY_FEATURES;
if (fl != 0) {
return fl == SET_SUPPORTED_BY_FEATURES;
}
if (isIgnoringIfFeatures()) {
flags |= SET_SUPPORTED_BY_FEATURES;
return true;
}
/*
* If parent is supported, we need to check if-features statements of this context.
*/
if (isParentSupportedByFeatures()) {
// If the set of supported features has not been provided, all features are supported by default.
final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class, Empty.value());
if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
flags |= SET_SUPPORTED_BY_FEATURES;
return true;
}
}
// Either parent is not supported or this statement is not supported
flags |= HAVE_SUPPORTED_BY_FEATURES;
return false;
}
protected abstract boolean isParentSupportedByFeatures();
/**
* Config statements are not all that common which means we are performing a recursive search towards the root
* every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
* for the (usually non-existent) config statement.
*
* <p>
* This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
* result without performing any lookups, solely to support {@link #effectiveConfig()}.
*
* <p>
* Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
* {@link #isIgnoringConfig(StatementContextBase)}.
*/
final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
}
private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
final EffectiveConfig parentConfig = parent.effectiveConfig();
final EffectiveConfig myConfig;
if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
if (optConfig.isPresent()) {
if (optConfig.orElseThrow()) {
// Validity check: if parent is config=false this cannot be a config=true
InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
"Parent node has config=false, this node must not be specifed as config=true");
myConfig = EffectiveConfig.TRUE;
} else {
myConfig = EffectiveConfig.FALSE;
}
} else {
// If "config" statement is not specified, the default is the same as the parent's "config" value.
myConfig = parentConfig;
}
} else {
myConfig = EffectiveConfig.IGNORED;
}
flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
return myConfig;
}
protected abstract boolean isIgnoringConfig();
/**
* This method maintains a resolution cache for ignore config, so once we have returned a result, we will
* keep on returning the same result without performing any lookups. Exists only to support
* {@link SubstatementContext#isIgnoringConfig()}.
*
* <p>
* Note: use of this method implies that {@link #isConfiguration()} is realized with
* {@link #effectiveConfig(StatementContextBase)}.
*/
final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
return EffectiveConfig.IGNORED == effectiveConfig(parent);
}
protected abstract boolean isIgnoringIfFeatures();
/**
* This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
* keep on returning the same result without performing any lookups. Exists only to support
* {@link SubstatementContext#isIgnoringIfFeatures()}.
*/
final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
final int fl = flags & SET_IGNORE_IF_FEATURE;
if (fl != 0) {
return fl == SET_IGNORE_IF_FEATURE;
}
if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
flags |= SET_IGNORE_IF_FEATURE;
return true;
}
flags |= HAVE_IGNORE_IF_FEATURE;
return false;
}
// These two exist only due to memory optimization, should live in AbstractResumedStatement.
final boolean fullyDefined() {
return boolFlag;
}
final void setFullyDefined() {
boolFlag = true;
}
// This exists only due to memory optimization, should live in ReplicaStatementContext. In this context the flag
// indicates the need to drop source's reference count when we are being swept.
final boolean haveSourceReference() {
return boolFlag;
}
// These three exist due to memory optimization, should live in InferredStatementContext. In this context the flag
// indicates whether or not this statement's substatement file was modified, i.e. it is not quite the same as the
// prototype's file.
final boolean isModified() {
return boolFlag;
}
final void setModified() {
boolFlag = true;
}
final void setUnmodified() {
boolFlag = false;
}
// These two exist only for StatementContextBase. Since we are squeezed for size, with only a single bit available
// in flags, we default to 'false' and only set the flag to true when we are absolutely sure -- and all other cases
// err on the side of caution by taking the time to evaluate each substatement separately.
final boolean allSubstatementsContextIndependent() {
return (flags & ALL_INDEPENDENT) != 0;
}
final void setAllSubstatementsContextIndependent() {
flags |= ALL_INDEPENDENT;
}
//
//
// Various functionality from AbstractTypeStatementSupport. This used to work on top of SchemaPath, now it still
// lives here. Ultimate future is either proper graduation or (more likely) move to AbstractTypeStatementSupport.
//
//
@Override
public final QName argumentAsTypeQName() {
// FIXME: This may yield illegal argument exceptions
return StmtContextUtils.qnameFromArgument(getOriginalCtx().orElse(this), getRawArgument());
}
@Override
public final QNameModule effectiveNamespace() {
if (StmtContextUtils.isUnknownStatement(this)) {
return publicDefinition().getStatementName().getModule();
}
if (producesDeclared(UsesStatement.class)) {
return coerceParent().effectiveNamespace();
}
final Object argument = argument();
if (argument instanceof QName) {
return ((QName) argument).getModule();
}
if (argument instanceof String) {
// FIXME: This may yield illegal argument exceptions
return StmtContextUtils.qnameFromArgument(getOriginalCtx().orElse(this), (String) argument).getModule();
}
if (argument instanceof SchemaNodeIdentifier
&& (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
|| producesDeclared(DeviationStatement.class))) {
return ((SchemaNodeIdentifier) argument).lastNodeIdentifier().getModule();
}
return coerceParent().effectiveNamespace();
}
private ReactorStmtCtx<?, ?, ?> coerceParent() {
return (ReactorStmtCtx<?, ?, ?>) coerceParentContext();
}
//
//
// Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
// contribute to state visible outside of this package.
//
//
/**
* Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
* in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
* knowledge and update it when {@link #sweep()} is invoked.
*/
private byte parentRef = PARENTREF_UNKNOWN;
private static final byte PARENTREF_UNKNOWN = -1;
private static final byte PARENTREF_ABSENT = 0;
private static final byte PARENTREF_PRESENT = 1;
/**
* Acquire a reference on this context. As long as there is at least one reference outstanding,
* {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
*
* @throws VerifyException if {@link #effectiveSubstatements()} has already been discarded
*/
final void incRef() {
final int current = refcount;
verify(current >= REFCOUNT_NONE, "Attempted to access reference count of %s", this);
if (current != REFCOUNT_DEFUNCT) {
// Note: can end up becoming REFCOUNT_DEFUNCT on overflow
refcount = current + 1;
} else {
LOG.debug("Disabled refcount increment of {}", this);
}
}
/**
* Release a reference on this context. This call may result in {@link #effectiveSubstatements()} becoming
* unavailable.
*/
final void decRef() {
final int current = refcount;
if (current == REFCOUNT_DEFUNCT) {
// no-op
LOG.debug("Disabled refcount decrement of {}", this);
return;
}
if (current <= REFCOUNT_NONE) {
// Underflow, become defunct
// FIXME: add a global 'warn once' flag
LOG.warn("Statement refcount underflow, reference counting disabled for {}", this, new Throwable());
refcount = REFCOUNT_DEFUNCT;
return;
}
refcount = current - 1;
LOG.trace("Refcount {} on {}", refcount, this);
if (refcount == REFCOUNT_NONE) {
lastDecRef();
}
}
/**
* Return {@code true} if this context has no outstanding references.
*
* @return True if this context has no outstanding references.
*/
final boolean noRefs() {
final int local = refcount;
return local < REFCOUNT_NONE || local == REFCOUNT_NONE && noParentRef();
}
private void lastDecRef() {
if (noImplictRef()) {
// We are no longer guarded by effective instance
sweepOnDecrement();
return;
}
final byte prevRefs = parentRef;
if (prevRefs == PARENTREF_ABSENT) {
// We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
// updated
markNoParentRef();
} else if (prevRefs == PARENTREF_UNKNOWN) {
// Noone observed our parentRef, just update it
loadParentRefcount();
}
}
static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
final byte prevRef = stmt.parentRef;
stmt.parentRef = PARENTREF_ABSENT;
if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
// Child thinks it is pinned down, update its perspective
stmt.markNoParentRef();
}
}
}
abstract void markNoParentRef();
static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
stmt.sweep();
}
}
/**
* Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
*/
private void sweep() {
parentRef = PARENTREF_ABSENT;
if (refcount == REFCOUNT_NONE && noImplictRef()) {
LOG.trace("Releasing {}", this);
sweepState();
}
}
static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
int result = 0;
for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
if (stmt.refcount > REFCOUNT_NONE || !stmt.noImplictRef()) {
result++;
}
}
return result;
}
/**
* Implementation-specific sweep action. This is expected to perform a recursive {@link #sweep(Collection)} on all
* {@link #declaredSubstatements()} and {@link #effectiveSubstatements()} and report the result of the sweep
* operation.
*
* <p>
* {@link #effectiveSubstatements()} as well as namespaces may become inoperable as a result of this operation.
*
* @return True if the entire tree has been completely swept, false otherwise.
*/
abstract int sweepSubstatements();
// Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
private void sweepOnDecrement() {
LOG.trace("Sweeping on decrement {}", this);
if (noParentRef()) {
// No further parent references, sweep our state.
sweepState();
}
// Propagate towards parent if there is one
sweepParent();
}
private void sweepParent() {
final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
if (parent != null) {
parent.sweepOnChildDecrement();
}
}
// Called from child when it has lost its final reference
private void sweepOnChildDecrement() {
if (isAwaitingChildren()) {
// We are a child for which our parent is waiting. Notify it and we are done.
sweepOnChildDone();
return;
}
// Check parent reference count
final int refs = refcount;
if (refs > REFCOUNT_NONE || refs <= REFCOUNT_SWEEPING || !noImplictRef()) {
// No-op
return;
}
// parent is potentially reclaimable
if (noParentRef()) {
LOG.trace("Cleanup {} of parent {}", refs, this);
if (sweepState()) {
sweepParent();
}
}
}
private boolean noImplictRef() {
return effectiveInstance != null || !isSupportedToBuildEffective();
}
private boolean noParentRef() {
return parentRefcount() == PARENTREF_ABSENT;
}
private byte parentRefcount() {
final byte refs;
return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
}
private byte loadParentRefcount() {
return parentRef = calculateParentRefcount();
}
private byte calculateParentRefcount() {
final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
if (parent == null) {
return PARENTREF_ABSENT;
}
// A slight wrinkle here is that our machinery handles only PRESENT -> ABSENT invalidation and we can reach here
// while inference is still ongoing and hence we may not have a complete picture about existing references. We
// could therefore end up caching an ABSENT result and then that information becoming stale as a new reference
// is introduced.
if (parent.executionOrder() < ExecutionOrder.EFFECTIVE_MODEL) {
return PARENTREF_UNKNOWN;
}
// There are three possibilities:
// - REFCOUNT_NONE, in which case we need to search next parent
// - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
// a reference to us
// - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
final int refs = parent.refcount;
if (refs == REFCOUNT_NONE) {
return parent.parentRefcount();
}
return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
}
private boolean isAwaitingChildren() {
return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
}
private void sweepOnChildDone() {
LOG.trace("Sweeping on child done {}", this);
final int current = refcount;
if (current >= REFCOUNT_NONE) {
// no-op, perhaps we want to handle some cases differently?
LOG.trace("Ignoring child sweep of {} for {}", this, current);
return;
}
verify(current != REFCOUNT_SWEPT, "Attempt to sweep a child of swept %s", this);
refcount = current + 1;
LOG.trace("Child refcount {}", refcount);
if (refcount == REFCOUNT_NONE) {
sweepDone();
final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
LOG.trace("Propagating to parent {}", parent);
if (parent != null && parent.isAwaitingChildren()) {
parent.sweepOnChildDone();
}
}
}
private void sweepDone() {
LOG.trace("Sweep done for {}", this);
refcount = REFCOUNT_SWEPT;
sweepNamespaces();
}
private boolean sweepState() {
refcount = REFCOUNT_SWEEPING;
final int childRefs = sweepSubstatements();
if (childRefs == 0) {
sweepDone();
return true;
}
if (childRefs < 0 || childRefs >= REFCOUNT_DEFUNCT) {
// FIXME: add a global 'warn once' flag
LOG.warn("Negative child refcount {} cannot be stored, reference counting disabled for {}", childRefs, this,
new Throwable());
refcount = REFCOUNT_DEFUNCT;
} else {
LOG.trace("Still {} outstanding children of {}", childRefs, this);
refcount = -childRefs;
}
return false;
}
}
| parser/yang-parser-reactor/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/ReactorStmtCtx.java | /*
* Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.parser.stmt.reactor;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Verify.verify;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.VerifyException;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.common.YangVersion;
import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition;
import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.ConfigEffectiveStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.DeviationStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.RefineStatement;
import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStatementState;
import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase.ExecutionOrder;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Real "core" reactor statement implementation of {@link Mutable}, supporting basic reactor lifecycle.
*
* @param <A> Argument type
* @param <D> Declared Statement representation
* @param <E> Effective Statement representation
*/
abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
extends NamespaceStorageSupport implements Mutable<A, D, E>, Current<A, D> {
private static final Logger LOG = LoggerFactory.getLogger(ReactorStmtCtx.class);
/**
* Substatement refcount tracking. This mechanics deals with retaining substatements for the purposes of
* instantiating their lazy copies in InferredStatementContext. It works in concert with {@link #buildEffective()}
* and {@link #declared()}: declared/effective statement views hold an implicit reference and refcount-based
* sweep is not activated until they are done (or this statement is not {@link #isSupportedToBuildEffective}).
*
* <p>
* Reference count is hierarchical in that parent references also pin down their child statements and do not allow
* them to be swept.
*
* <p>
* The counter's positive values are tracking incoming references via {@link #incRef()}/{@link #decRef()} methods.
* Once we transition to sweeping, this value becomes negative counting upwards to {@link #REFCOUNT_NONE} based on
* {@link #sweepOnChildDone()}. Once we reach that, we transition to {@link #REFCOUNT_SWEPT}.
*/
private int refcount = REFCOUNT_NONE;
/**
* No outstanding references, this statement is a potential candidate for sweeping, provided it has populated its
* declared and effective views and {@link #parentRef} is known to be absent.
*/
private static final int REFCOUNT_NONE = 0;
/**
* Reference count overflow or some other recoverable logic error. Do not rely on refcounts and do not sweep
* anything.
*
* <p>
* Note on value assignment:
* This allow our incRef() to naturally progress to being saturated. Others jump there directly.
* It also makes it it impossible to observe {@code Interger.MAX_VALUE} children, which we take advantage of for
* {@link #REFCOUNT_SWEEPING}.
*/
private static final int REFCOUNT_DEFUNCT = Integer.MAX_VALUE;
/**
* This statement is being actively swept. This is a transient value set when we are sweeping our children, so that
* we prevent re-entering this statement.
*
* <p>
* Note on value assignment:
* The value is lower than any legal child refcount due to {@link #REFCOUNT_DEFUNCT} while still being higher than
* {@link #REFCOUNT_SWEPT}.
*/
private static final int REFCOUNT_SWEEPING = -Integer.MAX_VALUE;
/**
* This statement, along with its entire subtree has been swept and we positively know all our children have reached
* this state. We {@link #sweepNamespaces()} upon reaching this state.
*
* <p>
* Note on value assignment:
* This is the lowest value observable, making it easier on checking others on equality.
*/
private static final int REFCOUNT_SWEPT = Integer.MIN_VALUE;
/**
* Effective instance built from this context. This field as dual types. Under normal circumstances in matches the
* {@link #buildEffective()} instance. If this context is reused, it can be inflated to {@link EffectiveInstances}
* and also act as a common instance reuse site.
*/
private @Nullable Object effectiveInstance;
// Master flag controlling whether this context can yield an effective statement
// FIXME: investigate the mechanics that are being supported by this, as it would be beneficial if we can get rid
// of this flag -- eliminating the initial alignment shadow used by below gap-filler fields.
private boolean isSupportedToBuildEffective = true;
// EffectiveConfig mapping
private static final int MASK_CONFIG = 0x03;
private static final int HAVE_CONFIG = 0x04;
// Effective instantiation mechanics for StatementContextBase: if this flag is set all substatements are known not
// change when instantiated. This includes context-independent statements as well as any statements which are
// ignored during copy instantiation.
private static final int ALL_INDEPENDENT = 0x08;
// Flag bit assignments
private static final int IS_SUPPORTED_BY_FEATURES = 0x10;
private static final int HAVE_SUPPORTED_BY_FEATURES = 0x20;
private static final int IS_IGNORE_IF_FEATURE = 0x40;
private static final int HAVE_IGNORE_IF_FEATURE = 0x80;
// Have-and-set flag constants, also used as masks
private static final int SET_SUPPORTED_BY_FEATURES = HAVE_SUPPORTED_BY_FEATURES | IS_SUPPORTED_BY_FEATURES;
private static final int SET_IGNORE_IF_FEATURE = HAVE_IGNORE_IF_FEATURE | IS_IGNORE_IF_FEATURE;
private static final EffectiveConfig[] EFFECTIVE_CONFIGS;
static {
final EffectiveConfig[] values = EffectiveConfig.values();
final int length = values.length;
verify(length == 4, "Unexpected EffectiveConfig cardinality %s", length);
EFFECTIVE_CONFIGS = values;
}
// Flags for use with SubstatementContext. These are hiding in the alignment shadow created by above boolean and
// hence improve memory layout.
private byte flags;
// Flag for use by AbstractResumedStatement, ReplicaStatementContext and InferredStatementContext. Each of them
// uses it to indicated a different condition. This is hiding in the alignment shadow created by
// 'isSupportedToBuildEffective'.
// FIXME: move this out once we have JDK15+
private boolean boolFlag;
ReactorStmtCtx() {
// Empty on purpose
}
ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original) {
isSupportedToBuildEffective = original.isSupportedToBuildEffective;
boolFlag = original.boolFlag;
flags = original.flags;
}
// Used by ReplicaStatementContext only
ReactorStmtCtx(final ReactorStmtCtx<A, D, E> original, final Void dummy) {
boolFlag = isSupportedToBuildEffective = original.isSupportedToBuildEffective;
flags = original.flags;
}
//
//
// Common public interface contracts with simple mechanics. Please keep this in one logical block, so we do not end
// up mixing concerns and simple details with more complex logic.
//
//
@Override
public abstract StatementContextBase<?, ?, ?> getParentContext();
@Override
public abstract RootStatementContext<?, ?, ?> getRoot();
@Override
public abstract Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements();
@Override
public final @NonNull Registry getBehaviourRegistry() {
return getRoot().getBehaviourRegistryImpl();
}
@Override
public final YangVersion yangVersion() {
return getRoot().getRootVersionImpl();
}
@Override
public final void setRootVersion(final YangVersion version) {
getRoot().setRootVersionImpl(version);
}
@Override
public final void addRequiredSource(final SourceIdentifier dependency) {
getRoot().addRequiredSourceImpl(dependency);
}
@Override
public final void setRootIdentifier(final SourceIdentifier identifier) {
getRoot().setRootIdentifierImpl(identifier);
}
@Override
public final ModelActionBuilder newInferenceAction(final ModelProcessingPhase phase) {
return getRoot().getSourceContext().newInferenceAction(phase);
}
@Override
public final StatementDefinition publicDefinition() {
return definition().getPublicView();
}
@Override
public final Parent effectiveParent() {
return getParentContext();
}
@Override
public final QName moduleName() {
final RootStatementContext<?, ?, ?> root = getRoot();
return QName.create(StmtContextUtils.getRootModuleQName(root), root.getRawArgument());
}
@Override
@Deprecated(since = "7.0.9", forRemoval = true)
public final EffectiveStatement<?, ?> original() {
return getOriginalCtx().map(StmtContext::buildEffective).orElse(null);
}
//
// In the next two methods we are looking for an effective statement. If we already have an effective instance,
// defer to it's implementation of the equivalent search. Otherwise we search our substatement contexts.
//
// Note that the search function is split, so as to allow InferredStatementContext to do its own thing first.
//
@Override
public final <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument(
final @NonNull Class<Z> type) {
final E existing = effectiveInstance();
return existing != null ? existing.findFirstEffectiveSubstatementArgument(type)
: findSubstatementArgumentImpl(type);
}
@Override
public final boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
final E existing = effectiveInstance();
return existing != null ? existing.findFirstEffectiveSubstatement(type).isPresent() : hasSubstatementImpl(type);
}
private E effectiveInstance() {
final Object existing = effectiveInstance;
return existing != null ? EffectiveInstances.local(existing) : null;
}
// Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
<X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgumentImpl(
final @NonNull Class<Z> type) {
return allSubstatementsStream()
.filter(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type))
.findAny()
.map(ctx -> (X) ctx.getArgument());
}
// Visible due to InferredStatementContext's override. At this point we do not have an effective instance available.
boolean hasSubstatementImpl(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) {
return allSubstatementsStream()
.anyMatch(ctx -> ctx.isSupportedToBuildEffective() && ctx.producesEffective(type));
}
@Override
@Deprecated
@SuppressWarnings("unchecked")
public final <Z extends EffectiveStatement<A, D>> StmtContext<A, D, Z> caerbannog() {
return (StmtContext<A, D, Z>) this;
}
@Override
public final String toString() {
return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
}
protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
return toStringHelper.add("definition", definition()).add("argument", argument()).add("refCount", refString());
}
private String refString() {
final int current = refcount;
switch (current) {
case REFCOUNT_DEFUNCT:
return "DEFUNCT";
case REFCOUNT_SWEEPING:
return "SWEEPING";
case REFCOUNT_SWEPT:
return "SWEPT";
default:
return String.valueOf(refcount);
}
}
/**
* Return the context in which this statement was defined.
*
* @return statement definition
*/
abstract @NonNull StatementDefinitionContext<A, D, E> definition();
//
//
// NamespaceStorageSupport/Mutable integration methods. Keep these together.
//
//
@Override
public final <K, V, T extends K, N extends ParserNamespace<K, V>> V namespaceItem(final Class<@NonNull N> type,
final T key) {
return getBehaviourRegistry().getNamespaceBehaviour(type).getFrom(this, key);
}
@Override
public final <K, V, N extends ParserNamespace<K, V>> Map<K, V> namespace(final Class<@NonNull N> type) {
return getNamespace(type);
}
@Override
public final <K, V, N extends ParserNamespace<K, V>>
Map<K, V> localNamespacePortion(final Class<@NonNull N> type) {
return getLocalNamespace(type);
}
@Override
protected <K, V, N extends ParserNamespace<K, V>> void onNamespaceElementAdded(final Class<N> type, final K key,
final V value) {
// definition().onNamespaceElementAdded(this, type, key, value);
}
/**
* Return the effective statement view of a copy operation. This method may return one of:
* <ul>
* <li>{@code this}, when the effective view did not change</li>
* <li>an InferredStatementContext, when there is a need for inference-equivalent copy</li>
* <li>{@code null}, when the statement failed to materialize</li>
* </ul>
*
* @param parent Proposed new parent
* @param type Copy operation type
* @param targetModule New target module
* @return {@link ReactorStmtCtx} holding effective view
*/
abstract @Nullable ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(StatementContextBase<?, ?, ?> parent, CopyType type,
QNameModule targetModule);
@Override
public final ReactorStmtCtx<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
}
abstract @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(@NonNull StatementContextBase<?, ?, ?> parent);
//
//
// Statement build entry points -- both public and package-private.
//
//
@Override
public final E buildEffective() {
final Object existing;
return (existing = effectiveInstance) != null ? EffectiveInstances.local(existing) : loadEffective();
}
private @NonNull E loadEffective() {
final E ret = createEffective();
effectiveInstance = ret;
// we have called createEffective(), substatements are no longer guarded by us. Let's see if we can clear up
// some residue.
if (refcount == REFCOUNT_NONE) {
sweepOnDecrement();
}
return ret;
}
abstract @NonNull E createEffective();
/**
* Attach an effective copy of this statement. This essentially acts as a map, where we make a few assumptions:
* <ul>
* <li>{@code copy} and {@code this} statement share {@link #getOriginalCtx()} if it exists</li>
* <li>{@code copy} did not modify any statements relative to {@code this}</li>
* </ul>
*
* @param state effective statement state, acting as a lookup key
* @param stmt New copy to append
* @return {@code stmt} or a previously-created instances with the same {@code state}
*/
@SuppressWarnings("unchecked")
final @NonNull E attachEffectiveCopy(final @NonNull EffectiveStatementState state, final @NonNull E stmt) {
final Object local = effectiveInstance;
final EffectiveInstances<E> instances;
if (local instanceof EffectiveInstances) {
instances = (EffectiveInstances<E>) local;
} else {
effectiveInstance = instances = new EffectiveInstances<>((E) local);
}
return instances.attachCopy(state, stmt);
}
/**
* Walk this statement's copy history and return the statement closest to original which has not had its effective
* statements modified. This statement and returned substatement logically have the same set of substatements, hence
* share substatement-derived state.
*
* @return Closest {@link ReactorStmtCtx} with equivalent effective substatements
*/
abstract @NonNull ReactorStmtCtx<A, D, E> unmodifiedEffectiveSource();
@Override
public final ModelProcessingPhase getCompletedPhase() {
return ModelProcessingPhase.ofExecutionOrder(executionOrder());
}
abstract byte executionOrder();
/**
* Try to execute current {@link ModelProcessingPhase} of source parsing. If the phase has already been executed,
* this method does nothing. This must not be called with {@link ExecutionOrder#NULL}.
*
* @param phase to be executed (completed)
* @return true if phase was successfully completed
* @throws SourceException when an error occurred in source parsing
*/
final boolean tryToCompletePhase(final byte executionOrder) {
return executionOrder() >= executionOrder || doTryToCompletePhase(executionOrder);
}
abstract boolean doTryToCompletePhase(byte targetOrder);
//
//
// Flags-based mechanics. These include public interfaces as well as all the crud we have lurking in our alignment
// shadow.
//
//
@Override
public final boolean isSupportedToBuildEffective() {
return isSupportedToBuildEffective;
}
@Override
public final void setUnsupported() {
this.isSupportedToBuildEffective = false;
}
@Override
public final boolean isSupportedByFeatures() {
final int fl = flags & SET_SUPPORTED_BY_FEATURES;
if (fl != 0) {
return fl == SET_SUPPORTED_BY_FEATURES;
}
if (isIgnoringIfFeatures()) {
flags |= SET_SUPPORTED_BY_FEATURES;
return true;
}
/*
* If parent is supported, we need to check if-features statements of this context.
*/
if (isParentSupportedByFeatures()) {
// If the set of supported features has not been provided, all features are supported by default.
final Set<QName> supportedFeatures = getFromNamespace(SupportedFeaturesNamespace.class, Empty.value());
if (supportedFeatures == null || StmtContextUtils.checkFeatureSupport(this, supportedFeatures)) {
flags |= SET_SUPPORTED_BY_FEATURES;
return true;
}
}
// Either parent is not supported or this statement is not supported
flags |= HAVE_SUPPORTED_BY_FEATURES;
return false;
}
protected abstract boolean isParentSupportedByFeatures();
/**
* Config statements are not all that common which means we are performing a recursive search towards the root
* every time {@link #effectiveConfig()} is invoked. This is quite expensive because it causes a linear search
* for the (usually non-existent) config statement.
*
* <p>
* This method maintains a resolution cache, so once we have returned a result, we will keep on returning the same
* result without performing any lookups, solely to support {@link #effectiveConfig()}.
*
* <p>
* Note: use of this method implies that {@link #isIgnoringConfig()} is realized with
* {@link #isIgnoringConfig(StatementContextBase)}.
*/
final @NonNull EffectiveConfig effectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
return (flags & HAVE_CONFIG) != 0 ? EFFECTIVE_CONFIGS[flags & MASK_CONFIG] : loadEffectiveConfig(parent);
}
private @NonNull EffectiveConfig loadEffectiveConfig(final ReactorStmtCtx<?, ?, ?> parent) {
final EffectiveConfig parentConfig = parent.effectiveConfig();
final EffectiveConfig myConfig;
if (parentConfig != EffectiveConfig.IGNORED && !definition().support().isIgnoringConfig()) {
final Optional<Boolean> optConfig = findSubstatementArgument(ConfigEffectiveStatement.class);
if (optConfig.isPresent()) {
if (optConfig.orElseThrow()) {
// Validity check: if parent is config=false this cannot be a config=true
InferenceException.throwIf(parentConfig == EffectiveConfig.FALSE, this,
"Parent node has config=false, this node must not be specifed as config=true");
myConfig = EffectiveConfig.TRUE;
} else {
myConfig = EffectiveConfig.FALSE;
}
} else {
// If "config" statement is not specified, the default is the same as the parent's "config" value.
myConfig = parentConfig;
}
} else {
myConfig = EffectiveConfig.IGNORED;
}
flags = (byte) (flags & ~MASK_CONFIG | HAVE_CONFIG | myConfig.ordinal());
return myConfig;
}
protected abstract boolean isIgnoringConfig();
/**
* This method maintains a resolution cache for ignore config, so once we have returned a result, we will
* keep on returning the same result without performing any lookups. Exists only to support
* {@link SubstatementContext#isIgnoringConfig()}.
*
* <p>
* Note: use of this method implies that {@link #isConfiguration()} is realized with
* {@link #effectiveConfig(StatementContextBase)}.
*/
final boolean isIgnoringConfig(final StatementContextBase<?, ?, ?> parent) {
return EffectiveConfig.IGNORED == effectiveConfig(parent);
}
protected abstract boolean isIgnoringIfFeatures();
/**
* This method maintains a resolution cache for ignore if-feature, so once we have returned a result, we will
* keep on returning the same result without performing any lookups. Exists only to support
* {@link SubstatementContext#isIgnoringIfFeatures()}.
*/
final boolean isIgnoringIfFeatures(final StatementContextBase<?, ?, ?> parent) {
final int fl = flags & SET_IGNORE_IF_FEATURE;
if (fl != 0) {
return fl == SET_IGNORE_IF_FEATURE;
}
if (definition().support().isIgnoringIfFeatures() || parent.isIgnoringIfFeatures()) {
flags |= SET_IGNORE_IF_FEATURE;
return true;
}
flags |= HAVE_IGNORE_IF_FEATURE;
return false;
}
// These two exist only due to memory optimization, should live in AbstractResumedStatement.
final boolean fullyDefined() {
return boolFlag;
}
final void setFullyDefined() {
boolFlag = true;
}
// This exists only due to memory optimization, should live in ReplicaStatementContext. In this context the flag
// indicates the need to drop source's reference count when we are being swept.
final boolean haveSourceReference() {
return boolFlag;
}
// These three exist due to memory optimization, should live in InferredStatementContext. In this context the flag
// indicates whether or not this statement's substatement file was modified, i.e. it is not quite the same as the
// prototype's file.
final boolean isModified() {
return boolFlag;
}
final void setModified() {
boolFlag = true;
}
final void setUnmodified() {
boolFlag = false;
}
// These two exist only for StatementContextBase. Since we are squeezed for size, with only a single bit available
// in flags, we default to 'false' and only set the flag to true when we are absolutely sure -- and all other cases
// err on the side of caution by taking the time to evaluate each substatement separately.
final boolean allSubstatementsContextIndependent() {
return (flags & ALL_INDEPENDENT) != 0;
}
final void setAllSubstatementsContextIndependent() {
flags |= ALL_INDEPENDENT;
}
//
//
// Various functionality from AbstractTypeStatementSupport. This used to work on top of SchemaPath, now it still
// lives here. Ultimate future is either proper graduation or (more likely) move to AbstractTypeStatementSupport.
//
//
@Override
public final QName argumentAsTypeQName() {
// FIXME: This may yield illegal argument exceptions
return StmtContextUtils.qnameFromArgument(getOriginalCtx().orElse(this), getRawArgument());
}
@Override
public final QNameModule effectiveNamespace() {
if (StmtContextUtils.isUnknownStatement(this)) {
return publicDefinition().getStatementName().getModule();
}
if (producesDeclared(UsesStatement.class)) {
return coerceParent().effectiveNamespace();
}
final Object argument = argument();
if (argument instanceof QName) {
return ((QName) argument).getModule();
}
if (argument instanceof String) {
// FIXME: This may yield illegal argument exceptions
return StmtContextUtils.qnameFromArgument(getOriginalCtx().orElse(this), (String) argument).getModule();
}
if (argument instanceof SchemaNodeIdentifier
&& (producesDeclared(AugmentStatement.class) || producesDeclared(RefineStatement.class)
|| producesDeclared(DeviationStatement.class))) {
return ((SchemaNodeIdentifier) argument).lastNodeIdentifier().getModule();
}
return coerceParent().effectiveNamespace();
}
private ReactorStmtCtx<?, ?, ?> coerceParent() {
return (ReactorStmtCtx<?, ?, ?>) coerceParentContext();
}
//
//
// Reference counting mechanics start. Please keep these methods in one block for clarity. Note this does not
// contribute to state visible outside of this package.
//
//
/**
* Local knowledge of {@link #refcount} values up to statement root. We use this field to prevent recursive lookups
* in {@link #noParentRefs(StatementContextBase)} -- once we discover a parent reference once, we keep that
* knowledge and update it when {@link #sweep()} is invoked.
*/
private byte parentRef = PARENTREF_UNKNOWN;
private static final byte PARENTREF_UNKNOWN = -1;
private static final byte PARENTREF_ABSENT = 0;
private static final byte PARENTREF_PRESENT = 1;
/**
* Acquire a reference on this context. As long as there is at least one reference outstanding,
* {@link #buildEffective()} will not result in {@link #effectiveSubstatements()} being discarded.
*
* @throws VerifyException if {@link #effectiveSubstatements()} has already been discarded
*/
final void incRef() {
final int current = refcount;
verify(current >= REFCOUNT_NONE, "Attempted to access reference count of %s", this);
if (current != REFCOUNT_DEFUNCT) {
// Note: can end up becoming REFCOUNT_DEFUNCT on overflow
refcount = current + 1;
} else {
LOG.debug("Disabled refcount increment of {}", this);
}
}
/**
* Release a reference on this context. This call may result in {@link #effectiveSubstatements()} becoming
* unavailable.
*/
final void decRef() {
final int current = refcount;
if (current == REFCOUNT_DEFUNCT) {
// no-op
LOG.debug("Disabled refcount decrement of {}", this);
return;
}
if (current <= REFCOUNT_NONE) {
// Underflow, become defunct
// FIXME: add a global 'warn once' flag
LOG.warn("Statement refcount underflow, reference counting disabled for {}", this, new Throwable());
refcount = REFCOUNT_DEFUNCT;
return;
}
refcount = current - 1;
LOG.trace("Refcount {} on {}", refcount, this);
if (refcount == REFCOUNT_NONE) {
lastDecRef();
}
}
/**
* Return {@code true} if this context has no outstanding references.
*
* @return True if this context has no outstanding references.
*/
final boolean noRefs() {
final int local = refcount;
return local < REFCOUNT_NONE || local == REFCOUNT_NONE && noParentRef();
}
private void lastDecRef() {
if (noImplictRef()) {
// We are no longer guarded by effective instance
sweepOnDecrement();
return;
}
final byte prevRefs = parentRef;
if (prevRefs == PARENTREF_ABSENT) {
// We are the last reference towards root, any children who observed PARENTREF_PRESENT from us need to be
// updated
markNoParentRef();
} else if (prevRefs == PARENTREF_UNKNOWN) {
// Noone observed our parentRef, just update it
loadParentRefcount();
}
}
static final void markNoParentRef(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
final byte prevRef = stmt.parentRef;
stmt.parentRef = PARENTREF_ABSENT;
if (prevRef == PARENTREF_PRESENT && stmt.refcount == REFCOUNT_NONE) {
// Child thinks it is pinned down, update its perspective
stmt.markNoParentRef();
}
}
}
abstract void markNoParentRef();
static final void sweep(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
stmt.sweep();
}
}
/**
* Sweep this statement context as a result of {@link #sweepSubstatements()}, i.e. when parent is also being swept.
*/
private void sweep() {
parentRef = PARENTREF_ABSENT;
if (refcount == REFCOUNT_NONE && noImplictRef()) {
LOG.trace("Releasing {}", this);
sweepState();
}
}
static final int countUnswept(final Collection<? extends ReactorStmtCtx<?, ?, ?>> substatements) {
int result = 0;
for (ReactorStmtCtx<?, ?, ?> stmt : substatements) {
if (stmt.refcount > REFCOUNT_NONE || !stmt.noImplictRef()) {
result++;
}
}
return result;
}
/**
* Implementation-specific sweep action. This is expected to perform a recursive {@link #sweep(Collection)} on all
* {@link #declaredSubstatements()} and {@link #effectiveSubstatements()} and report the result of the sweep
* operation.
*
* <p>
* {@link #effectiveSubstatements()} as well as namespaces may become inoperable as a result of this operation.
*
* @return True if the entire tree has been completely swept, false otherwise.
*/
abstract int sweepSubstatements();
// Called when this statement does not have an implicit reference and have reached REFCOUNT_NONE
private void sweepOnDecrement() {
LOG.trace("Sweeping on decrement {}", this);
if (noParentRef()) {
// No further parent references, sweep our state.
sweepState();
}
// Propagate towards parent if there is one
sweepParent();
}
private void sweepParent() {
final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
if (parent != null) {
parent.sweepOnChildDecrement();
}
}
// Called from child when it has lost its final reference
private void sweepOnChildDecrement() {
if (isAwaitingChildren()) {
// We are a child for which our parent is waiting. Notify it and we are done.
sweepOnChildDone();
return;
}
// Check parent reference count
final int refs = refcount;
if (refs > REFCOUNT_NONE || refs <= REFCOUNT_SWEEPING || !noImplictRef()) {
// No-op
return;
}
// parent is potentially reclaimable
if (noParentRef()) {
LOG.trace("Cleanup {} of parent {}", refs, this);
if (sweepState()) {
sweepParent();
}
}
}
private boolean noImplictRef() {
return effectiveInstance != null || !isSupportedToBuildEffective();
}
private boolean noParentRef() {
return parentRefcount() == PARENTREF_ABSENT;
}
private byte parentRefcount() {
final byte refs;
return (refs = parentRef) != PARENTREF_UNKNOWN ? refs : loadParentRefcount();
}
private byte loadParentRefcount() {
return parentRef = calculateParentRefcount();
}
private byte calculateParentRefcount() {
final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
if (parent == null) {
return PARENTREF_ABSENT;
}
// A slight wrinkle here is that our machinery handles only PRESENT -> ABSENT invalidation and we can reach here
// while inference is still ongoing and hence we may not have a complete picture about existing references. We
// could therefore end up caching an ABSENT result and then that information becoming stale as a new reference
// is introduced.
if (parent.executionOrder() < ExecutionOrder.EFFECTIVE_MODEL) {
return PARENTREF_UNKNOWN;
}
// There are three possibilities:
// - REFCOUNT_NONE, in which case we need to search next parent
// - negative (< REFCOUNT_NONE), meaning parent is in some stage of sweeping, hence it does not have
// a reference to us
// - positive (> REFCOUNT_NONE), meaning parent has an explicit refcount which is holding us down
final int refs = parent.refcount;
if (refs == REFCOUNT_NONE) {
return parent.parentRefcount();
}
return refs < REFCOUNT_NONE ? PARENTREF_ABSENT : PARENTREF_PRESENT;
}
private boolean isAwaitingChildren() {
return refcount > REFCOUNT_SWEEPING && refcount < REFCOUNT_NONE;
}
private void sweepOnChildDone() {
LOG.trace("Sweeping on child done {}", this);
final int current = refcount;
if (current >= REFCOUNT_NONE) {
// no-op, perhaps we want to handle some cases differently?
LOG.trace("Ignoring child sweep of {} for {}", this, current);
return;
}
verify(current != REFCOUNT_SWEPT, "Attempt to sweep a child of swept %s", this);
refcount = current + 1;
LOG.trace("Child refcount {}", refcount);
if (refcount == REFCOUNT_NONE) {
sweepDone();
final ReactorStmtCtx<?, ?, ?> parent = getParentContext();
LOG.trace("Propagating to parent {}", parent);
if (parent != null && parent.isAwaitingChildren()) {
parent.sweepOnChildDone();
}
}
}
private void sweepDone() {
LOG.trace("Sweep done for {}", this);
refcount = REFCOUNT_SWEPT;
sweepNamespaces();
}
private boolean sweepState() {
refcount = REFCOUNT_SWEEPING;
final int childRefs = sweepSubstatements();
if (childRefs == 0) {
sweepDone();
return true;
}
if (childRefs < 0 || childRefs >= REFCOUNT_DEFUNCT) {
// FIXME: add a global 'warn once' flag
LOG.warn("Negative child refcount {} cannot be stored, reference counting disabled for {}", childRefs, this,
new Throwable());
refcount = REFCOUNT_DEFUNCT;
} else {
LOG.trace("Still {} outstanding children of {}", childRefs, this);
refcount = -childRefs;
}
return false;
}
}
| Trigger onStatementAdded() for replicas
When a statement is introduced through StmtContext.replicaAsChildOf(),
the corresponding statement support should be notified of this fact, so
it can properly do its thing. This makes it consistent with
Mutable.childCopyOf().
JIRA: YANGTOOLS-1386
Change-Id: Ic947ea5fc822a29ff915d47db1cc591a2a18fd44
Signed-off-by: Robert Varga <[email protected]>
| parser/yang-parser-reactor/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/ReactorStmtCtx.java | Trigger onStatementAdded() for replicas | <ide><path>arser/yang-parser-reactor/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/ReactorStmtCtx.java
<ide> import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
<ide> import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStatementState;
<ide> import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
<add>import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Parent;
<ide> import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
<ide> import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
<ide> import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
<ide> QNameModule targetModule);
<ide>
<ide> @Override
<del> public final ReactorStmtCtx<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
<add> public final ReplicaStatementContext<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> parent) {
<ide> checkArgument(parent instanceof StatementContextBase, "Unsupported parent %s", parent);
<del> return replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
<add> final var ret = replicaAsChildOf((StatementContextBase<?, ?, ?>) parent);
<add> definition().onStatementAdded(ret);
<add> return ret;
<ide> }
<ide>
<ide> abstract @NonNull ReplicaStatementContext<A, D, E> replicaAsChildOf(@NonNull StatementContextBase<?, ?, ?> parent); |
|
Java | apache-2.0 | ebfe2a004bc091195fa9ae6d25a6b87827af861c | 0 | webbukkit/dynmap,KovuTheHusky/dynmap,webbukkit/dynmap,webbukkit/dynmap,mg-1999/dynmap,webbukkit/dynmap | package org.dynmap;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.CustomEventListener;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Type;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkPopulateEvent;
import org.bukkit.event.world.SpawnChangeEvent;
import org.bukkit.event.world.WorldListener;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.dynmap.debug.Debug;
import org.dynmap.debug.Debugger;
import org.dynmap.hdmap.HDBlockModels;
import org.dynmap.hdmap.TexturePack;
import org.dynmap.markers.MarkerAPI;
import org.dynmap.markers.impl.MarkerAPIImpl;
import org.dynmap.permissions.BukkitPermissions;
import org.dynmap.permissions.NijikokunPermissions;
import org.dynmap.permissions.OpPermissions;
import org.dynmap.permissions.PermissionProvider;
import org.dynmap.web.HttpServer;
import org.dynmap.web.handlers.ClientConfigurationHandler;
import org.dynmap.web.handlers.FilesystemHandler;
public class DynmapPlugin extends JavaPlugin {
public HttpServer webServer = null;
public MapManager mapManager = null;
public PlayerList playerList;
public ConfigurationNode configuration;
public HashSet<String> enabledTriggers = new HashSet<String>();
public PermissionProvider permissions;
public ComponentManager componentManager = new ComponentManager();
public PlayerFaces playerfacemgr;
public Events events = new Events();
public String deftemplatesuffix = "";
/* Flag to let code know that we're doing reload - make sure we don't double-register event handlers */
public boolean is_reload = false;
private boolean generate_only = false;
private static boolean ignore_chunk_loads = false; /* Flag keep us from processing our own chunk loads */
private HashMap<Event.Type, List<Listener>> event_handlers = new HashMap<Event.Type, List<Listener>>();
private MarkerAPIImpl markerapi;
public static File dataDirectory;
public static File tilesDirectory;
public MapManager getMapManager() {
return mapManager;
}
public HttpServer getWebServer() {
return webServer;
}
/* Add/Replace branches in configuration tree with contribution from a separate file */
@SuppressWarnings("unchecked")
private void mergeConfigurationBranch(ConfigurationNode cfgnode, String branch, boolean replace_existing, boolean islist) {
Object srcbranch = cfgnode.getObject(branch);
if(srcbranch == null)
return;
/* See if top branch is in configuration - if not, just add whole thing */
Object destbranch = configuration.getObject(branch);
if(destbranch == null) { /* Not found */
configuration.put(branch, srcbranch); /* Add new tree to configuration */
return;
}
/* If list, merge by "name" attribute */
if(islist) {
List<ConfigurationNode> dest = configuration.getNodes(branch);
List<ConfigurationNode> src = cfgnode.getNodes(branch);
/* Go through new records : see what to do with each */
for(ConfigurationNode node : src) {
String name = node.getString("name", null);
if(name == null) continue;
/* Walk destination - see if match */
boolean matched = false;
for(ConfigurationNode dnode : dest) {
String dname = dnode.getString("name", null);
if(dname == null) continue;
if(dname.equals(name)) { /* Match? */
if(replace_existing) {
dnode.clear();
dnode.putAll(node);
}
matched = true;
break;
}
}
/* If no match, add to end */
if(!matched) {
dest.add(node);
}
}
configuration.put(branch,dest);
}
/* If configuration node, merge by key */
else {
ConfigurationNode src = cfgnode.getNode(branch);
ConfigurationNode dest = configuration.getNode(branch);
for(String key : src.keySet()) { /* Check each contribution */
if(dest.containsKey(key)) { /* Exists? */
if(replace_existing) { /* If replacing, do so */
dest.put(key, src.getObject(key));
}
}
else { /* Else, always add if not there */
dest.put(key, src.getObject(key));
}
}
}
}
/* Table of default templates - all are resources in dynmap.jar unnder templates/, and go in templates directory when needed */
private static final String[] stdtemplates = { "normal.txt", "nether.txt", "skylands.txt", "normal-lowres.txt",
"nether-lowres.txt", "skylands-lowres.txt", "normal-hires.txt", "nether-hires.txt", "skylands-hires.txt"
};
private static final String CUSTOM_PREFIX = "custom-";
/* Load templates from template folder */
private void loadTemplates() {
File templatedir = new File(dataDirectory, "templates");
templatedir.mkdirs();
/* First, prime the templates directory with default standard templates, if needed */
for(String stdtemplate : stdtemplates) {
File f = new File(templatedir, stdtemplate);
createDefaultFileFromResource("/templates/" + stdtemplate, f);
}
/* Now process files */
String[] templates = templatedir.list();
/* Go through list - process all ones not starting with 'custom' first */
for(String tname: templates) {
/* If matches naming convention */
if(tname.endsWith(".txt") && (!tname.startsWith(CUSTOM_PREFIX))) {
File tf = new File(templatedir, tname);
org.bukkit.util.config.Configuration cfg = new org.bukkit.util.config.Configuration(tf);
cfg.load();
ConfigurationNode cn = new ConfigurationNode(cfg);
/* Supplement existing values (don't replace), since configuration.txt is more custom than these */
mergeConfigurationBranch(cn, "templates", false, false);
}
}
/* Go through list again - this time do custom- ones */
for(String tname: templates) {
/* If matches naming convention */
if(tname.endsWith(".txt") && tname.startsWith(CUSTOM_PREFIX)) {
File tf = new File(templatedir, tname);
org.bukkit.util.config.Configuration cfg = new org.bukkit.util.config.Configuration(tf);
cfg.load();
ConfigurationNode cn = new ConfigurationNode(cfg);
/* This are overrides - replace even configuration.txt content */
mergeConfigurationBranch(cn, "templates", true, false);
}
}
}
@Override
public void onEnable() {
/* Start with clean events */
events = new Events();
permissions = NijikokunPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = BukkitPermissions.create("dynmap");
if (permissions == null)
permissions = new OpPermissions(new String[] { "fullrender", "cancelrender", "radiusrender", "resetstats", "reload" });
dataDirectory = this.getDataFolder();
/* Load block models */
HDBlockModels.loadModels(dataDirectory);
/* Load texture mappings */
TexturePack.loadTextureMapping(dataDirectory);
/* Initialize confguration.txt if needed */
File f = new File(this.getDataFolder(), "configuration.txt");
if(!createDefaultFileFromResource("/configuration.txt", f)) {
this.setEnabled(false);
return;
}
/* Load configuration.txt */
org.bukkit.util.config.Configuration bukkitConfiguration = new org.bukkit.util.config.Configuration(f);
bukkitConfiguration.load();
configuration = new ConfigurationNode(bukkitConfiguration);
/* Now, process worlds.txt - merge it in as an override of existing values (since it is only user supplied values) */
f = new File(this.getDataFolder(), "worlds.txt");
if(!createDefaultFileFromResource("/worlds.txt", f)) {
this.setEnabled(false);
return;
}
org.bukkit.util.config.Configuration cfg = new org.bukkit.util.config.Configuration(f);
cfg.load();
ConfigurationNode cn = new ConfigurationNode(cfg);
mergeConfigurationBranch(cn, "worlds", true, true);
/* Now, process templates */
loadTemplates();
Log.verbose = configuration.getBoolean("verbose", true);
deftemplatesuffix = configuration.getString("deftemplatesuffix", "");
loadDebuggers();
tilesDirectory = getFile(configuration.getString("tilespath", "web/tiles"));
if (!tilesDirectory.isDirectory() && !tilesDirectory.mkdirs()) {
Log.warning("Could not create directory for tiles ('" + tilesDirectory + "').");
}
playerList = new PlayerList(getServer(), getFile("hiddenplayers.txt"), configuration);
playerList.load();
mapManager = new MapManager(this, configuration);
mapManager.startRendering();
playerfacemgr = new PlayerFaces(this);
loadWebserver();
enabledTriggers.clear();
List<String> triggers = configuration.getStrings("render-triggers", new ArrayList<String>());
if (triggers != null)
{
for (Object trigger : triggers) {
enabledTriggers.add((String) trigger);
}
}
// Load components.
for(Component component : configuration.<Component>createInstances("components", new Class<?>[] { DynmapPlugin.class }, new Object[] { this })) {
componentManager.add(component);
}
Log.verboseinfo("Loaded " + componentManager.components.size() + " components.");
registerEvents();
if (!configuration.getBoolean("disable-webserver", false)) {
startWebserver();
}
/* Print version info */
PluginDescriptionFile pdfFile = this.getDescription();
Log.info("version " + pdfFile.getVersion() + " is enabled" );
events.<Object>trigger("initialized", null);
}
public void loadWebserver() {
InetAddress bindAddress;
{
String address = configuration.getString("webserver-bindaddress", "0.0.0.0");
try {
bindAddress = address.equals("0.0.0.0")
? null
: InetAddress.getByName(address);
} catch (UnknownHostException e) {
bindAddress = null;
}
}
int port = configuration.getInteger("webserver-port", 8123);
boolean allow_symlinks = configuration.getBoolean("allow-symlinks", false);
boolean checkbannedips = configuration.getBoolean("check-banned-ips", true);
int maxconnections = configuration.getInteger("max-sessions", 30);
if(maxconnections < 2) maxconnections = 2;
/* Load customized response headers, if any */
ConfigurationNode custhttp = configuration.getNode("http-response-headers");
HashMap<String, String> custhdrs = new HashMap<String,String>();
if(custhttp != null) {
for(String k : custhttp.keySet()) {
String v = custhttp.getString(k);
if(v != null) {
custhdrs.put(k, v);
}
}
}
HttpServer.setCustomHeaders(custhdrs);
if(allow_symlinks)
Log.verboseinfo("Web server is permitting symbolic links");
else
Log.verboseinfo("Web server is not permitting symbolic links");
webServer = new HttpServer(bindAddress, port, checkbannedips, maxconnections);
webServer.handlers.put("/", new FilesystemHandler(getFile(configuration.getString("webpath", "web")), allow_symlinks));
webServer.handlers.put("/tiles/", new FilesystemHandler(tilesDirectory, allow_symlinks));
webServer.handlers.put("/up/configuration", new ClientConfigurationHandler(this));
}
public void startWebserver() {
try {
webServer.startServer();
} catch (IOException e) {
Log.severe("Failed to start WebServer on " + webServer.getAddress() + ":" + webServer.getPort() + "!");
}
}
@Override
public void onDisable() {
if (componentManager != null) {
int componentCount = componentManager.components.size();
for(Component component : componentManager.components) {
component.dispose();
}
componentManager.clear();
Log.info("Unloaded " + componentCount + " components.");
}
if (mapManager != null) {
mapManager.stopRendering();
mapManager = null;
}
if (webServer != null) {
webServer.shutdown();
webServer = null;
}
/* Clean up all registered handlers */
for(Event.Type t : event_handlers.keySet()) {
List<Listener> ll = event_handlers.get(t);
ll.clear(); /* Empty list - we use presence of list to remember that we've registered with Bukkit */
}
playerfacemgr = null;
if(markerapi != null) {
markerapi.cleanup(this);
markerapi = null;
}
Debug.clearDebuggers();
}
public boolean isTrigger(String s) {
return enabledTriggers.contains(s);
}
private boolean onplace;
private boolean onbreak;
private boolean onblockform;
private boolean onblockfade;
private boolean onblockspread;
private boolean onleaves;
private boolean onburn;
private boolean onpiston;
private boolean onplayerjoin;
private boolean onplayermove;
private boolean ongeneratechunk;
private boolean onloadchunk;
private boolean onexplosion;
public void registerEvents() {
BlockListener blockTrigger = new BlockListener() {
@Override
public void onBlockPlace(BlockPlaceEvent event) {
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onplace) {
mapManager.touch(loc);
}
}
@Override
public void onBlockBreak(BlockBreakEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onbreak) {
mapManager.touch(loc);
}
}
@Override
public void onLeavesDecay(LeavesDecayEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onleaves) {
mapManager.touch(loc);
}
}
@Override
public void onBlockBurn(BlockBurnEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onburn) {
mapManager.touch(loc);
}
}
@Override
public void onBlockForm(BlockFormEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onblockform) {
mapManager.touch(loc);
}
}
@Override
public void onBlockFade(BlockFadeEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onblockfade) {
mapManager.touch(loc);
}
}
@Override
public void onBlockSpread(BlockSpreadEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onblockspread) {
mapManager.touch(loc);
}
}
@Override
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if(event.isCancelled())
return;
Block b = event.getBlock();
Location loc = b.getLocation();
mapManager.sscache.invalidateSnapshot(loc);
BlockFace dir;
try { /* Workaround Bukkit bug = http://leaky.bukkit.org/issues/1227 */
dir = event.getDirection();
} catch (ClassCastException ccx) {
dir = BlockFace.NORTH;
}
if(onpiston) {
mapManager.touchVolume(loc, b.getRelative(dir, 2).getLocation());
}
for(int i = 0; i < 2; i++) {
b = b.getRelative(dir, 1);
mapManager.sscache.invalidateSnapshot(b.getLocation());
}
}
@Override
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if(event.isCancelled())
return;
Block b = event.getBlock();
Location loc = b.getLocation();
mapManager.sscache.invalidateSnapshot(loc);
BlockFace dir;
try { /* Workaround Bukkit bug = http://leaky.bukkit.org/issues/1227 */
dir = event.getDirection();
} catch (ClassCastException ccx) {
dir = BlockFace.NORTH;
}
if(onpiston) {
mapManager.touchVolume(loc, b.getRelative(dir, 1+event.getLength()).getLocation());
}
for(int i = 0; i < 1+event.getLength(); i++) {
b = b.getRelative(dir, 1);
mapManager.sscache.invalidateSnapshot(b.getLocation());
}
}
};
// To trigger rendering.
onplace = isTrigger("blockplaced");
registerEvent(Event.Type.BLOCK_PLACE, blockTrigger);
onbreak = isTrigger("blockbreak");
registerEvent(Event.Type.BLOCK_BREAK, blockTrigger);
if(isTrigger("snowform")) Log.info("The 'snowform' trigger has been deprecated due to Bukkit changes - use 'blockformed'");
onleaves = isTrigger("leavesdecay");
registerEvent(Event.Type.LEAVES_DECAY, blockTrigger);
onburn = isTrigger("blockburn");
registerEvent(Event.Type.BLOCK_BURN, blockTrigger);
onblockform = isTrigger("blockformed");
registerEvent(Event.Type.BLOCK_FORM, blockTrigger);
onblockfade = isTrigger("blockfaded");
registerEvent(Event.Type.BLOCK_FADE, blockTrigger);
onblockspread = isTrigger("blockspread");
registerEvent(Event.Type.BLOCK_SPREAD, blockTrigger);
onpiston = isTrigger("pistonmoved");
registerEvent(Event.Type.BLOCK_PISTON_EXTEND, blockTrigger);
registerEvent(Event.Type.BLOCK_PISTON_RETRACT, blockTrigger);
/* Register player event trigger handlers */
PlayerListener playerTrigger = new PlayerListener() {
@Override
public void onPlayerJoin(PlayerJoinEvent event) {
mapManager.touch(event.getPlayer().getLocation());
}
@Override
public void onPlayerMove(PlayerMoveEvent event) {
mapManager.touch(event.getPlayer().getLocation());
}
};
onplayerjoin = isTrigger("playerjoin");
onplayermove = isTrigger("playermove");
if(onplayerjoin)
registerEvent(Event.Type.PLAYER_JOIN, playerTrigger);
if(onplayermove)
registerEvent(Event.Type.PLAYER_MOVE, playerTrigger);
/* Register entity event triggers */
EntityListener entityTrigger = new EntityListener() {
@Override
public void onEntityExplode(EntityExplodeEvent event) {
List<Block> blocks = event.blockList();
for(Block b: blocks) {
Location loc = b.getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onexplosion) {
mapManager.touch(loc);
}
}
}
};
onexplosion = isTrigger("explosion");
registerEvent(Event.Type.ENTITY_EXPLODE, entityTrigger);
/* Register world event triggers */
WorldListener worldTrigger = new WorldListener() {
@Override
public void onChunkLoad(ChunkLoadEvent event) {
if(ignore_chunk_loads)
return;
/* Touch extreme corners */
int x = event.getChunk().getX() << 4;
int z = event.getChunk().getZ() << 4;
mapManager.touchVolume(new Location(event.getWorld(), x, 0, z), new Location(event.getWorld(), x+15, 127, z+15));
}
@Override
public void onChunkPopulate(ChunkPopulateEvent event) {
int x = event.getChunk().getX() << 4;
int z = event.getChunk().getZ() << 4;
mapManager.touchVolume(new Location(event.getWorld(), x, 0, z), new Location(event.getWorld(), x+15, 127, z+15));
}
@Override
public void onWorldLoad(WorldLoadEvent event) {
mapManager.activateWorld(event.getWorld());
}
};
ongeneratechunk = isTrigger("chunkgenerated");
if(ongeneratechunk) {
registerEvent(Event.Type.CHUNK_POPULATED, worldTrigger);
}
onloadchunk = isTrigger("chunkloaded");
if(onloadchunk) {
registerEvent(Event.Type.CHUNK_LOAD, worldTrigger);
}
// To link configuration to real loaded worlds.
registerEvent(Event.Type.WORLD_LOAD, worldTrigger);
}
private static File combinePaths(File parent, String path) {
return combinePaths(parent, new File(path));
}
private static File combinePaths(File parent, File path) {
if (path.isAbsolute())
return path;
return new File(parent, path.getPath());
}
public File getFile(String path) {
return combinePaths(getDataFolder(), path);
}
protected void loadDebuggers() {
List<ConfigurationNode> debuggersConfiguration = configuration.getNodes("debuggers");
Debug.clearDebuggers();
for (ConfigurationNode debuggerConfiguration : debuggersConfiguration) {
try {
Class<?> debuggerClass = Class.forName((String) debuggerConfiguration.getString("class"));
Constructor<?> constructor = debuggerClass.getConstructor(JavaPlugin.class, ConfigurationNode.class);
Debugger debugger = (Debugger) constructor.newInstance(this, debuggerConfiguration);
Debug.addDebugger(debugger);
} catch (Exception e) {
Log.severe("Error loading debugger: " + e);
e.printStackTrace();
continue;
}
}
}
private static final Set<String> commands = new HashSet<String>(Arrays.asList(new String[] {
"render",
"hide",
"show",
"fullrender",
"cancelrender",
"radiusrender",
"reload",
"stats",
"resetstats" }));
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if(cmd.getName().equalsIgnoreCase("dmarker")) {
return MarkerAPIImpl.onCommand(this, sender, cmd, commandLabel, args);
}
if (!cmd.getName().equalsIgnoreCase("dynmap"))
return false;
Player player = null;
if (sender instanceof Player)
player = (Player) sender;
if (args.length > 0) {
String c = args[0];
if (!commands.contains(c)) {
return false;
}
if (c.equals("render") && checkPlayerPermission(sender,"render")) {
if (player != null) {
int invalidates = mapManager.touch(player.getLocation());
sender.sendMessage("Queued " + invalidates + " tiles" + (invalidates == 0
? " (world is not loaded?)"
: "..."));
}
else {
sender.sendMessage("Command can only be issued by player.");
}
}
else if(c.equals("radiusrender") && checkPlayerPermission(sender,"radiusrender")) {
if (player != null) {
int radius = 0;
String mapname = null;
if(args.length > 1) {
radius = Integer.parseInt(args[1]); /* Parse radius */
if(radius < 0)
radius = 0;
if(args.length > 2)
mapname = args[2];
}
Location loc = player.getLocation();
if(loc != null)
mapManager.renderWorldRadius(loc, sender, mapname, radius);
}
else {
sender.sendMessage("Command can only be issued by player.");
}
} else if (c.equals("hide")) {
if (args.length == 1) {
if(player != null && checkPlayerPermission(sender,"hide.self")) {
playerList.setVisible(player.getName(),false);
sender.sendMessage("You are now hidden on Dynmap.");
}
} else if (checkPlayerPermission(sender,"hide.others")) {
for (int i = 1; i < args.length; i++) {
playerList.setVisible(args[i],false);
sender.sendMessage(args[i] + " is now hidden on Dynmap.");
}
}
} else if (c.equals("show")) {
if (args.length == 1) {
if(player != null && checkPlayerPermission(sender,"show.self")) {
playerList.setVisible(player.getName(),true);
sender.sendMessage("You are now visible on Dynmap.");
}
} else if (checkPlayerPermission(sender,"show.others")) {
for (int i = 1; i < args.length; i++) {
playerList.setVisible(args[i],true);
sender.sendMessage(args[i] + " is now visible on Dynmap.");
}
}
} else if (c.equals("fullrender") && checkPlayerPermission(sender,"fullrender")) {
String map = null;
if (args.length > 1) {
for (int i = 1; i < args.length; i++) {
int dot = args[i].indexOf(":");
DynmapWorld w;
String wname = args[i];
if(dot >= 0) {
wname = args[i].substring(0, dot);
map = args[i].substring(dot+1);
}
w = mapManager.getWorld(wname);
if(w != null) {
Location loc = new Location(w.world, w.configuration.getFloat("center/x", 0.0f), w.configuration.getFloat("center/y", 64f), w.configuration.getFloat("center/z", 0.0f));
mapManager.renderFullWorld(loc,sender, map);
}
else
sender.sendMessage("World '" + wname + "' not defined/loaded");
}
} else if (player != null) {
Location loc = player.getLocation();
if(args.length > 1)
map = args[1];
if(loc != null)
mapManager.renderFullWorld(loc, sender, map);
} else {
sender.sendMessage("World name is required");
}
} else if (c.equals("cancelrender") && checkPlayerPermission(sender,"cancelrender")) {
if (args.length > 1) {
for (int i = 1; i < args.length; i++) {
World w = getServer().getWorld(args[i]);
if(w != null)
mapManager.cancelRender(w,sender);
else
sender.sendMessage("World '" + args[i] + "' not defined/loaded");
}
} else if (player != null) {
Location loc = player.getLocation();
if(loc != null)
mapManager.cancelRender(loc.getWorld(), sender);
} else {
sender.sendMessage("World name is required");
}
} else if (c.equals("reload") && checkPlayerPermission(sender, "reload")) {
sender.sendMessage("Reloading Dynmap...");
reload();
sender.sendMessage("Dynmap reloaded");
} else if (c.equals("stats") && checkPlayerPermission(sender, "stats")) {
if(args.length == 1)
mapManager.printStats(sender, null);
else
mapManager.printStats(sender, args[1]);
} else if (c.equals("resetstats") && checkPlayerPermission(sender, "resetstats")) {
if(args.length == 1)
mapManager.resetStats(sender, null);
else
mapManager.resetStats(sender, args[1]);
}
return true;
}
return false;
}
public boolean checkPlayerPermission(CommandSender sender, String permission) {
if (!(sender instanceof Player) || sender.isOp()) {
return true;
} else if (!permissions.has(sender, permission.toLowerCase())) {
sender.sendMessage("You don't have permission to use this command!");
return false;
}
return true;
}
public ConfigurationNode getWorldConfiguration(World world) {
ConfigurationNode finalConfiguration = new ConfigurationNode();
finalConfiguration.put("name", world.getName());
finalConfiguration.put("title", world.getName());
ConfigurationNode worldConfiguration = getWorldConfigurationNode(world.getName());
// Get the template.
ConfigurationNode templateConfiguration = null;
if (worldConfiguration != null) {
String templateName = worldConfiguration.getString("template");
if (templateName != null) {
templateConfiguration = getTemplateConfigurationNode(templateName);
}
}
// Template not found, using default template.
if (templateConfiguration == null) {
templateConfiguration = getDefaultTemplateConfigurationNode(world);
}
// Merge the finalConfiguration, templateConfiguration and worldConfiguration.
finalConfiguration.extend(templateConfiguration);
finalConfiguration.extend(worldConfiguration);
Log.verboseinfo("Configuration of world " + world.getName());
for(Map.Entry<String, Object> e : finalConfiguration.entrySet()) {
Log.verboseinfo(e.getKey() + ": " + e.getValue());
}
return finalConfiguration;
}
private ConfigurationNode getDefaultTemplateConfigurationNode(World world) {
Environment environment = world.getEnvironment();
String environmentName = environment.name().toLowerCase();
if(deftemplatesuffix.length() > 0) {
environmentName += "-" + deftemplatesuffix;
}
Log.verboseinfo("Using environment as template: " + environmentName);
return getTemplateConfigurationNode(environmentName);
}
private ConfigurationNode getWorldConfigurationNode(String worldName) {
for(ConfigurationNode worldNode : configuration.getNodes("worlds")) {
if (worldName.equals(worldNode.getString("name"))) {
return worldNode;
}
}
return new ConfigurationNode();
}
private ConfigurationNode getTemplateConfigurationNode(String templateName) {
ConfigurationNode templatesNode = configuration.getNode("templates");
if (templatesNode != null) {
return templatesNode.getNode(templateName);
}
return null;
}
public void reload() {
PluginManager pluginManager = getServer().getPluginManager();
pluginManager.disablePlugin(this);
pluginManager.enablePlugin(this);
}
public String getWebPath() {
return configuration.getString("webpath", "web");
}
public static void setIgnoreChunkLoads(boolean ignore) {
ignore_chunk_loads = ignore;
}
/* Uses resource to create default file, if file does not yet exist */
public boolean createDefaultFileFromResource(String resourcename, File deffile) {
if(deffile.canRead())
return true;
Log.info(deffile.getPath() + " not found - creating default");
InputStream in = getClass().getResourceAsStream(resourcename);
if(in == null) {
Log.severe("Unable to find default resource - " + resourcename);
return false;
}
else {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(deffile);
byte[] buf = new byte[512];
int len;
while((len = in.read(buf)) > 0) {
fos.write(buf, 0, len);
}
} catch (IOException iox) {
Log.severe("ERROR creatomg default for " + deffile.getPath());
return false;
} finally {
if(fos != null)
try { fos.close(); } catch (IOException iox) {}
if(in != null)
try { in.close(); } catch (IOException iox) {}
}
return true;
}
}
private BlockListener ourBlockEventHandler = new BlockListener() {
@Override
public void onBlockPlace(BlockPlaceEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockPlace(event);
}
}
}
@Override
public void onBlockBreak(BlockBreakEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockBreak(event);
}
}
}
@Override
public void onLeavesDecay(LeavesDecayEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onLeavesDecay(event);
}
}
}
@Override
public void onBlockBurn(BlockBurnEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockBurn(event);
}
}
}
@Override
public void onBlockForm(BlockFormEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockForm(event);
}
}
}
@Override
public void onBlockFade(BlockFadeEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockFade(event);
}
}
}
@Override
public void onBlockSpread(BlockSpreadEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockSpread(event);
}
}
}
@Override
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockPistonRetract(event);
}
}
}
@Override
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockPistonExtend(event);
}
}
}
};
private PlayerListener ourPlayerEventHandler = new PlayerListener() {
@Override
public void onPlayerJoin(PlayerJoinEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((PlayerListener)l).onPlayerJoin(event);
}
}
}
@Override
public void onPlayerLogin(PlayerLoginEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((PlayerListener)l).onPlayerLogin(event);
}
}
}
@Override
public void onPlayerMove(PlayerMoveEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((PlayerListener)l).onPlayerMove(event);
}
}
}
@Override
public void onPlayerQuit(PlayerQuitEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((PlayerListener)l).onPlayerQuit(event);
}
}
}
@Override
public void onPlayerChat(PlayerChatEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((PlayerListener)l).onPlayerChat(event);
}
}
}
};
private WorldListener ourWorldEventHandler = new WorldListener() {
@Override
public void onWorldLoad(WorldLoadEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((WorldListener)l).onWorldLoad(event);
}
}
}
@Override
public void onChunkLoad(ChunkLoadEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((WorldListener)l).onChunkLoad(event);
}
}
}
@Override
public void onChunkPopulate(ChunkPopulateEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((WorldListener)l).onChunkPopulate(event);
}
}
}
@Override
public void onSpawnChange(SpawnChangeEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((WorldListener)l).onSpawnChange(event);
}
}
}
};
private CustomEventListener ourCustomEventHandler = new CustomEventListener() {
@Override
public void onCustomEvent(Event event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((CustomEventListener)l).onCustomEvent(event);
}
}
}
};
private EntityListener ourEntityEventHandler = new EntityListener() {
@Override
public void onEntityExplode(EntityExplodeEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((EntityListener)l).onEntityExplode(event);
}
}
}
};
/**
* Register event listener - this will be cleaned up properly on a /dynmap reload, unlike
* registering with Bukkit directly
*/
public void registerEvent(Event.Type type, Listener listener) {
List<Listener> ll = event_handlers.get(type);
PluginManager pm = getServer().getPluginManager();
if(ll == null) {
switch(type) { /* See if it is a type we're brokering */
case PLAYER_LOGIN:
case PLAYER_CHAT:
case PLAYER_JOIN:
case PLAYER_QUIT:
case PLAYER_MOVE:
pm.registerEvent(type, ourPlayerEventHandler, Event.Priority.Monitor, this);
break;
case BLOCK_PLACE:
case BLOCK_BREAK:
case LEAVES_DECAY:
case BLOCK_BURN:
case BLOCK_FORM:
case BLOCK_FADE:
case BLOCK_SPREAD:
case BLOCK_PISTON_EXTEND:
case BLOCK_PISTON_RETRACT:
pm.registerEvent(type, ourBlockEventHandler, Event.Priority.Monitor, this);
break;
case WORLD_LOAD:
case CHUNK_LOAD:
case CHUNK_POPULATED:
case SPAWN_CHANGE:
pm.registerEvent(type, ourWorldEventHandler, Event.Priority.Monitor, this);
break;
case CUSTOM_EVENT:
pm.registerEvent(type, ourCustomEventHandler, Event.Priority.Monitor, this);
break;
case ENTITY_EXPLODE:
pm.registerEvent(type, ourEntityEventHandler, Event.Priority.Monitor, this);
break;
default:
Log.severe("registerEvent() in DynmapPlugin does not handle " + type);
return;
}
ll = new ArrayList<Listener>();
event_handlers.put(type, ll); /* Add list for this event */
}
ll.add(listener);
}
/**
* ** This is the public API for other plugins to use for accessing the Marker API **
* This method can return null if the 'markers' component has not been configured -
* a warning message will be issued to the server.log in this event.
*
* @return MarkerAPI, or null if not configured
*/
public MarkerAPI getMarkerAPI() {
if(markerapi == null) {
Log.warning("Marker API has been requested, but is not enabled. Uncomment or add 'markers' component to configuration.txt.");
}
return markerapi;
}
/**
* Register markers API - used by component to supply marker API to plugin
*/
public void registerMarkerAPI(MarkerAPIImpl api) {
markerapi = api;
}
}
| src/main/java/org/dynmap/DynmapPlugin.java | package org.dynmap;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.CustomEventListener;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Type;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkPopulateEvent;
import org.bukkit.event.world.SpawnChangeEvent;
import org.bukkit.event.world.WorldListener;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.dynmap.debug.Debug;
import org.dynmap.debug.Debugger;
import org.dynmap.hdmap.HDBlockModels;
import org.dynmap.hdmap.TexturePack;
import org.dynmap.markers.MarkerAPI;
import org.dynmap.markers.impl.MarkerAPIImpl;
import org.dynmap.permissions.BukkitPermissions;
import org.dynmap.permissions.NijikokunPermissions;
import org.dynmap.permissions.OpPermissions;
import org.dynmap.permissions.PermissionProvider;
import org.dynmap.web.HttpServer;
import org.dynmap.web.handlers.ClientConfigurationHandler;
import org.dynmap.web.handlers.FilesystemHandler;
public class DynmapPlugin extends JavaPlugin {
public HttpServer webServer = null;
public MapManager mapManager = null;
public PlayerList playerList;
public ConfigurationNode configuration;
public HashSet<String> enabledTriggers = new HashSet<String>();
public PermissionProvider permissions;
public ComponentManager componentManager = new ComponentManager();
public PlayerFaces playerfacemgr;
public Events events = new Events();
public String deftemplatesuffix = "";
/* Flag to let code know that we're doing reload - make sure we don't double-register event handlers */
public boolean is_reload = false;
private boolean generate_only = false;
private static boolean ignore_chunk_loads = false; /* Flag keep us from processing our own chunk loads */
private HashMap<Event.Type, List<Listener>> event_handlers = new HashMap<Event.Type, List<Listener>>();
private MarkerAPIImpl markerapi;
public static File dataDirectory;
public static File tilesDirectory;
public MapManager getMapManager() {
return mapManager;
}
public HttpServer getWebServer() {
return webServer;
}
/* Add/Replace branches in configuration tree with contribution from a separate file */
@SuppressWarnings("unchecked")
private void mergeConfigurationBranch(ConfigurationNode cfgnode, String branch, boolean replace_existing, boolean islist) {
Object srcbranch = cfgnode.getObject(branch);
if(srcbranch == null)
return;
/* See if top branch is in configuration - if not, just add whole thing */
Object destbranch = configuration.getObject(branch);
if(destbranch == null) { /* Not found */
configuration.put(branch, srcbranch); /* Add new tree to configuration */
return;
}
/* If list, merge by "name" attribute */
if(islist) {
List<ConfigurationNode> dest = configuration.getNodes(branch);
List<ConfigurationNode> src = cfgnode.getNodes(branch);
/* Go through new records : see what to do with each */
for(ConfigurationNode node : src) {
String name = node.getString("name", null);
if(name == null) continue;
/* Walk destination - see if match */
boolean matched = false;
for(ConfigurationNode dnode : dest) {
String dname = dnode.getString("name", null);
if(dname == null) continue;
if(dname.equals(name)) { /* Match? */
if(replace_existing) {
dnode.clear();
dnode.putAll(node);
}
matched = true;
break;
}
}
/* If no match, add to end */
if(!matched) {
dest.add(node);
}
}
configuration.put(branch,dest);
}
/* If configuration node, merge by key */
else {
ConfigurationNode src = cfgnode.getNode(branch);
ConfigurationNode dest = configuration.getNode(branch);
for(String key : src.keySet()) { /* Check each contribution */
if(dest.containsKey(key)) { /* Exists? */
if(replace_existing) { /* If replacing, do so */
dest.put(key, src.getObject(key));
}
}
else { /* Else, always add if not there */
dest.put(key, src.getObject(key));
}
}
}
}
/* Table of default templates - all are resources in dynmap.jar unnder templates/, and go in templates directory when needed */
private static final String[] stdtemplates = { "normal.txt", "nether.txt", "skylands.txt", "normal-lowres.txt",
"nether-lowres.txt", "skylands-lowres.txt", "normal-hires.txt", "nether-hires.txt", "skylands-hires.txt"
};
private static final String CUSTOM_PREFIX = "custom-";
/* Load templates from template folder */
private void loadTemplates() {
File templatedir = new File(dataDirectory, "templates");
templatedir.mkdirs();
/* First, prime the templates directory with default standard templates, if needed */
for(String stdtemplate : stdtemplates) {
File f = new File(templatedir, stdtemplate);
createDefaultFileFromResource("/templates/" + stdtemplate, f);
}
/* Now process files */
String[] templates = templatedir.list();
/* Go through list - process all ones not starting with 'custom' first */
for(String tname: templates) {
/* If matches naming convention */
if(tname.endsWith(".txt") && (!tname.startsWith(CUSTOM_PREFIX))) {
File tf = new File(templatedir, tname);
org.bukkit.util.config.Configuration cfg = new org.bukkit.util.config.Configuration(tf);
cfg.load();
ConfigurationNode cn = new ConfigurationNode(cfg);
/* Supplement existing values (don't replace), since configuration.txt is more custom than these */
mergeConfigurationBranch(cn, "templates", false, false);
}
}
/* Go through list again - this time do custom- ones */
for(String tname: templates) {
/* If matches naming convention */
if(tname.endsWith(".txt") && tname.startsWith(CUSTOM_PREFIX)) {
File tf = new File(templatedir, tname);
org.bukkit.util.config.Configuration cfg = new org.bukkit.util.config.Configuration(tf);
cfg.load();
ConfigurationNode cn = new ConfigurationNode(cfg);
/* This are overrides - replace even configuration.txt content */
mergeConfigurationBranch(cn, "templates", true, false);
}
}
}
@Override
public void onEnable() {
/* Start with clean events */
events = new Events();
permissions = NijikokunPermissions.create(getServer(), "dynmap");
if (permissions == null)
permissions = BukkitPermissions.create("dynmap");
if (permissions == null)
permissions = new OpPermissions(new String[] { "fullrender", "cancelrender", "radiusrender", "resetstats", "reload" });
dataDirectory = this.getDataFolder();
/* Load block models */
HDBlockModels.loadModels(dataDirectory);
/* Load texture mappings */
TexturePack.loadTextureMapping(dataDirectory);
/* Initialize confguration.txt if needed */
File f = new File(this.getDataFolder(), "configuration.txt");
if(!createDefaultFileFromResource("/configuration.txt", f)) {
this.setEnabled(false);
return;
}
/* Load configuration.txt */
org.bukkit.util.config.Configuration bukkitConfiguration = new org.bukkit.util.config.Configuration(f);
bukkitConfiguration.load();
configuration = new ConfigurationNode(bukkitConfiguration);
/* Now, process worlds.txt - merge it in as an override of existing values (since it is only user supplied values) */
f = new File(this.getDataFolder(), "worlds.txt");
if(!createDefaultFileFromResource("/worlds.txt", f)) {
this.setEnabled(false);
return;
}
org.bukkit.util.config.Configuration cfg = new org.bukkit.util.config.Configuration(f);
cfg.load();
ConfigurationNode cn = new ConfigurationNode(cfg);
mergeConfigurationBranch(cn, "worlds", true, true);
/* Now, process templates */
loadTemplates();
Log.verbose = configuration.getBoolean("verbose", true);
deftemplatesuffix = configuration.getString("deftemplatesuffix", "");
loadDebuggers();
tilesDirectory = getFile(configuration.getString("tilespath", "web/tiles"));
if (!tilesDirectory.isDirectory() && !tilesDirectory.mkdirs()) {
Log.warning("Could not create directory for tiles ('" + tilesDirectory + "').");
}
playerList = new PlayerList(getServer(), getFile("hiddenplayers.txt"), configuration);
playerList.load();
mapManager = new MapManager(this, configuration);
mapManager.startRendering();
playerfacemgr = new PlayerFaces(this);
loadWebserver();
enabledTriggers.clear();
List<String> triggers = configuration.getStrings("render-triggers", new ArrayList<String>());
if (triggers != null)
{
for (Object trigger : triggers) {
enabledTriggers.add((String) trigger);
}
}
// Load components.
for(Component component : configuration.<Component>createInstances("components", new Class<?>[] { DynmapPlugin.class }, new Object[] { this })) {
componentManager.add(component);
}
Log.verboseinfo("Loaded " + componentManager.components.size() + " components.");
registerEvents();
if (!configuration.getBoolean("disable-webserver", false)) {
startWebserver();
}
/* Print version info */
PluginDescriptionFile pdfFile = this.getDescription();
Log.info("version " + pdfFile.getVersion() + " is enabled" );
events.<Object>trigger("initialized", null);
}
public void loadWebserver() {
InetAddress bindAddress;
{
String address = configuration.getString("webserver-bindaddress", "0.0.0.0");
try {
bindAddress = address.equals("0.0.0.0")
? null
: InetAddress.getByName(address);
} catch (UnknownHostException e) {
bindAddress = null;
}
}
int port = configuration.getInteger("webserver-port", 8123);
boolean allow_symlinks = configuration.getBoolean("allow-symlinks", false);
boolean checkbannedips = configuration.getBoolean("check-banned-ips", true);
int maxconnections = configuration.getInteger("max-sessions", 30);
if(maxconnections < 2) maxconnections = 2;
/* Load customized response headers, if any */
ConfigurationNode custhttp = configuration.getNode("http-response-headers");
HashMap<String, String> custhdrs = new HashMap<String,String>();
if(custhttp != null) {
for(String k : custhttp.keySet()) {
String v = custhttp.getString(k);
if(v != null) {
custhdrs.put(k, v);
}
}
}
HttpServer.setCustomHeaders(custhdrs);
if(allow_symlinks)
Log.verboseinfo("Web server is permitting symbolic links");
else
Log.verboseinfo("Web server is not permitting symbolic links");
webServer = new HttpServer(bindAddress, port, checkbannedips, maxconnections);
webServer.handlers.put("/", new FilesystemHandler(getFile(configuration.getString("webpath", "web")), allow_symlinks));
webServer.handlers.put("/tiles/", new FilesystemHandler(tilesDirectory, allow_symlinks));
webServer.handlers.put("/up/configuration", new ClientConfigurationHandler(this));
}
public void startWebserver() {
try {
webServer.startServer();
} catch (IOException e) {
Log.severe("Failed to start WebServer on " + webServer.getAddress() + ":" + webServer.getPort() + "!");
}
}
@Override
public void onDisable() {
if (componentManager != null) {
int componentCount = componentManager.components.size();
for(Component component : componentManager.components) {
component.dispose();
}
componentManager.clear();
Log.info("Unloaded " + componentCount + " components.");
}
if (mapManager != null) {
mapManager.stopRendering();
mapManager = null;
}
if (webServer != null) {
webServer.shutdown();
webServer = null;
}
/* Clean up all registered handlers */
for(Event.Type t : event_handlers.keySet()) {
List<Listener> ll = event_handlers.get(t);
ll.clear(); /* Empty list - we use presence of list to remember that we've registered with Bukkit */
}
playerfacemgr = null;
if(markerapi != null) {
markerapi.cleanup(this);
markerapi = null;
}
Debug.clearDebuggers();
}
public boolean isTrigger(String s) {
return enabledTriggers.contains(s);
}
private boolean onplace;
private boolean onbreak;
private boolean onblockform;
private boolean onblockfade;
private boolean onblockspread;
private boolean onleaves;
private boolean onburn;
private boolean onpiston;
private boolean onplayerjoin;
private boolean onplayermove;
private boolean ongeneratechunk;
private boolean onloadchunk;
private boolean onexplosion;
public void registerEvents() {
BlockListener blockTrigger = new BlockListener() {
@Override
public void onBlockPlace(BlockPlaceEvent event) {
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onplace) {
mapManager.touch(loc);
}
}
@Override
public void onBlockBreak(BlockBreakEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onbreak) {
mapManager.touch(loc);
}
}
@Override
public void onLeavesDecay(LeavesDecayEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onleaves) {
mapManager.touch(loc);
}
}
@Override
public void onBlockBurn(BlockBurnEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onburn) {
mapManager.touch(loc);
}
}
@Override
public void onBlockForm(BlockFormEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onblockform) {
mapManager.touch(loc);
}
}
@Override
public void onBlockFade(BlockFadeEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onblockfade) {
mapManager.touch(loc);
}
}
@Override
public void onBlockSpread(BlockSpreadEvent event) {
if(event.isCancelled())
return;
Location loc = event.getBlock().getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onblockspread) {
mapManager.touch(loc);
}
}
@Override
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if(event.isCancelled())
return;
Block b = event.getBlock();
Location loc = b.getLocation();
mapManager.sscache.invalidateSnapshot(loc);
BlockFace dir;
try { /* Workaround Bukkit bug = http://leaky.bukkit.org/issues/1227 */
dir = event.getDirection();
} catch (ClassCastException ccx) {
dir = BlockFace.NORTH;
}
if(onpiston) {
mapManager.touchVolume(loc, b.getRelative(dir, 2).getLocation());
}
for(int i = 0; i < 2; i++) {
b = b.getRelative(dir, 1);
mapManager.sscache.invalidateSnapshot(b.getLocation());
}
}
@Override
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if(event.isCancelled())
return;
Block b = event.getBlock();
/* Avoid bogus piston events from Bukkit */
if((b.getType() != Material.PISTON_BASE) && (b.getType() != Material.PISTON_STICKY_BASE))
return;
Location loc = b.getLocation();
mapManager.sscache.invalidateSnapshot(loc);
BlockFace dir;
try { /* Workaround Bukkit bug = http://leaky.bukkit.org/issues/1227 */
dir = event.getDirection();
} catch (ClassCastException ccx) {
dir = BlockFace.NORTH;
}
if(onpiston) {
mapManager.touchVolume(loc, b.getRelative(dir, 1+event.getLength()).getLocation());
}
for(int i = 0; i < 1+event.getLength(); i++) {
b = b.getRelative(dir, 1);
mapManager.sscache.invalidateSnapshot(b.getLocation());
}
}
};
// To trigger rendering.
onplace = isTrigger("blockplaced");
registerEvent(Event.Type.BLOCK_PLACE, blockTrigger);
onbreak = isTrigger("blockbreak");
registerEvent(Event.Type.BLOCK_BREAK, blockTrigger);
if(isTrigger("snowform")) Log.info("The 'snowform' trigger has been deprecated due to Bukkit changes - use 'blockformed'");
onleaves = isTrigger("leavesdecay");
registerEvent(Event.Type.LEAVES_DECAY, blockTrigger);
onburn = isTrigger("blockburn");
registerEvent(Event.Type.BLOCK_BURN, blockTrigger);
onblockform = isTrigger("blockformed");
registerEvent(Event.Type.BLOCK_FORM, blockTrigger);
onblockfade = isTrigger("blockfaded");
registerEvent(Event.Type.BLOCK_FADE, blockTrigger);
onblockspread = isTrigger("blockspread");
registerEvent(Event.Type.BLOCK_SPREAD, blockTrigger);
onpiston = isTrigger("pistonmoved");
registerEvent(Event.Type.BLOCK_PISTON_EXTEND, blockTrigger);
registerEvent(Event.Type.BLOCK_PISTON_RETRACT, blockTrigger);
/* Register player event trigger handlers */
PlayerListener playerTrigger = new PlayerListener() {
@Override
public void onPlayerJoin(PlayerJoinEvent event) {
mapManager.touch(event.getPlayer().getLocation());
}
@Override
public void onPlayerMove(PlayerMoveEvent event) {
mapManager.touch(event.getPlayer().getLocation());
}
};
onplayerjoin = isTrigger("playerjoin");
onplayermove = isTrigger("playermove");
if(onplayerjoin)
registerEvent(Event.Type.PLAYER_JOIN, playerTrigger);
if(onplayermove)
registerEvent(Event.Type.PLAYER_MOVE, playerTrigger);
/* Register entity event triggers */
EntityListener entityTrigger = new EntityListener() {
@Override
public void onEntityExplode(EntityExplodeEvent event) {
List<Block> blocks = event.blockList();
for(Block b: blocks) {
Location loc = b.getLocation();
mapManager.sscache.invalidateSnapshot(loc);
if(onexplosion) {
mapManager.touch(loc);
}
}
}
};
onexplosion = isTrigger("explosion");
registerEvent(Event.Type.ENTITY_EXPLODE, entityTrigger);
/* Register world event triggers */
WorldListener worldTrigger = new WorldListener() {
@Override
public void onChunkLoad(ChunkLoadEvent event) {
if(ignore_chunk_loads)
return;
/* Touch extreme corners */
int x = event.getChunk().getX() << 4;
int z = event.getChunk().getZ() << 4;
mapManager.touchVolume(new Location(event.getWorld(), x, 0, z), new Location(event.getWorld(), x+15, 127, z+15));
}
@Override
public void onChunkPopulate(ChunkPopulateEvent event) {
int x = event.getChunk().getX() << 4;
int z = event.getChunk().getZ() << 4;
mapManager.touchVolume(new Location(event.getWorld(), x, 0, z), new Location(event.getWorld(), x+15, 127, z+15));
}
@Override
public void onWorldLoad(WorldLoadEvent event) {
mapManager.activateWorld(event.getWorld());
}
};
ongeneratechunk = isTrigger("chunkgenerated");
if(ongeneratechunk) {
registerEvent(Event.Type.CHUNK_POPULATED, worldTrigger);
}
onloadchunk = isTrigger("chunkloaded");
if(onloadchunk) {
registerEvent(Event.Type.CHUNK_LOAD, worldTrigger);
}
// To link configuration to real loaded worlds.
registerEvent(Event.Type.WORLD_LOAD, worldTrigger);
}
private static File combinePaths(File parent, String path) {
return combinePaths(parent, new File(path));
}
private static File combinePaths(File parent, File path) {
if (path.isAbsolute())
return path;
return new File(parent, path.getPath());
}
public File getFile(String path) {
return combinePaths(getDataFolder(), path);
}
protected void loadDebuggers() {
List<ConfigurationNode> debuggersConfiguration = configuration.getNodes("debuggers");
Debug.clearDebuggers();
for (ConfigurationNode debuggerConfiguration : debuggersConfiguration) {
try {
Class<?> debuggerClass = Class.forName((String) debuggerConfiguration.getString("class"));
Constructor<?> constructor = debuggerClass.getConstructor(JavaPlugin.class, ConfigurationNode.class);
Debugger debugger = (Debugger) constructor.newInstance(this, debuggerConfiguration);
Debug.addDebugger(debugger);
} catch (Exception e) {
Log.severe("Error loading debugger: " + e);
e.printStackTrace();
continue;
}
}
}
private static final Set<String> commands = new HashSet<String>(Arrays.asList(new String[] {
"render",
"hide",
"show",
"fullrender",
"cancelrender",
"radiusrender",
"reload",
"stats",
"resetstats" }));
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if(cmd.getName().equalsIgnoreCase("dmarker")) {
return MarkerAPIImpl.onCommand(this, sender, cmd, commandLabel, args);
}
if (!cmd.getName().equalsIgnoreCase("dynmap"))
return false;
Player player = null;
if (sender instanceof Player)
player = (Player) sender;
if (args.length > 0) {
String c = args[0];
if (!commands.contains(c)) {
return false;
}
if (c.equals("render") && checkPlayerPermission(sender,"render")) {
if (player != null) {
int invalidates = mapManager.touch(player.getLocation());
sender.sendMessage("Queued " + invalidates + " tiles" + (invalidates == 0
? " (world is not loaded?)"
: "..."));
}
else {
sender.sendMessage("Command can only be issued by player.");
}
}
else if(c.equals("radiusrender") && checkPlayerPermission(sender,"radiusrender")) {
if (player != null) {
int radius = 0;
String mapname = null;
if(args.length > 1) {
radius = Integer.parseInt(args[1]); /* Parse radius */
if(radius < 0)
radius = 0;
if(args.length > 2)
mapname = args[2];
}
Location loc = player.getLocation();
if(loc != null)
mapManager.renderWorldRadius(loc, sender, mapname, radius);
}
else {
sender.sendMessage("Command can only be issued by player.");
}
} else if (c.equals("hide")) {
if (args.length == 1) {
if(player != null && checkPlayerPermission(sender,"hide.self")) {
playerList.setVisible(player.getName(),false);
sender.sendMessage("You are now hidden on Dynmap.");
}
} else if (checkPlayerPermission(sender,"hide.others")) {
for (int i = 1; i < args.length; i++) {
playerList.setVisible(args[i],false);
sender.sendMessage(args[i] + " is now hidden on Dynmap.");
}
}
} else if (c.equals("show")) {
if (args.length == 1) {
if(player != null && checkPlayerPermission(sender,"show.self")) {
playerList.setVisible(player.getName(),true);
sender.sendMessage("You are now visible on Dynmap.");
}
} else if (checkPlayerPermission(sender,"show.others")) {
for (int i = 1; i < args.length; i++) {
playerList.setVisible(args[i],true);
sender.sendMessage(args[i] + " is now visible on Dynmap.");
}
}
} else if (c.equals("fullrender") && checkPlayerPermission(sender,"fullrender")) {
String map = null;
if (args.length > 1) {
for (int i = 1; i < args.length; i++) {
int dot = args[i].indexOf(":");
DynmapWorld w;
String wname = args[i];
if(dot >= 0) {
wname = args[i].substring(0, dot);
map = args[i].substring(dot+1);
}
w = mapManager.getWorld(wname);
if(w != null) {
Location loc = new Location(w.world, w.configuration.getFloat("center/x", 0.0f), w.configuration.getFloat("center/y", 64f), w.configuration.getFloat("center/z", 0.0f));
mapManager.renderFullWorld(loc,sender, map);
}
else
sender.sendMessage("World '" + wname + "' not defined/loaded");
}
} else if (player != null) {
Location loc = player.getLocation();
if(args.length > 1)
map = args[1];
if(loc != null)
mapManager.renderFullWorld(loc, sender, map);
} else {
sender.sendMessage("World name is required");
}
} else if (c.equals("cancelrender") && checkPlayerPermission(sender,"cancelrender")) {
if (args.length > 1) {
for (int i = 1; i < args.length; i++) {
World w = getServer().getWorld(args[i]);
if(w != null)
mapManager.cancelRender(w,sender);
else
sender.sendMessage("World '" + args[i] + "' not defined/loaded");
}
} else if (player != null) {
Location loc = player.getLocation();
if(loc != null)
mapManager.cancelRender(loc.getWorld(), sender);
} else {
sender.sendMessage("World name is required");
}
} else if (c.equals("reload") && checkPlayerPermission(sender, "reload")) {
sender.sendMessage("Reloading Dynmap...");
reload();
sender.sendMessage("Dynmap reloaded");
} else if (c.equals("stats") && checkPlayerPermission(sender, "stats")) {
if(args.length == 1)
mapManager.printStats(sender, null);
else
mapManager.printStats(sender, args[1]);
} else if (c.equals("resetstats") && checkPlayerPermission(sender, "resetstats")) {
if(args.length == 1)
mapManager.resetStats(sender, null);
else
mapManager.resetStats(sender, args[1]);
}
return true;
}
return false;
}
public boolean checkPlayerPermission(CommandSender sender, String permission) {
if (!(sender instanceof Player) || sender.isOp()) {
return true;
} else if (!permissions.has(sender, permission.toLowerCase())) {
sender.sendMessage("You don't have permission to use this command!");
return false;
}
return true;
}
public ConfigurationNode getWorldConfiguration(World world) {
ConfigurationNode finalConfiguration = new ConfigurationNode();
finalConfiguration.put("name", world.getName());
finalConfiguration.put("title", world.getName());
ConfigurationNode worldConfiguration = getWorldConfigurationNode(world.getName());
// Get the template.
ConfigurationNode templateConfiguration = null;
if (worldConfiguration != null) {
String templateName = worldConfiguration.getString("template");
if (templateName != null) {
templateConfiguration = getTemplateConfigurationNode(templateName);
}
}
// Template not found, using default template.
if (templateConfiguration == null) {
templateConfiguration = getDefaultTemplateConfigurationNode(world);
}
// Merge the finalConfiguration, templateConfiguration and worldConfiguration.
finalConfiguration.extend(templateConfiguration);
finalConfiguration.extend(worldConfiguration);
Log.verboseinfo("Configuration of world " + world.getName());
for(Map.Entry<String, Object> e : finalConfiguration.entrySet()) {
Log.verboseinfo(e.getKey() + ": " + e.getValue());
}
return finalConfiguration;
}
private ConfigurationNode getDefaultTemplateConfigurationNode(World world) {
Environment environment = world.getEnvironment();
String environmentName = environment.name().toLowerCase();
if(deftemplatesuffix.length() > 0) {
environmentName += "-" + deftemplatesuffix;
}
Log.verboseinfo("Using environment as template: " + environmentName);
return getTemplateConfigurationNode(environmentName);
}
private ConfigurationNode getWorldConfigurationNode(String worldName) {
for(ConfigurationNode worldNode : configuration.getNodes("worlds")) {
if (worldName.equals(worldNode.getString("name"))) {
return worldNode;
}
}
return new ConfigurationNode();
}
private ConfigurationNode getTemplateConfigurationNode(String templateName) {
ConfigurationNode templatesNode = configuration.getNode("templates");
if (templatesNode != null) {
return templatesNode.getNode(templateName);
}
return null;
}
public void reload() {
PluginManager pluginManager = getServer().getPluginManager();
pluginManager.disablePlugin(this);
pluginManager.enablePlugin(this);
}
public String getWebPath() {
return configuration.getString("webpath", "web");
}
public static void setIgnoreChunkLoads(boolean ignore) {
ignore_chunk_loads = ignore;
}
/* Uses resource to create default file, if file does not yet exist */
public boolean createDefaultFileFromResource(String resourcename, File deffile) {
if(deffile.canRead())
return true;
Log.info(deffile.getPath() + " not found - creating default");
InputStream in = getClass().getResourceAsStream(resourcename);
if(in == null) {
Log.severe("Unable to find default resource - " + resourcename);
return false;
}
else {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(deffile);
byte[] buf = new byte[512];
int len;
while((len = in.read(buf)) > 0) {
fos.write(buf, 0, len);
}
} catch (IOException iox) {
Log.severe("ERROR creatomg default for " + deffile.getPath());
return false;
} finally {
if(fos != null)
try { fos.close(); } catch (IOException iox) {}
if(in != null)
try { in.close(); } catch (IOException iox) {}
}
return true;
}
}
private BlockListener ourBlockEventHandler = new BlockListener() {
@Override
public void onBlockPlace(BlockPlaceEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockPlace(event);
}
}
}
@Override
public void onBlockBreak(BlockBreakEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockBreak(event);
}
}
}
@Override
public void onLeavesDecay(LeavesDecayEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onLeavesDecay(event);
}
}
}
@Override
public void onBlockBurn(BlockBurnEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockBurn(event);
}
}
}
@Override
public void onBlockForm(BlockFormEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockForm(event);
}
}
}
@Override
public void onBlockFade(BlockFadeEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockFade(event);
}
}
}
@Override
public void onBlockSpread(BlockSpreadEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockSpread(event);
}
}
}
@Override
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockPistonRetract(event);
}
}
}
@Override
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((BlockListener)l).onBlockPistonExtend(event);
}
}
}
};
private PlayerListener ourPlayerEventHandler = new PlayerListener() {
@Override
public void onPlayerJoin(PlayerJoinEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((PlayerListener)l).onPlayerJoin(event);
}
}
}
@Override
public void onPlayerLogin(PlayerLoginEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((PlayerListener)l).onPlayerLogin(event);
}
}
}
@Override
public void onPlayerMove(PlayerMoveEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((PlayerListener)l).onPlayerMove(event);
}
}
}
@Override
public void onPlayerQuit(PlayerQuitEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((PlayerListener)l).onPlayerQuit(event);
}
}
}
@Override
public void onPlayerChat(PlayerChatEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((PlayerListener)l).onPlayerChat(event);
}
}
}
};
private WorldListener ourWorldEventHandler = new WorldListener() {
@Override
public void onWorldLoad(WorldLoadEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((WorldListener)l).onWorldLoad(event);
}
}
}
@Override
public void onChunkLoad(ChunkLoadEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((WorldListener)l).onChunkLoad(event);
}
}
}
@Override
public void onChunkPopulate(ChunkPopulateEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((WorldListener)l).onChunkPopulate(event);
}
}
}
@Override
public void onSpawnChange(SpawnChangeEvent event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((WorldListener)l).onSpawnChange(event);
}
}
}
};
private CustomEventListener ourCustomEventHandler = new CustomEventListener() {
@Override
public void onCustomEvent(Event event) {
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((CustomEventListener)l).onCustomEvent(event);
}
}
}
};
private EntityListener ourEntityEventHandler = new EntityListener() {
@Override
public void onEntityExplode(EntityExplodeEvent event) {
if(event.isCancelled())
return;
/* Call listeners */
List<Listener> ll = event_handlers.get(event.getType());
if(ll != null) {
for(Listener l : ll) {
((EntityListener)l).onEntityExplode(event);
}
}
}
};
/**
* Register event listener - this will be cleaned up properly on a /dynmap reload, unlike
* registering with Bukkit directly
*/
public void registerEvent(Event.Type type, Listener listener) {
List<Listener> ll = event_handlers.get(type);
PluginManager pm = getServer().getPluginManager();
if(ll == null) {
switch(type) { /* See if it is a type we're brokering */
case PLAYER_LOGIN:
case PLAYER_CHAT:
case PLAYER_JOIN:
case PLAYER_QUIT:
case PLAYER_MOVE:
pm.registerEvent(type, ourPlayerEventHandler, Event.Priority.Monitor, this);
break;
case BLOCK_PLACE:
case BLOCK_BREAK:
case LEAVES_DECAY:
case BLOCK_BURN:
case BLOCK_FORM:
case BLOCK_FADE:
case BLOCK_SPREAD:
case BLOCK_PISTON_EXTEND:
case BLOCK_PISTON_RETRACT:
pm.registerEvent(type, ourBlockEventHandler, Event.Priority.Monitor, this);
break;
case WORLD_LOAD:
case CHUNK_LOAD:
case CHUNK_POPULATED:
case SPAWN_CHANGE:
pm.registerEvent(type, ourWorldEventHandler, Event.Priority.Monitor, this);
break;
case CUSTOM_EVENT:
pm.registerEvent(type, ourCustomEventHandler, Event.Priority.Monitor, this);
break;
case ENTITY_EXPLODE:
pm.registerEvent(type, ourEntityEventHandler, Event.Priority.Monitor, this);
break;
default:
Log.severe("registerEvent() in DynmapPlugin does not handle " + type);
return;
}
ll = new ArrayList<Listener>();
event_handlers.put(type, ll); /* Add list for this event */
}
ll.add(listener);
}
/**
* ** This is the public API for other plugins to use for accessing the Marker API **
* This method can return null if the 'markers' component has not been configured -
* a warning message will be issued to the server.log in this event.
*
* @return MarkerAPI, or null if not configured
*/
public MarkerAPI getMarkerAPI() {
if(markerapi == null) {
Log.warning("Marker API has been requested, but is not enabled. Uncomment or add 'markers' component to configuration.txt.");
}
return markerapi;
}
/**
* Register markers API - used by component to supply marker API to plugin
*/
public void registerMarkerAPI(MarkerAPIImpl api) {
markerapi = api;
}
}
| Add bukkit bug workaround (http://leaky.bukkit.org/issues/1227) - piston exceptions
| src/main/java/org/dynmap/DynmapPlugin.java | Add bukkit bug workaround (http://leaky.bukkit.org/issues/1227) - piston exceptions | <ide><path>rc/main/java/org/dynmap/DynmapPlugin.java
<ide> if(event.isCancelled())
<ide> return;
<ide> Block b = event.getBlock();
<del> /* Avoid bogus piston events from Bukkit */
<del> if((b.getType() != Material.PISTON_BASE) && (b.getType() != Material.PISTON_STICKY_BASE))
<del> return;
<ide> Location loc = b.getLocation();
<ide> mapManager.sscache.invalidateSnapshot(loc);
<ide> BlockFace dir; |
|
Java | apache-2.0 | 283bd92305f8f0e391119dc27c10da42f858795a | 0 | RackerWilliams/xercesj,ronsigal/xerces,RackerWilliams/xercesj,jimma/xerces,RackerWilliams/xercesj,jimma/xerces,jimma/xerces,ronsigal/xerces,ronsigal/xerces | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999,2000 The Apache Software Foundation. All rights
* reserved.
*
* 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.framework;
import org.apache.xerces.readers.XMLEntityHandler;
import org.apache.xerces.readers.DefaultEntityHandler;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.StringPool;
import org.apache.xerces.utils.XMLCharacterProperties;
import org.apache.xerces.utils.XMLMessages;
import org.apache.xerces.validators.common.Grammar;
import org.apache.xerces.validators.common.GrammarResolver;
import org.apache.xerces.validators.common.XMLAttributeDecl;
import org.apache.xerces.validators.common.XMLElementDecl;
import org.apache.xerces.validators.dtd.DTDGrammar;
import org.xml.sax.Locator;
import org.xml.sax.SAXParseException;
import java.util.StringTokenizer;
/**
* Default implementation of an XML DTD scanner.
* <p>
* Clients who wish to scan a DTD should implement
* XMLDTDScanner.EventHandler to provide the desired behavior
* when various DTD components are encountered.
* <p>
* To process the DTD, the client application should follow the
* following sequence:
* <ol>
* <li>call scanDocTypeDecl() to scan the DOCTYPE declaration
* <li>call getReadingExternalEntity() to determine if scanDocTypeDecl found an
* external subset
* <li>if scanning an external subset, call scanDecls(true) to process the external subset
* </ol>
*
* @see XMLDTDScanner.EventHandler
* @version $Id$
*/
public final class XMLDTDScanner {
//
// Constants
//
//
// [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ")
//
private static final char[] version_string = { 'v','e','r','s','i','o','n' };
//
// [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'
//
private static final char[] element_string = { 'E','L','E','M','E','N','T' };
//
// [46] contentspec ::= 'EMPTY' | 'ANY' | Mixed | children
//
private static final char[] empty_string = { 'E','M','P','T','Y' };
private static final char[] any_string = { 'A','N','Y' };
//
// [51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*'
// | '(' S? '#PCDATA' S? ')'
//
private static final char[] pcdata_string = { '#','P','C','D','A','T','A' };
//
// [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
//
private static final char[] attlist_string = { 'A','T','T','L','I','S','T' };
//
// [55] StringType ::= 'CDATA'
//
private static final char[] cdata_string = { 'C','D','A','T','A' };
//
// [56] TokenizedType ::= 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' | 'ENTITIES'
// | 'NMTOKEN' | 'NMTOKENS'
//
// Note: We search for common substrings always trying to move forward
//
// 'ID' - Common prefix of ID, IDREF and IDREFS
// 'REF' - Common substring of IDREF and IDREFS after matching ID prefix
// 'ENTIT' - Common prefix of ENTITY and ENTITIES
// 'IES' - Suffix of ENTITIES
// 'NMTOKEN' - Common prefix of NMTOKEN and NMTOKENS
//
private static final char[] id_string = { 'I','D' };
private static final char[] ref_string = { 'R','E','F' };
private static final char[] entit_string = { 'E','N','T','I','T' };
private static final char[] ies_string = { 'I','E','S' };
private static final char[] nmtoken_string = { 'N','M','T','O','K','E','N' };
//
// [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
// [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'
//
private static final char[] notation_string = { 'N','O','T','A','T','I','O','N' };
//
// [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
//
private static final char[] required_string = { '#','R','E','Q','U','I','R','E','D' };
private static final char[] implied_string = { '#','I','M','P','L','I','E','D' };
private static final char[] fixed_string = { '#','F','I','X','E','D' };
//
// [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>'
//
private static final char[] include_string = { 'I','N','C','L','U','D','E' };
//
// [63] ignoreSect ::= '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>'
//
private static final char[] ignore_string = { 'I','G','N','O','R','E' };
//
// [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
// [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
//
private static final char[] entity_string = { 'E','N','T','I','T','Y' };
//
// [75] ExternalID ::= 'SYSTEM' S SystemLiteral
// | 'PUBLIC' S PubidLiteral S SystemLiteral
// [83] PublicID ::= 'PUBLIC' S PubidLiteral
//
private static final char[] system_string = { 'S','Y','S','T','E','M' };
private static final char[] public_string = { 'P','U','B','L','I','C' };
//
// [76] NDataDecl ::= S 'NDATA' S Name
//
private static final char[] ndata_string = { 'N','D','A','T','A' };
//
// [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" )
//
private static final char[] encoding_string = { 'e','n','c','o','d','i','n','g' };
//
// Instance Variables
//
private DTDGrammar fDTDGrammar = null;
private GrammarResolver fGrammarResolver = null;
private boolean fNamespacesEnabled = false;
private boolean fValidationEnabled = false;
private XMLElementDecl fTempElementDecl = new XMLElementDecl();
private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl();
private QName fElementQName = new QName();
private QName fAttributeQName = new QName();
private QName fElementRefQName = new QName();
private EventHandler fEventHandler = null;
private XMLDocumentHandler.DTDHandler fDTDHandler = null;
private StringPool fStringPool = null;
private XMLErrorReporter fErrorReporter = null;
private XMLEntityHandler fEntityHandler = null;
private XMLEntityHandler.EntityReader fEntityReader = null;
private XMLEntityHandler.CharBuffer fLiteralData = null;
private int fReaderId = -1;
private int fSystemLiteral = -1;
private int fPubidLiteral = -1;
private int[] fOpStack = null;
private int[] fNodeIndexStack = null;
private int[] fPrevNodeIndexStack = null;
private int fScannerState = SCANNER_STATE_INVALID;
private int fIncludeSectDepth = 0;
private int fDoctypeReader = -1;
private int fExternalSubsetReader = -1;
private int fDefaultAttValueReader = -1;
private int fDefaultAttValueElementType = -1;
private int fDefaultAttValueAttrName = -1;
private int fDefaultAttValueOffset = -1;
private int fDefaultAttValueMark = -1;
private int fEntityValueReader = -1;
private int fEntityValueMark = -1;
private int fXMLSymbol = -1;
private int fXMLNamespace = -1;
private int fXMLSpace = -1;
private int fDefault = -1;
private int fPreserve = -1;
private int fScannerMarkupDepth = 0;
private int fScannerParenDepth = 0;
//
// Constructors
//
public XMLDTDScanner(StringPool stringPool,
XMLErrorReporter errorReporter,
XMLEntityHandler entityHandler,
XMLEntityHandler.CharBuffer literalData) {
fStringPool = stringPool;
fErrorReporter = errorReporter;
fEntityHandler = entityHandler;
fLiteralData = literalData;
init();
}
/**
* Set the event handler
*
* @param eventHandler The place to send our callbacks.
*/
public void setEventHandler(XMLDTDScanner.EventHandler eventHandler) {
fEventHandler = eventHandler;
}
/** Set the DTD handler. */
public void setDTDHandler(XMLDocumentHandler.DTDHandler dtdHandler) {
fDTDHandler = dtdHandler;
}
/** Sets the grammar resolver. */
public void setGrammarResolver(GrammarResolver resolver) {
fGrammarResolver = resolver;
}
/** set fNamespacesEnabled **/
public void setNamespacesEnabled(boolean enabled) {
fNamespacesEnabled = enabled;
}
/** set fValidationEnabled **/
public void setValidationEnabled(boolean enabled) {
fValidationEnabled = enabled;
}
/**
* Is the XMLDTDScanner reading from an external entity?
*
* This will be true, in particular if there was an external subset
*
* @return true if the XMLDTDScanner is reading from an external entity.
*/
public boolean getReadingExternalEntity() {
return fReaderId != fDoctypeReader;
}
/**
* Is the scanner reading a ContentSpec?
*
* @return true if the scanner is reading a ContentSpec
*/
public boolean getReadingContentSpec() {
return getScannerState() == SCANNER_STATE_CONTENTSPEC;
}
/**
* Report the markup nesting depth. This allows a client to
* perform validation checks for correct markup nesting. This keeps
* scanning and validation separate.
*
* @return the markup nesting depth
*/
public int markupDepth() {
return fScannerMarkupDepth;
}
private int increaseMarkupDepth() {
return fScannerMarkupDepth++;
}
private int decreaseMarkupDepth() {
return fScannerMarkupDepth--;
}
/**
* Report the parenthesis nesting depth. This allows a client to
* perform validation checks for correct parenthesis balancing. This keeps
* scanning and validation separate.
*
* @return the parenthesis depth
*/
public int parenDepth() {
return fScannerParenDepth;
}
private void setParenDepth(int parenDepth) {
fScannerParenDepth = parenDepth;
}
private void increaseParenDepth() {
fScannerParenDepth++;
}
private void decreaseParenDepth() {
fScannerParenDepth--;
}
//
//
//
/**
* Allow XMLDTDScanner to be reused. This method is called from an
* XMLParser reset method, which passes the StringPool to be used
* by the reset DTD scanner instance.
*
* @param stringPool the string pool to be used by XMLDTDScanner.
*/
public void reset(StringPool stringPool, XMLEntityHandler.CharBuffer literalData) throws Exception {
fStringPool = stringPool;
fLiteralData = literalData;
fEntityReader = null;
fReaderId = -1;
fSystemLiteral = -1;
fPubidLiteral = -1;
fOpStack = null;
fNodeIndexStack = null;
fPrevNodeIndexStack = null;
fScannerState = SCANNER_STATE_INVALID;
fIncludeSectDepth = 0;
fDoctypeReader = -1;
fExternalSubsetReader = -1;
fDefaultAttValueReader = -1;
fDefaultAttValueElementType = -1;
fDefaultAttValueAttrName = -1;
fDefaultAttValueOffset = -1;
fDefaultAttValueMark = -1;
fEntityValueReader = -1;
fEntityValueMark = -1;
fScannerMarkupDepth = 0;
fScannerParenDepth = 0;
init();
}
private void init() {
fXMLSymbol = fStringPool.addSymbol("xml");
fXMLNamespace = fStringPool.addSymbol("http://www.w3.org/XML/1998/namespace");
fXMLSpace = fStringPool.addSymbol("xml:space");
fDefault = fStringPool.addSymbol("default");
fPreserve = fStringPool.addSymbol("preserve");
}
//
// Interfaces
//
/**
* This interface must be implemented by the users of the XMLDTDScanner class.
* These methods form the abstraction between the implementation semantics and the
* more generic task of scanning the DTD-specific XML grammar.
*/
public interface EventHandler {
/** Start of DTD. */
public void callStartDTD() throws Exception;
/** End of DTD. */
public void callEndDTD() throws Exception;
/**
* Signal the Text declaration of an external entity.
*
* @param version the handle in the string pool for the version number
* @param encoding the handle in the string pool for the encoding
* @exception java.lang.Exception
*/
public void callTextDecl(int version, int encoding) throws Exception;
/**
* Called when the doctype decl is scanned
*
* @param rootElementType handle of the rootElement
* @param publicId StringPool handle of the public id
* @param systemId StringPool handle of the system id
* @exception java.lang.Exception
*/
public void doctypeDecl(QName rootElement, int publicId, int systemId) throws Exception;
/**
* Called when the DTDScanner starts reading from the external subset
*
* @param publicId StringPool handle of the public id
* @param systemId StringPool handle of the system id
* @exception java.lang.Exception
*/
public void startReadingFromExternalSubset(int publicId, int systemId) throws Exception;
/**
* Called when the DTDScanner stop reading from the external subset
*
* @exception java.lang.Exception
*/
public void stopReadingFromExternalSubset() throws Exception;
/**
* Add an element declaration (forward reference)
*
* @param handle to the name of the element being declared
* @return handle to the element whose declaration was added
* @exception java.lang.Exception
*/
public int addElementDecl(QName elementDecl) throws Exception;
/**
* Add an element declaration
*
* @param handle to the name of the element being declared
* @param contentSpecType handle to the type name of the content spec
* @param ContentSpec handle to the content spec node for the contentSpecType
* @return handle to the element declaration that was added
* @exception java.lang.Exception
*/
public int addElementDecl(QName elementDecl, int contentSpecType, int contentSpec, boolean isExternal) throws Exception;
/**
* Add an attribute definition
*
* @param handle to the element whose attribute is being declared
* @param attName StringPool handle to the attribute name being declared
* @param attType type of the attribute
* @param enumeration StringPool handle of the attribute's enumeration list (if any)
* @param attDefaultType an integer value denoting the DefaultDecl value
* @param attDefaultValue StringPool handle of this attribute's default value
* @return handle to the attribute definition
* @exception java.lang.Exception
*/
public int addAttDef(QName elementDecl, QName attributeDecl,
int attType, boolean attList, int enumeration,
int attDefaultType, int attDefaultValue, boolean isExternal) throws Exception;
/**
* create an XMLContentSpec for a leaf
*
* @param nameIndex StringPool handle to the name (Element) for the node
* @return handle to the newly create XMLContentSpec
* @exception java.lang.Exception
*/
public int addUniqueLeafNode(int nameIndex) throws Exception;
/**
* Create an XMLContentSpec for a single non-leaf
*
* @param nodeType the type of XMLContentSpec to create - from XMLContentSpec.CONTENTSPECNODE_*
* @param nodeValue handle to an XMLContentSpec
* @return handle to the newly create XMLContentSpec
* @exception java.lang.Exception
*/
public int addContentSpecNode(int nodeType, int nodeValue) throws Exception;
/**
* Create an XMLContentSpec for a two child leaf
*
* @param nodeType the type of XMLContentSpec to create - from XMLContentSpec.CONTENTSPECNODE_*
* @param leftNodeIndex handle to an XMLContentSpec
* @param rightNodeIndex handle to an XMLContentSpec
* @return handle to the newly create XMLContentSpec
* @exception java.lang.Exception
*/
public int addContentSpecNode(int nodeType, int leftNodeIndex, int rightNodeIndex) throws Exception;
/**
* Create a string representation of an XMLContentSpec tree
*
* @param handle to an XMLContentSpec
* @return String representation of the content spec tree
* @exception java.lang.Exception
*/
public String getContentSpecNodeAsString(int nodeIndex) throws Exception;
/**
* Start the scope of an entity declaration.
*
* @return <code>true</code> on success; otherwise
* <code>false</code> if the entity declaration is recursive.
* @exception java.lang.Exception
*/
public boolean startEntityDecl(boolean isPE, int entityName) throws Exception;
/**
* End the scope of an entity declaration.
* @exception java.lang.Exception
*/
public void endEntityDecl() throws Exception;
/**
* Add a declaration for an internal parameter entity
*
* @param name StringPool handle of the parameter entity name
* @param value StringPool handle of the parameter entity value
* @return handle to the parameter entity declaration
* @exception java.lang.Exception
*/
public int addInternalPEDecl(int name, int value) throws Exception;
/**
* Add a declaration for an external parameter entity
*
* @param name StringPool handle of the parameter entity name
* @param publicId StringPool handle of the publicId
* @param systemId StringPool handle of the systemId
* @return handle to the parameter entity declaration
* @exception java.lang.Exception
*/
public int addExternalPEDecl(int name, int publicId, int systemId) throws Exception;
/**
* Add a declaration for an internal entity
*
* @param name StringPool handle of the entity name
* @param value StringPool handle of the entity value
* @return handle to the entity declaration
* @exception java.lang.Exception
*/
public int addInternalEntityDecl(int name, int value) throws Exception;
/**
* Add a declaration for an entity
*
* @param name StringPool handle of the entity name
* @param publicId StringPool handle of the publicId
* @param systemId StringPool handle of the systemId
* @return handle to the entity declaration
* @exception java.lang.Exception
*/
public int addExternalEntityDecl(int name, int publicId, int systemId) throws Exception;
/**
* Add a declaration for an unparsed entity
*
* @param name StringPool handle of the entity name
* @param publicId StringPool handle of the publicId
* @param systemId StringPool handle of the systemId
* @param notationName StringPool handle of the notationName
* @return handle to the entity declaration
* @exception java.lang.Exception
*/
public int addUnparsedEntityDecl(int name, int publicId, int systemId, int notationName) throws Exception;
/**
* Called when the scanner start scanning an enumeration
* @return StringPool handle to a string list that will hold the enumeration names
* @exception java.lang.Exception
*/
public int startEnumeration() throws Exception;
/**
* Add a name to an enumeration
* @param enumIndex StringPool handle to the string list for the enumeration
* @param elementType handle to the element that owns the attribute with the enumeration
* @param attrName StringPool handle to the name of the attribut with the enumeration
* @param nameIndex StringPool handle to the name to be added to the enumeration
* @param isNotationType true if the enumeration is an enumeration of NOTATION names
* @exception java.lang.Exception
*/
public void addNameToEnumeration(int enumIndex, int elementType, int attrName, int nameIndex, boolean isNotationType) throws Exception;
/**
* Finish processing an enumeration
*
* @param enumIndex handle to the string list which holds the enumeration to be finshed.
* @exception java.lang.Exception
*/
public void endEnumeration(int enumIndex) throws Exception;
/**
* Add a declaration for a notation
*
* @param notationName
* @param publicId
* @param systemId
* @return handle to the notation declaration
* @exception java.lang.Exception
*/
public int addNotationDecl(int notationName, int publicId, int systemId) throws Exception;
/**
* Called when a comment has been scanned
*
* @param data StringPool handle of the comment text
* @exception java.lang.Exception
*/
public void callComment(int data) throws Exception;
/**
* Called when a processing instruction has been scanned
* @param piTarget StringPool handle of the PI target
* @param piData StringPool handle of the PI data
* @exception java.lang.Exception
*/
public void callProcessingInstruction(int piTarget, int piData) throws Exception;
/**
* Supports DOM Level 2 internalSubset additions.
* Called when the internal subset is completely scanned.
*/
public void internalSubset(int internalSubset) throws Exception;
}
//
//
//
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
int stringIndex1)
throws Exception {
Object[] args = { fStringPool.toString(stringIndex1) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1) throws Exception {
Object[] args = { string1 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1, String string2)
throws Exception {
Object[] args = { string1, string2 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String,String)
private void reportFatalXMLError(int majorCode, int minorCode) throws Exception {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void reportFatalXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception {
Object[] args = { fStringPool.toString(stringIndex1) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void reportFatalXMLError(int majorCode, int minorCode, String string1) throws Exception {
Object[] args = { string1 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void reportFatalXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception {
Object[] args = { fStringPool.toString(stringIndex1),
fStringPool.toString(stringIndex2) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void reportFatalXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception {
Object[] args = { string1, string2 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void reportFatalXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception {
Object[] args = { string1, string2, string3 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void abortMarkup(int majorCode, int minorCode) throws Exception {
reportFatalXMLError(majorCode, minorCode);
skipPastEndOfCurrentMarkup();
}
private void abortMarkup(int majorCode, int minorCode, int stringIndex1) throws Exception {
reportFatalXMLError(majorCode, minorCode, stringIndex1);
skipPastEndOfCurrentMarkup();
}
private void abortMarkup(int majorCode, int minorCode, String string1) throws Exception {
reportFatalXMLError(majorCode, minorCode, string1);
skipPastEndOfCurrentMarkup();
}
private void abortMarkup(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception {
reportFatalXMLError(majorCode, minorCode, stringIndex1, stringIndex2);
skipPastEndOfCurrentMarkup();
}
private void skipPastEndOfCurrentMarkup() throws Exception {
fEntityReader.skipToChar('>');
if (fEntityReader.lookingAtChar('>', true))
decreaseMarkupDepth();
}
//
//
//
static private final int SCANNER_STATE_INVALID = -1;
static private final int SCANNER_STATE_END_OF_INPUT = 0;
static private final int SCANNER_STATE_DOCTYPEDECL = 50;
static private final int SCANNER_STATE_MARKUP_DECL = 51;
static private final int SCANNER_STATE_TEXTDECL = 53;
static private final int SCANNER_STATE_COMMENT = 54;
static private final int SCANNER_STATE_PI = 55;
static private final int SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE = 56;
static private final int SCANNER_STATE_CONTENTSPEC = 57;
static private final int SCANNER_STATE_ENTITY_VALUE = 58;
static private final int SCANNER_STATE_SYSTEMLITERAL = 59;
static private final int SCANNER_STATE_PUBIDLITERAL = 60;
private int setScannerState(int scannerState) {
int prevState = fScannerState;
fScannerState = scannerState;
return prevState;
}
private int getScannerState() {
return fScannerState;
}
private void restoreScannerState(int scannerState) {
if (fScannerState != SCANNER_STATE_END_OF_INPUT)
fScannerState = scannerState;
}
/**
* Change readers
*
* @param nextReader the new reader that the scanner will use
* @param nextReaderId id of the reader to change to
* @exception throws java.lang.Exception
*/
public void readerChange(XMLEntityHandler.EntityReader nextReader, int nextReaderId) throws Exception {
fEntityReader = nextReader;
fReaderId = nextReaderId;
if (fScannerState == SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE) {
fDefaultAttValueOffset = fEntityReader.currentOffset();
fDefaultAttValueMark = fDefaultAttValueOffset;
} else if (fScannerState == SCANNER_STATE_ENTITY_VALUE) {
fEntityValueMark = fEntityReader.currentOffset();
}
}
/**
* Handle the end of input
*
* @param entityName the handle in the string pool of the name of the entity which has reached end of input
* @param moreToFollow if true, there is still input left to process in other readers
* @exception java.lang.Exception
*/
public void endOfInput(int entityNameIndex, boolean moreToFollow) throws Exception {
if (fValidationEnabled ) {
int readerDepth = fEntityHandler.getReaderDepth();
if (getReadingContentSpec()) {
int parenDepth = parenDepth();
if (readerDepth != parenDepth) {
reportRecoverableXMLError(XMLMessages.MSG_IMPROPER_GROUP_NESTING,
XMLMessages.VC_PROPER_GROUP_PE_NESTING,
entityNameIndex);
}
} else {
int markupDepth = markupDepth();
if (readerDepth != markupDepth) {
reportRecoverableXMLError(XMLMessages.MSG_IMPROPER_DECLARATION_NESTING,
XMLMessages.VC_PROPER_DECLARATION_PE_NESTING,
entityNameIndex);
}
}
}
//REVISIT, why are we doing this?
moreToFollow = fReaderId != fExternalSubsetReader;
// System.out.println("current Scanner state " + getScannerState() +","+ fScannerState + moreToFollow);
switch (fScannerState) {
case SCANNER_STATE_INVALID:
throw new RuntimeException("FWK004 XMLDTDScanner.endOfInput: cannot happen: 2"+"\n2");
case SCANNER_STATE_END_OF_INPUT:
break;
case SCANNER_STATE_MARKUP_DECL:
if (!moreToFollow && fIncludeSectDepth > 0) {
reportFatalXMLError(XMLMessages.MSG_INCLUDESECT_UNTERMINATED,
XMLMessages.P62_UNTERMINATED);
}
break;
case SCANNER_STATE_DOCTYPEDECL:
throw new RuntimeException("FWK004 XMLDTDScanner.endOfInput: cannot happen: 2.5"+"\n2.5");
// break;
case SCANNER_STATE_TEXTDECL:
// REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0);
break;
case SCANNER_STATE_SYSTEMLITERAL:
if (!moreToFollow) {
reportFatalXMLError(XMLMessages.MSG_SYSTEMID_UNTERMINATED,
XMLMessages.P11_UNTERMINATED);
} else {
// REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0);
}
break;
case SCANNER_STATE_PUBIDLITERAL:
if (!moreToFollow) {
reportFatalXMLError(XMLMessages.MSG_PUBLICID_UNTERMINATED,
XMLMessages.P12_UNTERMINATED);
} else {
// REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0);
}
break;
case SCANNER_STATE_COMMENT:
if (!moreToFollow && !getReadingExternalEntity()) {
reportFatalXMLError(XMLMessages.MSG_COMMENT_UNTERMINATED,
XMLMessages.P15_UNTERMINATED);
} else {
//
// REVISIT - HACK !!! code changed to pass incorrect OASIS test 'invalid--001'
// Uncomment the next line to conform to the spec...
//
//reportFatalXMLError(XMLMessages.MSG_COMMENT_NOT_IN_ONE_ENTITY,
// XMLMessages.P78_NOT_WELLFORMED);
}
break;
case SCANNER_STATE_PI:
if (!moreToFollow) {
reportFatalXMLError(XMLMessages.MSG_PI_UNTERMINATED,
XMLMessages.P16_UNTERMINATED);
} else {
reportFatalXMLError(XMLMessages.MSG_PI_NOT_IN_ONE_ENTITY,
XMLMessages.P78_NOT_WELLFORMED);
}
break;
case SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE:
if (!moreToFollow) {
reportFatalXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_UNTERMINATED,
XMLMessages.P10_UNTERMINATED,
fDefaultAttValueElementType,
fDefaultAttValueAttrName);
} else if (fReaderId == fDefaultAttValueReader) {
// REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0);
} else {
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
}
break;
case SCANNER_STATE_CONTENTSPEC:
break;
case SCANNER_STATE_ENTITY_VALUE:
if (fReaderId == fEntityValueReader) {
// REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0);
} else {
fEntityReader.append(fLiteralData, fEntityValueMark, fEntityReader.currentOffset() - fEntityValueMark);
}
break;
default:
throw new RuntimeException("FWK004 XMLDTDScanner.endOfInput: cannot happen: 3"+"\n3");
}
if (!moreToFollow) {
setScannerState(SCANNER_STATE_END_OF_INPUT);
}
}
//
// [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'
//
private int scanCharRef() throws Exception {
int valueOffset = fEntityReader.currentOffset();
boolean hex = fEntityReader.lookingAtChar('x', true);
int num = fEntityReader.scanCharRef(hex);
if (num < 0) {
switch (num) {
case XMLEntityHandler.CHARREF_RESULT_SEMICOLON_REQUIRED:
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_CHARREF,
XMLMessages.P66_SEMICOLON_REQUIRED);
return -1;
case XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR:
int majorCode = hex ? XMLMessages.MSG_HEXDIGIT_REQUIRED_IN_CHARREF :
XMLMessages.MSG_DIGIT_REQUIRED_IN_CHARREF;
int minorCode = hex ? XMLMessages.P66_HEXDIGIT_REQUIRED :
XMLMessages.P66_DIGIT_REQUIRED;
reportFatalXMLError(majorCode, minorCode);
return -1;
case XMLEntityHandler.CHARREF_RESULT_OUT_OF_RANGE:
num = 0x110000; // this will cause the right error to be reported below...
break;
}
}
//
// [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] // any Unicode character, excluding the
// | [#xE000-#xFFFD] | [#x10000-#x10FFFF] // surrogate blocks, FFFE, and FFFF.
//
if (num < 0x20) {
if (num == 0x09 || num == 0x0A || num == 0x0D) {
return num;
}
} else if (num <= 0xD7FF || (num >= 0xE000 && (num <= 0xFFFD || (num >= 0x10000 && num <= 0x10FFFF)))) {
return num;
}
int valueLength = fEntityReader.currentOffset() - valueOffset;
reportFatalXMLError(XMLMessages.MSG_INVALID_CHARREF,
XMLMessages.WFC_LEGAL_CHARACTER,
fEntityReader.addString(valueOffset, valueLength));
return -1;
}
//
// From the standard:
//
// [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
//
// Called after scanning past '<!--'
//
private void scanComment() throws Exception
{
int commentOffset = fEntityReader.currentOffset();
boolean sawDashDash = false;
int previousState = setScannerState(SCANNER_STATE_COMMENT);
while (fScannerState == SCANNER_STATE_COMMENT) {
if (fEntityReader.lookingAtChar('-', false)) {
int nextEndOffset = fEntityReader.currentOffset();
int endOffset = 0;
fEntityReader.lookingAtChar('-', true);
int offset = fEntityReader.currentOffset();
int count = 1;
while (fEntityReader.lookingAtChar('-', true)) {
count++;
endOffset = nextEndOffset;
nextEndOffset = offset;
offset = fEntityReader.currentOffset();
}
if (count > 1) {
if (fEntityReader.lookingAtChar('>', true)) {
if (!sawDashDash && count > 2) {
reportFatalXMLError(XMLMessages.MSG_DASH_DASH_IN_COMMENT,
XMLMessages.P15_DASH_DASH);
sawDashDash = true;
}
decreaseMarkupDepth();
int comment = fEntityReader.addString(commentOffset, endOffset - commentOffset);
fDTDGrammar.callComment(comment);
if (fDTDHandler != null) {
fDTDHandler.comment(comment);
}
restoreScannerState(previousState);
return;
} else if (!sawDashDash) {
reportFatalXMLError(XMLMessages.MSG_DASH_DASH_IN_COMMENT,
XMLMessages.P15_DASH_DASH);
sawDashDash = true;
}
}
} else {
if (!fEntityReader.lookingAtValidChar(true)) {
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState != SCANNER_STATE_END_OF_INPUT) {
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_COMMENT,
XMLMessages.P15_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
}
}
}
}
restoreScannerState(previousState);
}
//
// From the standard:
//
// [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
// [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
//
private void scanPI(int piTarget) throws Exception
{
String piTargetString = fStringPool.toString(piTarget);
if (piTargetString.length() == 3 &&
(piTargetString.charAt(0) == 'X' || piTargetString.charAt(0) == 'x') &&
(piTargetString.charAt(1) == 'M' || piTargetString.charAt(1) == 'm') &&
(piTargetString.charAt(2) == 'L' || piTargetString.charAt(2) == 'l')) {
abortMarkup(XMLMessages.MSG_RESERVED_PITARGET,
XMLMessages.P17_RESERVED_PITARGET);
return;
}
int prevState = setScannerState(SCANNER_STATE_PI);
int piDataOffset = -1;
int piDataLength = 0;
if (!fEntityReader.lookingAtSpace(true)) {
if (!fEntityReader.lookingAtChar('?', true) || !fEntityReader.lookingAtChar('>', true)) {
if (fScannerState != SCANNER_STATE_END_OF_INPUT) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_IN_PI,
XMLMessages.P16_WHITESPACE_REQUIRED);
restoreScannerState(prevState);
}
return;
}
decreaseMarkupDepth();
restoreScannerState(prevState);
} else {
fEntityReader.skipPastSpaces();
piDataOffset = fEntityReader.currentOffset();
while (fScannerState == SCANNER_STATE_PI) {
while (fEntityReader.lookingAtChar('?', false)) {
int offset = fEntityReader.currentOffset();
fEntityReader.lookingAtChar('?', true);
if (fEntityReader.lookingAtChar('>', true)) {
piDataLength = offset - piDataOffset;
decreaseMarkupDepth();
restoreScannerState(prevState);
break;
}
}
if (fScannerState != SCANNER_STATE_PI)
break;
if (!fEntityReader.lookingAtValidChar(true)) {
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState != SCANNER_STATE_END_OF_INPUT) {
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_PI,
XMLMessages.P16_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
skipPastEndOfCurrentMarkup();
restoreScannerState(prevState);
}
return;
}
}
}
int piData = piDataLength == 0 ?
StringPool.EMPTY_STRING : fEntityReader.addString(piDataOffset, piDataLength);
fDTDGrammar.callProcessingInstruction(piTarget, piData);
if (fDTDHandler != null) {
fDTDHandler.processingInstruction(piTarget, piData);
}
}
//
// From the standard:
//
// [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S?
// ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
// [29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl
// | NotationDecl | PI | Comment
//
// Called after scanning '<!DOCTYPE'
//
/**
* This routine is called after the <!DOCTYPE portion of a DOCTYPE
* line has been called. scanDocTypeDecl goes onto scan the rest of the DOCTYPE
* decl. If an internal DTD subset exists, it is scanned. If an external DTD
* subset exists, scanDocTypeDecl sets up the state necessary to process it.
*
* @return true if successful
* @exception java.lang.Exception
*/
public boolean scanDoctypeDecl() throws Exception
{
//System.out.println("XMLDTDScanner#scanDoctypeDecl()");
fDTDGrammar = new DTDGrammar(fStringPool);
fDTDGrammar.callStartDTD();
increaseMarkupDepth();
fEntityReader = fEntityHandler.getEntityReader();
fReaderId = fEntityHandler.getReaderId();
fDoctypeReader = fReaderId;
setScannerState(SCANNER_STATE_DOCTYPEDECL);
if (!fEntityReader.lookingAtSpace(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL,
XMLMessages.P28_SPACE_REQUIRED);
return false;
}
fEntityReader.skipPastSpaces();
scanElementType(fEntityReader, ' ', fElementQName);
if (fElementQName.rawname == -1) {
abortMarkup(XMLMessages.MSG_ROOT_ELEMENT_TYPE_REQUIRED,
XMLMessages.P28_ROOT_ELEMENT_TYPE_REQUIRED);
return false;
}
boolean lbrkt;
boolean scanExternalSubset = false;
int publicId = -1;
int systemId = -1;
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
if (!(lbrkt = fEntityReader.lookingAtChar('[', true)) && !fEntityReader.lookingAtChar('>', false)) {
if (!scanExternalID(false)) {
skipPastEndOfCurrentMarkup();
return false;
}
scanExternalSubset = true;
publicId = fPubidLiteral;
systemId = fSystemLiteral;
fEntityReader.skipPastSpaces();
lbrkt = fEntityReader.lookingAtChar('[', true);
}
} else
lbrkt = fEntityReader.lookingAtChar('[', true);
fDTDGrammar.doctypeDecl(fElementQName, publicId, systemId);
if (fDTDHandler != null) {
fDTDHandler.startDTD(fElementQName, publicId, systemId);
}
if (lbrkt) {
scanDecls(false);
fEntityReader.skipPastSpaces();
}
if (!fEntityReader.lookingAtChar('>', true)) {
if (fScannerState != SCANNER_STATE_END_OF_INPUT) {
abortMarkup(XMLMessages.MSG_DOCTYPEDECL_UNTERMINATED,
XMLMessages.P28_UNTERMINATED,
fElementQName.rawname);
}
return false;
}
decreaseMarkupDepth();
//System.out.println(" scanExternalSubset: "+scanExternalSubset);
if (scanExternalSubset) {
((DefaultEntityHandler) fEntityHandler).startReadingFromExternalSubset( fStringPool.toString(publicId),
fStringPool.toString(systemId),
markupDepth());
fDTDGrammar.startReadingFromExternalSubset(publicId, systemId);
}
fGrammarResolver.putGrammar("", fDTDGrammar);
return true;
}
//
// [75] ExternalID ::= 'SYSTEM' S SystemLiteral
// | 'PUBLIC' S PubidLiteral S SystemLiteral
// [83] PublicID ::= 'PUBLIC' S PubidLiteral
//
private boolean scanExternalID(boolean scanPublicID) throws Exception
{
fSystemLiteral = -1;
fPubidLiteral = -1;
int offset = fEntityReader.currentOffset();
if (fEntityReader.skippedString(system_string)) {
if (!fEntityReader.lookingAtSpace(true)) {
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_SYSTEMLITERAL_IN_EXTERNALID,
XMLMessages.P75_SPACE_REQUIRED);
return false;
}
fEntityReader.skipPastSpaces();
if( getReadingExternalEntity() == true ) { //Are we in external subset?
checkForPEReference(false);//If so Check for PE Ref
}
return scanSystemLiteral();
}
if (fEntityReader.skippedString(public_string)) {
if (!fEntityReader.lookingAtSpace(true)) {
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_PUBIDLITERAL_IN_EXTERNALID,
XMLMessages.P75_SPACE_REQUIRED);
return false;
}
fEntityReader.skipPastSpaces();
if (!scanPubidLiteral())
return false;
if (scanPublicID) {
//
// [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'
//
if (!fEntityReader.lookingAtSpace(true))
return true; // no S, not an ExternalID
fEntityReader.skipPastSpaces();
if (fEntityReader.lookingAtChar('>', false)) // matches end of NotationDecl
return true;
} else {
if (!fEntityReader.lookingAtSpace(true)) {
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_AFTER_PUBIDLITERAL_IN_EXTERNALID,
XMLMessages.P75_SPACE_REQUIRED);
return false;
}
fEntityReader.skipPastSpaces();
}
return scanSystemLiteral();
}
reportFatalXMLError(XMLMessages.MSG_EXTERNALID_REQUIRED,
XMLMessages.P75_INVALID);
return false;
}
//
// [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
//
// REVISIT - need to look into uri escape mechanism for non-ascii characters.
//
private boolean scanSystemLiteral() throws Exception
{
boolean single;
if (!(single = fEntityReader.lookingAtChar('\'', true)) && !fEntityReader.lookingAtChar('\"', true)) {
reportFatalXMLError(XMLMessages.MSG_QUOTE_REQUIRED_IN_SYSTEMID,
XMLMessages.P11_QUOTE_REQUIRED);
return false;
}
int prevState = setScannerState(SCANNER_STATE_SYSTEMLITERAL);
int offset = fEntityReader.currentOffset();
char qchar = single ? '\'' : '\"';
boolean dataok = true;
boolean fragment = false;
while (!fEntityReader.lookingAtChar(qchar, false)) {
//ericye
//System.out.println("XMLDTDScanner#scanDoctypeDecl() 3333333, "+fReaderId+", " + fScannerState+", " +fExternalSubsetReader);
if (fEntityReader.lookingAtChar('#', true)) {
fragment = true;
} else if (!fEntityReader.lookingAtValidChar(true)) {
//System.out.println("XMLDTDScanner#scanDoctypeDecl() 555555 scan state: " + fScannerState);
dataok = false;
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
return false;
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_SYSTEMID,
XMLMessages.P11_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
}
}
if (dataok) {
fSystemLiteral = fEntityReader.addString(offset, fEntityReader.currentOffset() - offset);
if (fragment) {
// NOTE: RECOVERABLE ERROR
Object[] args = { fStringPool.toString(fSystemLiteral) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_URI_FRAGMENT_IN_SYSTEMID,
XMLMessages.P11_URI_FRAGMENT,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
fEntityReader.lookingAtChar(qchar, true);
restoreScannerState(prevState);
return dataok;
}
//
// [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
// [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]
//
private boolean scanPubidLiteral() throws Exception
{
boolean single;
if (!(single = fEntityReader.lookingAtChar('\'', true)) && !fEntityReader.lookingAtChar('\"', true)) {
reportFatalXMLError(XMLMessages.MSG_QUOTE_REQUIRED_IN_PUBLICID,
XMLMessages.P12_QUOTE_REQUIRED);
return false;
}
char qchar = single ? '\'' : '\"';
int prevState = setScannerState(SCANNER_STATE_PUBIDLITERAL);
boolean dataok = true;
while (true) {
if (fEntityReader.lookingAtChar((char)0x09, true)) {
dataok = false;
reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL,
XMLMessages.P12_INVALID_CHARACTER, "9");
}
if (!fEntityReader.lookingAtSpace(true))
break;
}
int offset = fEntityReader.currentOffset();
int dataOffset = fLiteralData.length();
int toCopy = offset;
while (true) {
if (fEntityReader.lookingAtChar(qchar, true)) {
if (dataok && offset - toCopy > 0)
fEntityReader.append(fLiteralData, toCopy, offset - toCopy);
break;
}
if (fEntityReader.lookingAtChar((char)0x09, true)) {
dataok = false;
reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL,
XMLMessages.P12_INVALID_CHARACTER, "9");
continue;
}
if (fEntityReader.lookingAtSpace(true)) {
if (dataok && offset - toCopy > 0)
fEntityReader.append(fLiteralData, toCopy, offset - toCopy);
while (true) {
if (fEntityReader.lookingAtChar((char)0x09, true)) {
dataok = false;
reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL,
XMLMessages.P12_INVALID_CHARACTER, "9");
break;
} else if (!fEntityReader.lookingAtSpace(true)) {
break;
}
}
if (fEntityReader.lookingAtChar(qchar, true))
break;
if (dataok) {
fLiteralData.append(' ');
offset = fEntityReader.currentOffset();
toCopy = offset;
}
continue;
}
if (!fEntityReader.lookingAtValidChar(true)) {
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
return false;
dataok = false;
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_PUBLICID,
XMLMessages.P12_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
}
if (dataok)
offset = fEntityReader.currentOffset();
}
if (dataok) {
int dataLength = fLiteralData.length() - dataOffset;
fPubidLiteral = fLiteralData.addString(dataOffset, dataLength);
String publicId = fStringPool.toString(fPubidLiteral);
int invCharIndex = validPublicId(publicId);
if (invCharIndex >= 0) {
reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL,
XMLMessages.P12_INVALID_CHARACTER,
Integer.toHexString(publicId.charAt(invCharIndex)));
return false;
}
}
restoreScannerState(prevState);
return dataok;
}
//
// [??] intSubsetDecl = '[' (markupdecl | PEReference | S)* ']'
//
// [31] extSubsetDecl ::= ( markupdecl | conditionalSect | PEReference | S )*
// [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>'
//
// [29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl
// | NotationDecl | PI | Comment
//
// [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'
//
// [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
//
// [70] EntityDecl ::= GEDecl | PEDecl
// [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
// [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
//
// [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'
//
// [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
//
// [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
//
// [61] conditionalSect ::= includeSect | ignoreSect
// [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>'
// [63] ignoreSect ::= '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>'
// [64] ignoreSectContents ::= Ignore ('<![' ignoreSectContents ']]>' Ignore)*
// [65] Ignore ::= Char* - (Char* ('<![' | ']]>') Char*)
//
/**
* Scan markup declarations
*
* @param extSubset true if the scanner is scanning an external subset, false
* if it is scanning an internal subset
* @exception java.lang.Exception
*/
public void scanDecls(boolean extSubset) throws Exception
{
int subsetOffset = fEntityReader.currentOffset();
if (extSubset)
fExternalSubsetReader = fReaderId;
fIncludeSectDepth = 0;
boolean parseTextDecl = extSubset;
int prevState = setScannerState(SCANNER_STATE_MARKUP_DECL);
while (fScannerState == SCANNER_STATE_MARKUP_DECL) {
boolean newParseTextDecl = false;
if (!extSubset && fEntityReader.lookingAtChar(']', false)) {
int subsetLength = fEntityReader.currentOffset() - subsetOffset;
int internalSubset = fEntityReader.addString(subsetOffset, subsetLength);
fDTDGrammar.internalSubset(internalSubset);
if (fDTDHandler != null) {
fDTDHandler.internalSubset(internalSubset);
}
fEntityReader.lookingAtChar(']', true);
restoreScannerState(prevState);
return;
}
if (fEntityReader.lookingAtChar('<', true)) {
int olddepth = markupDepth();
increaseMarkupDepth();
if (fEntityReader.lookingAtChar('!', true)) {
if (fEntityReader.lookingAtChar('-', true)) {
if (fEntityReader.lookingAtChar('-', true)) {
scanComment();
} else {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
}
} else if (fEntityReader.lookingAtChar('[', true) && getReadingExternalEntity()) {
checkForPEReference(false);
if (fEntityReader.skippedString(include_string)) {
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('[', true)) {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
} else {
fIncludeSectDepth++;
}
} else if (fEntityReader.skippedString(ignore_string)) {
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('[', true)) {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
} else
scanIgnoreSectContents();
} else {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
}
} else if (fEntityReader.skippedString(element_string)) {
scanElementDecl();
}
else if (fEntityReader.skippedString(attlist_string))
scanAttlistDecl();
else if (fEntityReader.skippedString(entity_string))
scanEntityDecl();
else if (fEntityReader.skippedString(notation_string))
scanNotationDecl();
else {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
}
} else if (fEntityReader.lookingAtChar('?', true)) {
int piTarget = fEntityReader.scanName(' ');
if (piTarget == -1) {
abortMarkup(XMLMessages.MSG_PITARGET_REQUIRED,
XMLMessages.P16_REQUIRED);
} else if ("xml".equals(fStringPool.toString(piTarget))) {
if (fEntityReader.lookingAtSpace(true)) {
if (parseTextDecl) { // a TextDecl looks like a PI with the target 'xml'
scanTextDecl();
} else {
abortMarkup(XMLMessages.MSG_TEXTDECL_MUST_BE_FIRST,
XMLMessages.P30_TEXTDECL_MUST_BE_FIRST);
}
} else { // a PI target matching 'xml'
abortMarkup(XMLMessages.MSG_RESERVED_PITARGET,
XMLMessages.P17_RESERVED_PITARGET);
}
} else // PI
scanPI(piTarget);
} else {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
}
} else if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
} else if (fEntityReader.lookingAtChar('%', true)) {
//
// [69] PEReference ::= '%' Name ';'
//
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_NAME_REQUIRED);
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
} else {
int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength);
newParseTextDecl = fEntityHandler.startReadingFromEntity(peNameIndex, markupDepth(), XMLEntityHandler.ENTITYREF_IN_DTD_AS_MARKUP);
}
} else if (fIncludeSectDepth > 0 && fEntityReader.lookingAtChar(']', true)) {
if (!fEntityReader.lookingAtChar(']', true) || !fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_INCLUDESECT_UNTERMINATED,
XMLMessages.P62_UNTERMINATED);
} else
decreaseMarkupDepth();
fIncludeSectDepth--;
} else {
if (!fEntityReader.lookingAtValidChar(false)) {
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
break;
if (invChar >= 0) {
if (!extSubset) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_INTERNAL_SUBSET,
XMLMessages.P28_INVALID_CHARACTER,
Integer.toHexString(invChar));
} else {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_EXTERNAL_SUBSET,
XMLMessages.P30_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
}
} else {
reportFatalXMLError(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
fEntityReader.lookingAtValidChar(true);
}
}
parseTextDecl = newParseTextDecl;
}
if (extSubset) {
((DefaultEntityHandler) fEntityHandler).stopReadingFromExternalSubset();
fDTDGrammar.stopReadingFromExternalSubset();
fDTDGrammar.callEndDTD();
if (fDTDHandler != null) {
fDTDHandler.endDTD();
}
// REVISIT: What should the namspace URI of a DTD be?
fGrammarResolver.putGrammar("", fDTDGrammar);
}
}
//
// [64] ignoreSectContents ::= Ignore ('<![' ignoreSectContents ']]>' Ignore)*
// [65] Ignore ::= Char* - (Char* ('<![' | ']]>') Char*)
//
private void scanIgnoreSectContents() throws Exception
{
int initialDepth = ++fIncludeSectDepth;
while (true) {
if (fEntityReader.lookingAtChar('<', true)) {
//
// These tests are split so that we handle cases like
// '<<![' and '<!<![' which we might otherwise miss.
//
if (fEntityReader.lookingAtChar('!', true) && fEntityReader.lookingAtChar('[', true))
fIncludeSectDepth++;
} else if (fEntityReader.lookingAtChar(']', true)) {
//
// The same thing goes for ']<![' and '<]]>', etc.
//
if (fEntityReader.lookingAtChar(']', true)) {
while (fEntityReader.lookingAtChar(']', true)) {
/* empty loop body */
}
if (fEntityReader.lookingAtChar('>', true)) {
if (fIncludeSectDepth-- == initialDepth) {
decreaseMarkupDepth();
return;
}
}
}
} else if (!fEntityReader.lookingAtValidChar(true)) {
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
return;
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_IGNORESECT,
XMLMessages.P65_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
}
}
}
//
// From the standard:
//
// [77] TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>'
// [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ")
// [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" )
// [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
//
private void scanTextDecl() throws Exception {
int version = -1;
int encoding = -1;
final int TEXTDECL_START = 0;
final int TEXTDECL_VERSION = 1;
final int TEXTDECL_ENCODING = 2;
final int TEXTDECL_FINISHED = 3;
int prevState = setScannerState(SCANNER_STATE_TEXTDECL);
int state = TEXTDECL_START;
do {
fEntityReader.skipPastSpaces();
int offset = fEntityReader.currentOffset();
if (state == TEXTDECL_START && fEntityReader.skippedString(version_string)) {
state = TEXTDECL_VERSION;
} else if (fEntityReader.skippedString(encoding_string)) {
state = TEXTDECL_ENCODING;
} else {
abortMarkup(XMLMessages.MSG_ENCODINGDECL_REQUIRED,
XMLMessages.P77_ENCODINGDECL_REQUIRED);
restoreScannerState(prevState);
return;
}
int length = fEntityReader.currentOffset() - offset;
fEntityReader.skipPastSpaces();
if (!fEntityReader.lookingAtChar('=', true)) {
int minorCode = state == TEXTDECL_VERSION ?
XMLMessages.P24_EQ_REQUIRED :
XMLMessages.P80_EQ_REQUIRED;
abortMarkup(XMLMessages.MSG_EQ_REQUIRED_IN_TEXTDECL, minorCode,
fEntityReader.addString(offset, length));
restoreScannerState(prevState);
return;
}
fEntityReader.skipPastSpaces();
int result = fEntityReader.scanStringLiteral();
switch (result) {
case XMLEntityHandler.STRINGLIT_RESULT_QUOTE_REQUIRED:
{
int minorCode = state == TEXTDECL_VERSION ?
XMLMessages.P24_QUOTE_REQUIRED :
XMLMessages.P80_QUOTE_REQUIRED;
abortMarkup(XMLMessages.MSG_QUOTE_REQUIRED_IN_TEXTDECL, minorCode,
fEntityReader.addString(offset, length));
restoreScannerState(prevState);
return;
}
case XMLEntityHandler.STRINGLIT_RESULT_INVALID_CHAR:
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState != SCANNER_STATE_END_OF_INPUT) {
if (invChar >= 0) {
int minorCode = state == TEXTDECL_VERSION ?
XMLMessages.P26_INVALID_CHARACTER :
XMLMessages.P81_INVALID_CHARACTER;
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_TEXTDECL, minorCode,
Integer.toHexString(invChar));
}
skipPastEndOfCurrentMarkup();
restoreScannerState(prevState);
}
return;
default:
break;
}
switch (state) {
case TEXTDECL_VERSION:
//
// version="..."
//
version = result;
String versionString = fStringPool.toString(version);
if (!"1.0".equals(versionString)) {
if (!validVersionNum(versionString)) {
abortMarkup(XMLMessages.MSG_VERSIONINFO_INVALID,
XMLMessages.P26_INVALID_VALUE,
versionString);
restoreScannerState(prevState);
return;
}
// NOTE: RECOVERABLE ERROR
Object[] args = { versionString };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_VERSION_NOT_SUPPORTED,
XMLMessages.P26_NOT_SUPPORTED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
// REVISIT - hope it is a compatible version...
// skipPastEndOfCurrentMarkup();
// return;
}
if (!fEntityReader.lookingAtSpace(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_IN_TEXTDECL,
XMLMessages.P80_WHITESPACE_REQUIRED);
restoreScannerState(prevState);
return;
}
break;
case TEXTDECL_ENCODING:
//
// encoding = "..."
//
encoding = result;
String encodingString = fStringPool.toString(encoding);
if (!validEncName(encodingString)) {
abortMarkup(XMLMessages.MSG_ENCODINGDECL_INVALID,
XMLMessages.P81_INVALID_VALUE,
encodingString);
restoreScannerState(prevState);
return;
}
fEntityReader.skipPastSpaces();
state = TEXTDECL_FINISHED;
break;
}
} while (state != TEXTDECL_FINISHED);
if (!fEntityReader.lookingAtChar('?', true) || !fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_TEXTDECL_UNTERMINATED,
XMLMessages.P77_UNTERMINATED);
restoreScannerState(prevState);
return;
}
decreaseMarkupDepth();
fDTDGrammar.callTextDecl(version, encoding);
if (fDTDHandler != null) {
fDTDHandler.textDecl(version, encoding);
}
restoreScannerState(prevState);
}
private QName fElementDeclQName = new QName();
/**
* Scans an element declaration.
* <pre>
* [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'
* </pre>
*/
private void scanElementDecl() throws Exception {
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ELEMENTDECL,
XMLMessages.P45_SPACE_REQUIRED);
return;
}
checkForElementTypeWithPEReference(fEntityReader, ' ', fElementQName);
if (fElementQName.rawname == -1) {
abortMarkup(XMLMessages.MSG_ELEMENT_TYPE_REQUIRED_IN_ELEMENTDECL,
XMLMessages.P45_ELEMENT_TYPE_REQUIRED);
return;
}
if (fDTDHandler != null) {
fElementDeclQName.setValues(fElementQName);
}
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_CONTENTSPEC_IN_ELEMENTDECL,
XMLMessages.P45_SPACE_REQUIRED,
fElementQName.rawname);
return;
}
int contentSpecType = -1;
int contentSpec = -1;
if (fEntityReader.skippedString(empty_string)) {
contentSpecType = XMLElementDecl.TYPE_EMPTY;
} else if (fEntityReader.skippedString(any_string)) {
contentSpecType = XMLElementDecl.TYPE_ANY;
} else if (!fEntityReader.lookingAtChar('(', true)) {
abortMarkup(XMLMessages.MSG_CONTENTSPEC_REQUIRED_IN_ELEMENTDECL,
XMLMessages.P45_CONTENTSPEC_REQUIRED,
fElementQName.rawname);
return;
} else {
int contentSpecReader = fReaderId;
int contentSpecReaderDepth = fEntityHandler.getReaderDepth();
int prevState = setScannerState(SCANNER_STATE_CONTENTSPEC);
int oldDepth = parenDepth();
fEntityHandler.setReaderDepth(oldDepth);
increaseParenDepth();
checkForPEReference(false);
boolean skippedPCDATA = fEntityReader.skippedString(pcdata_string);
if (skippedPCDATA) {
contentSpecType = XMLElementDecl.TYPE_MIXED;
// REVISIT: Validation. Should we pass in QName?
contentSpec = scanMixed(fElementQName);
} else {
contentSpecType = XMLElementDecl.TYPE_CHILDREN;
// REVISIT: Validation. Should we pass in QName?
contentSpec = scanChildren(fElementQName);
}
boolean success = contentSpec != -1;
restoreScannerState(prevState);
fEntityHandler.setReaderDepth(contentSpecReaderDepth);
if (!success) {
setParenDepth(oldDepth);
skipPastEndOfCurrentMarkup();
return;
} else {
if (parenDepth() != oldDepth) // REVISIT - should not be needed
// System.out.println("nesting depth mismatch");
;
}
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ELEMENTDECL_UNTERMINATED,
XMLMessages.P45_UNTERMINATED,
fElementQName.rawname);
return;
}
decreaseMarkupDepth();
int elementIndex = fDTDGrammar.getElementDeclIndex(fElementQName, -1);
boolean elementDeclIsExternal = getReadingExternalEntity();
if (elementIndex == -1) {
elementIndex = fDTDGrammar.addElementDecl(fElementQName, contentSpecType, contentSpec, elementDeclIsExternal);
//System.out.println("XMLDTDScanner#scanElementDecl->DTDGrammar#addElementDecl: "+elementIndex+" ("+fElementQName.localpart+","+fStringPool.toString(fElementQName.localpart)+')');
}
else {
//now check if we already add this element Decl by foward reference
fDTDGrammar.getElementDecl(elementIndex, fTempElementDecl);
if (fTempElementDecl.type == -1) {
fTempElementDecl.type = contentSpecType;
fTempElementDecl.contentSpecIndex = contentSpec;
fDTDGrammar.setElementDeclDTD(elementIndex, fTempElementDecl);
fDTDGrammar.setElementDeclIsExternal(elementIndex, elementDeclIsExternal);
}
else {
//REVISIT, valiate VC duplicate element type.
if ( fValidationEnabled )
//&&
// (elemenetDeclIsExternal==fDTDGrammar.getElementDeclIsExternal(elementIndex)
{
reportRecoverableXMLError(
XMLMessages.MSG_ELEMENT_ALREADY_DECLARED,
XMLMessages.VC_UNIQUE_ELEMENT_TYPE_DECLARATION,
fStringPool.toString(fElementQName.rawname)
);
}
}
}
if (fDTDHandler != null) {
fDTDGrammar.getElementDecl(elementIndex, fTempElementDecl);
fDTDHandler.elementDecl(fElementDeclQName, contentSpecType, contentSpec, fDTDGrammar);
}
} // scanElementDecl()
/**
* Scans mixed content model. Called after scanning past '(' S? '#PCDATA'
* <pre>
* [51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')'
* </pre>
*/
private int scanMixed(QName element) throws Exception {
int valueIndex = -1; // -1 is special value for #PCDATA
int prevNodeIndex = -1;
boolean starRequired = false;
int[] valueSeen = new int[32];
int valueCount = 0;
boolean dupAttrType = false;
int nodeIndex = -1;
while (true) {
if (fValidationEnabled) {
for (int i=0; i<valueCount;i++) {
if ( valueSeen[i] == valueIndex) {
dupAttrType = true;
break;
}
}
}
if (dupAttrType && fValidationEnabled) {
reportRecoverableXMLError(XMLMessages.MSG_DUPLICATE_TYPE_IN_MIXED_CONTENT,
XMLMessages.VC_NO_DUPLICATE_TYPES,
valueIndex);
dupAttrType = false;
}
else {
try {
valueSeen[valueCount] = valueIndex;
}
catch (ArrayIndexOutOfBoundsException ae) {
int[] newArray = new int[valueSeen.length*2];
System.arraycopy(valueSeen,0,newArray,0,valueSeen.length);
valueSeen = newArray;
valueSeen[valueCount] = valueIndex;
}
valueCount++;
nodeIndex = fDTDGrammar.addUniqueLeafNode(valueIndex);
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('|', true)) {
if (!fEntityReader.lookingAtChar(')', true)) {
reportFatalXMLError(XMLMessages.MSG_CLOSE_PAREN_REQUIRED_IN_MIXED,
XMLMessages.P51_CLOSE_PAREN_REQUIRED,
element.rawname);
return -1;
}
decreaseParenDepth();
if (nodeIndex == -1) {
nodeIndex = prevNodeIndex;
} else if (prevNodeIndex != -1) {
nodeIndex = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, prevNodeIndex, nodeIndex);
}
if (fEntityReader.lookingAtChar('*', true)) {
nodeIndex = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE, nodeIndex);
} else if (starRequired) {
reportFatalXMLError(XMLMessages.MSG_MIXED_CONTENT_UNTERMINATED,
XMLMessages.P51_UNTERMINATED,
fStringPool.toString(element.rawname),
fDTDGrammar.getContentSpecNodeAsString(nodeIndex));
return -1;
}
return nodeIndex;
}
if (nodeIndex != -1) {
if (prevNodeIndex != -1) {
nodeIndex = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, prevNodeIndex, nodeIndex);
}
prevNodeIndex = nodeIndex;
}
starRequired = true;
checkForPEReference(false);
checkForElementTypeWithPEReference(fEntityReader, ')', fElementRefQName);
valueIndex = fElementRefQName.rawname;
if (valueIndex == -1) {
reportFatalXMLError(XMLMessages.MSG_ELEMENT_TYPE_REQUIRED_IN_MIXED_CONTENT,
XMLMessages.P51_ELEMENT_TYPE_REQUIRED,
element.rawname);
return -1;
}
}
} // scanMixed(QName):int
/**
* Scans a children content model.
* <pre>
* [47] children ::= (choice | seq) ('?' | '*' | '+')?
* [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')'
* [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'
* [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')?
* </pre>
*/
private int scanChildren(QName element) throws Exception {
int depth = 1;
initializeContentModelStack(depth);
while (true) {
if (fEntityReader.lookingAtChar('(', true)) {
increaseParenDepth();
checkForPEReference(false);
depth++;
initializeContentModelStack(depth);
continue;
}
checkForElementTypeWithPEReference(fEntityReader, ')', fElementRefQName);
int valueIndex = fElementRefQName.rawname;
if (valueIndex == -1) {
reportFatalXMLError(XMLMessages.MSG_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED_IN_CHILDREN,
XMLMessages.P47_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED,
element.rawname);
return -1;
}
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF, valueIndex);
if (fEntityReader.lookingAtChar('?', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE, fNodeIndexStack[depth]);
} else if (fEntityReader.lookingAtChar('*', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE, fNodeIndexStack[depth]);
} else if (fEntityReader.lookingAtChar('+', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ONE_OR_MORE, fNodeIndexStack[depth]);
}
while (true) {
checkForPEReference(false);
if (fOpStack[depth] != XMLContentSpec.CONTENTSPECNODE_SEQ && fEntityReader.lookingAtChar('|', true)) {
if (fPrevNodeIndexStack[depth] != -1) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(fOpStack[depth], fPrevNodeIndexStack[depth], fNodeIndexStack[depth]);
}
fPrevNodeIndexStack[depth] = fNodeIndexStack[depth];
fOpStack[depth] = XMLContentSpec.CONTENTSPECNODE_CHOICE;
break;
} else if (fOpStack[depth] != XMLContentSpec.CONTENTSPECNODE_CHOICE && fEntityReader.lookingAtChar(',', true)) {
if (fPrevNodeIndexStack[depth] != -1) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(fOpStack[depth], fPrevNodeIndexStack[depth], fNodeIndexStack[depth]);
}
fPrevNodeIndexStack[depth] = fNodeIndexStack[depth];
fOpStack[depth] = XMLContentSpec.CONTENTSPECNODE_SEQ;
break;
} else {
if (!fEntityReader.lookingAtChar(')', true)) {
reportFatalXMLError(XMLMessages.MSG_CLOSE_PAREN_REQUIRED_IN_CHILDREN,
XMLMessages.P47_CLOSE_PAREN_REQUIRED,
element.rawname);
}
decreaseParenDepth();
if (fPrevNodeIndexStack[depth] != -1) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(fOpStack[depth], fPrevNodeIndexStack[depth], fNodeIndexStack[depth]);
}
int nodeIndex = fNodeIndexStack[depth--];
fNodeIndexStack[depth] = nodeIndex;
if (fEntityReader.lookingAtChar('?', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE, fNodeIndexStack[depth]);
} else if (fEntityReader.lookingAtChar('*', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE, fNodeIndexStack[depth]);
} else if (fEntityReader.lookingAtChar('+', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ONE_OR_MORE, fNodeIndexStack[depth]);
}
if (depth == 0) {
return fNodeIndexStack[0];
}
}
}
checkForPEReference(false);
}
} // scanChildren(QName):int
//
// [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
// [53] AttDef ::= S Name S AttType S DefaultDecl
// [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
//
private void scanAttlistDecl() throws Exception
{
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ATTLISTDECL,
XMLMessages.P52_SPACE_REQUIRED);
return;
}
checkForElementTypeWithPEReference(fEntityReader, ' ', fElementQName);
int elementTypeIndex = fElementQName.rawname;
if (elementTypeIndex == -1) {
abortMarkup(XMLMessages.MSG_ELEMENT_TYPE_REQUIRED_IN_ATTLISTDECL,
XMLMessages.P52_ELEMENT_TYPE_REQUIRED);
return;
}
int elementIndex = fDTDGrammar.getElementDeclIndex(fElementQName, -1);
if (elementIndex == -1) {
elementIndex = fDTDGrammar.addElementDecl(fElementQName);
//System.out.println("XMLDTDScanner#scanAttListDecl->DTDGrammar#addElementDecl: "+elementIndex+" ("+fElementQName.localpart+","+fStringPool.toString(fElementQName.localpart)+')');
}
boolean sawSpace = checkForPEReference(true);
if (fEntityReader.lookingAtChar('>', true)) {
decreaseMarkupDepth();
return;
}
// REVISIT - review this code...
if (!sawSpace) {
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
} else
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ATTRIBUTE_NAME_IN_ATTDEF,
XMLMessages.P53_SPACE_REQUIRED);
} else {
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
}
}
if (fEntityReader.lookingAtChar('>', true)) {
decreaseMarkupDepth();
return;
}
while (true) {
checkForAttributeNameWithPEReference(fEntityReader, ' ', fAttributeQName);
int attDefName = fAttributeQName.rawname;
if (attDefName == -1) {
abortMarkup(XMLMessages.MSG_ATTRIBUTE_NAME_REQUIRED_IN_ATTDEF,
XMLMessages.P53_NAME_REQUIRED,
fElementQName.rawname);
return;
}
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ATTTYPE_IN_ATTDEF,
XMLMessages.P53_SPACE_REQUIRED);
return;
}
int attDefType = -1;
boolean attDefList = false;
int attDefEnumeration = -1;
if (fEntityReader.skippedString(cdata_string)) {
attDefType = XMLAttributeDecl.TYPE_CDATA;
} else if (fEntityReader.skippedString(id_string)) {
if (!fEntityReader.skippedString(ref_string)) {
attDefType = XMLAttributeDecl.TYPE_ID;
} else if (!fEntityReader.lookingAtChar('S', true)) {
attDefType = XMLAttributeDecl.TYPE_IDREF;
} else {
attDefType = XMLAttributeDecl.TYPE_IDREF;
attDefList = true;
}
} else if (fEntityReader.skippedString(entit_string)) {
if (fEntityReader.lookingAtChar('Y', true)) {
attDefType = XMLAttributeDecl.TYPE_ENTITY;
} else if (fEntityReader.skippedString(ies_string)) {
attDefType = XMLAttributeDecl.TYPE_ENTITY;
attDefList = true;
} else {
abortMarkup(XMLMessages.MSG_ATTTYPE_REQUIRED_IN_ATTDEF,
XMLMessages.P53_ATTTYPE_REQUIRED,
elementTypeIndex, attDefName);
return;
}
} else if (fEntityReader.skippedString(nmtoken_string)) {
if (fEntityReader.lookingAtChar('S', true)) {
attDefType = XMLAttributeDecl.TYPE_NMTOKEN;
attDefList = true;
} else {
attDefType = XMLAttributeDecl.TYPE_NMTOKEN;
}
} else if (fEntityReader.skippedString(notation_string)) {
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_NOTATION_IN_NOTATIONTYPE,
XMLMessages.P58_SPACE_REQUIRED,
elementTypeIndex, attDefName);
return;
}
if (!fEntityReader.lookingAtChar('(', true)) {
abortMarkup(XMLMessages.MSG_OPEN_PAREN_REQUIRED_IN_NOTATIONTYPE,
XMLMessages.P58_OPEN_PAREN_REQUIRED,
elementTypeIndex, attDefName);
return;
}
increaseParenDepth();
attDefType = XMLAttributeDecl.TYPE_NOTATION;
attDefEnumeration = scanEnumeration(elementTypeIndex, attDefName, true);
if (attDefEnumeration == -1) {
skipPastEndOfCurrentMarkup();
return;
}
} else if (fEntityReader.lookingAtChar('(', true)) {
increaseParenDepth();
attDefType = XMLAttributeDecl.TYPE_ENUMERATION;
attDefEnumeration = scanEnumeration(elementTypeIndex, attDefName, false);
if (attDefEnumeration == -1) {
skipPastEndOfCurrentMarkup();
return;
}
} else {
abortMarkup(XMLMessages.MSG_ATTTYPE_REQUIRED_IN_ATTDEF,
XMLMessages.P53_ATTTYPE_REQUIRED,
elementTypeIndex, attDefName);
return;
}
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_DEFAULTDECL_IN_ATTDEF,
XMLMessages.P53_SPACE_REQUIRED,
elementTypeIndex, attDefName);
return;
}
int attDefDefaultType = -1;
int attDefDefaultValue = -1;
if (fEntityReader.skippedString(required_string)) {
attDefDefaultType = XMLAttributeDecl.DEFAULT_TYPE_REQUIRED;
} else if (fEntityReader.skippedString(implied_string)) {
attDefDefaultType = XMLAttributeDecl.DEFAULT_TYPE_IMPLIED;
} else {
if (fEntityReader.skippedString(fixed_string)) {
if (!fEntityReader.lookingAtSpace(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_FIXED_IN_DEFAULTDECL,
XMLMessages.P60_SPACE_REQUIRED,
elementTypeIndex, attDefName);
return;
}
fEntityReader.skipPastSpaces();
attDefDefaultType = XMLAttributeDecl.DEFAULT_TYPE_FIXED;
} else
attDefDefaultType = XMLAttributeDecl.DEFAULT_TYPE_DEFAULT;
//fElementQName.setValues(-1, elementTypeIndex, elementTypeIndex);
// if attribute name has a prefix "xml", bind it to the XML Namespace.
// since this is the only pre-defined namespace.
/***
if (fAttributeQName.prefix == fXMLSymbol) {
fAttributeQName.uri = fXMLNamespace;
}
else
fAttributeQName.setValues(-1, attDefName, attDefName);
****/
attDefDefaultValue = scanDefaultAttValue(fElementQName, fAttributeQName,
attDefType,
attDefEnumeration);
//normalize and check VC: Attribute Default Legal
if (attDefDefaultValue != -1 && attDefType != XMLAttributeDecl.TYPE_CDATA ) {
attDefDefaultValue = normalizeDefaultAttValue( fAttributeQName, attDefDefaultValue,
attDefType, attDefEnumeration,
attDefList);
}
if (attDefDefaultValue == -1) {
skipPastEndOfCurrentMarkup();
return;
}
}
if (attDefName == fXMLSpace) {
boolean ok = false;
if (attDefType == XMLAttributeDecl.TYPE_ENUMERATION) {
int index = attDefEnumeration;
if (index != -1) {
ok = (fStringPool.stringListLength(index) == 1 &&
(fStringPool.stringInList(index, fDefault) ||
fStringPool.stringInList(index, fPreserve))) ||
(fStringPool.stringListLength(index) == 2 &&
fStringPool.stringInList(index, fDefault) &&
fStringPool.stringInList(index, fPreserve));
}
}
if (!ok) {
reportFatalXMLError(XMLMessages.MSG_XML_SPACE_DECLARATION_ILLEGAL,
XMLMessages.S2_10_DECLARATION_ILLEGAL,
elementTypeIndex);
}
}
sawSpace = checkForPEReference(true);
// if attribute name has a prefix "xml", bind it to the XML Namespace.
// since this is the only pre-defined namespace.
if (fAttributeQName.prefix == fXMLSymbol) {
fAttributeQName.uri = fXMLNamespace;
}
if (fEntityReader.lookingAtChar('>', true)) {
int attDefIndex = addAttDef(fElementQName, fAttributeQName,
attDefType, attDefList, attDefEnumeration,
attDefDefaultType, attDefDefaultValue,
getReadingExternalEntity());
//System.out.println("XMLDTDScanner#scanAttlistDecl->DTDGrammar#addAttDef: "+attDefIndex+
// " ("+fElementQName.localpart+","+fStringPool.toString(fElementQName.rawname)+')'+
// " ("+fAttributeQName.localpart+","+fStringPool.toString(fAttributeQName.rawname)+')');
decreaseMarkupDepth();
return;
}
// REVISIT - review this code...
if (!sawSpace) {
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
} else
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ATTRIBUTE_NAME_IN_ATTDEF,
XMLMessages.P53_SPACE_REQUIRED);
} else {
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
}
}
if (fEntityReader.lookingAtChar('>', true)) {
int attDefIndex = addAttDef(fElementQName, fAttributeQName,
attDefType, attDefList, attDefEnumeration,
attDefDefaultType, attDefDefaultValue,
getReadingExternalEntity() );
//System.out.println("XMLDTDScanner#scanAttlistDecl->DTDGrammar#addAttDef: "+attDefIndex+
// " ("+fElementQName.localpart+","+fStringPool.toString(fElementQName.rawname)+')'+
// " ("+fAttributeQName.localpart+","+fStringPool.toString(fAttributeQName.rawname)+')');
decreaseMarkupDepth();
return;
}
int attDefIndex = addAttDef(fElementQName, fAttributeQName,
attDefType, attDefList, attDefEnumeration,
attDefDefaultType, attDefDefaultValue,
getReadingExternalEntity());
//System.out.println("XMLDTDScanner#scanAttlistDecl->DTDGrammar#addAttDef: "+attDefIndex+
// " ("+fElementQName.localpart+","+fStringPool.toString(fElementQName.rawname)+')'+
// " ("+fAttributeQName.localpart+","+fStringPool.toString(fAttributeQName.rawname)+')');
}
}
private int addAttDef(QName element, QName attribute,
int attDefType, boolean attDefList, int attDefEnumeration,
int attDefDefaultType, int attDefDefaultValue,
boolean isExternal ) throws Exception {
if (fDTDHandler != null) {
String enumString = attDefEnumeration != -1 ? fStringPool.stringListAsString(attDefEnumeration) : null;
fDTDHandler.attlistDecl(element, attribute,
attDefType, attDefList,
enumString,
attDefDefaultType, attDefDefaultValue);
}
int elementIndex = fDTDGrammar.getElementDeclIndex(element, -1);
if (elementIndex == -1) {
// REPORT Internal error here
}
else {
int attlistIndex = fDTDGrammar.getFirstAttributeDeclIndex(elementIndex);
int dupID = -1;
int dupNotation = -1;
while (attlistIndex != -1) {
fDTDGrammar.getAttributeDecl(attlistIndex, fTempAttributeDecl);
// REVISIT: Validation. Attributes are also tuples.
if (fStringPool.equalNames(fTempAttributeDecl.name.rawname, attribute.rawname)) {
/******
if (fWarningOnDuplicateAttDef) {
Object[] args = { fStringPool.toString(fElementType[elemChunk][elemIndex]),
fStringPool.toString(attributeDecl.rawname) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_DUPLICATE_ATTDEF,
XMLMessages.P53_DUPLICATE,
args,
XMLErrorReporter.ERRORTYPE_WARNING);
}
******/
return -1;
}
if (fValidationEnabled) {
if (attDefType == XMLAttributeDecl.TYPE_ID &&
fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ID ) {
dupID = fTempAttributeDecl.name.rawname;
}
if (attDefType == XMLAttributeDecl.TYPE_NOTATION
&& fTempAttributeDecl.type == XMLAttributeDecl.TYPE_NOTATION) {
dupNotation = fTempAttributeDecl.name.rawname;
}
}
attlistIndex = fDTDGrammar.getNextAttributeDeclIndex(attlistIndex);
}
if (fValidationEnabled) {
if (dupID != -1) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(dupID),
fStringPool.toString(attribute.rawname) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_MORE_THAN_ONE_ID_ATTRIBUTE,
XMLMessages.VC_ONE_ID_PER_ELEMENT_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
return -1;
}
if (dupNotation != -1) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(dupNotation),
fStringPool.toString(attribute.rawname) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_MORE_THAN_ONE_NOTATION_ATTRIBUTE,
XMLMessages.VC_ONE_NOTATION_PER_ELEMENT_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
return -1;
}
}
}
return fDTDGrammar.addAttDef(element, attribute,
attDefType, attDefList, attDefEnumeration,
attDefDefaultType, attDefDefaultValue,
isExternal);
}
//
// [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
// [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
//
private int scanEnumeration(int elementType, int attrName, boolean isNotationType) throws Exception
{
int enumIndex = fDTDGrammar.startEnumeration();
while (true) {
checkForPEReference(false);
int nameIndex = isNotationType ?
checkForNameWithPEReference(fEntityReader, ')') :
checkForNmtokenWithPEReference(fEntityReader, ')');
if (nameIndex == -1) {
if (isNotationType) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_NOTATIONTYPE,
XMLMessages.P58_NAME_REQUIRED,
elementType,
attrName);
} else {
reportFatalXMLError(XMLMessages.MSG_NMTOKEN_REQUIRED_IN_ENUMERATION,
XMLMessages.P59_NMTOKEN_REQUIRED,
elementType,
attrName);
}
fDTDGrammar.endEnumeration(enumIndex);
return -1;
}
fDTDGrammar.addNameToEnumeration(enumIndex, elementType, attrName, nameIndex, isNotationType);
/*****/
if (isNotationType && !((DefaultEntityHandler)fEntityHandler).isNotationDeclared(nameIndex)) {
Object[] args = { fStringPool.toString(elementType),
fStringPool.toString(attrName),
fStringPool.toString(nameIndex) };
((DefaultEntityHandler)fEntityHandler).addRequiredNotation(nameIndex,
fErrorReporter.getLocator(),
XMLMessages.MSG_NOTATION_NOT_DECLARED_FOR_NOTATIONTYPE_ATTRIBUTE,
XMLMessages.VC_NOTATION_DECLARED,
args);
}
/*****/
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('|', true)) {
fDTDGrammar.endEnumeration(enumIndex);
if (!fEntityReader.lookingAtChar(')', true)) {
if (isNotationType) {
reportFatalXMLError(XMLMessages.MSG_NOTATIONTYPE_UNTERMINATED,
XMLMessages.P58_UNTERMINATED,
elementType,
attrName);
} else {
reportFatalXMLError(XMLMessages.MSG_ENUMERATION_UNTERMINATED,
XMLMessages.P59_UNTERMINATED,
elementType,
attrName);
}
return -1;
}
decreaseParenDepth();
return enumIndex;
}
}
}
//
// [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
// | "'" ([^<&'] | Reference)* "'"
//
/**
* Scan the default value in an attribute declaration
*
* @param elementType handle to the element that owns the attribute
* @param attrName handle in the string pool for the attribute name
* @return handle in the string pool for the default attribute value
* @exception java.lang.Exception
*/
public int scanDefaultAttValue(QName element, QName attribute) throws Exception
{
boolean single;
if (!(single = fEntityReader.lookingAtChar('\'', true)) && !fEntityReader.lookingAtChar('\"', true)) {
reportFatalXMLError(XMLMessages.MSG_QUOTE_REQUIRED_IN_ATTVALUE,
XMLMessages.P10_QUOTE_REQUIRED,
element.rawname,
attribute.rawname);
return -1;
}
int previousState = setScannerState(SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE);
char qchar = single ? '\'' : '\"';
fDefaultAttValueReader = fReaderId;
fDefaultAttValueElementType = element.rawname;
fDefaultAttValueAttrName = attribute.rawname;
boolean setMark = true;
int dataOffset = fLiteralData.length();
while (true) {
fDefaultAttValueOffset = fEntityReader.currentOffset();
if (setMark) {
fDefaultAttValueMark = fDefaultAttValueOffset;
setMark = false;
}
if (fEntityReader.lookingAtChar(qchar, true)) {
if (fReaderId == fDefaultAttValueReader)
break;
continue;
}
if (fEntityReader.lookingAtChar(' ', true)) {
continue;
}
boolean skippedCR;
if ((skippedCR = fEntityReader.lookingAtChar((char)0x0D, true)) || fEntityReader.lookingAtSpace(true)) {
if (fDefaultAttValueOffset - fDefaultAttValueMark > 0)
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
setMark = true;
fLiteralData.append(' ');
if (skippedCR)
fEntityReader.lookingAtChar((char)0x0A, true);
continue;
}
if (fEntityReader.lookingAtChar('&', true)) {
if (fDefaultAttValueOffset - fDefaultAttValueMark > 0)
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
setMark = true;
//
// Check for character reference first.
//
if (fEntityReader.lookingAtChar('#', true)) {
int ch = scanCharRef();
if (ch != -1) {
if (ch < 0x10000)
fLiteralData.append((char)ch);
else {
fLiteralData.append((char)(((ch-0x00010000)>>10)+0xd800));
fLiteralData.append((char)(((ch-0x00010000)&0x3ff)+0xdc00));
}
}
} else {
//
// Entity reference
//
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_REFERENCE,
XMLMessages.P68_NAME_REQUIRED);
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_REFERENCE,
XMLMessages.P68_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
} else {
int entityNameIndex = fEntityReader.addSymbol(nameOffset, nameLength);
fEntityHandler.startReadingFromEntity(entityNameIndex, markupDepth(), XMLEntityHandler.ENTITYREF_IN_DEFAULTATTVALUE);
}
}
continue;
}
if (fEntityReader.lookingAtChar('<', true)) {
if (fDefaultAttValueOffset - fDefaultAttValueMark > 0)
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
setMark = true;
reportFatalXMLError(XMLMessages.MSG_LESSTHAN_IN_ATTVALUE,
XMLMessages.WFC_NO_LESSTHAN_IN_ATTVALUE,
element.rawname,
attribute.rawname);
continue;
}
//
// REVISIT - HACK !!! code added to pass incorrect OASIS test 'valid-sa-094'
// Remove this next section to conform to the spec...
//
if (!getReadingExternalEntity() && fEntityReader.lookingAtChar('%', true)) {
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength != 0 && fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_PEREFERENCE_WITHIN_MARKUP,
XMLMessages.WFC_PES_IN_INTERNAL_SUBSET,
fEntityReader.addString(nameOffset, nameLength));
}
}
//
// END HACK !!!
//
if (!fEntityReader.lookingAtValidChar(true)) {
if (fDefaultAttValueOffset - fDefaultAttValueMark > 0)
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
setMark = true;
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
return -1;
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_ATTVALUE,
XMLMessages.P10_INVALID_CHARACTER,
fStringPool.toString(element.rawname),
fStringPool.toString(attribute.rawname),
Integer.toHexString(invChar));
}
continue;
}
}
restoreScannerState(previousState);
int dataLength = fLiteralData.length() - dataOffset;
if (dataLength == 0) {
return fEntityReader.addString(fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
}
if (fDefaultAttValueOffset - fDefaultAttValueMark > 0) {
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
dataLength = fLiteralData.length() - dataOffset;
}
return fLiteralData.addString(dataOffset, dataLength);
}
//
// [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'
//
private void scanNotationDecl() throws Exception
{
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_NOTATION_NAME_IN_NOTATIONDECL,
XMLMessages.P82_SPACE_REQUIRED);
return;
}
int notationName = checkForNameWithPEReference(fEntityReader, ' ');
if (notationName == -1) {
abortMarkup(XMLMessages.MSG_NOTATION_NAME_REQUIRED_IN_NOTATIONDECL,
XMLMessages.P82_NAME_REQUIRED);
return;
}
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_NOTATION_NAME_IN_NOTATIONDECL,
XMLMessages.P82_SPACE_REQUIRED,
notationName);
return;
}
if (!scanExternalID(true)) {
skipPastEndOfCurrentMarkup();
return;
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_NOTATIONDECL_UNTERMINATED,
XMLMessages.P82_UNTERMINATED,
notationName);
return;
}
decreaseMarkupDepth();
/****
System.out.println(fStringPool.toString(notationName)+","
+fStringPool.toString(fPubidLiteral) + ","
+fStringPool.toString(fSystemLiteral) + ","
+getReadingExternalEntity());
/****/
int notationIndex = ((DefaultEntityHandler) fEntityHandler).addNotationDecl( notationName,
fPubidLiteral,
fSystemLiteral,
getReadingExternalEntity());
fDTDGrammar.addNotationDecl(notationName, fPubidLiteral, fSystemLiteral);
if (fDTDHandler != null) {
fDTDHandler.notationDecl(notationName, fPubidLiteral, fSystemLiteral);
}
}
//
// [70] EntityDecl ::= GEDecl | PEDecl
// [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
// [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
// [73] EntityDef ::= EntityValue | (ExternalID NDataDecl?)
// [74] PEDef ::= EntityValue | ExternalID
// [75] ExternalID ::= 'SYSTEM' S SystemLiteral
// | 'PUBLIC' S PubidLiteral S SystemLiteral
// [76] NDataDecl ::= S 'NDATA' S Name
// [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
// | "'" ([^%&'] | PEReference | Reference)* "'"
//
// Called after scanning 'ENTITY'
//
private void scanEntityDecl() throws Exception
{
boolean isPEDecl = false;
boolean sawPERef = false;
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
if (!fEntityReader.lookingAtChar('%', true)) {
isPEDecl = false; // <!ENTITY x "x">
} else if (fEntityReader.lookingAtSpace(true)) {
checkForPEReference(false); // <!ENTITY % x "x">
isPEDecl = true;
} else if (!getReadingExternalEntity()) {
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ENTITY_NAME_IN_PEDECL,
XMLMessages.P72_SPACE);
isPEDecl = true;
} else if (fEntityReader.lookingAtChar('%', false)) {
checkForPEReference(false); // <!ENTITY %%x; "x"> is legal
isPEDecl = true;
} else {
sawPERef = true;
}
} else if (!getReadingExternalEntity() || !fEntityReader.lookingAtChar('%', true)) {
// <!ENTITY[^ ]...> or <!ENTITY[^ %]...>
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ENTITY_NAME_IN_ENTITYDECL,
XMLMessages.P70_SPACE);
isPEDecl = false;
} else if (fEntityReader.lookingAtSpace(false)) {
// <!ENTITY% ...>
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_PERCENT_IN_PEDECL,
XMLMessages.P72_SPACE);
isPEDecl = false;
} else {
sawPERef = true;
}
if (sawPERef) {
while (true) {
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_NAME_REQUIRED);
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
} else {
int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength);
int readerDepth = (fScannerState == SCANNER_STATE_CONTENTSPEC) ? parenDepth() : markupDepth();
fEntityHandler.startReadingFromEntity(peNameIndex, readerDepth, XMLEntityHandler.ENTITYREF_IN_DTD_WITHIN_MARKUP);
}
fEntityReader.skipPastSpaces();
if (!fEntityReader.lookingAtChar('%', true))
break;
if (!isPEDecl) {
if (fEntityReader.lookingAtSpace(true)) {
checkForPEReference(false);
isPEDecl = true;
break;
}
isPEDecl = fEntityReader.lookingAtChar('%', true);
}
}
}
int entityName = checkForNameWithPEReference(fEntityReader, ' ');
if (entityName == -1) {
abortMarkup(XMLMessages.MSG_ENTITY_NAME_REQUIRED_IN_ENTITYDECL,
XMLMessages.P70_REQUIRED_NAME);
return;
}
if (!fDTDGrammar.startEntityDecl(isPEDecl, entityName)) {
skipPastEndOfCurrentMarkup();
return;
}
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_ENTITY_NAME_IN_ENTITYDECL,
XMLMessages.P70_REQUIRED_SPACE,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
if (isPEDecl) {
boolean single;
if ((single = fEntityReader.lookingAtChar('\'', true)) || fEntityReader.lookingAtChar('\"', true)) {
int value = scanEntityValue(single);
if (value == -1) {
skipPastEndOfCurrentMarkup();
fDTDGrammar.endEntityDecl();
return;
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED,
XMLMessages.P72_UNTERMINATED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
decreaseMarkupDepth();
fDTDGrammar.endEntityDecl();
// a hack by Eric
//REVISIT
fDTDGrammar.addInternalPEDecl(entityName, value);
if (fDTDHandler != null) {
fDTDHandler.internalPEDecl(entityName, value);
}
int entityIndex = ((DefaultEntityHandler) fEntityHandler).addInternalPEDecl(entityName,
value,
getReadingExternalEntity());
} else {
if (!scanExternalID(false)) {
skipPastEndOfCurrentMarkup();
fDTDGrammar.endEntityDecl();
return;
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED,
XMLMessages.P72_UNTERMINATED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
decreaseMarkupDepth();
fDTDGrammar.endEntityDecl();
//a hack by Eric
//REVISIT
fDTDGrammar.addExternalPEDecl(entityName, fPubidLiteral, fSystemLiteral);
if (fDTDHandler != null) {
fDTDHandler.externalPEDecl(entityName, fPubidLiteral, fSystemLiteral);
}
int entityIndex = ((DefaultEntityHandler) fEntityHandler).addExternalPEDecl(entityName,
fPubidLiteral,
fSystemLiteral, getReadingExternalEntity());
}
} else {
boolean single;
if ((single = fEntityReader.lookingAtChar('\'', true)) || fEntityReader.lookingAtChar('\"', true)) {
int value = scanEntityValue(single);
if (value == -1) {
skipPastEndOfCurrentMarkup();
fDTDGrammar.endEntityDecl();
return;
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED,
XMLMessages.P71_UNTERMINATED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
decreaseMarkupDepth();
fDTDGrammar.endEntityDecl();
//a hack by Eric
//REVISIT
fDTDGrammar.addInternalEntityDecl(entityName, value);
if (fDTDHandler != null) {
fDTDHandler.internalEntityDecl(entityName, value);
}
int entityIndex = ((DefaultEntityHandler) fEntityHandler).addInternalEntityDecl(entityName,
value,
getReadingExternalEntity());
} else {
if (!scanExternalID(false)) {
skipPastEndOfCurrentMarkup();
fDTDGrammar.endEntityDecl();
return;
}
boolean unparsed = false;
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
unparsed = fEntityReader.skippedString(ndata_string);
}
if (!unparsed) {
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED,
XMLMessages.P72_UNTERMINATED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
decreaseMarkupDepth();
fDTDGrammar.endEntityDecl();
//a hack by Eric
//REVISIT
fDTDGrammar.addExternalEntityDecl(entityName, fPubidLiteral, fSystemLiteral);
if (fDTDHandler != null) {
fDTDHandler.externalEntityDecl(entityName, fPubidLiteral, fSystemLiteral);
}
int entityIndex = ((DefaultEntityHandler) fEntityHandler).addExternalEntityDecl(entityName,
fPubidLiteral,
fSystemLiteral,
getReadingExternalEntity());
} else {
if (!fEntityReader.lookingAtSpace(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_NOTATION_NAME_IN_UNPARSED_ENTITYDECL,
XMLMessages.P76_SPACE_REQUIRED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
fEntityReader.skipPastSpaces();
int ndataOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName('>');
int ndataLength = fEntityReader.currentOffset() - ndataOffset;
if (ndataLength == 0) {
abortMarkup(XMLMessages.MSG_NOTATION_NAME_REQUIRED_FOR_UNPARSED_ENTITYDECL,
XMLMessages.P76_REQUIRED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
int notationName = fEntityReader.addSymbol(ndataOffset, ndataLength);
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED,
XMLMessages.P72_UNTERMINATED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
decreaseMarkupDepth();
fDTDGrammar.endEntityDecl();
//a hack by Eric
//REVISIT
fDTDGrammar.addUnparsedEntityDecl(entityName, fPubidLiteral, fSystemLiteral, notationName);
if (fDTDHandler != null) {
fDTDHandler.unparsedEntityDecl(entityName, fPubidLiteral, fSystemLiteral, notationName);
}
/****
System.out.println("----addUnparsedEntity--- "+ fStringPool.toString(entityName)+","
+fStringPool.toString(notationName)+","
+fStringPool.toString(fPubidLiteral) + ","
+fStringPool.toString(fSystemLiteral) + ","
+getReadingExternalEntity());
/****/
int entityIndex = ((DefaultEntityHandler) fEntityHandler).addUnparsedEntityDecl(entityName,
fPubidLiteral,
fSystemLiteral,
notationName,
getReadingExternalEntity());
}
}
}
}
//
// [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
// | "'" ([^%&'] | PEReference | Reference)* "'"
//
private int scanEntityValue(boolean single) throws Exception
{
char qchar = single ? '\'' : '\"';
fEntityValueMark = fEntityReader.currentOffset();
int entityValue = fEntityReader.scanEntityValue(qchar, true);
if (entityValue < 0)
entityValue = scanComplexEntityValue(qchar, entityValue);
return entityValue;
}
private int scanComplexEntityValue(char qchar, int result) throws Exception
{
int previousState = setScannerState(SCANNER_STATE_ENTITY_VALUE);
fEntityValueReader = fReaderId;
int dataOffset = fLiteralData.length();
while (true) {
switch (result) {
case XMLEntityHandler.ENTITYVALUE_RESULT_FINISHED:
{
int offset = fEntityReader.currentOffset();
fEntityReader.lookingAtChar(qchar, true);
restoreScannerState(previousState);
int dataLength = fLiteralData.length() - dataOffset;
if (dataLength == 0) {
return fEntityReader.addString(fEntityValueMark, offset - fEntityValueMark);
}
if (offset - fEntityValueMark > 0) {
fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark);
dataLength = fLiteralData.length() - dataOffset;
}
return fLiteralData.addString(dataOffset, dataLength);
}
case XMLEntityHandler.ENTITYVALUE_RESULT_REFERENCE:
{
int offset = fEntityReader.currentOffset();
if (offset - fEntityValueMark > 0)
fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark);
fEntityReader.lookingAtChar('&', true);
//
// Check for character reference first.
//
if (fEntityReader.lookingAtChar('#', true)) {
int ch = scanCharRef();
if (ch != -1) {
if (ch < 0x10000)
fLiteralData.append((char)ch);
else {
fLiteralData.append((char)(((ch-0x00010000)>>10)+0xd800));
fLiteralData.append((char)(((ch-0x00010000)&0x3ff)+0xdc00));
}
}
fEntityValueMark = fEntityReader.currentOffset();
} else {
//
// Entity reference
//
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_REFERENCE,
XMLMessages.P68_NAME_REQUIRED);
fEntityValueMark = fEntityReader.currentOffset();
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_REFERENCE,
XMLMessages.P68_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
fEntityValueMark = fEntityReader.currentOffset();
} else {
//
// 4.4.7 Bypassed
//
// When a general entity reference appears in the EntityValue in an
// entity declaration, it is bypassed and left as is.
//
fEntityValueMark = offset;
}
}
break;
}
case XMLEntityHandler.ENTITYVALUE_RESULT_PEREF:
{
int offset = fEntityReader.currentOffset();
if (offset - fEntityValueMark > 0)
fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark);
fEntityReader.lookingAtChar('%', true);
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_NAME_REQUIRED);
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
} else if (!getReadingExternalEntity()) {
reportFatalXMLError(XMLMessages.MSG_PEREFERENCE_WITHIN_MARKUP,
XMLMessages.WFC_PES_IN_INTERNAL_SUBSET,
fEntityReader.addString(nameOffset, nameLength));
} else {
int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength);
fEntityHandler.startReadingFromEntity(peNameIndex, markupDepth(), XMLEntityHandler.ENTITYREF_IN_ENTITYVALUE);
}
fEntityValueMark = fEntityReader.currentOffset();
break;
}
case XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR:
{
int offset = fEntityReader.currentOffset();
if (offset - fEntityValueMark > 0)
fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark);
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
return -1;
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_ENTITYVALUE,
XMLMessages.P9_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
fEntityValueMark = fEntityReader.currentOffset();
break;
}
case XMLEntityHandler.ENTITYVALUE_RESULT_END_OF_INPUT:
// all the work is done by the previous reader, just invoke the next one now.
break;
default:
break;
}
result = fEntityReader.scanEntityValue(fReaderId == fEntityValueReader ? qchar : -1, false);
}
}
//
//
//
private boolean checkForPEReference(boolean spaceRequired) throws Exception
{
boolean sawSpace = true;
if (spaceRequired)
sawSpace = fEntityReader.lookingAtSpace(true);
fEntityReader.skipPastSpaces();
if (!getReadingExternalEntity())
return sawSpace;
if (!fEntityReader.lookingAtChar('%', true))
return sawSpace;
while (true) {
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_NAME_REQUIRED);
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
} else {
int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength);
int readerDepth = (fScannerState == SCANNER_STATE_CONTENTSPEC) ? parenDepth() : markupDepth();
fEntityHandler.startReadingFromEntity(peNameIndex, readerDepth, XMLEntityHandler.ENTITYREF_IN_DTD_WITHIN_MARKUP);
}
fEntityReader.skipPastSpaces();
if (!fEntityReader.lookingAtChar('%', true))
return true;
}
}
//
// content model stack
//
private void initializeContentModelStack(int depth) {
if (fOpStack == null) {
fOpStack = new int[8];
fNodeIndexStack = new int[8];
fPrevNodeIndexStack = new int[8];
} else if (depth == fOpStack.length) {
int[] newStack = new int[depth * 2];
System.arraycopy(fOpStack, 0, newStack, 0, depth);
fOpStack = newStack;
newStack = new int[depth * 2];
System.arraycopy(fNodeIndexStack, 0, newStack, 0, depth);
fNodeIndexStack = newStack;
newStack = new int[depth * 2];
System.arraycopy(fPrevNodeIndexStack, 0, newStack, 0, depth);
fPrevNodeIndexStack = newStack;
}
fOpStack[depth] = -1;
fNodeIndexStack[depth] = -1;
fPrevNodeIndexStack[depth] = -1;
}
private boolean validVersionNum(String version) {
return XMLCharacterProperties.validVersionNum(version);
}
private boolean validEncName(String encoding) {
return XMLCharacterProperties.validEncName(encoding);
}
private int validPublicId(String publicId) {
return XMLCharacterProperties.validPublicId(publicId);
}
private void scanElementType(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName element) throws Exception {
if (!fNamespacesEnabled) {
element.clear();
element.localpart = entityReader.scanName(fastchar);
element.rawname = element.localpart;
return;
}
entityReader.scanQName(fastchar, element);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
} // scanElementType(XMLEntityHandler.EntityReader,char,QName)
public void checkForElementTypeWithPEReference(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName element) throws Exception {
if (!fNamespacesEnabled) {
element.clear();
element.localpart = entityReader.scanName(fastchar);
element.rawname = element.localpart;
return;
}
entityReader.scanQName(fastchar, element);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
} // checkForElementTypeWithPEReference(XMLEntityHandler.EntityReader,char,QName)
public void checkForAttributeNameWithPEReference(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName attribute) throws Exception {
if (!fNamespacesEnabled) {
attribute.clear();
attribute.localpart = entityReader.scanName(fastchar);
attribute.rawname = attribute.localpart;
return;
}
entityReader.scanQName(fastchar, attribute);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
} // checkForAttributeNameWithPEReference(XMLEntityHandler.EntityReader,char,QName)
public int checkForNameWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastcheck) throws Exception {
//
// REVISIT - what does this have to do with PE references?
//
int valueIndex = entityReader.scanName(fastcheck);
return valueIndex;
}
public int checkForNmtokenWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastcheck) throws Exception {
//
// REVISIT - what does this have to do with PE references?
//
int nameOffset = entityReader.currentOffset();
entityReader.skipPastNmtoken(fastcheck);
int nameLength = entityReader.currentOffset() - nameOffset;
if (nameLength == 0)
return -1;
int valueIndex = entityReader.addSymbol(nameOffset, nameLength);
return valueIndex;
}
public int scanDefaultAttValue(QName element, QName attribute,
int attType, int enumeration) throws Exception {
/***/
if (fValidationEnabled && attType == XMLAttributeDecl.TYPE_ID) {
reportRecoverableXMLError(XMLMessages.MSG_ID_DEFAULT_TYPE_INVALID,
XMLMessages.VC_ID_ATTRIBUTE_DEFAULT,
fStringPool.toString(attribute.rawname));
}
/***/
int defaultAttValue = scanDefaultAttValue(element, attribute);
if (defaultAttValue == -1)
return -1;
// REVISIT
/***
if (attType != fCDATASymbol) {
// REVISIT: Validation. Should we pass in the element or is this
// default attribute value normalization?
defaultAttValue = fValidator.normalizeAttValue(null, attribute, defaultAttValue, attType, enumeration);
}
/***/
return defaultAttValue;
}
public int normalizeDefaultAttValue( QName attribute, int defaultAttValue,
int attType, int enumeration,
boolean list) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(defaultAttValue);
if (list) {
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String nmtoken = tokenizer.nextToken();
if (attType == XMLAttributeDecl.TYPE_NMTOKEN) {
if (fValidationEnabled && !XMLCharacterProperties.validNmtoken(nmtoken)) {
ok = false;
}
}
else if (attType == XMLAttributeDecl.TYPE_IDREF || attType == XMLAttributeDecl.TYPE_ENTITY) {
if (fValidationEnabled && !XMLCharacterProperties.validName(nmtoken)) {
ok = false;
}
// REVISIT: a Hack!!! THis is to pass SUN test /invalid/attr11.xml and attr12.xml
// not consistent with XML1.0 spec VC: Attribute Default Legal
if (fValidationEnabled && attType == XMLAttributeDecl.TYPE_ENTITY)
if (! ((DefaultEntityHandler) fEntityHandler).isUnparsedEntity(defaultAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID,
XMLMessages.VC_ENTITY_NAME,
fStringPool.toString(attribute.rawname), nmtoken);
}
}
sb.append(nmtoken);
if (!tokenizer.hasMoreTokens()) {
break;
}
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidationEnabled && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_ATT_DEFAULT_INVALID,
XMLMessages.VC_ATTRIBUTE_DEFAULT_LEGAL,
fStringPool.toString(attribute.rawname), newAttValue);
}
if (!newAttValue.equals(attValue)) {
defaultAttValue = fStringPool.addString(newAttValue);
}
return defaultAttValue;
}
else {
String newAttValue = attValue.trim();
if (fValidationEnabled) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
defaultAttValue = fStringPool.addSymbol(newAttValue);
}
else {
defaultAttValue = fStringPool.addSymbol(defaultAttValue);
}
if (attType == XMLAttributeDecl.TYPE_ENTITY ||
attType == XMLAttributeDecl.TYPE_ID ||
attType == XMLAttributeDecl.TYPE_IDREF ||
attType == XMLAttributeDecl.TYPE_NOTATION) {
// REVISIT: A Hack!!! THis is to pass SUN test /invalid/attr11.xml and attr12.xml
// not consistent with XML1.0 spec VC: Attribute Default Legal
if (attType == XMLAttributeDecl.TYPE_ENTITY)
if (! ((DefaultEntityHandler) fEntityHandler).isUnparsedEntity(defaultAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID,
XMLMessages.VC_ENTITY_NAME,
fStringPool.toString(attribute.rawname), newAttValue);
}
if (!XMLCharacterProperties.validName(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ATT_DEFAULT_INVALID,
XMLMessages.VC_ATTRIBUTE_DEFAULT_LEGAL,
fStringPool.toString(attribute.rawname), newAttValue);
}
}
else if (attType == XMLAttributeDecl.TYPE_NMTOKEN ||
attType == XMLAttributeDecl.TYPE_ENUMERATION ) {
if (!XMLCharacterProperties.validNmtoken(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ATT_DEFAULT_INVALID,
XMLMessages.VC_ATTRIBUTE_DEFAULT_LEGAL,
fStringPool.toString(attribute.rawname), newAttValue);
}
}
if (attType == XMLAttributeDecl.TYPE_NOTATION ||
attType == XMLAttributeDecl.TYPE_ENUMERATION ) {
if ( !fStringPool.stringInList(enumeration, defaultAttValue) ) {
reportRecoverableXMLError(XMLMessages.MSG_ATT_DEFAULT_INVALID,
XMLMessages.VC_ATTRIBUTE_DEFAULT_LEGAL,
fStringPool.toString(attribute.rawname), newAttValue);
}
}
}
else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
defaultAttValue = fStringPool.addSymbol(newAttValue);
}
}
return defaultAttValue;
}
/***
public boolean scanDoctypeDecl(boolean standalone) throws Exception {
fStandaloneReader = standalone ? fEntityHandler.getReaderId() : -1;
fDeclsAreExternal = false;
if (!fDTDScanner.scanDoctypeDecl()) {
return false;
}
if (fDTDScanner.getReadingExternalEntity()) {
fDTDScanner.scanDecls(true);
}
fDTDHandler.endDTD();
return true;
}
/***/
} // class XMLDTDScanner
| src/org/apache/xerces/framework/XMLDTDScanner.java | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999,2000 The Apache Software Foundation. All rights
* reserved.
*
* 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.framework;
import org.apache.xerces.readers.XMLEntityHandler;
import org.apache.xerces.readers.DefaultEntityHandler;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.StringPool;
import org.apache.xerces.utils.XMLCharacterProperties;
import org.apache.xerces.utils.XMLMessages;
import org.apache.xerces.validators.common.Grammar;
import org.apache.xerces.validators.common.GrammarResolver;
import org.apache.xerces.validators.common.XMLAttributeDecl;
import org.apache.xerces.validators.common.XMLElementDecl;
import org.apache.xerces.validators.dtd.DTDGrammar;
import org.xml.sax.Locator;
import org.xml.sax.SAXParseException;
import java.util.StringTokenizer;
/**
* Default implementation of an XML DTD scanner.
* <p>
* Clients who wish to scan a DTD should implement
* XMLDTDScanner.EventHandler to provide the desired behavior
* when various DTD components are encountered.
* <p>
* To process the DTD, the client application should follow the
* following sequence:
* <ol>
* <li>call scanDocTypeDecl() to scan the DOCTYPE declaration
* <li>call getReadingExternalEntity() to determine if scanDocTypeDecl found an
* external subset
* <li>if scanning an external subset, call scanDecls(true) to process the external subset
* </ol>
*
* @see XMLDTDScanner.EventHandler
* @version $Id$
*/
public final class XMLDTDScanner {
//
// Constants
//
//
// [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ")
//
private static final char[] version_string = { 'v','e','r','s','i','o','n' };
//
// [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'
//
private static final char[] element_string = { 'E','L','E','M','E','N','T' };
//
// [46] contentspec ::= 'EMPTY' | 'ANY' | Mixed | children
//
private static final char[] empty_string = { 'E','M','P','T','Y' };
private static final char[] any_string = { 'A','N','Y' };
//
// [51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*'
// | '(' S? '#PCDATA' S? ')'
//
private static final char[] pcdata_string = { '#','P','C','D','A','T','A' };
//
// [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
//
private static final char[] attlist_string = { 'A','T','T','L','I','S','T' };
//
// [55] StringType ::= 'CDATA'
//
private static final char[] cdata_string = { 'C','D','A','T','A' };
//
// [56] TokenizedType ::= 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' | 'ENTITIES'
// | 'NMTOKEN' | 'NMTOKENS'
//
// Note: We search for common substrings always trying to move forward
//
// 'ID' - Common prefix of ID, IDREF and IDREFS
// 'REF' - Common substring of IDREF and IDREFS after matching ID prefix
// 'ENTIT' - Common prefix of ENTITY and ENTITIES
// 'IES' - Suffix of ENTITIES
// 'NMTOKEN' - Common prefix of NMTOKEN and NMTOKENS
//
private static final char[] id_string = { 'I','D' };
private static final char[] ref_string = { 'R','E','F' };
private static final char[] entit_string = { 'E','N','T','I','T' };
private static final char[] ies_string = { 'I','E','S' };
private static final char[] nmtoken_string = { 'N','M','T','O','K','E','N' };
//
// [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
// [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'
//
private static final char[] notation_string = { 'N','O','T','A','T','I','O','N' };
//
// [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
//
private static final char[] required_string = { '#','R','E','Q','U','I','R','E','D' };
private static final char[] implied_string = { '#','I','M','P','L','I','E','D' };
private static final char[] fixed_string = { '#','F','I','X','E','D' };
//
// [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>'
//
private static final char[] include_string = { 'I','N','C','L','U','D','E' };
//
// [63] ignoreSect ::= '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>'
//
private static final char[] ignore_string = { 'I','G','N','O','R','E' };
//
// [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
// [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
//
private static final char[] entity_string = { 'E','N','T','I','T','Y' };
//
// [75] ExternalID ::= 'SYSTEM' S SystemLiteral
// | 'PUBLIC' S PubidLiteral S SystemLiteral
// [83] PublicID ::= 'PUBLIC' S PubidLiteral
//
private static final char[] system_string = { 'S','Y','S','T','E','M' };
private static final char[] public_string = { 'P','U','B','L','I','C' };
//
// [76] NDataDecl ::= S 'NDATA' S Name
//
private static final char[] ndata_string = { 'N','D','A','T','A' };
//
// [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" )
//
private static final char[] encoding_string = { 'e','n','c','o','d','i','n','g' };
//
// Instance Variables
//
private DTDGrammar fDTDGrammar = null;
private GrammarResolver fGrammarResolver = null;
private boolean fNamespacesEnabled = false;
private boolean fValidationEnabled = false;
private XMLElementDecl fTempElementDecl = new XMLElementDecl();
private XMLAttributeDecl fTempAttributeDecl = new XMLAttributeDecl();
private QName fElementQName = new QName();
private QName fAttributeQName = new QName();
private QName fElementRefQName = new QName();
private EventHandler fEventHandler = null;
private XMLDocumentHandler.DTDHandler fDTDHandler = null;
private StringPool fStringPool = null;
private XMLErrorReporter fErrorReporter = null;
private XMLEntityHandler fEntityHandler = null;
private XMLEntityHandler.EntityReader fEntityReader = null;
private XMLEntityHandler.CharBuffer fLiteralData = null;
private int fReaderId = -1;
private int fSystemLiteral = -1;
private int fPubidLiteral = -1;
private int[] fOpStack = null;
private int[] fNodeIndexStack = null;
private int[] fPrevNodeIndexStack = null;
private int fScannerState = SCANNER_STATE_INVALID;
private int fIncludeSectDepth = 0;
private int fDoctypeReader = -1;
private int fExternalSubsetReader = -1;
private int fDefaultAttValueReader = -1;
private int fDefaultAttValueElementType = -1;
private int fDefaultAttValueAttrName = -1;
private int fDefaultAttValueOffset = -1;
private int fDefaultAttValueMark = -1;
private int fEntityValueReader = -1;
private int fEntityValueMark = -1;
private int fXMLSymbol = -1;
private int fXMLNamespace = -1;
private int fXMLSpace = -1;
private int fDefault = -1;
private int fPreserve = -1;
private int fScannerMarkupDepth = 0;
private int fScannerParenDepth = 0;
//
// Constructors
//
public XMLDTDScanner(StringPool stringPool,
XMLErrorReporter errorReporter,
XMLEntityHandler entityHandler,
XMLEntityHandler.CharBuffer literalData) {
fStringPool = stringPool;
fErrorReporter = errorReporter;
fEntityHandler = entityHandler;
fLiteralData = literalData;
init();
}
/**
* Set the event handler
*
* @param eventHandler The place to send our callbacks.
*/
public void setEventHandler(XMLDTDScanner.EventHandler eventHandler) {
fEventHandler = eventHandler;
}
/** Set the DTD handler. */
public void setDTDHandler(XMLDocumentHandler.DTDHandler dtdHandler) {
fDTDHandler = dtdHandler;
}
/** Sets the grammar resolver. */
public void setGrammarResolver(GrammarResolver resolver) {
fGrammarResolver = resolver;
}
/** set fNamespacesEnabled **/
public void setNamespacesEnabled(boolean enabled) {
fNamespacesEnabled = enabled;
}
/** set fValidationEnabled **/
public void setValidationEnabled(boolean enabled) {
fValidationEnabled = enabled;
}
/**
* Is the XMLDTDScanner reading from an external entity?
*
* This will be true, in particular if there was an external subset
*
* @return true if the XMLDTDScanner is reading from an external entity.
*/
public boolean getReadingExternalEntity() {
return fReaderId != fDoctypeReader;
}
/**
* Is the scanner reading a ContentSpec?
*
* @return true if the scanner is reading a ContentSpec
*/
public boolean getReadingContentSpec() {
return getScannerState() == SCANNER_STATE_CONTENTSPEC;
}
/**
* Report the markup nesting depth. This allows a client to
* perform validation checks for correct markup nesting. This keeps
* scanning and validation separate.
*
* @return the markup nesting depth
*/
public int markupDepth() {
return fScannerMarkupDepth;
}
private int increaseMarkupDepth() {
return fScannerMarkupDepth++;
}
private int decreaseMarkupDepth() {
return fScannerMarkupDepth--;
}
/**
* Report the parenthesis nesting depth. This allows a client to
* perform validation checks for correct parenthesis balancing. This keeps
* scanning and validation separate.
*
* @return the parenthesis depth
*/
public int parenDepth() {
return fScannerParenDepth;
}
private void setParenDepth(int parenDepth) {
fScannerParenDepth = parenDepth;
}
private void increaseParenDepth() {
fScannerParenDepth++;
}
private void decreaseParenDepth() {
fScannerParenDepth--;
}
//
//
//
/**
* Allow XMLDTDScanner to be reused. This method is called from an
* XMLParser reset method, which passes the StringPool to be used
* by the reset DTD scanner instance.
*
* @param stringPool the string pool to be used by XMLDTDScanner.
*/
public void reset(StringPool stringPool, XMLEntityHandler.CharBuffer literalData) throws Exception {
fStringPool = stringPool;
fLiteralData = literalData;
fEntityReader = null;
fReaderId = -1;
fSystemLiteral = -1;
fPubidLiteral = -1;
fOpStack = null;
fNodeIndexStack = null;
fPrevNodeIndexStack = null;
fScannerState = SCANNER_STATE_INVALID;
fIncludeSectDepth = 0;
fDoctypeReader = -1;
fExternalSubsetReader = -1;
fDefaultAttValueReader = -1;
fDefaultAttValueElementType = -1;
fDefaultAttValueAttrName = -1;
fDefaultAttValueOffset = -1;
fDefaultAttValueMark = -1;
fEntityValueReader = -1;
fEntityValueMark = -1;
fScannerMarkupDepth = 0;
fScannerParenDepth = 0;
init();
}
private void init() {
fXMLSymbol = fStringPool.addSymbol("xml");
fXMLNamespace = fStringPool.addSymbol("http://www.w3.org/XML/1998/namespace");
fXMLSpace = fStringPool.addSymbol("xml:space");
fDefault = fStringPool.addSymbol("default");
fPreserve = fStringPool.addSymbol("preserve");
}
//
// Interfaces
//
/**
* This interface must be implemented by the users of the XMLDTDScanner class.
* These methods form the abstraction between the implementation semantics and the
* more generic task of scanning the DTD-specific XML grammar.
*/
public interface EventHandler {
/** Start of DTD. */
public void callStartDTD() throws Exception;
/** End of DTD. */
public void callEndDTD() throws Exception;
/**
* Signal the Text declaration of an external entity.
*
* @param version the handle in the string pool for the version number
* @param encoding the handle in the string pool for the encoding
* @exception java.lang.Exception
*/
public void callTextDecl(int version, int encoding) throws Exception;
/**
* Called when the doctype decl is scanned
*
* @param rootElementType handle of the rootElement
* @param publicId StringPool handle of the public id
* @param systemId StringPool handle of the system id
* @exception java.lang.Exception
*/
public void doctypeDecl(QName rootElement, int publicId, int systemId) throws Exception;
/**
* Called when the DTDScanner starts reading from the external subset
*
* @param publicId StringPool handle of the public id
* @param systemId StringPool handle of the system id
* @exception java.lang.Exception
*/
public void startReadingFromExternalSubset(int publicId, int systemId) throws Exception;
/**
* Called when the DTDScanner stop reading from the external subset
*
* @exception java.lang.Exception
*/
public void stopReadingFromExternalSubset() throws Exception;
/**
* Add an element declaration (forward reference)
*
* @param handle to the name of the element being declared
* @return handle to the element whose declaration was added
* @exception java.lang.Exception
*/
public int addElementDecl(QName elementDecl) throws Exception;
/**
* Add an element declaration
*
* @param handle to the name of the element being declared
* @param contentSpecType handle to the type name of the content spec
* @param ContentSpec handle to the content spec node for the contentSpecType
* @return handle to the element declaration that was added
* @exception java.lang.Exception
*/
public int addElementDecl(QName elementDecl, int contentSpecType, int contentSpec, boolean isExternal) throws Exception;
/**
* Add an attribute definition
*
* @param handle to the element whose attribute is being declared
* @param attName StringPool handle to the attribute name being declared
* @param attType type of the attribute
* @param enumeration StringPool handle of the attribute's enumeration list (if any)
* @param attDefaultType an integer value denoting the DefaultDecl value
* @param attDefaultValue StringPool handle of this attribute's default value
* @return handle to the attribute definition
* @exception java.lang.Exception
*/
public int addAttDef(QName elementDecl, QName attributeDecl,
int attType, boolean attList, int enumeration,
int attDefaultType, int attDefaultValue, boolean isExternal) throws Exception;
/**
* create an XMLContentSpec for a leaf
*
* @param nameIndex StringPool handle to the name (Element) for the node
* @return handle to the newly create XMLContentSpec
* @exception java.lang.Exception
*/
public int addUniqueLeafNode(int nameIndex) throws Exception;
/**
* Create an XMLContentSpec for a single non-leaf
*
* @param nodeType the type of XMLContentSpec to create - from XMLContentSpec.CONTENTSPECNODE_*
* @param nodeValue handle to an XMLContentSpec
* @return handle to the newly create XMLContentSpec
* @exception java.lang.Exception
*/
public int addContentSpecNode(int nodeType, int nodeValue) throws Exception;
/**
* Create an XMLContentSpec for a two child leaf
*
* @param nodeType the type of XMLContentSpec to create - from XMLContentSpec.CONTENTSPECNODE_*
* @param leftNodeIndex handle to an XMLContentSpec
* @param rightNodeIndex handle to an XMLContentSpec
* @return handle to the newly create XMLContentSpec
* @exception java.lang.Exception
*/
public int addContentSpecNode(int nodeType, int leftNodeIndex, int rightNodeIndex) throws Exception;
/**
* Create a string representation of an XMLContentSpec tree
*
* @param handle to an XMLContentSpec
* @return String representation of the content spec tree
* @exception java.lang.Exception
*/
public String getContentSpecNodeAsString(int nodeIndex) throws Exception;
/**
* Start the scope of an entity declaration.
*
* @return <code>true</code> on success; otherwise
* <code>false</code> if the entity declaration is recursive.
* @exception java.lang.Exception
*/
public boolean startEntityDecl(boolean isPE, int entityName) throws Exception;
/**
* End the scope of an entity declaration.
* @exception java.lang.Exception
*/
public void endEntityDecl() throws Exception;
/**
* Add a declaration for an internal parameter entity
*
* @param name StringPool handle of the parameter entity name
* @param value StringPool handle of the parameter entity value
* @return handle to the parameter entity declaration
* @exception java.lang.Exception
*/
public int addInternalPEDecl(int name, int value) throws Exception;
/**
* Add a declaration for an external parameter entity
*
* @param name StringPool handle of the parameter entity name
* @param publicId StringPool handle of the publicId
* @param systemId StringPool handle of the systemId
* @return handle to the parameter entity declaration
* @exception java.lang.Exception
*/
public int addExternalPEDecl(int name, int publicId, int systemId) throws Exception;
/**
* Add a declaration for an internal entity
*
* @param name StringPool handle of the entity name
* @param value StringPool handle of the entity value
* @return handle to the entity declaration
* @exception java.lang.Exception
*/
public int addInternalEntityDecl(int name, int value) throws Exception;
/**
* Add a declaration for an entity
*
* @param name StringPool handle of the entity name
* @param publicId StringPool handle of the publicId
* @param systemId StringPool handle of the systemId
* @return handle to the entity declaration
* @exception java.lang.Exception
*/
public int addExternalEntityDecl(int name, int publicId, int systemId) throws Exception;
/**
* Add a declaration for an unparsed entity
*
* @param name StringPool handle of the entity name
* @param publicId StringPool handle of the publicId
* @param systemId StringPool handle of the systemId
* @param notationName StringPool handle of the notationName
* @return handle to the entity declaration
* @exception java.lang.Exception
*/
public int addUnparsedEntityDecl(int name, int publicId, int systemId, int notationName) throws Exception;
/**
* Called when the scanner start scanning an enumeration
* @return StringPool handle to a string list that will hold the enumeration names
* @exception java.lang.Exception
*/
public int startEnumeration() throws Exception;
/**
* Add a name to an enumeration
* @param enumIndex StringPool handle to the string list for the enumeration
* @param elementType handle to the element that owns the attribute with the enumeration
* @param attrName StringPool handle to the name of the attribut with the enumeration
* @param nameIndex StringPool handle to the name to be added to the enumeration
* @param isNotationType true if the enumeration is an enumeration of NOTATION names
* @exception java.lang.Exception
*/
public void addNameToEnumeration(int enumIndex, int elementType, int attrName, int nameIndex, boolean isNotationType) throws Exception;
/**
* Finish processing an enumeration
*
* @param enumIndex handle to the string list which holds the enumeration to be finshed.
* @exception java.lang.Exception
*/
public void endEnumeration(int enumIndex) throws Exception;
/**
* Add a declaration for a notation
*
* @param notationName
* @param publicId
* @param systemId
* @return handle to the notation declaration
* @exception java.lang.Exception
*/
public int addNotationDecl(int notationName, int publicId, int systemId) throws Exception;
/**
* Called when a comment has been scanned
*
* @param data StringPool handle of the comment text
* @exception java.lang.Exception
*/
public void callComment(int data) throws Exception;
/**
* Called when a processing instruction has been scanned
* @param piTarget StringPool handle of the PI target
* @param piData StringPool handle of the PI data
* @exception java.lang.Exception
*/
public void callProcessingInstruction(int piTarget, int piData) throws Exception;
/**
* Supports DOM Level 2 internalSubset additions.
* Called when the internal subset is completely scanned.
*/
public void internalSubset(int internalSubset) throws Exception;
}
//
//
//
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
int stringIndex1)
throws Exception {
Object[] args = { fStringPool.toString(stringIndex1) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,int)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1) throws Exception {
Object[] args = { string1 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String)
/** Report a recoverable xml error. */
protected void reportRecoverableXMLError(int majorCode, int minorCode,
String string1, String string2)
throws Exception {
Object[] args = { string1, string2 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
} // reportRecoverableXMLError(int,int,String,String)
private void reportFatalXMLError(int majorCode, int minorCode) throws Exception {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void reportFatalXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception {
Object[] args = { fStringPool.toString(stringIndex1) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void reportFatalXMLError(int majorCode, int minorCode, String string1) throws Exception {
Object[] args = { string1 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void reportFatalXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception {
Object[] args = { fStringPool.toString(stringIndex1),
fStringPool.toString(stringIndex2) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void reportFatalXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception {
Object[] args = { string1, string2 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void reportFatalXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception {
Object[] args = { string1, string2, string3 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
private void abortMarkup(int majorCode, int minorCode) throws Exception {
reportFatalXMLError(majorCode, minorCode);
skipPastEndOfCurrentMarkup();
}
private void abortMarkup(int majorCode, int minorCode, int stringIndex1) throws Exception {
reportFatalXMLError(majorCode, minorCode, stringIndex1);
skipPastEndOfCurrentMarkup();
}
private void abortMarkup(int majorCode, int minorCode, String string1) throws Exception {
reportFatalXMLError(majorCode, minorCode, string1);
skipPastEndOfCurrentMarkup();
}
private void abortMarkup(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception {
reportFatalXMLError(majorCode, minorCode, stringIndex1, stringIndex2);
skipPastEndOfCurrentMarkup();
}
private void skipPastEndOfCurrentMarkup() throws Exception {
fEntityReader.skipToChar('>');
if (fEntityReader.lookingAtChar('>', true))
decreaseMarkupDepth();
}
//
//
//
static private final int SCANNER_STATE_INVALID = -1;
static private final int SCANNER_STATE_END_OF_INPUT = 0;
static private final int SCANNER_STATE_DOCTYPEDECL = 50;
static private final int SCANNER_STATE_MARKUP_DECL = 51;
static private final int SCANNER_STATE_TEXTDECL = 53;
static private final int SCANNER_STATE_COMMENT = 54;
static private final int SCANNER_STATE_PI = 55;
static private final int SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE = 56;
static private final int SCANNER_STATE_CONTENTSPEC = 57;
static private final int SCANNER_STATE_ENTITY_VALUE = 58;
static private final int SCANNER_STATE_SYSTEMLITERAL = 59;
static private final int SCANNER_STATE_PUBIDLITERAL = 60;
private int setScannerState(int scannerState) {
int prevState = fScannerState;
fScannerState = scannerState;
return prevState;
}
private int getScannerState() {
return fScannerState;
}
private void restoreScannerState(int scannerState) {
if (fScannerState != SCANNER_STATE_END_OF_INPUT)
fScannerState = scannerState;
}
/**
* Change readers
*
* @param nextReader the new reader that the scanner will use
* @param nextReaderId id of the reader to change to
* @exception throws java.lang.Exception
*/
public void readerChange(XMLEntityHandler.EntityReader nextReader, int nextReaderId) throws Exception {
fEntityReader = nextReader;
fReaderId = nextReaderId;
if (fScannerState == SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE) {
fDefaultAttValueOffset = fEntityReader.currentOffset();
fDefaultAttValueMark = fDefaultAttValueOffset;
} else if (fScannerState == SCANNER_STATE_ENTITY_VALUE) {
fEntityValueMark = fEntityReader.currentOffset();
}
}
/**
* Handle the end of input
*
* @param entityName the handle in the string pool of the name of the entity which has reached end of input
* @param moreToFollow if true, there is still input left to process in other readers
* @exception java.lang.Exception
*/
public void endOfInput(int entityNameIndex, boolean moreToFollow) throws Exception {
if (fValidationEnabled ) {
int readerDepth = fEntityHandler.getReaderDepth();
if (getReadingContentSpec()) {
int parenDepth = parenDepth();
if (readerDepth != parenDepth) {
reportRecoverableXMLError(XMLMessages.MSG_IMPROPER_GROUP_NESTING,
XMLMessages.VC_PROPER_GROUP_PE_NESTING,
entityNameIndex);
}
} else {
int markupDepth = markupDepth();
if (readerDepth != markupDepth) {
reportRecoverableXMLError(XMLMessages.MSG_IMPROPER_DECLARATION_NESTING,
XMLMessages.VC_PROPER_DECLARATION_PE_NESTING,
entityNameIndex);
}
}
}
//REVISIT, why are we doing this?
moreToFollow = fReaderId != fExternalSubsetReader;
// System.out.println("current Scanner state " + getScannerState() +","+ fScannerState + moreToFollow);
switch (fScannerState) {
case SCANNER_STATE_INVALID:
throw new RuntimeException("FWK004 XMLDTDScanner.endOfInput: cannot happen: 2"+"\n2");
case SCANNER_STATE_END_OF_INPUT:
break;
case SCANNER_STATE_MARKUP_DECL:
if (!moreToFollow && fIncludeSectDepth > 0) {
reportFatalXMLError(XMLMessages.MSG_INCLUDESECT_UNTERMINATED,
XMLMessages.P62_UNTERMINATED);
}
break;
case SCANNER_STATE_DOCTYPEDECL:
throw new RuntimeException("FWK004 XMLDTDScanner.endOfInput: cannot happen: 2.5"+"\n2.5");
// break;
case SCANNER_STATE_TEXTDECL:
// REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0);
break;
case SCANNER_STATE_SYSTEMLITERAL:
if (!moreToFollow) {
reportFatalXMLError(XMLMessages.MSG_SYSTEMID_UNTERMINATED,
XMLMessages.P11_UNTERMINATED);
} else {
// REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0);
}
break;
case SCANNER_STATE_PUBIDLITERAL:
if (!moreToFollow) {
reportFatalXMLError(XMLMessages.MSG_PUBLICID_UNTERMINATED,
XMLMessages.P12_UNTERMINATED);
} else {
// REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0);
}
break;
case SCANNER_STATE_COMMENT:
if (!moreToFollow && !getReadingExternalEntity()) {
reportFatalXMLError(XMLMessages.MSG_COMMENT_UNTERMINATED,
XMLMessages.P15_UNTERMINATED);
} else {
//
// REVISIT - HACK !!! code changed to pass incorrect OASIS test 'invalid--001'
// Uncomment the next line to conform to the spec...
//
//reportFatalXMLError(XMLMessages.MSG_COMMENT_NOT_IN_ONE_ENTITY,
// XMLMessages.P78_NOT_WELLFORMED);
}
break;
case SCANNER_STATE_PI:
if (!moreToFollow) {
reportFatalXMLError(XMLMessages.MSG_PI_UNTERMINATED,
XMLMessages.P16_UNTERMINATED);
} else {
reportFatalXMLError(XMLMessages.MSG_PI_NOT_IN_ONE_ENTITY,
XMLMessages.P78_NOT_WELLFORMED);
}
break;
case SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE:
if (!moreToFollow) {
reportFatalXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_UNTERMINATED,
XMLMessages.P10_UNTERMINATED,
fDefaultAttValueElementType,
fDefaultAttValueAttrName);
} else if (fReaderId == fDefaultAttValueReader) {
// REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0);
} else {
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
}
break;
case SCANNER_STATE_CONTENTSPEC:
break;
case SCANNER_STATE_ENTITY_VALUE:
if (fReaderId == fEntityValueReader) {
// REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0);
} else {
fEntityReader.append(fLiteralData, fEntityValueMark, fEntityReader.currentOffset() - fEntityValueMark);
}
break;
default:
throw new RuntimeException("FWK004 XMLDTDScanner.endOfInput: cannot happen: 3"+"\n3");
}
if (!moreToFollow) {
setScannerState(SCANNER_STATE_END_OF_INPUT);
}
}
//
// [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';'
//
private int scanCharRef() throws Exception {
int valueOffset = fEntityReader.currentOffset();
boolean hex = fEntityReader.lookingAtChar('x', true);
int num = fEntityReader.scanCharRef(hex);
if (num < 0) {
switch (num) {
case XMLEntityHandler.CHARREF_RESULT_SEMICOLON_REQUIRED:
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_CHARREF,
XMLMessages.P66_SEMICOLON_REQUIRED);
return -1;
case XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR:
int majorCode = hex ? XMLMessages.MSG_HEXDIGIT_REQUIRED_IN_CHARREF :
XMLMessages.MSG_DIGIT_REQUIRED_IN_CHARREF;
int minorCode = hex ? XMLMessages.P66_HEXDIGIT_REQUIRED :
XMLMessages.P66_DIGIT_REQUIRED;
reportFatalXMLError(majorCode, minorCode);
return -1;
case XMLEntityHandler.CHARREF_RESULT_OUT_OF_RANGE:
num = 0x110000; // this will cause the right error to be reported below...
break;
}
}
//
// [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] // any Unicode character, excluding the
// | [#xE000-#xFFFD] | [#x10000-#x10FFFF] // surrogate blocks, FFFE, and FFFF.
//
if (num < 0x20) {
if (num == 0x09 || num == 0x0A || num == 0x0D) {
return num;
}
} else if (num <= 0xD7FF || (num >= 0xE000 && (num <= 0xFFFD || (num >= 0x10000 && num <= 0x10FFFF)))) {
return num;
}
int valueLength = fEntityReader.currentOffset() - valueOffset;
reportFatalXMLError(XMLMessages.MSG_INVALID_CHARREF,
XMLMessages.WFC_LEGAL_CHARACTER,
fEntityReader.addString(valueOffset, valueLength));
return -1;
}
//
// From the standard:
//
// [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
//
// Called after scanning past '<!--'
//
private void scanComment() throws Exception
{
int commentOffset = fEntityReader.currentOffset();
boolean sawDashDash = false;
int previousState = setScannerState(SCANNER_STATE_COMMENT);
while (fScannerState == SCANNER_STATE_COMMENT) {
if (fEntityReader.lookingAtChar('-', false)) {
int nextEndOffset = fEntityReader.currentOffset();
int endOffset = 0;
fEntityReader.lookingAtChar('-', true);
int offset = fEntityReader.currentOffset();
int count = 1;
while (fEntityReader.lookingAtChar('-', true)) {
count++;
endOffset = nextEndOffset;
nextEndOffset = offset;
offset = fEntityReader.currentOffset();
}
if (count > 1) {
if (fEntityReader.lookingAtChar('>', true)) {
if (!sawDashDash && count > 2) {
reportFatalXMLError(XMLMessages.MSG_DASH_DASH_IN_COMMENT,
XMLMessages.P15_DASH_DASH);
sawDashDash = true;
}
decreaseMarkupDepth();
int comment = fEntityReader.addString(commentOffset, endOffset - commentOffset);
fDTDGrammar.callComment(comment);
if (fDTDHandler != null) {
fDTDHandler.comment(comment);
}
restoreScannerState(previousState);
return;
} else if (!sawDashDash) {
reportFatalXMLError(XMLMessages.MSG_DASH_DASH_IN_COMMENT,
XMLMessages.P15_DASH_DASH);
sawDashDash = true;
}
}
} else {
if (!fEntityReader.lookingAtValidChar(true)) {
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState != SCANNER_STATE_END_OF_INPUT) {
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_COMMENT,
XMLMessages.P15_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
}
}
}
}
restoreScannerState(previousState);
}
//
// From the standard:
//
// [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
// [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
//
private void scanPI(int piTarget) throws Exception
{
String piTargetString = fStringPool.toString(piTarget);
if (piTargetString.length() == 3 &&
(piTargetString.charAt(0) == 'X' || piTargetString.charAt(0) == 'x') &&
(piTargetString.charAt(1) == 'M' || piTargetString.charAt(1) == 'm') &&
(piTargetString.charAt(2) == 'L' || piTargetString.charAt(2) == 'l')) {
abortMarkup(XMLMessages.MSG_RESERVED_PITARGET,
XMLMessages.P17_RESERVED_PITARGET);
return;
}
int prevState = setScannerState(SCANNER_STATE_PI);
int piDataOffset = -1;
int piDataLength = 0;
if (!fEntityReader.lookingAtSpace(true)) {
if (!fEntityReader.lookingAtChar('?', true) || !fEntityReader.lookingAtChar('>', true)) {
if (fScannerState != SCANNER_STATE_END_OF_INPUT) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_IN_PI,
XMLMessages.P16_WHITESPACE_REQUIRED);
restoreScannerState(prevState);
}
return;
}
decreaseMarkupDepth();
restoreScannerState(prevState);
} else {
fEntityReader.skipPastSpaces();
piDataOffset = fEntityReader.currentOffset();
while (fScannerState == SCANNER_STATE_PI) {
while (fEntityReader.lookingAtChar('?', false)) {
int offset = fEntityReader.currentOffset();
fEntityReader.lookingAtChar('?', true);
if (fEntityReader.lookingAtChar('>', true)) {
piDataLength = offset - piDataOffset;
decreaseMarkupDepth();
restoreScannerState(prevState);
break;
}
}
if (fScannerState != SCANNER_STATE_PI)
break;
if (!fEntityReader.lookingAtValidChar(true)) {
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState != SCANNER_STATE_END_OF_INPUT) {
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_PI,
XMLMessages.P16_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
skipPastEndOfCurrentMarkup();
restoreScannerState(prevState);
}
return;
}
}
}
int piData = piDataLength == 0 ?
StringPool.EMPTY_STRING : fEntityReader.addString(piDataOffset, piDataLength);
fDTDGrammar.callProcessingInstruction(piTarget, piData);
if (fDTDHandler != null) {
fDTDHandler.processingInstruction(piTarget, piData);
}
}
//
// From the standard:
//
// [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S?
// ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
// [29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl
// | NotationDecl | PI | Comment
//
// Called after scanning '<!DOCTYPE'
//
/**
* This routine is called after the <!DOCTYPE portion of a DOCTYPE
* line has been called. scanDocTypeDecl goes onto scan the rest of the DOCTYPE
* decl. If an internal DTD subset exists, it is scanned. If an external DTD
* subset exists, scanDocTypeDecl sets up the state necessary to process it.
*
* @return true if successful
* @exception java.lang.Exception
*/
public boolean scanDoctypeDecl() throws Exception
{
//System.out.println("XMLDTDScanner#scanDoctypeDecl()");
fDTDGrammar = new DTDGrammar(fStringPool);
fDTDGrammar.callStartDTD();
increaseMarkupDepth();
fEntityReader = fEntityHandler.getEntityReader();
fReaderId = fEntityHandler.getReaderId();
fDoctypeReader = fReaderId;
setScannerState(SCANNER_STATE_DOCTYPEDECL);
if (!fEntityReader.lookingAtSpace(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL,
XMLMessages.P28_SPACE_REQUIRED);
return false;
}
fEntityReader.skipPastSpaces();
scanElementType(fEntityReader, ' ', fElementQName);
if (fElementQName.rawname == -1) {
abortMarkup(XMLMessages.MSG_ROOT_ELEMENT_TYPE_REQUIRED,
XMLMessages.P28_ROOT_ELEMENT_TYPE_REQUIRED);
return false;
}
boolean lbrkt;
boolean scanExternalSubset = false;
int publicId = -1;
int systemId = -1;
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
if (!(lbrkt = fEntityReader.lookingAtChar('[', true)) && !fEntityReader.lookingAtChar('>', false)) {
if (!scanExternalID(false)) {
skipPastEndOfCurrentMarkup();
return false;
}
scanExternalSubset = true;
publicId = fPubidLiteral;
systemId = fSystemLiteral;
fEntityReader.skipPastSpaces();
lbrkt = fEntityReader.lookingAtChar('[', true);
}
} else
lbrkt = fEntityReader.lookingAtChar('[', true);
fDTDGrammar.doctypeDecl(fElementQName, publicId, systemId);
if (fDTDHandler != null) {
fDTDHandler.startDTD(fElementQName, publicId, systemId);
}
if (lbrkt) {
scanDecls(false);
fEntityReader.skipPastSpaces();
}
if (!fEntityReader.lookingAtChar('>', true)) {
if (fScannerState != SCANNER_STATE_END_OF_INPUT) {
abortMarkup(XMLMessages.MSG_DOCTYPEDECL_UNTERMINATED,
XMLMessages.P28_UNTERMINATED,
fElementQName.rawname);
}
return false;
}
decreaseMarkupDepth();
//System.out.println(" scanExternalSubset: "+scanExternalSubset);
if (scanExternalSubset) {
((DefaultEntityHandler) fEntityHandler).startReadingFromExternalSubset( fStringPool.toString(publicId),
fStringPool.toString(systemId),
markupDepth());
fDTDGrammar.startReadingFromExternalSubset(publicId, systemId);
}
fGrammarResolver.putGrammar("", fDTDGrammar);
return true;
}
//
// [75] ExternalID ::= 'SYSTEM' S SystemLiteral
// | 'PUBLIC' S PubidLiteral S SystemLiteral
// [83] PublicID ::= 'PUBLIC' S PubidLiteral
//
private boolean scanExternalID(boolean scanPublicID) throws Exception
{
fSystemLiteral = -1;
fPubidLiteral = -1;
int offset = fEntityReader.currentOffset();
if (fEntityReader.skippedString(system_string)) {
if (!fEntityReader.lookingAtSpace(true)) {
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_SYSTEMLITERAL_IN_EXTERNALID,
XMLMessages.P75_SPACE_REQUIRED);
return false;
}
fEntityReader.skipPastSpaces();
if( getReadingExternalEntity() == true ) { //Are we in external subset?
checkForPEReference(false);//If so Check for PE Ref
}
return scanSystemLiteral();
}
if (fEntityReader.skippedString(public_string)) {
if (!fEntityReader.lookingAtSpace(true)) {
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_PUBIDLITERAL_IN_EXTERNALID,
XMLMessages.P75_SPACE_REQUIRED);
return false;
}
fEntityReader.skipPastSpaces();
if (!scanPubidLiteral())
return false;
if (scanPublicID) {
//
// [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'
//
if (!fEntityReader.lookingAtSpace(true))
return true; // no S, not an ExternalID
fEntityReader.skipPastSpaces();
if (fEntityReader.lookingAtChar('>', false)) // matches end of NotationDecl
return true;
} else {
if (!fEntityReader.lookingAtSpace(true)) {
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_AFTER_PUBIDLITERAL_IN_EXTERNALID,
XMLMessages.P75_SPACE_REQUIRED);
return false;
}
fEntityReader.skipPastSpaces();
}
return scanSystemLiteral();
}
reportFatalXMLError(XMLMessages.MSG_EXTERNALID_REQUIRED,
XMLMessages.P75_INVALID);
return false;
}
//
// [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
//
// REVISIT - need to look into uri escape mechanism for non-ascii characters.
//
private boolean scanSystemLiteral() throws Exception
{
boolean single;
if (!(single = fEntityReader.lookingAtChar('\'', true)) && !fEntityReader.lookingAtChar('\"', true)) {
reportFatalXMLError(XMLMessages.MSG_QUOTE_REQUIRED_IN_SYSTEMID,
XMLMessages.P11_QUOTE_REQUIRED);
return false;
}
int prevState = setScannerState(SCANNER_STATE_SYSTEMLITERAL);
int offset = fEntityReader.currentOffset();
char qchar = single ? '\'' : '\"';
boolean dataok = true;
boolean fragment = false;
while (!fEntityReader.lookingAtChar(qchar, false)) {
//ericye
//System.out.println("XMLDTDScanner#scanDoctypeDecl() 3333333, "+fReaderId+", " + fScannerState+", " +fExternalSubsetReader);
if (fEntityReader.lookingAtChar('#', true)) {
fragment = true;
} else if (!fEntityReader.lookingAtValidChar(true)) {
//System.out.println("XMLDTDScanner#scanDoctypeDecl() 555555 scan state: " + fScannerState);
dataok = false;
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
return false;
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_SYSTEMID,
XMLMessages.P11_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
}
}
if (dataok) {
fSystemLiteral = fEntityReader.addString(offset, fEntityReader.currentOffset() - offset);
if (fragment) {
// NOTE: RECOVERABLE ERROR
Object[] args = { fStringPool.toString(fSystemLiteral) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_URI_FRAGMENT_IN_SYSTEMID,
XMLMessages.P11_URI_FRAGMENT,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
fEntityReader.lookingAtChar(qchar, true);
restoreScannerState(prevState);
return dataok;
}
//
// [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
// [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]
//
private boolean scanPubidLiteral() throws Exception
{
boolean single;
if (!(single = fEntityReader.lookingAtChar('\'', true)) && !fEntityReader.lookingAtChar('\"', true)) {
reportFatalXMLError(XMLMessages.MSG_QUOTE_REQUIRED_IN_PUBLICID,
XMLMessages.P12_QUOTE_REQUIRED);
return false;
}
char qchar = single ? '\'' : '\"';
int prevState = setScannerState(SCANNER_STATE_PUBIDLITERAL);
boolean dataok = true;
while (true) {
if (fEntityReader.lookingAtChar((char)0x09, true)) {
dataok = false;
reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL,
XMLMessages.P12_INVALID_CHARACTER, "9");
}
if (!fEntityReader.lookingAtSpace(true))
break;
}
int offset = fEntityReader.currentOffset();
int dataOffset = fLiteralData.length();
int toCopy = offset;
while (true) {
if (fEntityReader.lookingAtChar(qchar, true)) {
if (dataok && offset - toCopy > 0)
fEntityReader.append(fLiteralData, toCopy, offset - toCopy);
break;
}
if (fEntityReader.lookingAtChar((char)0x09, true)) {
dataok = false;
reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL,
XMLMessages.P12_INVALID_CHARACTER, "9");
continue;
}
if (fEntityReader.lookingAtSpace(true)) {
if (dataok && offset - toCopy > 0)
fEntityReader.append(fLiteralData, toCopy, offset - toCopy);
while (true) {
if (fEntityReader.lookingAtChar((char)0x09, true)) {
dataok = false;
reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL,
XMLMessages.P12_INVALID_CHARACTER, "9");
break;
} else if (!fEntityReader.lookingAtSpace(true)) {
break;
}
}
if (fEntityReader.lookingAtChar(qchar, true))
break;
if (dataok) {
fLiteralData.append(' ');
offset = fEntityReader.currentOffset();
toCopy = offset;
}
continue;
}
if (!fEntityReader.lookingAtValidChar(true)) {
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
return false;
dataok = false;
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_PUBLICID,
XMLMessages.P12_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
}
if (dataok)
offset = fEntityReader.currentOffset();
}
if (dataok) {
int dataLength = fLiteralData.length() - dataOffset;
fPubidLiteral = fLiteralData.addString(dataOffset, dataLength);
String publicId = fStringPool.toString(fPubidLiteral);
int invCharIndex = validPublicId(publicId);
if (invCharIndex >= 0) {
reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL,
XMLMessages.P12_INVALID_CHARACTER,
Integer.toHexString(publicId.charAt(invCharIndex)));
return false;
}
}
restoreScannerState(prevState);
return dataok;
}
//
// [??] intSubsetDecl = '[' (markupdecl | PEReference | S)* ']'
//
// [31] extSubsetDecl ::= ( markupdecl | conditionalSect | PEReference | S )*
// [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>'
//
// [29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl
// | NotationDecl | PI | Comment
//
// [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'
//
// [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
//
// [70] EntityDecl ::= GEDecl | PEDecl
// [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
// [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
//
// [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'
//
// [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
//
// [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
//
// [61] conditionalSect ::= includeSect | ignoreSect
// [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>'
// [63] ignoreSect ::= '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>'
// [64] ignoreSectContents ::= Ignore ('<![' ignoreSectContents ']]>' Ignore)*
// [65] Ignore ::= Char* - (Char* ('<![' | ']]>') Char*)
//
/**
* Scan markup declarations
*
* @param extSubset true if the scanner is scanning an external subset, false
* if it is scanning an internal subset
* @exception java.lang.Exception
*/
public void scanDecls(boolean extSubset) throws Exception
{
int subsetOffset = fEntityReader.currentOffset();
if (extSubset)
fExternalSubsetReader = fReaderId;
fIncludeSectDepth = 0;
boolean parseTextDecl = extSubset;
int prevState = setScannerState(SCANNER_STATE_MARKUP_DECL);
while (fScannerState == SCANNER_STATE_MARKUP_DECL) {
boolean newParseTextDecl = false;
if (!extSubset && fEntityReader.lookingAtChar(']', false)) {
int subsetLength = fEntityReader.currentOffset() - subsetOffset;
int internalSubset = fEntityReader.addString(subsetOffset, subsetLength);
fDTDGrammar.internalSubset(internalSubset);
if (fDTDHandler != null) {
fDTDHandler.internalSubset(internalSubset);
}
fEntityReader.lookingAtChar(']', true);
restoreScannerState(prevState);
return;
}
if (fEntityReader.lookingAtChar('<', true)) {
int olddepth = markupDepth();
increaseMarkupDepth();
if (fEntityReader.lookingAtChar('!', true)) {
if (fEntityReader.lookingAtChar('-', true)) {
if (fEntityReader.lookingAtChar('-', true)) {
scanComment();
} else {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
}
} else if (fEntityReader.lookingAtChar('[', true) && getReadingExternalEntity()) {
checkForPEReference(false);
if (fEntityReader.skippedString(include_string)) {
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('[', true)) {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
} else {
fIncludeSectDepth++;
}
} else if (fEntityReader.skippedString(ignore_string)) {
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('[', true)) {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
} else
scanIgnoreSectContents();
} else {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
}
} else if (fEntityReader.skippedString(element_string)) {
scanElementDecl();
}
else if (fEntityReader.skippedString(attlist_string))
scanAttlistDecl();
else if (fEntityReader.skippedString(entity_string))
scanEntityDecl();
else if (fEntityReader.skippedString(notation_string))
scanNotationDecl();
else {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
}
} else if (fEntityReader.lookingAtChar('?', true)) {
int piTarget = fEntityReader.scanName(' ');
if (piTarget == -1) {
abortMarkup(XMLMessages.MSG_PITARGET_REQUIRED,
XMLMessages.P16_REQUIRED);
} else if ("xml".equals(fStringPool.toString(piTarget))) {
if (fEntityReader.lookingAtSpace(true)) {
if (parseTextDecl) { // a TextDecl looks like a PI with the target 'xml'
scanTextDecl();
} else {
abortMarkup(XMLMessages.MSG_TEXTDECL_MUST_BE_FIRST,
XMLMessages.P30_TEXTDECL_MUST_BE_FIRST);
}
} else { // a PI target matching 'xml'
abortMarkup(XMLMessages.MSG_RESERVED_PITARGET,
XMLMessages.P17_RESERVED_PITARGET);
}
} else // PI
scanPI(piTarget);
} else {
abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
}
} else if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
} else if (fEntityReader.lookingAtChar('%', true)) {
//
// [69] PEReference ::= '%' Name ';'
//
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_NAME_REQUIRED);
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
} else {
int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength);
newParseTextDecl = fEntityHandler.startReadingFromEntity(peNameIndex, markupDepth(), XMLEntityHandler.ENTITYREF_IN_DTD_AS_MARKUP);
}
} else if (fIncludeSectDepth > 0 && fEntityReader.lookingAtChar(']', true)) {
if (!fEntityReader.lookingAtChar(']', true) || !fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_INCLUDESECT_UNTERMINATED,
XMLMessages.P62_UNTERMINATED);
} else
decreaseMarkupDepth();
fIncludeSectDepth--;
} else {
if (!fEntityReader.lookingAtValidChar(false)) {
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
break;
if (invChar >= 0) {
if (!extSubset) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_INTERNAL_SUBSET,
XMLMessages.P28_INVALID_CHARACTER,
Integer.toHexString(invChar));
} else {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_EXTERNAL_SUBSET,
XMLMessages.P30_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
}
} else {
reportFatalXMLError(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD,
XMLMessages.P29_NOT_RECOGNIZED);
fEntityReader.lookingAtValidChar(true);
}
}
parseTextDecl = newParseTextDecl;
}
if (extSubset) {
((DefaultEntityHandler) fEntityHandler).stopReadingFromExternalSubset();
fDTDGrammar.stopReadingFromExternalSubset();
fDTDGrammar.callEndDTD();
if (fDTDHandler != null) {
fDTDHandler.endDTD();
}
// REVISIT: What should the namspace URI of a DTD be?
fGrammarResolver.putGrammar("", fDTDGrammar);
}
}
//
// [64] ignoreSectContents ::= Ignore ('<![' ignoreSectContents ']]>' Ignore)*
// [65] Ignore ::= Char* - (Char* ('<![' | ']]>') Char*)
//
private void scanIgnoreSectContents() throws Exception
{
int initialDepth = ++fIncludeSectDepth;
while (true) {
if (fEntityReader.lookingAtChar('<', true)) {
//
// These tests are split so that we handle cases like
// '<<![' and '<!<![' which we might otherwise miss.
//
if (fEntityReader.lookingAtChar('!', true) && fEntityReader.lookingAtChar('[', true))
fIncludeSectDepth++;
} else if (fEntityReader.lookingAtChar(']', true)) {
//
// The same thing goes for ']<![' and '<]]>', etc.
//
if (fEntityReader.lookingAtChar(']', true)) {
while (fEntityReader.lookingAtChar(']', true)) {
/* empty loop body */
}
if (fEntityReader.lookingAtChar('>', true)) {
if (fIncludeSectDepth-- == initialDepth) {
decreaseMarkupDepth();
return;
}
}
}
} else if (!fEntityReader.lookingAtValidChar(true)) {
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
return;
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_IGNORESECT,
XMLMessages.P65_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
}
}
}
//
// From the standard:
//
// [77] TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>'
// [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ")
// [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" )
// [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')*
//
private void scanTextDecl() throws Exception {
int version = -1;
int encoding = -1;
final int TEXTDECL_START = 0;
final int TEXTDECL_VERSION = 1;
final int TEXTDECL_ENCODING = 2;
final int TEXTDECL_FINISHED = 3;
int prevState = setScannerState(SCANNER_STATE_TEXTDECL);
int state = TEXTDECL_START;
do {
fEntityReader.skipPastSpaces();
int offset = fEntityReader.currentOffset();
if (state == TEXTDECL_START && fEntityReader.skippedString(version_string)) {
state = TEXTDECL_VERSION;
} else if (fEntityReader.skippedString(encoding_string)) {
state = TEXTDECL_ENCODING;
} else {
abortMarkup(XMLMessages.MSG_ENCODINGDECL_REQUIRED,
XMLMessages.P77_ENCODINGDECL_REQUIRED);
restoreScannerState(prevState);
return;
}
int length = fEntityReader.currentOffset() - offset;
fEntityReader.skipPastSpaces();
if (!fEntityReader.lookingAtChar('=', true)) {
int minorCode = state == TEXTDECL_VERSION ?
XMLMessages.P24_EQ_REQUIRED :
XMLMessages.P80_EQ_REQUIRED;
abortMarkup(XMLMessages.MSG_EQ_REQUIRED_IN_TEXTDECL, minorCode,
fEntityReader.addString(offset, length));
restoreScannerState(prevState);
return;
}
fEntityReader.skipPastSpaces();
int result = fEntityReader.scanStringLiteral();
switch (result) {
case XMLEntityHandler.STRINGLIT_RESULT_QUOTE_REQUIRED:
{
int minorCode = state == TEXTDECL_VERSION ?
XMLMessages.P24_QUOTE_REQUIRED :
XMLMessages.P80_QUOTE_REQUIRED;
abortMarkup(XMLMessages.MSG_QUOTE_REQUIRED_IN_TEXTDECL, minorCode,
fEntityReader.addString(offset, length));
restoreScannerState(prevState);
return;
}
case XMLEntityHandler.STRINGLIT_RESULT_INVALID_CHAR:
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState != SCANNER_STATE_END_OF_INPUT) {
if (invChar >= 0) {
int minorCode = state == TEXTDECL_VERSION ?
XMLMessages.P26_INVALID_CHARACTER :
XMLMessages.P81_INVALID_CHARACTER;
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_TEXTDECL, minorCode,
Integer.toHexString(invChar));
}
skipPastEndOfCurrentMarkup();
restoreScannerState(prevState);
}
return;
default:
break;
}
switch (state) {
case TEXTDECL_VERSION:
//
// version="..."
//
version = result;
String versionString = fStringPool.toString(version);
if (!"1.0".equals(versionString)) {
if (!validVersionNum(versionString)) {
abortMarkup(XMLMessages.MSG_VERSIONINFO_INVALID,
XMLMessages.P26_INVALID_VALUE,
versionString);
restoreScannerState(prevState);
return;
}
// NOTE: RECOVERABLE ERROR
Object[] args = { versionString };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_VERSION_NOT_SUPPORTED,
XMLMessages.P26_NOT_SUPPORTED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
// REVISIT - hope it is a compatible version...
// skipPastEndOfCurrentMarkup();
// return;
}
if (!fEntityReader.lookingAtSpace(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_IN_TEXTDECL,
XMLMessages.P80_WHITESPACE_REQUIRED);
restoreScannerState(prevState);
return;
}
break;
case TEXTDECL_ENCODING:
//
// encoding = "..."
//
encoding = result;
String encodingString = fStringPool.toString(encoding);
if (!validEncName(encodingString)) {
abortMarkup(XMLMessages.MSG_ENCODINGDECL_INVALID,
XMLMessages.P81_INVALID_VALUE,
encodingString);
restoreScannerState(prevState);
return;
}
fEntityReader.skipPastSpaces();
state = TEXTDECL_FINISHED;
break;
}
} while (state != TEXTDECL_FINISHED);
if (!fEntityReader.lookingAtChar('?', true) || !fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_TEXTDECL_UNTERMINATED,
XMLMessages.P77_UNTERMINATED);
restoreScannerState(prevState);
return;
}
decreaseMarkupDepth();
fDTDGrammar.callTextDecl(version, encoding);
if (fDTDHandler != null) {
fDTDHandler.textDecl(version, encoding);
}
restoreScannerState(prevState);
}
private QName fElementDeclQName = new QName();
/**
* Scans an element declaration.
* <pre>
* [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>'
* </pre>
*/
private void scanElementDecl() throws Exception {
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ELEMENTDECL,
XMLMessages.P45_SPACE_REQUIRED);
return;
}
checkForElementTypeWithPEReference(fEntityReader, ' ', fElementQName);
if (fElementQName.rawname == -1) {
abortMarkup(XMLMessages.MSG_ELEMENT_TYPE_REQUIRED_IN_ELEMENTDECL,
XMLMessages.P45_ELEMENT_TYPE_REQUIRED);
return;
}
if (fDTDHandler != null) {
fElementDeclQName.setValues(fElementQName);
}
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_CONTENTSPEC_IN_ELEMENTDECL,
XMLMessages.P45_SPACE_REQUIRED,
fElementQName.rawname);
return;
}
int contentSpecType = -1;
int contentSpec = -1;
if (fEntityReader.skippedString(empty_string)) {
contentSpecType = XMLElementDecl.TYPE_EMPTY;
} else if (fEntityReader.skippedString(any_string)) {
contentSpecType = XMLElementDecl.TYPE_ANY;
} else if (!fEntityReader.lookingAtChar('(', true)) {
abortMarkup(XMLMessages.MSG_CONTENTSPEC_REQUIRED_IN_ELEMENTDECL,
XMLMessages.P45_CONTENTSPEC_REQUIRED,
fElementQName.rawname);
return;
} else {
int contentSpecReader = fReaderId;
int contentSpecReaderDepth = fEntityHandler.getReaderDepth();
int prevState = setScannerState(SCANNER_STATE_CONTENTSPEC);
int oldDepth = parenDepth();
fEntityHandler.setReaderDepth(oldDepth);
increaseParenDepth();
checkForPEReference(false);
boolean skippedPCDATA = fEntityReader.skippedString(pcdata_string);
if (skippedPCDATA) {
contentSpecType = XMLElementDecl.TYPE_MIXED;
// REVISIT: Validation. Should we pass in QName?
contentSpec = scanMixed(fElementQName);
} else {
contentSpecType = XMLElementDecl.TYPE_CHILDREN;
// REVISIT: Validation. Should we pass in QName?
contentSpec = scanChildren(fElementQName);
}
boolean success = contentSpec != -1;
restoreScannerState(prevState);
fEntityHandler.setReaderDepth(contentSpecReaderDepth);
if (!success) {
setParenDepth(oldDepth);
skipPastEndOfCurrentMarkup();
return;
} else {
if (parenDepth() != oldDepth) // REVISIT - should not be needed
// System.out.println("nesting depth mismatch");
;
}
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ELEMENTDECL_UNTERMINATED,
XMLMessages.P45_UNTERMINATED,
fElementQName.rawname);
return;
}
decreaseMarkupDepth();
int elementIndex = fDTDGrammar.getElementDeclIndex(fElementQName, -1);
boolean elementDeclIsExternal = getReadingExternalEntity();
if (elementIndex == -1) {
elementIndex = fDTDGrammar.addElementDecl(fElementQName, contentSpecType, contentSpec, elementDeclIsExternal);
//System.out.println("XMLDTDScanner#scanElementDecl->DTDGrammar#addElementDecl: "+elementIndex+" ("+fElementQName.localpart+","+fStringPool.toString(fElementQName.localpart)+')');
}
else {
//now check if we already add this element Decl by foward reference
fDTDGrammar.getElementDecl(elementIndex, fTempElementDecl);
if (fTempElementDecl.type == -1) {
fTempElementDecl.type = contentSpecType;
fTempElementDecl.contentSpecIndex = contentSpec;
fDTDGrammar.setElementDeclDTD(elementIndex, fTempElementDecl);
fDTDGrammar.setElementDeclIsExternal(elementIndex, elementDeclIsExternal);
}
else {
//REVISIT, valiate VC duplicate element type.
if ( fValidationEnabled )
//&&
// (elemenetDeclIsExternal==fDTDGrammar.getElementDeclIsExternal(elementIndex)
{
reportRecoverableXMLError(
XMLMessages.MSG_ELEMENT_ALREADY_DECLARED,
XMLMessages.VC_UNIQUE_ELEMENT_TYPE_DECLARATION,
fStringPool.toString(fElementQName.rawname)
);
}
}
}
if (fDTDHandler != null) {
fDTDGrammar.getElementDecl(elementIndex, fTempElementDecl);
fDTDHandler.elementDecl(fElementDeclQName, contentSpecType, contentSpec, fDTDGrammar);
}
} // scanElementDecl()
/**
* Scans mixed content model. Called after scanning past '(' S? '#PCDATA'
* <pre>
* [51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')'
* </pre>
*/
private int scanMixed(QName element) throws Exception {
int valueIndex = -1; // -1 is special value for #PCDATA
int prevNodeIndex = -1;
boolean starRequired = false;
int[] valueSeen = new int[32];
int valueCount = 0;
boolean dupAttrType = false;
int nodeIndex = -1;
while (true) {
if (fValidationEnabled) {
for (int i=0; i<valueCount;i++) {
if ( valueSeen[i] == valueIndex) {
dupAttrType = true;
break;
}
}
}
if (dupAttrType && fValidationEnabled) {
reportRecoverableXMLError(XMLMessages.MSG_DUPLICATE_TYPE_IN_MIXED_CONTENT,
XMLMessages.VC_NO_DUPLICATE_TYPES,
valueIndex);
dupAttrType = false;
}
else {
try {
valueSeen[valueCount] = valueIndex;
}
catch (ArrayIndexOutOfBoundsException ae) {
int[] newArray = new int[valueSeen.length*2];
System.arraycopy(valueSeen,0,newArray,0,valueSeen.length);
valueSeen = newArray;
valueSeen[valueCount] = valueIndex;
}
valueCount++;
nodeIndex = fDTDGrammar.addUniqueLeafNode(valueIndex);
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('|', true)) {
if (!fEntityReader.lookingAtChar(')', true)) {
reportFatalXMLError(XMLMessages.MSG_CLOSE_PAREN_REQUIRED_IN_MIXED,
XMLMessages.P51_CLOSE_PAREN_REQUIRED,
element.rawname);
return -1;
}
decreaseParenDepth();
if (nodeIndex == -1) {
nodeIndex = prevNodeIndex;
} else if (prevNodeIndex != -1) {
nodeIndex = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, prevNodeIndex, nodeIndex);
}
if (fEntityReader.lookingAtChar('*', true)) {
nodeIndex = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE, nodeIndex);
} else if (starRequired) {
reportFatalXMLError(XMLMessages.MSG_MIXED_CONTENT_UNTERMINATED,
XMLMessages.P51_UNTERMINATED,
fStringPool.toString(element.rawname),
fDTDGrammar.getContentSpecNodeAsString(nodeIndex));
return -1;
}
return nodeIndex;
}
if (nodeIndex != -1) {
if (prevNodeIndex != -1) {
nodeIndex = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_CHOICE, prevNodeIndex, nodeIndex);
}
prevNodeIndex = nodeIndex;
}
starRequired = true;
checkForPEReference(false);
checkForElementTypeWithPEReference(fEntityReader, ')', fElementRefQName);
valueIndex = fElementRefQName.rawname;
if (valueIndex == -1) {
reportFatalXMLError(XMLMessages.MSG_ELEMENT_TYPE_REQUIRED_IN_MIXED_CONTENT,
XMLMessages.P51_ELEMENT_TYPE_REQUIRED,
element.rawname);
return -1;
}
}
} // scanMixed(QName):int
/**
* Scans a children content model.
* <pre>
* [47] children ::= (choice | seq) ('?' | '*' | '+')?
* [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')'
* [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')'
* [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')?
* </pre>
*/
private int scanChildren(QName element) throws Exception {
int depth = 1;
initializeContentModelStack(depth);
while (true) {
if (fEntityReader.lookingAtChar('(', true)) {
increaseParenDepth();
checkForPEReference(false);
depth++;
initializeContentModelStack(depth);
continue;
}
checkForElementTypeWithPEReference(fEntityReader, ')', fElementRefQName);
int valueIndex = fElementRefQName.rawname;
if (valueIndex == -1) {
reportFatalXMLError(XMLMessages.MSG_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED_IN_CHILDREN,
XMLMessages.P47_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED,
element.rawname);
return -1;
}
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_LEAF, valueIndex);
if (fEntityReader.lookingAtChar('?', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE, fNodeIndexStack[depth]);
} else if (fEntityReader.lookingAtChar('*', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE, fNodeIndexStack[depth]);
} else if (fEntityReader.lookingAtChar('+', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ONE_OR_MORE, fNodeIndexStack[depth]);
}
while (true) {
checkForPEReference(false);
if (fOpStack[depth] != XMLContentSpec.CONTENTSPECNODE_SEQ && fEntityReader.lookingAtChar('|', true)) {
if (fPrevNodeIndexStack[depth] != -1) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(fOpStack[depth], fPrevNodeIndexStack[depth], fNodeIndexStack[depth]);
}
fPrevNodeIndexStack[depth] = fNodeIndexStack[depth];
fOpStack[depth] = XMLContentSpec.CONTENTSPECNODE_CHOICE;
break;
} else if (fOpStack[depth] != XMLContentSpec.CONTENTSPECNODE_CHOICE && fEntityReader.lookingAtChar(',', true)) {
if (fPrevNodeIndexStack[depth] != -1) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(fOpStack[depth], fPrevNodeIndexStack[depth], fNodeIndexStack[depth]);
}
fPrevNodeIndexStack[depth] = fNodeIndexStack[depth];
fOpStack[depth] = XMLContentSpec.CONTENTSPECNODE_SEQ;
break;
} else {
if (!fEntityReader.lookingAtChar(')', true)) {
reportFatalXMLError(XMLMessages.MSG_CLOSE_PAREN_REQUIRED_IN_CHILDREN,
XMLMessages.P47_CLOSE_PAREN_REQUIRED,
element.rawname);
}
decreaseParenDepth();
if (fPrevNodeIndexStack[depth] != -1) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(fOpStack[depth], fPrevNodeIndexStack[depth], fNodeIndexStack[depth]);
}
int nodeIndex = fNodeIndexStack[depth--];
fNodeIndexStack[depth] = nodeIndex;
if (fEntityReader.lookingAtChar('?', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_ONE, fNodeIndexStack[depth]);
} else if (fEntityReader.lookingAtChar('*', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ZERO_OR_MORE, fNodeIndexStack[depth]);
} else if (fEntityReader.lookingAtChar('+', true)) {
fNodeIndexStack[depth] = fDTDGrammar.addContentSpecNode(XMLContentSpec.CONTENTSPECNODE_ONE_OR_MORE, fNodeIndexStack[depth]);
}
if (depth == 0) {
return fNodeIndexStack[0];
}
}
}
checkForPEReference(false);
}
} // scanChildren(QName):int
//
// [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>'
// [53] AttDef ::= S Name S AttType S DefaultDecl
// [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)
//
private void scanAttlistDecl() throws Exception
{
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ATTLISTDECL,
XMLMessages.P52_SPACE_REQUIRED);
return;
}
checkForElementTypeWithPEReference(fEntityReader, ' ', fElementQName);
int elementTypeIndex = fElementQName.rawname;
if (elementTypeIndex == -1) {
abortMarkup(XMLMessages.MSG_ELEMENT_TYPE_REQUIRED_IN_ATTLISTDECL,
XMLMessages.P52_ELEMENT_TYPE_REQUIRED);
return;
}
int elementIndex = fDTDGrammar.getElementDeclIndex(fElementQName, -1);
if (elementIndex == -1) {
elementIndex = fDTDGrammar.addElementDecl(fElementQName);
//System.out.println("XMLDTDScanner#scanAttListDecl->DTDGrammar#addElementDecl: "+elementIndex+" ("+fElementQName.localpart+","+fStringPool.toString(fElementQName.localpart)+')');
}
boolean sawSpace = checkForPEReference(true);
if (fEntityReader.lookingAtChar('>', true)) {
decreaseMarkupDepth();
return;
}
// REVISIT - review this code...
if (!sawSpace) {
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
} else
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ATTRIBUTE_NAME_IN_ATTDEF,
XMLMessages.P53_SPACE_REQUIRED);
} else {
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
}
}
if (fEntityReader.lookingAtChar('>', true)) {
decreaseMarkupDepth();
return;
}
while (true) {
checkForAttributeNameWithPEReference(fEntityReader, ' ', fAttributeQName);
int attDefName = fAttributeQName.rawname;
if (attDefName == -1) {
abortMarkup(XMLMessages.MSG_ATTRIBUTE_NAME_REQUIRED_IN_ATTDEF,
XMLMessages.P53_NAME_REQUIRED,
fElementQName.rawname);
return;
}
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ATTTYPE_IN_ATTDEF,
XMLMessages.P53_SPACE_REQUIRED);
return;
}
int attDefType = -1;
boolean attDefList = false;
int attDefEnumeration = -1;
if (fEntityReader.skippedString(cdata_string)) {
attDefType = XMLAttributeDecl.TYPE_CDATA;
} else if (fEntityReader.skippedString(id_string)) {
if (!fEntityReader.skippedString(ref_string)) {
attDefType = XMLAttributeDecl.TYPE_ID;
} else if (!fEntityReader.lookingAtChar('S', true)) {
attDefType = XMLAttributeDecl.TYPE_IDREF;
} else {
attDefType = XMLAttributeDecl.TYPE_IDREF;
attDefList = true;
}
} else if (fEntityReader.skippedString(entit_string)) {
if (fEntityReader.lookingAtChar('Y', true)) {
attDefType = XMLAttributeDecl.TYPE_ENTITY;
} else if (fEntityReader.skippedString(ies_string)) {
attDefType = XMLAttributeDecl.TYPE_ENTITY;
attDefList = true;
} else {
abortMarkup(XMLMessages.MSG_ATTTYPE_REQUIRED_IN_ATTDEF,
XMLMessages.P53_ATTTYPE_REQUIRED,
elementTypeIndex, attDefName);
return;
}
} else if (fEntityReader.skippedString(nmtoken_string)) {
if (fEntityReader.lookingAtChar('S', true)) {
attDefType = XMLAttributeDecl.TYPE_NMTOKEN;
attDefList = true;
} else {
attDefType = XMLAttributeDecl.TYPE_NMTOKEN;
}
} else if (fEntityReader.skippedString(notation_string)) {
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_NOTATION_IN_NOTATIONTYPE,
XMLMessages.P58_SPACE_REQUIRED,
elementTypeIndex, attDefName);
return;
}
if (!fEntityReader.lookingAtChar('(', true)) {
abortMarkup(XMLMessages.MSG_OPEN_PAREN_REQUIRED_IN_NOTATIONTYPE,
XMLMessages.P58_OPEN_PAREN_REQUIRED,
elementTypeIndex, attDefName);
return;
}
increaseParenDepth();
attDefType = XMLAttributeDecl.TYPE_NOTATION;
attDefEnumeration = scanEnumeration(elementTypeIndex, attDefName, true);
if (attDefEnumeration == -1) {
skipPastEndOfCurrentMarkup();
return;
}
} else if (fEntityReader.lookingAtChar('(', true)) {
increaseParenDepth();
attDefType = XMLAttributeDecl.TYPE_ENUMERATION;
attDefEnumeration = scanEnumeration(elementTypeIndex, attDefName, false);
if (attDefEnumeration == -1) {
skipPastEndOfCurrentMarkup();
return;
}
} else {
abortMarkup(XMLMessages.MSG_ATTTYPE_REQUIRED_IN_ATTDEF,
XMLMessages.P53_ATTTYPE_REQUIRED,
elementTypeIndex, attDefName);
return;
}
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_DEFAULTDECL_IN_ATTDEF,
XMLMessages.P53_SPACE_REQUIRED,
elementTypeIndex, attDefName);
return;
}
int attDefDefaultType = -1;
int attDefDefaultValue = -1;
if (fEntityReader.skippedString(required_string)) {
attDefDefaultType = XMLAttributeDecl.DEFAULT_TYPE_REQUIRED;
} else if (fEntityReader.skippedString(implied_string)) {
attDefDefaultType = XMLAttributeDecl.DEFAULT_TYPE_IMPLIED;
} else {
if (fEntityReader.skippedString(fixed_string)) {
if (!fEntityReader.lookingAtSpace(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_FIXED_IN_DEFAULTDECL,
XMLMessages.P60_SPACE_REQUIRED,
elementTypeIndex, attDefName);
return;
}
fEntityReader.skipPastSpaces();
attDefDefaultType = XMLAttributeDecl.DEFAULT_TYPE_FIXED;
} else
attDefDefaultType = XMLAttributeDecl.DEFAULT_TYPE_DEFAULT;
//fElementQName.setValues(-1, elementTypeIndex, elementTypeIndex);
// if attribute name has a prefix "xml", bind it to the XML Namespace.
// since this is the only pre-defined namespace.
/***
if (fAttributeQName.prefix == fXMLSymbol) {
fAttributeQName.uri = fXMLNamespace;
}
else
fAttributeQName.setValues(-1, attDefName, attDefName);
****/
attDefDefaultValue = scanDefaultAttValue(fElementQName, fAttributeQName,
attDefType,
attDefEnumeration);
//normalize and check VC: Attribute Default Legal
if (attDefDefaultValue != -1 && attDefType != XMLAttributeDecl.TYPE_CDATA ) {
attDefDefaultValue = normalizeDefaultAttValue( fAttributeQName, attDefDefaultValue,
attDefType, attDefEnumeration,
attDefList);
}
if (attDefDefaultValue == -1) {
skipPastEndOfCurrentMarkup();
return;
}
}
if (attDefName == fXMLSpace) {
boolean ok = false;
if (attDefType == XMLAttributeDecl.TYPE_ENUMERATION) {
int index = attDefEnumeration;
if (index != -1) {
ok = fStringPool.stringListLength(index) == 2 &&
fStringPool.stringInList(index, fDefault) &&
fStringPool.stringInList(index, fPreserve);
}
}
if (!ok) {
reportFatalXMLError(XMLMessages.MSG_XML_SPACE_DECLARATION_ILLEGAL,
XMLMessages.S2_10_DECLARATION_ILLEGAL,
elementTypeIndex);
}
}
sawSpace = checkForPEReference(true);
// if attribute name has a prefix "xml", bind it to the XML Namespace.
// since this is the only pre-defined namespace.
if (fAttributeQName.prefix == fXMLSymbol) {
fAttributeQName.uri = fXMLNamespace;
}
if (fEntityReader.lookingAtChar('>', true)) {
int attDefIndex = addAttDef(fElementQName, fAttributeQName,
attDefType, attDefList, attDefEnumeration,
attDefDefaultType, attDefDefaultValue,
getReadingExternalEntity());
//System.out.println("XMLDTDScanner#scanAttlistDecl->DTDGrammar#addAttDef: "+attDefIndex+
// " ("+fElementQName.localpart+","+fStringPool.toString(fElementQName.rawname)+')'+
// " ("+fAttributeQName.localpart+","+fStringPool.toString(fAttributeQName.rawname)+')');
decreaseMarkupDepth();
return;
}
// REVISIT - review this code...
if (!sawSpace) {
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
} else
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ATTRIBUTE_NAME_IN_ATTDEF,
XMLMessages.P53_SPACE_REQUIRED);
} else {
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
}
}
if (fEntityReader.lookingAtChar('>', true)) {
int attDefIndex = addAttDef(fElementQName, fAttributeQName,
attDefType, attDefList, attDefEnumeration,
attDefDefaultType, attDefDefaultValue,
getReadingExternalEntity() );
//System.out.println("XMLDTDScanner#scanAttlistDecl->DTDGrammar#addAttDef: "+attDefIndex+
// " ("+fElementQName.localpart+","+fStringPool.toString(fElementQName.rawname)+')'+
// " ("+fAttributeQName.localpart+","+fStringPool.toString(fAttributeQName.rawname)+')');
decreaseMarkupDepth();
return;
}
int attDefIndex = addAttDef(fElementQName, fAttributeQName,
attDefType, attDefList, attDefEnumeration,
attDefDefaultType, attDefDefaultValue,
getReadingExternalEntity());
//System.out.println("XMLDTDScanner#scanAttlistDecl->DTDGrammar#addAttDef: "+attDefIndex+
// " ("+fElementQName.localpart+","+fStringPool.toString(fElementQName.rawname)+')'+
// " ("+fAttributeQName.localpart+","+fStringPool.toString(fAttributeQName.rawname)+')');
}
}
private int addAttDef(QName element, QName attribute,
int attDefType, boolean attDefList, int attDefEnumeration,
int attDefDefaultType, int attDefDefaultValue,
boolean isExternal ) throws Exception {
if (fDTDHandler != null) {
String enumString = attDefEnumeration != -1 ? fStringPool.stringListAsString(attDefEnumeration) : null;
fDTDHandler.attlistDecl(element, attribute,
attDefType, attDefList,
enumString,
attDefDefaultType, attDefDefaultValue);
}
int elementIndex = fDTDGrammar.getElementDeclIndex(element, -1);
if (elementIndex == -1) {
// REPORT Internal error here
}
else {
int attlistIndex = fDTDGrammar.getFirstAttributeDeclIndex(elementIndex);
int dupID = -1;
int dupNotation = -1;
while (attlistIndex != -1) {
fDTDGrammar.getAttributeDecl(attlistIndex, fTempAttributeDecl);
// REVISIT: Validation. Attributes are also tuples.
if (fStringPool.equalNames(fTempAttributeDecl.name.rawname, attribute.rawname)) {
/******
if (fWarningOnDuplicateAttDef) {
Object[] args = { fStringPool.toString(fElementType[elemChunk][elemIndex]),
fStringPool.toString(attributeDecl.rawname) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_DUPLICATE_ATTDEF,
XMLMessages.P53_DUPLICATE,
args,
XMLErrorReporter.ERRORTYPE_WARNING);
}
******/
return -1;
}
if (fValidationEnabled) {
if (attDefType == XMLAttributeDecl.TYPE_ID &&
fTempAttributeDecl.type == XMLAttributeDecl.TYPE_ID ) {
dupID = fTempAttributeDecl.name.rawname;
}
if (attDefType == XMLAttributeDecl.TYPE_NOTATION
&& fTempAttributeDecl.type == XMLAttributeDecl.TYPE_NOTATION) {
dupNotation = fTempAttributeDecl.name.rawname;
}
}
attlistIndex = fDTDGrammar.getNextAttributeDeclIndex(attlistIndex);
}
if (fValidationEnabled) {
if (dupID != -1) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(dupID),
fStringPool.toString(attribute.rawname) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_MORE_THAN_ONE_ID_ATTRIBUTE,
XMLMessages.VC_ONE_ID_PER_ELEMENT_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
return -1;
}
if (dupNotation != -1) {
Object[] args = { fStringPool.toString(element.rawname),
fStringPool.toString(dupNotation),
fStringPool.toString(attribute.rawname) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_MORE_THAN_ONE_NOTATION_ATTRIBUTE,
XMLMessages.VC_ONE_NOTATION_PER_ELEMENT_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
return -1;
}
}
}
return fDTDGrammar.addAttDef(element, attribute,
attDefType, attDefList, attDefEnumeration,
attDefDefaultType, attDefDefaultValue,
isExternal);
}
//
// [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')'
// [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')'
//
private int scanEnumeration(int elementType, int attrName, boolean isNotationType) throws Exception
{
int enumIndex = fDTDGrammar.startEnumeration();
while (true) {
checkForPEReference(false);
int nameIndex = isNotationType ?
checkForNameWithPEReference(fEntityReader, ')') :
checkForNmtokenWithPEReference(fEntityReader, ')');
if (nameIndex == -1) {
if (isNotationType) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_NOTATIONTYPE,
XMLMessages.P58_NAME_REQUIRED,
elementType,
attrName);
} else {
reportFatalXMLError(XMLMessages.MSG_NMTOKEN_REQUIRED_IN_ENUMERATION,
XMLMessages.P59_NMTOKEN_REQUIRED,
elementType,
attrName);
}
fDTDGrammar.endEnumeration(enumIndex);
return -1;
}
fDTDGrammar.addNameToEnumeration(enumIndex, elementType, attrName, nameIndex, isNotationType);
/*****/
if (isNotationType && !((DefaultEntityHandler)fEntityHandler).isNotationDeclared(nameIndex)) {
Object[] args = { fStringPool.toString(elementType),
fStringPool.toString(attrName),
fStringPool.toString(nameIndex) };
((DefaultEntityHandler)fEntityHandler).addRequiredNotation(nameIndex,
fErrorReporter.getLocator(),
XMLMessages.MSG_NOTATION_NOT_DECLARED_FOR_NOTATIONTYPE_ATTRIBUTE,
XMLMessages.VC_NOTATION_DECLARED,
args);
}
/*****/
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('|', true)) {
fDTDGrammar.endEnumeration(enumIndex);
if (!fEntityReader.lookingAtChar(')', true)) {
if (isNotationType) {
reportFatalXMLError(XMLMessages.MSG_NOTATIONTYPE_UNTERMINATED,
XMLMessages.P58_UNTERMINATED,
elementType,
attrName);
} else {
reportFatalXMLError(XMLMessages.MSG_ENUMERATION_UNTERMINATED,
XMLMessages.P59_UNTERMINATED,
elementType,
attrName);
}
return -1;
}
decreaseParenDepth();
return enumIndex;
}
}
}
//
// [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
// | "'" ([^<&'] | Reference)* "'"
//
/**
* Scan the default value in an attribute declaration
*
* @param elementType handle to the element that owns the attribute
* @param attrName handle in the string pool for the attribute name
* @return handle in the string pool for the default attribute value
* @exception java.lang.Exception
*/
public int scanDefaultAttValue(QName element, QName attribute) throws Exception
{
boolean single;
if (!(single = fEntityReader.lookingAtChar('\'', true)) && !fEntityReader.lookingAtChar('\"', true)) {
reportFatalXMLError(XMLMessages.MSG_QUOTE_REQUIRED_IN_ATTVALUE,
XMLMessages.P10_QUOTE_REQUIRED,
element.rawname,
attribute.rawname);
return -1;
}
int previousState = setScannerState(SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE);
char qchar = single ? '\'' : '\"';
fDefaultAttValueReader = fReaderId;
fDefaultAttValueElementType = element.rawname;
fDefaultAttValueAttrName = attribute.rawname;
boolean setMark = true;
int dataOffset = fLiteralData.length();
while (true) {
fDefaultAttValueOffset = fEntityReader.currentOffset();
if (setMark) {
fDefaultAttValueMark = fDefaultAttValueOffset;
setMark = false;
}
if (fEntityReader.lookingAtChar(qchar, true)) {
if (fReaderId == fDefaultAttValueReader)
break;
continue;
}
if (fEntityReader.lookingAtChar(' ', true)) {
continue;
}
boolean skippedCR;
if ((skippedCR = fEntityReader.lookingAtChar((char)0x0D, true)) || fEntityReader.lookingAtSpace(true)) {
if (fDefaultAttValueOffset - fDefaultAttValueMark > 0)
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
setMark = true;
fLiteralData.append(' ');
if (skippedCR)
fEntityReader.lookingAtChar((char)0x0A, true);
continue;
}
if (fEntityReader.lookingAtChar('&', true)) {
if (fDefaultAttValueOffset - fDefaultAttValueMark > 0)
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
setMark = true;
//
// Check for character reference first.
//
if (fEntityReader.lookingAtChar('#', true)) {
int ch = scanCharRef();
if (ch != -1) {
if (ch < 0x10000)
fLiteralData.append((char)ch);
else {
fLiteralData.append((char)(((ch-0x00010000)>>10)+0xd800));
fLiteralData.append((char)(((ch-0x00010000)&0x3ff)+0xdc00));
}
}
} else {
//
// Entity reference
//
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_REFERENCE,
XMLMessages.P68_NAME_REQUIRED);
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_REFERENCE,
XMLMessages.P68_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
} else {
int entityNameIndex = fEntityReader.addSymbol(nameOffset, nameLength);
fEntityHandler.startReadingFromEntity(entityNameIndex, markupDepth(), XMLEntityHandler.ENTITYREF_IN_DEFAULTATTVALUE);
}
}
continue;
}
if (fEntityReader.lookingAtChar('<', true)) {
if (fDefaultAttValueOffset - fDefaultAttValueMark > 0)
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
setMark = true;
reportFatalXMLError(XMLMessages.MSG_LESSTHAN_IN_ATTVALUE,
XMLMessages.WFC_NO_LESSTHAN_IN_ATTVALUE,
element.rawname,
attribute.rawname);
continue;
}
//
// REVISIT - HACK !!! code added to pass incorrect OASIS test 'valid-sa-094'
// Remove this next section to conform to the spec...
//
if (!getReadingExternalEntity() && fEntityReader.lookingAtChar('%', true)) {
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength != 0 && fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_PEREFERENCE_WITHIN_MARKUP,
XMLMessages.WFC_PES_IN_INTERNAL_SUBSET,
fEntityReader.addString(nameOffset, nameLength));
}
}
//
// END HACK !!!
//
if (!fEntityReader.lookingAtValidChar(true)) {
if (fDefaultAttValueOffset - fDefaultAttValueMark > 0)
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
setMark = true;
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
return -1;
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_ATTVALUE,
XMLMessages.P10_INVALID_CHARACTER,
fStringPool.toString(element.rawname),
fStringPool.toString(attribute.rawname),
Integer.toHexString(invChar));
}
continue;
}
}
restoreScannerState(previousState);
int dataLength = fLiteralData.length() - dataOffset;
if (dataLength == 0) {
return fEntityReader.addString(fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
}
if (fDefaultAttValueOffset - fDefaultAttValueMark > 0) {
fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark);
dataLength = fLiteralData.length() - dataOffset;
}
return fLiteralData.addString(dataOffset, dataLength);
}
//
// [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>'
//
private void scanNotationDecl() throws Exception
{
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_NOTATION_NAME_IN_NOTATIONDECL,
XMLMessages.P82_SPACE_REQUIRED);
return;
}
int notationName = checkForNameWithPEReference(fEntityReader, ' ');
if (notationName == -1) {
abortMarkup(XMLMessages.MSG_NOTATION_NAME_REQUIRED_IN_NOTATIONDECL,
XMLMessages.P82_NAME_REQUIRED);
return;
}
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_NOTATION_NAME_IN_NOTATIONDECL,
XMLMessages.P82_SPACE_REQUIRED,
notationName);
return;
}
if (!scanExternalID(true)) {
skipPastEndOfCurrentMarkup();
return;
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_NOTATIONDECL_UNTERMINATED,
XMLMessages.P82_UNTERMINATED,
notationName);
return;
}
decreaseMarkupDepth();
/****
System.out.println(fStringPool.toString(notationName)+","
+fStringPool.toString(fPubidLiteral) + ","
+fStringPool.toString(fSystemLiteral) + ","
+getReadingExternalEntity());
/****/
int notationIndex = ((DefaultEntityHandler) fEntityHandler).addNotationDecl( notationName,
fPubidLiteral,
fSystemLiteral,
getReadingExternalEntity());
fDTDGrammar.addNotationDecl(notationName, fPubidLiteral, fSystemLiteral);
if (fDTDHandler != null) {
fDTDHandler.notationDecl(notationName, fPubidLiteral, fSystemLiteral);
}
}
//
// [70] EntityDecl ::= GEDecl | PEDecl
// [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>'
// [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>'
// [73] EntityDef ::= EntityValue | (ExternalID NDataDecl?)
// [74] PEDef ::= EntityValue | ExternalID
// [75] ExternalID ::= 'SYSTEM' S SystemLiteral
// | 'PUBLIC' S PubidLiteral S SystemLiteral
// [76] NDataDecl ::= S 'NDATA' S Name
// [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
// | "'" ([^%&'] | PEReference | Reference)* "'"
//
// Called after scanning 'ENTITY'
//
private void scanEntityDecl() throws Exception
{
boolean isPEDecl = false;
boolean sawPERef = false;
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
if (!fEntityReader.lookingAtChar('%', true)) {
isPEDecl = false; // <!ENTITY x "x">
} else if (fEntityReader.lookingAtSpace(true)) {
checkForPEReference(false); // <!ENTITY % x "x">
isPEDecl = true;
} else if (!getReadingExternalEntity()) {
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ENTITY_NAME_IN_PEDECL,
XMLMessages.P72_SPACE);
isPEDecl = true;
} else if (fEntityReader.lookingAtChar('%', false)) {
checkForPEReference(false); // <!ENTITY %%x; "x"> is legal
isPEDecl = true;
} else {
sawPERef = true;
}
} else if (!getReadingExternalEntity() || !fEntityReader.lookingAtChar('%', true)) {
// <!ENTITY[^ ]...> or <!ENTITY[^ %]...>
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ENTITY_NAME_IN_ENTITYDECL,
XMLMessages.P70_SPACE);
isPEDecl = false;
} else if (fEntityReader.lookingAtSpace(false)) {
// <!ENTITY% ...>
reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_PERCENT_IN_PEDECL,
XMLMessages.P72_SPACE);
isPEDecl = false;
} else {
sawPERef = true;
}
if (sawPERef) {
while (true) {
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_NAME_REQUIRED);
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
} else {
int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength);
int readerDepth = (fScannerState == SCANNER_STATE_CONTENTSPEC) ? parenDepth() : markupDepth();
fEntityHandler.startReadingFromEntity(peNameIndex, readerDepth, XMLEntityHandler.ENTITYREF_IN_DTD_WITHIN_MARKUP);
}
fEntityReader.skipPastSpaces();
if (!fEntityReader.lookingAtChar('%', true))
break;
if (!isPEDecl) {
if (fEntityReader.lookingAtSpace(true)) {
checkForPEReference(false);
isPEDecl = true;
break;
}
isPEDecl = fEntityReader.lookingAtChar('%', true);
}
}
}
int entityName = checkForNameWithPEReference(fEntityReader, ' ');
if (entityName == -1) {
abortMarkup(XMLMessages.MSG_ENTITY_NAME_REQUIRED_IN_ENTITYDECL,
XMLMessages.P70_REQUIRED_NAME);
return;
}
if (!fDTDGrammar.startEntityDecl(isPEDecl, entityName)) {
skipPastEndOfCurrentMarkup();
return;
}
if (!checkForPEReference(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_ENTITY_NAME_IN_ENTITYDECL,
XMLMessages.P70_REQUIRED_SPACE,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
if (isPEDecl) {
boolean single;
if ((single = fEntityReader.lookingAtChar('\'', true)) || fEntityReader.lookingAtChar('\"', true)) {
int value = scanEntityValue(single);
if (value == -1) {
skipPastEndOfCurrentMarkup();
fDTDGrammar.endEntityDecl();
return;
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED,
XMLMessages.P72_UNTERMINATED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
decreaseMarkupDepth();
fDTDGrammar.endEntityDecl();
// a hack by Eric
//REVISIT
fDTDGrammar.addInternalPEDecl(entityName, value);
if (fDTDHandler != null) {
fDTDHandler.internalPEDecl(entityName, value);
}
int entityIndex = ((DefaultEntityHandler) fEntityHandler).addInternalPEDecl(entityName,
value,
getReadingExternalEntity());
} else {
if (!scanExternalID(false)) {
skipPastEndOfCurrentMarkup();
fDTDGrammar.endEntityDecl();
return;
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED,
XMLMessages.P72_UNTERMINATED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
decreaseMarkupDepth();
fDTDGrammar.endEntityDecl();
//a hack by Eric
//REVISIT
fDTDGrammar.addExternalPEDecl(entityName, fPubidLiteral, fSystemLiteral);
if (fDTDHandler != null) {
fDTDHandler.externalPEDecl(entityName, fPubidLiteral, fSystemLiteral);
}
int entityIndex = ((DefaultEntityHandler) fEntityHandler).addExternalPEDecl(entityName,
fPubidLiteral,
fSystemLiteral, getReadingExternalEntity());
}
} else {
boolean single;
if ((single = fEntityReader.lookingAtChar('\'', true)) || fEntityReader.lookingAtChar('\"', true)) {
int value = scanEntityValue(single);
if (value == -1) {
skipPastEndOfCurrentMarkup();
fDTDGrammar.endEntityDecl();
return;
}
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED,
XMLMessages.P71_UNTERMINATED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
decreaseMarkupDepth();
fDTDGrammar.endEntityDecl();
//a hack by Eric
//REVISIT
fDTDGrammar.addInternalEntityDecl(entityName, value);
if (fDTDHandler != null) {
fDTDHandler.internalEntityDecl(entityName, value);
}
int entityIndex = ((DefaultEntityHandler) fEntityHandler).addInternalEntityDecl(entityName,
value,
getReadingExternalEntity());
} else {
if (!scanExternalID(false)) {
skipPastEndOfCurrentMarkup();
fDTDGrammar.endEntityDecl();
return;
}
boolean unparsed = false;
if (fEntityReader.lookingAtSpace(true)) {
fEntityReader.skipPastSpaces();
unparsed = fEntityReader.skippedString(ndata_string);
}
if (!unparsed) {
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED,
XMLMessages.P72_UNTERMINATED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
decreaseMarkupDepth();
fDTDGrammar.endEntityDecl();
//a hack by Eric
//REVISIT
fDTDGrammar.addExternalEntityDecl(entityName, fPubidLiteral, fSystemLiteral);
if (fDTDHandler != null) {
fDTDHandler.externalEntityDecl(entityName, fPubidLiteral, fSystemLiteral);
}
int entityIndex = ((DefaultEntityHandler) fEntityHandler).addExternalEntityDecl(entityName,
fPubidLiteral,
fSystemLiteral,
getReadingExternalEntity());
} else {
if (!fEntityReader.lookingAtSpace(true)) {
abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_NOTATION_NAME_IN_UNPARSED_ENTITYDECL,
XMLMessages.P76_SPACE_REQUIRED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
fEntityReader.skipPastSpaces();
int ndataOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName('>');
int ndataLength = fEntityReader.currentOffset() - ndataOffset;
if (ndataLength == 0) {
abortMarkup(XMLMessages.MSG_NOTATION_NAME_REQUIRED_FOR_UNPARSED_ENTITYDECL,
XMLMessages.P76_REQUIRED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
int notationName = fEntityReader.addSymbol(ndataOffset, ndataLength);
checkForPEReference(false);
if (!fEntityReader.lookingAtChar('>', true)) {
abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED,
XMLMessages.P72_UNTERMINATED,
entityName);
fDTDGrammar.endEntityDecl();
return;
}
decreaseMarkupDepth();
fDTDGrammar.endEntityDecl();
//a hack by Eric
//REVISIT
fDTDGrammar.addUnparsedEntityDecl(entityName, fPubidLiteral, fSystemLiteral, notationName);
if (fDTDHandler != null) {
fDTDHandler.unparsedEntityDecl(entityName, fPubidLiteral, fSystemLiteral, notationName);
}
/****
System.out.println("----addUnparsedEntity--- "+ fStringPool.toString(entityName)+","
+fStringPool.toString(notationName)+","
+fStringPool.toString(fPubidLiteral) + ","
+fStringPool.toString(fSystemLiteral) + ","
+getReadingExternalEntity());
/****/
int entityIndex = ((DefaultEntityHandler) fEntityHandler).addUnparsedEntityDecl(entityName,
fPubidLiteral,
fSystemLiteral,
notationName,
getReadingExternalEntity());
}
}
}
}
//
// [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"'
// | "'" ([^%&'] | PEReference | Reference)* "'"
//
private int scanEntityValue(boolean single) throws Exception
{
char qchar = single ? '\'' : '\"';
fEntityValueMark = fEntityReader.currentOffset();
int entityValue = fEntityReader.scanEntityValue(qchar, true);
if (entityValue < 0)
entityValue = scanComplexEntityValue(qchar, entityValue);
return entityValue;
}
private int scanComplexEntityValue(char qchar, int result) throws Exception
{
int previousState = setScannerState(SCANNER_STATE_ENTITY_VALUE);
fEntityValueReader = fReaderId;
int dataOffset = fLiteralData.length();
while (true) {
switch (result) {
case XMLEntityHandler.ENTITYVALUE_RESULT_FINISHED:
{
int offset = fEntityReader.currentOffset();
fEntityReader.lookingAtChar(qchar, true);
restoreScannerState(previousState);
int dataLength = fLiteralData.length() - dataOffset;
if (dataLength == 0) {
return fEntityReader.addString(fEntityValueMark, offset - fEntityValueMark);
}
if (offset - fEntityValueMark > 0) {
fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark);
dataLength = fLiteralData.length() - dataOffset;
}
return fLiteralData.addString(dataOffset, dataLength);
}
case XMLEntityHandler.ENTITYVALUE_RESULT_REFERENCE:
{
int offset = fEntityReader.currentOffset();
if (offset - fEntityValueMark > 0)
fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark);
fEntityReader.lookingAtChar('&', true);
//
// Check for character reference first.
//
if (fEntityReader.lookingAtChar('#', true)) {
int ch = scanCharRef();
if (ch != -1) {
if (ch < 0x10000)
fLiteralData.append((char)ch);
else {
fLiteralData.append((char)(((ch-0x00010000)>>10)+0xd800));
fLiteralData.append((char)(((ch-0x00010000)&0x3ff)+0xdc00));
}
}
fEntityValueMark = fEntityReader.currentOffset();
} else {
//
// Entity reference
//
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_REFERENCE,
XMLMessages.P68_NAME_REQUIRED);
fEntityValueMark = fEntityReader.currentOffset();
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_REFERENCE,
XMLMessages.P68_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
fEntityValueMark = fEntityReader.currentOffset();
} else {
//
// 4.4.7 Bypassed
//
// When a general entity reference appears in the EntityValue in an
// entity declaration, it is bypassed and left as is.
//
fEntityValueMark = offset;
}
}
break;
}
case XMLEntityHandler.ENTITYVALUE_RESULT_PEREF:
{
int offset = fEntityReader.currentOffset();
if (offset - fEntityValueMark > 0)
fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark);
fEntityReader.lookingAtChar('%', true);
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_NAME_REQUIRED);
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
} else if (!getReadingExternalEntity()) {
reportFatalXMLError(XMLMessages.MSG_PEREFERENCE_WITHIN_MARKUP,
XMLMessages.WFC_PES_IN_INTERNAL_SUBSET,
fEntityReader.addString(nameOffset, nameLength));
} else {
int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength);
fEntityHandler.startReadingFromEntity(peNameIndex, markupDepth(), XMLEntityHandler.ENTITYREF_IN_ENTITYVALUE);
}
fEntityValueMark = fEntityReader.currentOffset();
break;
}
case XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR:
{
int offset = fEntityReader.currentOffset();
if (offset - fEntityValueMark > 0)
fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark);
int invChar = fEntityReader.scanInvalidChar();
if (fScannerState == SCANNER_STATE_END_OF_INPUT)
return -1;
if (invChar >= 0) {
reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_ENTITYVALUE,
XMLMessages.P9_INVALID_CHARACTER,
Integer.toHexString(invChar));
}
fEntityValueMark = fEntityReader.currentOffset();
break;
}
case XMLEntityHandler.ENTITYVALUE_RESULT_END_OF_INPUT:
// all the work is done by the previous reader, just invoke the next one now.
break;
default:
break;
}
result = fEntityReader.scanEntityValue(fReaderId == fEntityValueReader ? qchar : -1, false);
}
}
//
//
//
private boolean checkForPEReference(boolean spaceRequired) throws Exception
{
boolean sawSpace = true;
if (spaceRequired)
sawSpace = fEntityReader.lookingAtSpace(true);
fEntityReader.skipPastSpaces();
if (!getReadingExternalEntity())
return sawSpace;
if (!fEntityReader.lookingAtChar('%', true))
return sawSpace;
while (true) {
int nameOffset = fEntityReader.currentOffset();
fEntityReader.skipPastName(';');
int nameLength = fEntityReader.currentOffset() - nameOffset;
if (nameLength == 0) {
reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_NAME_REQUIRED);
} else if (!fEntityReader.lookingAtChar(';', true)) {
reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE,
XMLMessages.P69_SEMICOLON_REQUIRED,
fEntityReader.addString(nameOffset, nameLength));
} else {
int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength);
int readerDepth = (fScannerState == SCANNER_STATE_CONTENTSPEC) ? parenDepth() : markupDepth();
fEntityHandler.startReadingFromEntity(peNameIndex, readerDepth, XMLEntityHandler.ENTITYREF_IN_DTD_WITHIN_MARKUP);
}
fEntityReader.skipPastSpaces();
if (!fEntityReader.lookingAtChar('%', true))
return true;
}
}
//
// content model stack
//
private void initializeContentModelStack(int depth) {
if (fOpStack == null) {
fOpStack = new int[8];
fNodeIndexStack = new int[8];
fPrevNodeIndexStack = new int[8];
} else if (depth == fOpStack.length) {
int[] newStack = new int[depth * 2];
System.arraycopy(fOpStack, 0, newStack, 0, depth);
fOpStack = newStack;
newStack = new int[depth * 2];
System.arraycopy(fNodeIndexStack, 0, newStack, 0, depth);
fNodeIndexStack = newStack;
newStack = new int[depth * 2];
System.arraycopy(fPrevNodeIndexStack, 0, newStack, 0, depth);
fPrevNodeIndexStack = newStack;
}
fOpStack[depth] = -1;
fNodeIndexStack[depth] = -1;
fPrevNodeIndexStack[depth] = -1;
}
private boolean validVersionNum(String version) {
return XMLCharacterProperties.validVersionNum(version);
}
private boolean validEncName(String encoding) {
return XMLCharacterProperties.validEncName(encoding);
}
private int validPublicId(String publicId) {
return XMLCharacterProperties.validPublicId(publicId);
}
private void scanElementType(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName element) throws Exception {
if (!fNamespacesEnabled) {
element.clear();
element.localpart = entityReader.scanName(fastchar);
element.rawname = element.localpart;
return;
}
entityReader.scanQName(fastchar, element);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
} // scanElementType(XMLEntityHandler.EntityReader,char,QName)
public void checkForElementTypeWithPEReference(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName element) throws Exception {
if (!fNamespacesEnabled) {
element.clear();
element.localpart = entityReader.scanName(fastchar);
element.rawname = element.localpart;
return;
}
entityReader.scanQName(fastchar, element);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
} // checkForElementTypeWithPEReference(XMLEntityHandler.EntityReader,char,QName)
public void checkForAttributeNameWithPEReference(XMLEntityHandler.EntityReader entityReader,
char fastchar, QName attribute) throws Exception {
if (!fNamespacesEnabled) {
attribute.clear();
attribute.localpart = entityReader.scanName(fastchar);
attribute.rawname = attribute.localpart;
return;
}
entityReader.scanQName(fastchar, attribute);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
} // checkForAttributeNameWithPEReference(XMLEntityHandler.EntityReader,char,QName)
public int checkForNameWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastcheck) throws Exception {
//
// REVISIT - what does this have to do with PE references?
//
int valueIndex = entityReader.scanName(fastcheck);
return valueIndex;
}
public int checkForNmtokenWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastcheck) throws Exception {
//
// REVISIT - what does this have to do with PE references?
//
int nameOffset = entityReader.currentOffset();
entityReader.skipPastNmtoken(fastcheck);
int nameLength = entityReader.currentOffset() - nameOffset;
if (nameLength == 0)
return -1;
int valueIndex = entityReader.addSymbol(nameOffset, nameLength);
return valueIndex;
}
public int scanDefaultAttValue(QName element, QName attribute,
int attType, int enumeration) throws Exception {
/***/
if (fValidationEnabled && attType == XMLAttributeDecl.TYPE_ID) {
reportRecoverableXMLError(XMLMessages.MSG_ID_DEFAULT_TYPE_INVALID,
XMLMessages.VC_ID_ATTRIBUTE_DEFAULT,
fStringPool.toString(attribute.rawname));
}
/***/
int defaultAttValue = scanDefaultAttValue(element, attribute);
if (defaultAttValue == -1)
return -1;
// REVISIT
/***
if (attType != fCDATASymbol) {
// REVISIT: Validation. Should we pass in the element or is this
// default attribute value normalization?
defaultAttValue = fValidator.normalizeAttValue(null, attribute, defaultAttValue, attType, enumeration);
}
/***/
return defaultAttValue;
}
public int normalizeDefaultAttValue( QName attribute, int defaultAttValue,
int attType, int enumeration,
boolean list) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(defaultAttValue);
if (list) {
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String nmtoken = tokenizer.nextToken();
if (attType == XMLAttributeDecl.TYPE_NMTOKEN) {
if (fValidationEnabled && !XMLCharacterProperties.validNmtoken(nmtoken)) {
ok = false;
}
}
else if (attType == XMLAttributeDecl.TYPE_IDREF || attType == XMLAttributeDecl.TYPE_ENTITY) {
if (fValidationEnabled && !XMLCharacterProperties.validName(nmtoken)) {
ok = false;
}
// REVISIT: a Hack!!! THis is to pass SUN test /invalid/attr11.xml and attr12.xml
// not consistent with XML1.0 spec VC: Attribute Default Legal
if (fValidationEnabled && attType == XMLAttributeDecl.TYPE_ENTITY)
if (! ((DefaultEntityHandler) fEntityHandler).isUnparsedEntity(defaultAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID,
XMLMessages.VC_ENTITY_NAME,
fStringPool.toString(attribute.rawname), nmtoken);
}
}
sb.append(nmtoken);
if (!tokenizer.hasMoreTokens()) {
break;
}
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidationEnabled && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_ATT_DEFAULT_INVALID,
XMLMessages.VC_ATTRIBUTE_DEFAULT_LEGAL,
fStringPool.toString(attribute.rawname), newAttValue);
}
if (!newAttValue.equals(attValue)) {
defaultAttValue = fStringPool.addString(newAttValue);
}
return defaultAttValue;
}
else {
String newAttValue = attValue.trim();
if (fValidationEnabled) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
defaultAttValue = fStringPool.addSymbol(newAttValue);
}
else {
defaultAttValue = fStringPool.addSymbol(defaultAttValue);
}
if (attType == XMLAttributeDecl.TYPE_ENTITY ||
attType == XMLAttributeDecl.TYPE_ID ||
attType == XMLAttributeDecl.TYPE_IDREF ||
attType == XMLAttributeDecl.TYPE_NOTATION) {
// REVISIT: A Hack!!! THis is to pass SUN test /invalid/attr11.xml and attr12.xml
// not consistent with XML1.0 spec VC: Attribute Default Legal
if (attType == XMLAttributeDecl.TYPE_ENTITY)
if (! ((DefaultEntityHandler) fEntityHandler).isUnparsedEntity(defaultAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID,
XMLMessages.VC_ENTITY_NAME,
fStringPool.toString(attribute.rawname), newAttValue);
}
if (!XMLCharacterProperties.validName(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ATT_DEFAULT_INVALID,
XMLMessages.VC_ATTRIBUTE_DEFAULT_LEGAL,
fStringPool.toString(attribute.rawname), newAttValue);
}
}
else if (attType == XMLAttributeDecl.TYPE_NMTOKEN ||
attType == XMLAttributeDecl.TYPE_ENUMERATION ) {
if (!XMLCharacterProperties.validNmtoken(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ATT_DEFAULT_INVALID,
XMLMessages.VC_ATTRIBUTE_DEFAULT_LEGAL,
fStringPool.toString(attribute.rawname), newAttValue);
}
}
if (attType == XMLAttributeDecl.TYPE_NOTATION ||
attType == XMLAttributeDecl.TYPE_ENUMERATION ) {
if ( !fStringPool.stringInList(enumeration, defaultAttValue) ) {
reportRecoverableXMLError(XMLMessages.MSG_ATT_DEFAULT_INVALID,
XMLMessages.VC_ATTRIBUTE_DEFAULT_LEGAL,
fStringPool.toString(attribute.rawname), newAttValue);
}
}
}
else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
defaultAttValue = fStringPool.addSymbol(newAttValue);
}
}
return defaultAttValue;
}
/***
public boolean scanDoctypeDecl(boolean standalone) throws Exception {
fStandaloneReader = standalone ? fEntityHandler.getReaderId() : -1;
fDeclsAreExternal = false;
if (!fDTDScanner.scanDoctypeDecl()) {
return false;
}
if (fDTDScanner.getReadingExternalEntity()) {
fDTDScanner.scanDecls(true);
}
fDTDHandler.endDTD();
return true;
}
/***/
} // class XMLDTDScanner
| put back in code that was inadvertently lost in 1.6
and which allows xml:space to be declared as only having one of the two
possible values
git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@315930 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/xerces/framework/XMLDTDScanner.java | put back in code that was inadvertently lost in 1.6 and which allows xml:space to be declared as only having one of the two possible values | <ide><path>rc/org/apache/xerces/framework/XMLDTDScanner.java
<ide> if (attDefType == XMLAttributeDecl.TYPE_ENUMERATION) {
<ide> int index = attDefEnumeration;
<ide> if (index != -1) {
<del> ok = fStringPool.stringListLength(index) == 2 &&
<add> ok = (fStringPool.stringListLength(index) == 1 &&
<add> (fStringPool.stringInList(index, fDefault) ||
<add> fStringPool.stringInList(index, fPreserve))) ||
<add> (fStringPool.stringListLength(index) == 2 &&
<ide> fStringPool.stringInList(index, fDefault) &&
<del> fStringPool.stringInList(index, fPreserve);
<add> fStringPool.stringInList(index, fPreserve));
<ide> }
<ide> }
<ide> if (!ok) { |
|
Java | apache-2.0 | 77c6d31553d0e23f45032e700ca4a8c398240e1e | 0 | dbrimley/hazelcast,dsukhoroslov/hazelcast,dsukhoroslov/hazelcast,mdogan/hazelcast,Donnerbart/hazelcast,mesutcelik/hazelcast,emre-aydin/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast,dbrimley/hazelcast,emrahkocaman/hazelcast,Donnerbart/hazelcast,juanavelez/hazelcast,emre-aydin/hazelcast,tufangorel/hazelcast,tkountis/hazelcast,mesutcelik/hazelcast,Donnerbart/hazelcast,juanavelez/hazelcast,mdogan/hazelcast,emre-aydin/hazelcast,mdogan/hazelcast,tkountis/hazelcast,tufangorel/hazelcast,tombujok/hazelcast,tkountis/hazelcast,lmjacksoniii/hazelcast,dbrimley/hazelcast,tombujok/hazelcast,emrahkocaman/hazelcast,lmjacksoniii/hazelcast | /*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.spi.impl;
import com.hazelcast.client.*;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.connection.Authenticator;
import com.hazelcast.client.connection.ClientConnectionManager;
import com.hazelcast.client.connection.Connection;
import com.hazelcast.client.spi.ClientClusterService;
import com.hazelcast.client.spi.ResponseHandler;
import com.hazelcast.client.spi.ResponseStream;
import com.hazelcast.client.util.AddressHelper;
import com.hazelcast.client.util.ErrorHandler;
import com.hazelcast.cluster.client.AddMembershipListenerRequest;
import com.hazelcast.cluster.client.ClientMembershipEvent;
import com.hazelcast.core.*;
import com.hazelcast.instance.MemberImpl;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.IOUtil;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.nio.serialization.SerializationService;
import com.hazelcast.security.Credentials;
import com.hazelcast.spi.impl.SerializableCollection;
import com.hazelcast.util.Clock;
import com.hazelcast.util.ExceptionUtil;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import static com.hazelcast.util.ExceptionUtil.fixRemoteStackTrace;
/**
* @author mdogan 5/15/13
*/
public final class ClientClusterServiceImpl implements ClientClusterService {
private static final ILogger logger = Logger.getLogger(ClientClusterService.class);
private static int RETRY_COUNT = 20;
private static int RETRY_WAIT_TIME = 500;
private final HazelcastClient client;
private final ClusterListenerThread clusterThread;
private final AtomicReference<Map<Address, MemberImpl>> membersRef = new AtomicReference<Map<Address, MemberImpl>>();
private final ConcurrentMap<String, MembershipListener> listeners = new ConcurrentHashMap<String, MembershipListener>();
private final boolean redoOperation;
private final Credentials credentials;
private volatile ClientPrincipal principal;
private volatile boolean active = false;
public ClientClusterServiceImpl(HazelcastClient client) {
this.client = client;
clusterThread = new ClusterListenerThread(client.getThreadGroup(), client.getName() + ".cluster-listener");
final ClientConfig clientConfig = getClientConfig();
redoOperation = clientConfig.isRedoOperation();
credentials = clientConfig.getCredentials();
final Collection<EventListener> listenersList = client.getClientConfig().getListeners();
if (listenersList != null && !listenersList.isEmpty()) {
for (EventListener listener : listenersList) {
if (listener instanceof MembershipListener) {
addMembershipListener((MembershipListener) listener);
}
}
}
}
public MemberImpl getMember(Address address) {
final Map<Address, MemberImpl> members = membersRef.get();
return members != null ? members.get(address) : null;
}
public MemberImpl getMember(String uuid) {
final Collection<MemberImpl> memberList = getMemberList();
for (MemberImpl member : memberList) {
if (uuid.equals(member.getUuid())) {
return member;
}
}
return null;
}
public Collection<MemberImpl> getMemberList() {
final Map<Address, MemberImpl> members = membersRef.get();
return members != null ? members.values() : Collections.<MemberImpl>emptySet();
}
public Address getMasterAddress() {
final Collection<MemberImpl> memberList = getMemberList();
return !memberList.isEmpty() ? memberList.iterator().next().getAddress() : null;
}
public int getSize() {
return getMemberList().size();
}
public long getClusterTime() {
return Clock.currentTimeMillis();
}
<T> T sendAndReceive(Object obj) throws IOException {
return _sendAndReceive(randomConnectionFactory, obj);
}
<T> T sendAndReceive(final Address address, Object obj) throws IOException {
return _sendAndReceive(new TargetConnectionFactory(address), obj);
}
private interface ConnectionFactory {
Connection create() throws IOException;
}
private final ConnectionFactory randomConnectionFactory = new ConnectionFactory() {
public Connection create() throws IOException {
return getRandomConnection();
}
};
private class TargetConnectionFactory implements ConnectionFactory {
final Address target;
private TargetConnectionFactory(Address target) {
this.target = target;
}
public Connection create() throws IOException {
return getConnection(target);
}
}
private <T> T _sendAndReceive(ConnectionFactory connectionFactory, Object obj) throws IOException {
while (active) {
Connection conn = null;
boolean release = true;
try {
conn = connectionFactory.create();
final SerializationService serializationService = getSerializationService();
final Data request = serializationService.toData(obj);
conn.write(request);
final Data response = conn.read();
final Object result = serializationService.toObject(response);
return ErrorHandler.returnResultOrThrowException(result);
} catch (Exception e) {
if (e instanceof IOException) {
if (logger.isFinestEnabled()) {
logger.finest( "Error on connection... conn: " + conn + ", error: " + e);
}
IOUtil.closeResource(conn);
release = false;
}
if (ErrorHandler.isRetryable(e)) {
if (redoOperation || obj instanceof RetryableRequest) {
if (logger.isFinestEnabled()) {
logger.finest( "Retrying " + obj + ", last-conn: " + conn + ", last-error: " + e);
}
beforeRetry();
continue;
}
}
throw ExceptionUtil.rethrow(e, IOException.class);
} finally {
if (release && conn != null) {
conn.release();
}
}
}
throw new HazelcastInstanceNotActiveException();
}
public <T> T sendAndReceiveFixedConnection(Connection conn, Object obj) throws IOException {
final SerializationService serializationService = getSerializationService();
final Data request = serializationService.toData(obj);
conn.write(request);
final Data response = conn.read();
final Object result = serializationService.toObject(response);
return ErrorHandler.returnResultOrThrowException(result);
}
private SerializationService getSerializationService() {
return client.getSerializationService();
}
private ClientConnectionManager getConnectionManager() {
return client.getConnectionManager();
}
private Connection getRandomConnection() throws IOException {
return getConnection(null);
}
private Connection getConnection(Address address) throws IOException {
if (!client.getLifecycleService().isRunning()) {
throw new HazelcastInstanceNotActiveException();
}
Connection connection = null;
int retryCount = RETRY_COUNT;
while (connection == null && retryCount > 0) {
if (address != null) {
connection = client.getConnectionManager().getConnection(address);
address = null;
} else {
connection = client.getConnectionManager().getRandomConnection();
}
if (connection == null) {
retryCount--;
beforeRetry();
}
}
if (connection == null) {
throw new IOException("Unable to connect to " + address);
}
return connection;
}
private void beforeRetry() {
try {
Thread.sleep(RETRY_WAIT_TIME);
((ClientPartitionServiceImpl) client.getClientPartitionService()).refreshPartitions();
} catch (InterruptedException ignored) {
}
}
void sendAndHandle(final Address address, Object obj, ResponseHandler handler) throws IOException {
_sendAndHandle(new TargetConnectionFactory(address), obj, handler);
}
void sendAndHandle(Object obj, ResponseHandler handler) throws IOException {
_sendAndHandle(randomConnectionFactory, obj, handler);
}
private void _sendAndHandle(ConnectionFactory connectionFactory, Object obj, ResponseHandler handler) throws IOException {
ResponseStream stream = null;
while (stream == null) {
if (active){
throw new HazelcastInstanceNotActiveException();
}
Connection conn = null;
try {
conn = connectionFactory.create();
final SerializationService serializationService = getSerializationService();
final Data request = serializationService.toData(obj);
conn.write(request);
stream = new ResponseStreamImpl(serializationService, conn);
} catch (Exception e) {
if (e instanceof IOException) {
if (logger.isFinestEnabled()) {
logger.finest( "Error on connection... conn: " + conn + ", error: " + e);
}
}
if (conn != null) {
IOUtil.closeResource(conn);
}
if (ErrorHandler.isRetryable(e)) {
if (redoOperation || obj instanceof RetryableRequest) {
if (logger.isFinestEnabled()) {
logger.finest( "Retrying " + obj + ", last-conn: " + conn + ", last-error: " + e);
}
beforeRetry();
continue;
}
}
throw ExceptionUtil.rethrow(e, IOException.class);
}
}
try {
handler.handle(stream);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e, IOException.class);
} finally {
stream.end();
}
}
public Authenticator getAuthenticator() {
return new ClusterAuthenticator();
}
public String addMembershipListener(MembershipListener listener) {
final String id = UUID.randomUUID().toString();
if (listener instanceof InitialMembershipListener) {
// TODO: needs sync with membership events...
final Cluster cluster = client.getCluster();
((InitialMembershipListener) listener).init(new InitialMembershipEvent(cluster, cluster.getMembers()));
}
listeners.put(id, listener);
return id;
}
public boolean removeMembershipListener(String registrationId) {
return listeners.remove(registrationId) != null;
}
public void start() {
final Future<Connection> f = client.getClientExecutionService().submit(new InitialConnectionCall());
try {
final Connection connection = f.get(30, TimeUnit.SECONDS);
clusterThread.setInitialConn(connection);
} catch (Throwable e) {
if (e instanceof ExecutionException && e.getCause() != null) {
e = e.getCause();
fixRemoteStackTrace(e, Thread.currentThread().getStackTrace());
}
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new HazelcastException(e);
}
clusterThread.start();
// TODO: replace with a better wait-notify
while (membersRef.get() == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new HazelcastException(e);
}
}
active = true;
// started
}
public void stop() {
active = false;
clusterThread.shutdown();
}
private class InitialConnectionCall implements Callable<Connection> {
public Connection call() throws Exception {
return connectToOne(getConfigAddresses());
}
}
private class ClusterListenerThread extends Thread {
private ClusterListenerThread(ThreadGroup group, String name) {
super(group, name);
}
private volatile Connection conn;
private final List<MemberImpl> members = new LinkedList<MemberImpl>();
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
if (conn == null) {
try {
conn = pickConnection();
} catch (Exception e) {
logger.severe("Error while connecting to cluster!", e);
client.getLifecycleService().shutdown();
return;
}
}
loadInitialMemberList();
listenMembershipEvents();
} catch (Exception e) {
if (client.getLifecycleService().isRunning()) {
if (logger.isFinestEnabled()) {
logger.warning("Error while listening cluster events! -> " + conn, e);
} else {
logger.warning("Error while listening cluster events! -> " + conn + ", Error: " + e.toString());
}
}
IOUtil.closeResource(conn);
conn = null;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
private Connection pickConnection() throws Exception {
final Collection<InetSocketAddress> addresses = new HashSet<InetSocketAddress>();
if (!members.isEmpty()) {
addresses.addAll(getClusterAddresses());
}
addresses.addAll(getConfigAddresses());
return connectToOne(addresses);
}
private void loadInitialMemberList() throws IOException {
final SerializationService serializationService = getSerializationService();
final Data request = serializationService.toData(new AddMembershipListenerRequest());
conn.write(request);
final Data response = conn.read();
SerializableCollection coll = ErrorHandler.returnResultOrThrowException(serializationService.toObject(response));
Map<String, MemberImpl> prevMembers = Collections.emptyMap();
if (!members.isEmpty()) {
prevMembers = new HashMap<String, MemberImpl>(members.size());
for (MemberImpl member : members) {
prevMembers.put(member.getUuid(), member);
}
members.clear();
}
for (Data d : coll.getCollection()) {
members.add((MemberImpl) serializationService.toObject(d));
}
updateMembersRef();
logger.info(membersString());
final List<MembershipEvent> events = new LinkedList<MembershipEvent>();
final Set<Member> eventMembers = Collections.unmodifiableSet(new LinkedHashSet<Member>(members));
for (MemberImpl member : members) {
final MemberImpl former = prevMembers.remove(member.getUuid());
if (former == null) {
events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_ADDED, eventMembers));
}
}
for (MemberImpl member : prevMembers.values()) {
events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_REMOVED, eventMembers));
}
for (MembershipEvent event : events) {
fireMembershipEvent(event);
}
}
private void listenMembershipEvents() throws IOException {
final SerializationService serializationService = getSerializationService();
while (!Thread.currentThread().isInterrupted()) {
final Data eventData = conn.read();
final ClientMembershipEvent event = (ClientMembershipEvent) serializationService.toObject(eventData);
final MemberImpl member = (MemberImpl) event.getMember();
if (event.getEventType() == MembershipEvent.MEMBER_ADDED) {
members.add(member);
} else {
members.remove(member);
getConnectionManager().removeConnectionPool(member.getAddress());
}
updateMembersRef();
logger.info(membersString());
fireMembershipEvent(new MembershipEvent(client.getCluster(), member, event.getEventType(),
Collections.unmodifiableSet(new LinkedHashSet<Member>(members))));
}
}
private void fireMembershipEvent(final MembershipEvent event) {
client.getClientExecutionService().execute(new Runnable() {
public void run() {
for (MembershipListener listener : listeners.values()) {
if (event.getEventType() == MembershipEvent.MEMBER_ADDED) {
listener.memberAdded(event);
} else {
listener.memberRemoved(event);
}
}
}
});
}
private void updateMembersRef() {
final Map<Address, MemberImpl> map = new LinkedHashMap<Address, MemberImpl>(members.size());
for (MemberImpl member : members) {
map.put(member.getAddress(), member);
}
membersRef.set(Collections.unmodifiableMap(map));
}
private Collection<InetSocketAddress> getClusterAddresses() {
final List<InetSocketAddress> socketAddresses = new LinkedList<InetSocketAddress>();
for (MemberImpl member : members) {
socketAddresses.add(member.getInetSocketAddress());
}
Collections.shuffle(socketAddresses);
return socketAddresses;
}
void setInitialConn(Connection conn) {
this.conn = conn;
}
void shutdown() {
interrupt();
final Connection c = conn;
if (c != null) {
try {
c.close();
} catch (IOException e) {
logger.warning("Error while closing connection!", e);
}
}
}
}
private Connection connectToOne(final Collection<InetSocketAddress> socketAddresses) throws Exception {
final int connectionAttemptLimit = getClientConfig().getConnectionAttemptLimit();
final ManagerAuthenticator authenticator = new ManagerAuthenticator();
int attempt = 0;
Throwable lastError = null;
while (true) {
final long nextTry = Clock.currentTimeMillis() + getClientConfig().getConnectionAttemptPeriod();
for (InetSocketAddress isa : socketAddresses) {
Address address = new Address(isa);
try {
return getConnectionManager().firstConnection(address, authenticator);
} catch (IOException e) {
lastError = e;
logger.finest( "IO error during initial connection...", e);
} catch (AuthenticationException e) {
lastError = e;
logger.warning("Authentication error on " + address, e);
}
}
if (attempt++ >= connectionAttemptLimit) {
break;
}
final long remainingTime = nextTry - Clock.currentTimeMillis();
logger.warning(
String.format("Unable to get alive cluster connection," +
" try in %d ms later, attempt %d of %d.",
Math.max(0, remainingTime), attempt, connectionAttemptLimit));
if (remainingTime > 0) {
try {
Thread.sleep(remainingTime);
} catch (InterruptedException e) {
break;
}
}
}
throw new IllegalStateException("Unable to connect to any address in the config!", lastError);
}
private Collection<InetSocketAddress> getConfigAddresses() {
final List<InetSocketAddress> socketAddresses = new LinkedList<InetSocketAddress>();
for (String address : getClientConfig().getAddressList()) {
socketAddresses.addAll(AddressHelper.getSocketAddresses(address));
}
Collections.shuffle(socketAddresses);
return socketAddresses;
}
private ClientConfig getClientConfig() {
return client.getClientConfig();
}
private class ManagerAuthenticator implements Authenticator {
public void auth(Connection connection) throws AuthenticationException, IOException {
final Object response = authenticate(connection, credentials, principal, true, true);
principal = (ClientPrincipal) response;
}
}
private class ClusterAuthenticator implements Authenticator {
public void auth(Connection connection) throws AuthenticationException, IOException {
authenticate(connection, credentials, principal, false, false);
}
}
private Object authenticate(Connection connection, Credentials credentials, ClientPrincipal principal, boolean reAuth, boolean firstConnection) throws IOException {
AuthenticationRequest auth = new AuthenticationRequest(credentials, principal);
auth.setReAuth(reAuth);
auth.setFirstConnection(firstConnection);
final SerializationService serializationService = getSerializationService();
connection.write(serializationService.toData(auth));
final Data addressData = connection.read();
Address address = ErrorHandler.returnResultOrThrowException(serializationService.toObject(addressData));
connection.setEndpoint(address);
final Data data = connection.read();
return ErrorHandler.returnResultOrThrowException(serializationService.toObject(data));
}
public String membersString() {
StringBuilder sb = new StringBuilder("\n\nMembers [");
final Collection<MemberImpl> members = getMemberList();
sb.append(members != null ? members.size() : 0);
sb.append("] {");
if (members != null) {
for (Member member : members) {
sb.append("\n\t").append(member);
}
}
sb.append("\n}\n");
return sb.toString();
}
}
| hazelcast-client/src/main/java/com/hazelcast/client/spi/impl/ClientClusterServiceImpl.java | /*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.spi.impl;
import com.hazelcast.client.*;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.connection.Authenticator;
import com.hazelcast.client.connection.ClientConnectionManager;
import com.hazelcast.client.connection.Connection;
import com.hazelcast.client.spi.ClientClusterService;
import com.hazelcast.client.spi.ResponseHandler;
import com.hazelcast.client.spi.ResponseStream;
import com.hazelcast.client.util.AddressHelper;
import com.hazelcast.client.util.ErrorHandler;
import com.hazelcast.cluster.client.AddMembershipListenerRequest;
import com.hazelcast.cluster.client.ClientMembershipEvent;
import com.hazelcast.core.*;
import com.hazelcast.instance.MemberImpl;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.IOUtil;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.nio.serialization.SerializationService;
import com.hazelcast.security.Credentials;
import com.hazelcast.spi.impl.SerializableCollection;
import com.hazelcast.util.Clock;
import com.hazelcast.util.ExceptionUtil;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import static com.hazelcast.util.ExceptionUtil.fixRemoteStackTrace;
/**
* @author mdogan 5/15/13
*/
public final class ClientClusterServiceImpl implements ClientClusterService {
private static final ILogger logger = Logger.getLogger(ClientClusterService.class);
private static int RETRY_COUNT = 20;
private static int RETRY_WAIT_TIME = 500;
private final HazelcastClient client;
private final ClusterListenerThread clusterThread;
private final AtomicReference<Map<Address, MemberImpl>> membersRef = new AtomicReference<Map<Address, MemberImpl>>();
private final ConcurrentMap<String, MembershipListener> listeners = new ConcurrentHashMap<String, MembershipListener>();
private final boolean redoOperation;
private final Credentials credentials;
private volatile ClientPrincipal principal;
public ClientClusterServiceImpl(HazelcastClient client) {
this.client = client;
clusterThread = new ClusterListenerThread(client.getThreadGroup(), client.getName() + ".cluster-listener");
final ClientConfig clientConfig = getClientConfig();
redoOperation = clientConfig.isRedoOperation();
credentials = clientConfig.getCredentials();
final Collection<EventListener> listenersList = client.getClientConfig().getListeners();
if (listenersList != null && !listenersList.isEmpty()) {
for (EventListener listener : listenersList) {
if (listener instanceof MembershipListener) {
addMembershipListener((MembershipListener) listener);
}
}
}
}
public MemberImpl getMember(Address address) {
final Map<Address, MemberImpl> members = membersRef.get();
return members != null ? members.get(address) : null;
}
public MemberImpl getMember(String uuid) {
final Collection<MemberImpl> memberList = getMemberList();
for (MemberImpl member : memberList) {
if (uuid.equals(member.getUuid())) {
return member;
}
}
return null;
}
public Collection<MemberImpl> getMemberList() {
final Map<Address, MemberImpl> members = membersRef.get();
return members != null ? members.values() : Collections.<MemberImpl>emptySet();
}
public Address getMasterAddress() {
final Collection<MemberImpl> memberList = getMemberList();
return !memberList.isEmpty() ? memberList.iterator().next().getAddress() : null;
}
public int getSize() {
return getMemberList().size();
}
public long getClusterTime() {
return Clock.currentTimeMillis();
}
<T> T sendAndReceive(Object obj) throws IOException {
return _sendAndReceive(randomConnectionFactory, obj);
}
<T> T sendAndReceive(final Address address, Object obj) throws IOException {
return _sendAndReceive(new TargetConnectionFactory(address), obj);
}
private interface ConnectionFactory {
Connection create() throws IOException;
}
private final ConnectionFactory randomConnectionFactory = new ConnectionFactory() {
public Connection create() throws IOException {
return getRandomConnection();
}
};
private class TargetConnectionFactory implements ConnectionFactory {
final Address target;
private TargetConnectionFactory(Address target) {
this.target = target;
}
public Connection create() throws IOException {
return getConnection(target);
}
}
private <T> T _sendAndReceive(ConnectionFactory connectionFactory, Object obj) throws IOException {
while (true) {
Connection conn = null;
boolean release = true;
try {
conn = connectionFactory.create();
final SerializationService serializationService = getSerializationService();
final Data request = serializationService.toData(obj);
conn.write(request);
final Data response = conn.read();
final Object result = serializationService.toObject(response);
return ErrorHandler.returnResultOrThrowException(result);
} catch (Exception e) {
if (e instanceof IOException) {
if (logger.isFinestEnabled()) {
logger.finest( "Error on connection... conn: " + conn + ", error: " + e);
}
IOUtil.closeResource(conn);
release = false;
}
if (ErrorHandler.isRetryable(e)) {
if (redoOperation || obj instanceof RetryableRequest) {
if (logger.isFinestEnabled()) {
logger.finest( "Retrying " + obj + ", last-conn: " + conn + ", last-error: " + e);
}
beforeRetry();
continue;
}
}
throw ExceptionUtil.rethrow(e, IOException.class);
} finally {
if (release && conn != null) {
conn.release();
}
}
}
}
public <T> T sendAndReceiveFixedConnection(Connection conn, Object obj) throws IOException {
final SerializationService serializationService = getSerializationService();
final Data request = serializationService.toData(obj);
conn.write(request);
final Data response = conn.read();
final Object result = serializationService.toObject(response);
return ErrorHandler.returnResultOrThrowException(result);
}
private SerializationService getSerializationService() {
return client.getSerializationService();
}
private ClientConnectionManager getConnectionManager() {
return client.getConnectionManager();
}
private Connection getRandomConnection() throws IOException {
return getConnection(null);
}
private Connection getConnection(Address address) throws IOException {
if (!client.getLifecycleService().isRunning()) {
throw new HazelcastInstanceNotActiveException();
}
Connection connection = null;
int retryCount = RETRY_COUNT;
while (connection == null && retryCount > 0) {
if (address != null) {
connection = client.getConnectionManager().getConnection(address);
address = null;
} else {
connection = client.getConnectionManager().getRandomConnection();
}
if (connection == null) {
retryCount--;
beforeRetry();
}
}
if (connection == null) {
throw new IOException("Unable to connect to " + address);
}
return connection;
}
private void beforeRetry() {
try {
Thread.sleep(RETRY_WAIT_TIME);
((ClientPartitionServiceImpl) client.getClientPartitionService()).refreshPartitions();
} catch (InterruptedException ignored) {
}
}
void sendAndHandle(final Address address, Object obj, ResponseHandler handler) throws IOException {
_sendAndHandle(new TargetConnectionFactory(address), obj, handler);
}
void sendAndHandle(Object obj, ResponseHandler handler) throws IOException {
_sendAndHandle(randomConnectionFactory, obj, handler);
}
private void _sendAndHandle(ConnectionFactory connectionFactory, Object obj, ResponseHandler handler) throws IOException {
ResponseStream stream = null;
while (stream == null) {
Connection conn = null;
try {
conn = connectionFactory.create();
final SerializationService serializationService = getSerializationService();
final Data request = serializationService.toData(obj);
conn.write(request);
stream = new ResponseStreamImpl(serializationService, conn);
} catch (Exception e) {
if (e instanceof IOException) {
if (logger.isFinestEnabled()) {
logger.finest( "Error on connection... conn: " + conn + ", error: " + e);
}
}
if (conn != null) {
IOUtil.closeResource(conn);
}
if (ErrorHandler.isRetryable(e)) {
if (redoOperation || obj instanceof RetryableRequest) {
if (logger.isFinestEnabled()) {
logger.finest( "Retrying " + obj + ", last-conn: " + conn + ", last-error: " + e);
}
beforeRetry();
continue;
}
}
throw ExceptionUtil.rethrow(e, IOException.class);
}
}
try {
handler.handle(stream);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e, IOException.class);
} finally {
stream.end();
}
}
public Authenticator getAuthenticator() {
return new ClusterAuthenticator();
}
public String addMembershipListener(MembershipListener listener) {
final String id = UUID.randomUUID().toString();
if (listener instanceof InitialMembershipListener) {
// TODO: needs sync with membership events...
final Cluster cluster = client.getCluster();
((InitialMembershipListener) listener).init(new InitialMembershipEvent(cluster, cluster.getMembers()));
}
listeners.put(id, listener);
return id;
}
public boolean removeMembershipListener(String registrationId) {
return listeners.remove(registrationId) != null;
}
public void start() {
final Future<Connection> f = client.getClientExecutionService().submit(new InitialConnectionCall());
try {
final Connection connection = f.get(30, TimeUnit.SECONDS);
clusterThread.setInitialConn(connection);
} catch (Throwable e) {
if (e instanceof ExecutionException && e.getCause() != null) {
e = e.getCause();
fixRemoteStackTrace(e, Thread.currentThread().getStackTrace());
}
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new HazelcastException(e);
}
clusterThread.start();
// TODO: replace with a better wait-notify
while (membersRef.get() == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new HazelcastException(e);
}
}
// started
}
public void stop() {
clusterThread.shutdown();
}
private class InitialConnectionCall implements Callable<Connection> {
public Connection call() throws Exception {
return connectToOne(getConfigAddresses());
}
}
private class ClusterListenerThread extends Thread {
private ClusterListenerThread(ThreadGroup group, String name) {
super(group, name);
}
private volatile Connection conn;
private final List<MemberImpl> members = new LinkedList<MemberImpl>();
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
if (conn == null) {
try {
conn = pickConnection();
} catch (Exception e) {
logger.severe("Error while connecting to cluster!", e);
client.getLifecycleService().shutdown();
return;
}
}
loadInitialMemberList();
listenMembershipEvents();
} catch (Exception e) {
if (client.getLifecycleService().isRunning()) {
if (logger.isFinestEnabled()) {
logger.warning("Error while listening cluster events! -> " + conn, e);
} else {
logger.warning("Error while listening cluster events! -> " + conn + ", Error: " + e.toString());
}
}
IOUtil.closeResource(conn);
conn = null;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
private Connection pickConnection() throws Exception {
final Collection<InetSocketAddress> addresses = new HashSet<InetSocketAddress>();
if (!members.isEmpty()) {
addresses.addAll(getClusterAddresses());
}
addresses.addAll(getConfigAddresses());
return connectToOne(addresses);
}
private void loadInitialMemberList() throws IOException {
final SerializationService serializationService = getSerializationService();
final Data request = serializationService.toData(new AddMembershipListenerRequest());
conn.write(request);
final Data response = conn.read();
SerializableCollection coll = ErrorHandler.returnResultOrThrowException(serializationService.toObject(response));
Map<String, MemberImpl> prevMembers = Collections.emptyMap();
if (!members.isEmpty()) {
prevMembers = new HashMap<String, MemberImpl>(members.size());
for (MemberImpl member : members) {
prevMembers.put(member.getUuid(), member);
}
members.clear();
}
for (Data d : coll.getCollection()) {
members.add((MemberImpl) serializationService.toObject(d));
}
updateMembersRef();
logger.info(membersString());
final List<MembershipEvent> events = new LinkedList<MembershipEvent>();
final Set<Member> eventMembers = Collections.unmodifiableSet(new LinkedHashSet<Member>(members));
for (MemberImpl member : members) {
final MemberImpl former = prevMembers.remove(member.getUuid());
if (former == null) {
events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_ADDED, eventMembers));
}
}
for (MemberImpl member : prevMembers.values()) {
events.add(new MembershipEvent(client.getCluster(), member, MembershipEvent.MEMBER_REMOVED, eventMembers));
}
for (MembershipEvent event : events) {
fireMembershipEvent(event);
}
}
private void listenMembershipEvents() throws IOException {
final SerializationService serializationService = getSerializationService();
while (!Thread.currentThread().isInterrupted()) {
final Data eventData = conn.read();
final ClientMembershipEvent event = (ClientMembershipEvent) serializationService.toObject(eventData);
final MemberImpl member = (MemberImpl) event.getMember();
if (event.getEventType() == MembershipEvent.MEMBER_ADDED) {
members.add(member);
} else {
members.remove(member);
getConnectionManager().removeConnectionPool(member.getAddress());
}
updateMembersRef();
logger.info(membersString());
fireMembershipEvent(new MembershipEvent(client.getCluster(), member, event.getEventType(),
Collections.unmodifiableSet(new LinkedHashSet<Member>(members))));
}
}
private void fireMembershipEvent(final MembershipEvent event) {
client.getClientExecutionService().execute(new Runnable() {
public void run() {
for (MembershipListener listener : listeners.values()) {
if (event.getEventType() == MembershipEvent.MEMBER_ADDED) {
listener.memberAdded(event);
} else {
listener.memberRemoved(event);
}
}
}
});
}
private void updateMembersRef() {
final Map<Address, MemberImpl> map = new LinkedHashMap<Address, MemberImpl>(members.size());
for (MemberImpl member : members) {
map.put(member.getAddress(), member);
}
membersRef.set(Collections.unmodifiableMap(map));
}
private Collection<InetSocketAddress> getClusterAddresses() {
final List<InetSocketAddress> socketAddresses = new LinkedList<InetSocketAddress>();
for (MemberImpl member : members) {
socketAddresses.add(member.getInetSocketAddress());
}
Collections.shuffle(socketAddresses);
return socketAddresses;
}
void setInitialConn(Connection conn) {
this.conn = conn;
}
void shutdown() {
interrupt();
final Connection c = conn;
if (c != null) {
try {
c.close();
} catch (IOException e) {
logger.warning("Error while closing connection!", e);
}
}
}
}
private Connection connectToOne(final Collection<InetSocketAddress> socketAddresses) throws Exception {
final int connectionAttemptLimit = getClientConfig().getConnectionAttemptLimit();
final ManagerAuthenticator authenticator = new ManagerAuthenticator();
int attempt = 0;
Throwable lastError = null;
while (true) {
final long nextTry = Clock.currentTimeMillis() + getClientConfig().getConnectionAttemptPeriod();
for (InetSocketAddress isa : socketAddresses) {
Address address = new Address(isa);
try {
return getConnectionManager().firstConnection(address, authenticator);
} catch (IOException e) {
lastError = e;
logger.finest( "IO error during initial connection...", e);
} catch (AuthenticationException e) {
lastError = e;
logger.warning("Authentication error on " + address, e);
}
}
if (attempt++ >= connectionAttemptLimit) {
break;
}
final long remainingTime = nextTry - Clock.currentTimeMillis();
logger.warning(
String.format("Unable to get alive cluster connection," +
" try in %d ms later, attempt %d of %d.",
Math.max(0, remainingTime), attempt, connectionAttemptLimit));
if (remainingTime > 0) {
try {
Thread.sleep(remainingTime);
} catch (InterruptedException e) {
break;
}
}
}
throw new IllegalStateException("Unable to connect to any address in the config!", lastError);
}
private Collection<InetSocketAddress> getConfigAddresses() {
final List<InetSocketAddress> socketAddresses = new LinkedList<InetSocketAddress>();
for (String address : getClientConfig().getAddressList()) {
socketAddresses.addAll(AddressHelper.getSocketAddresses(address));
}
Collections.shuffle(socketAddresses);
return socketAddresses;
}
private ClientConfig getClientConfig() {
return client.getClientConfig();
}
private class ManagerAuthenticator implements Authenticator {
public void auth(Connection connection) throws AuthenticationException, IOException {
final Object response = authenticate(connection, credentials, principal, true, true);
principal = (ClientPrincipal) response;
}
}
private class ClusterAuthenticator implements Authenticator {
public void auth(Connection connection) throws AuthenticationException, IOException {
authenticate(connection, credentials, principal, false, false);
}
}
private Object authenticate(Connection connection, Credentials credentials, ClientPrincipal principal, boolean reAuth, boolean firstConnection) throws IOException {
AuthenticationRequest auth = new AuthenticationRequest(credentials, principal);
auth.setReAuth(reAuth);
auth.setFirstConnection(firstConnection);
final SerializationService serializationService = getSerializationService();
connection.write(serializationService.toData(auth));
final Data addressData = connection.read();
Address address = ErrorHandler.returnResultOrThrowException(serializationService.toObject(addressData));
connection.setEndpoint(address);
final Data data = connection.read();
return ErrorHandler.returnResultOrThrowException(serializationService.toObject(data));
}
public String membersString() {
StringBuilder sb = new StringBuilder("\n\nMembers [");
final Collection<MemberImpl> members = getMemberList();
sb.append(members != null ? members.size() : 0);
sb.append("] {");
if (members != null) {
for (Member member : members) {
sb.append("\n\t").append(member);
}
}
sb.append("\n}\n");
return sb.toString();
}
}
| client hangs after shutdown fixes #issue821
| hazelcast-client/src/main/java/com/hazelcast/client/spi/impl/ClientClusterServiceImpl.java | client hangs after shutdown fixes #issue821 | <ide><path>azelcast-client/src/main/java/com/hazelcast/client/spi/impl/ClientClusterServiceImpl.java
<ide> private final boolean redoOperation;
<ide> private final Credentials credentials;
<ide> private volatile ClientPrincipal principal;
<add> private volatile boolean active = false;
<ide>
<ide> public ClientClusterServiceImpl(HazelcastClient client) {
<ide> this.client = client;
<ide> }
<ide>
<ide> private <T> T _sendAndReceive(ConnectionFactory connectionFactory, Object obj) throws IOException {
<del> while (true) {
<add> while (active) {
<ide> Connection conn = null;
<ide> boolean release = true;
<ide> try {
<ide> }
<ide> }
<ide> }
<add> throw new HazelcastInstanceNotActiveException();
<ide> }
<ide>
<ide> public <T> T sendAndReceiveFixedConnection(Connection conn, Object obj) throws IOException {
<ide> private void _sendAndHandle(ConnectionFactory connectionFactory, Object obj, ResponseHandler handler) throws IOException {
<ide> ResponseStream stream = null;
<ide> while (stream == null) {
<add> if (active){
<add> throw new HazelcastInstanceNotActiveException();
<add> }
<ide> Connection conn = null;
<ide> try {
<ide> conn = connectionFactory.create();
<ide> throw new HazelcastException(e);
<ide> }
<ide> }
<add> active = true;
<ide> // started
<ide> }
<ide>
<ide> public void stop() {
<add> active = false;
<ide> clusterThread.shutdown();
<ide> }
<ide> |
|
Java | lgpl-2.1 | 966a4c282204e954266952532eeebeb285712941 | 0 | baranovRP/functional-tests,TheNoise/functional-tests,dmitryakushev/JTalks,johnnybigfoot/FTests,jtalks-org/functional-tests,DentonA/functional-tests | package org.jtalks.tests.jcommune;
import org.jtalks.tests.jcommune.common.JCommuneSeleniumTest;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import utils.CollectionHelp;
import utils.StringHelp;
import java.util.List;
/**
* This functional test covers Topic edit validation test case TC-JC10
* http://jtalks.org/display/jcommune/TC-JC10+Topic+edit+validation
*
* @autor masyan
*/
public class TopicEditValidationTCJC10 extends JCommuneSeleniumTest {
List<WebElement> branches;
String subject;
String message;
@Test(priority = 1)
@Parameters({"app-url", "uUsername", "uPassword"})
public void checkBranchesListTest(String appUrl, String username, String password) {
driver.get(appUrl);
signIn(username, password, appUrl);
branches = driver.findElements(By.xpath("//a[@class='forum_link']"));
if (branches.size() == 0) {
throw new NoSuchElementException("Branches not found");
}
}
@Test(priority = 2)
public void createTopicForCheckValidationTest() {
CollectionHelp.getRandomWebElementFromCollection(branches).click();
driver.findElement(By.xpath("//a[contains(@href, '/jcommune/topics/new')]")).click();
driver.findElement(By.id("subject")).sendKeys(StringHelp.getRandomString(10));
driver.findElement(By.id("tbMsg")).sendKeys(StringHelp.getRandomString(20));
driver.findElement(By.id("post")).click();
}
@Test(priority = 3)
public void clickButtonEditTopicTest() {
driver.findElement(By.xpath("//a[contains(@href, '/jcommune/topics') and contains(@href, 'edit')]")).click();
Assert.assertNotNull(driver.findElement(By.id("topicDto")));
}
@Test(priority = 4)
public void checkErrorMessageWithEmptyTitleTopicTest() {
driver.findElement(By.id("tbMsg")).clear();
driver.findElement(By.xpath("//input[@id='subject']")).clear();
driver.findElement(By.id("post")).click();
Assert.assertNotNull(driver.findElement(By.xpath("//span[@id='subject']")));
}
@Test(priority = 5)
public void checkErrorMessageWithShortTitleTopicTest() {
driver.findElement(By.xpath("//input[@id='subject']")).sendKeys(StringHelp.getRandomString(3));
driver.findElement(By.id("post")).click();
Assert.assertNotNull(driver.findElement(By.xpath("//span[@id='subject']")));
}
//checking on the value of more than 255 characters do not need, because the field is limited to 255 characters
@Test(priority = 6)
public void checkErrorMessageWithValidTitleTopicTest() {
subject = StringHelp.getRandomString(10);
driver.findElement(By.xpath("//input[@id='subject']")).clear();
driver.findElement(By.xpath("//input[@id='subject']")).sendKeys(subject);
driver.findElement(By.id("post")).click();
try {
driver.findElement(By.xpath("//span[@id='subject']"));
//if element exists, then generate false to test. Because title is valid
Assert.assertFalse(true);
}
catch (NoSuchElementException e) {
}
}
@Test(priority = 7)
public void checkErrorMessageWithEmptyBodyTopicTest() {
driver.findElement(By.id("tbMsg")).clear();
driver.findElement(By.id("post")).click();
Assert.assertNotNull(driver.findElement(By.id("bodyText.errors")));
}
@Test(priority = 8)
public void checkErrorMessageWithShortBodyTopicTest() {
driver.findElement(By.id("tbMsg")).clear();
driver.findElement(By.id("tbMsg")).sendKeys(StringHelp.getRandomString(3));
driver.findElement(By.id("post")).click();
Assert.assertNotNull(driver.findElement(By.id("bodyText.errors")));
}
@Test(priority = 9)
public void checkErrorMessageWithLongBodyTopicTest() {
driver.findElement(By.id("tbMsg")).clear();
StringHelp.setLongTextValue(driver, driver.findElement(By.id("tbMsg")), StringHelp.getRandomString(20001));
driver.findElement(By.id("post")).click();
Assert.assertNotNull(driver.findElement(By.id("bodyText.errors")));
}
@Test(priority = 10)
public void checkErrorMessageWithValidBodyTopicTest() {
message = StringHelp.getRandomString(20000);
driver.findElement(By.id("tbMsg")).clear();
StringHelp.setLongTextValue(driver, driver.findElement(By.id("tbMsg")), message);
driver.findElement(By.id("post")).click();
}
@Test(priority = 11)
public void checkEditedSubjectTopicTest() {
String currentSubject = driver.findElement(By.xpath("//a[@class='heading']")).getText();
Assert.assertEquals(currentSubject, subject);
}
@Test(priority = 12)
@Parameters({"app-url"})
public void checkEditedMessageTopicTest(String appUrl) {
String currentMessage = driver.findElement(By.xpath("//div[@class='forum_message_cell_text']")).getText();
Assert.assertEquals(currentMessage, message);
logOut(appUrl);
}
}
| functional-tests-jcommune/src/test/java/org/jtalks/tests/jcommune/TopicEditValidationTCJC10.java | package org.jtalks.tests.jcommune;
import org.jtalks.tests.jcommune.common.JCommuneSeleniumTest;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import utils.CollectionHelp;
import utils.StringHelp;
import java.util.List;
/**
* This functional test covers Topic edit validation test case TC-JC10
* http://jtalks.org/display/jcommune/TC-JC10+Topic+edit+validation
*
* @autor masyan
*/
public class TopicEditValidationTCJC10 extends JCommuneSeleniumTest {
List<WebElement> branches;
String subject;
String message;
@Test(priority = 1)
@Parameters({"app-url", "uUsername", "uPassword"})
public void checkBranchesListTest(String appUrl, String username, String password) {
driver = new FirefoxDriver();
driver.get(appUrl);
signIn(username, password, appUrl);
branches = driver.findElements(By.xpath("//a[@class='forum_link']"));
if (branches.size() == 0) {
throw new NoSuchElementException("Branches not found");
}
}
@Test(priority = 2)
public void createTopicForCheckValidationTest() {
CollectionHelp.getRandomWebElementFromCollection(branches).click();
driver.findElement(By.xpath("//a[contains(@href, '/jcommune/topics/new')]")).click();
driver.findElement(By.id("subject")).sendKeys(StringHelp.getRandomString(10));
driver.findElement(By.id("tbMsg")).sendKeys(StringHelp.getRandomString(20));
driver.findElement(By.id("post")).click();
}
@Test(priority = 3)
public void clickButtonEditTopicTest() {
driver.findElement(By.xpath("//a[contains(@href, '/jcommune/topics') and contains(@href, 'edit')]")).click();
Assert.assertNotNull(driver.findElement(By.id("topicDto")));
}
@Test(priority = 4)
public void checkErrorMessageWithEmptyTitleTopicTest() {
driver.findElement(By.id("tbMsg")).clear();
driver.findElement(By.xpath("//input[@id='subject']")).clear();
driver.findElement(By.id("post")).click();
Assert.assertNotNull(driver.findElement(By.xpath("//span[@id='subject']")));
}
@Test(priority = 5)
public void checkErrorMessageWithShortTitleTopicTest() {
driver.findElement(By.xpath("//input[@id='subject']")).sendKeys(StringHelp.getRandomString(3));
driver.findElement(By.id("post")).click();
Assert.assertNotNull(driver.findElement(By.xpath("//span[@id='subject']")));
}
//checking on the value of more than 255 characters do not need, because the field is limited to 255 characters
@Test(priority = 6)
public void checkErrorMessageWithValidTitleTopicTest() {
subject = StringHelp.getRandomString(10);
driver.findElement(By.xpath("//input[@id='subject']")).clear();
driver.findElement(By.xpath("//input[@id='subject']")).sendKeys(subject);
driver.findElement(By.id("post")).click();
try {
driver.findElement(By.xpath("//span[@id='subject']"));
//if element exists, then generate false to test. Because title is valid
Assert.assertFalse(true);
}
catch (NoSuchElementException e) {
}
}
@Test(priority = 7)
public void checkErrorMessageWithEmptyBodyTopicTest() {
driver.findElement(By.id("tbMsg")).clear();
driver.findElement(By.id("post")).click();
Assert.assertNotNull(driver.findElement(By.id("bodyText.errors")));
}
@Test(priority = 8)
public void checkErrorMessageWithShortBodyTopicTest() {
driver.findElement(By.id("tbMsg")).clear();
driver.findElement(By.id("tbMsg")).sendKeys(StringHelp.getRandomString(3));
driver.findElement(By.id("post")).click();
Assert.assertNotNull(driver.findElement(By.id("bodyText.errors")));
}
@Test(priority = 9)
public void checkErrorMessageWithLongBodyTopicTest() {
driver.findElement(By.id("tbMsg")).clear();
StringHelp.setLongTextValue(driver, driver.findElement(By.id("tbMsg")), StringHelp.getRandomString(20001));
driver.findElement(By.id("post")).click();
Assert.assertNotNull(driver.findElement(By.id("bodyText.errors")));
}
@Test(priority = 10)
public void checkErrorMessageWithValidBodyTopicTest() {
message = StringHelp.getRandomString(20000);
driver.findElement(By.id("tbMsg")).clear();
StringHelp.setLongTextValue(driver, driver.findElement(By.id("tbMsg")), message);
driver.findElement(By.id("post")).click();
}
@Test(priority = 11)
public void checkEditedSubjectTopicTest() {
String currentSubject = driver.findElement(By.xpath("//a[@class='heading']")).getText();
Assert.assertEquals(currentSubject, subject);
}
@Test(priority = 12)
@Parameters({"app-url"})
public void checkEditedMessageTopicTest(String appUrl) {
String currentMessage = driver.findElement(By.xpath("//div[@class='forum_message_cell_text']")).getText();
Assert.assertEquals(currentMessage, message);
logOut(appUrl);
}
}
| clean
| functional-tests-jcommune/src/test/java/org/jtalks/tests/jcommune/TopicEditValidationTCJC10.java | clean | <ide><path>unctional-tests-jcommune/src/test/java/org/jtalks/tests/jcommune/TopicEditValidationTCJC10.java
<ide> @Test(priority = 1)
<ide> @Parameters({"app-url", "uUsername", "uPassword"})
<ide> public void checkBranchesListTest(String appUrl, String username, String password) {
<del> driver = new FirefoxDriver();
<ide> driver.get(appUrl);
<ide> signIn(username, password, appUrl);
<ide> branches = driver.findElements(By.xpath("//a[@class='forum_link']")); |
|
Java | apache-2.0 | 2b241f137c30c401380e74f6d96f0e6f2a8cf95e | 0 | cefolger/needsmoredojo,cefolger/needsmoredojo | package com.chrisfolger.needsmoredojo.intellij.reference;
import com.chrisfolger.needsmoredojo.core.amd.DefineResolver;
import com.intellij.lang.javascript.psi.*;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class NlsLookupReference extends PsiReferenceBase<JSLiteralExpression> {
private PsiElement qualifier;
private JSIndexedPropertyAccessExpression accessor;
private PsiFile file;
public NlsLookupReference(PsiElement qualifier, JSIndexedPropertyAccessExpression accessor, JSLiteralExpression sourceElement)
{
super(sourceElement);
this.qualifier = qualifier;
this.accessor = accessor;
}
public List<JSProperty> getI18nKeys(PsiFile file)
{
final List<JSProperty> keys = new ArrayList<JSProperty>();
file.acceptChildren(new JSRecursiveElementVisitor() {
@Override
public void visitJSObjectLiteralExpression(JSObjectLiteralExpression node)
{
if(!node.getParent().getText().startsWith("root:"))
{
super.visitJSObjectLiteralExpression(node);
return;
}
for(JSProperty property : node.getProperties())
{
keys.add(property);
}
super.visitJSObjectLiteralExpression(node);
}
});
return keys;
}
public PsiFile getFileContainingI18nKeys()
{
if(file != null)
{
return file;
}
// get the list of defines
// find one that matches
// check to see if it's an i18n file
// resolve the reference to the file
List<PsiElement> defines = new ArrayList<PsiElement>();
List<PsiElement> parameters = new ArrayList<PsiElement>();
new DefineResolver().gatherDefineAndParameters(qualifier.getContainingFile(), defines, parameters);
PsiElement correctDefine = null;
for(int i=0;i<parameters.size();i++)
{
if(parameters.get(i).getText().equals(qualifier.getText()))
{
correctDefine = defines.get(i);
}
}
// didn't get a define, so there is no reference to an i18n item
if(correctDefine == null)
{
return null;
}
String defineText = correctDefine.getText();
defineText = defineText.substring(defineText.lastIndexOf("!") + 1).replaceAll("'", "");
// TODO find relative path etc.
PsiFile[] files = FilenameIndex.getFilesByName(correctDefine.getProject(), "dojo.js", GlobalSearchScope.projectScope(correctDefine.getProject()));
PsiFile dojoFile = null;
for(PsiFile file : files)
{
if(file.getContainingDirectory().getName().equals("dojo"))
{
dojoFile = file;
break;
}
}
VirtualFile i18nFile = dojoFile.getContainingDirectory().getParent().getVirtualFile().findFileByRelativePath("/" + defineText + ".js");
PsiFile templateFile = PsiManager.getInstance(dojoFile.getProject()).findFile(i18nFile);
file = templateFile;
return templateFile;
}
@Nullable
@Override
public PsiElement resolve() {
PsiFile templateFile = getFileContainingI18nKeys();
if(templateFile == null)
{
return null;
}
for(JSProperty property : getI18nKeys(templateFile))
{
String propertyText = accessor.getIndexExpression().getText();
propertyText = propertyText.substring(1, propertyText.length() - 1);
if(property.getName().equals(propertyText))
{
return property;
}
}
return null;
}
@NotNull
@Override
public Object[] getVariants() {
PsiFile templateFile = getFileContainingI18nKeys();
if(templateFile == null)
{
return new Object[0];
}
List<JSProperty> keys = getI18nKeys(file);
List<Object> keyStrings = new ArrayList<Object>();
for(JSProperty key : keys)
{
keyStrings.add(key.getName());
}
return keyStrings.toArray();
}
}
| src/com/chrisfolger/needsmoredojo/intellij/reference/NlsLookupReference.java | package com.chrisfolger.needsmoredojo.intellij.reference;
import com.chrisfolger.needsmoredojo.core.amd.DefineResolver;
import com.intellij.lang.javascript.psi.*;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class NlsLookupReference extends PsiReferenceBase<JSLiteralExpression> {
private PsiElement qualifier;
private JSIndexedPropertyAccessExpression accessor;
public NlsLookupReference(PsiElement qualifier, JSIndexedPropertyAccessExpression accessor, JSLiteralExpression sourceElement)
{
super(sourceElement);
this.qualifier = qualifier;
this.accessor = accessor;
}
public List<JSProperty> getI18nKeys(PsiFile file)
{
final List<JSProperty> keys = new ArrayList<JSProperty>();
file.acceptChildren(new JSRecursiveElementVisitor() {
@Override
public void visitJSObjectLiteralExpression(JSObjectLiteralExpression node)
{
if(!node.getParent().getText().startsWith("root:"))
{
super.visitJSObjectLiteralExpression(node);
return;
}
for(JSProperty property : node.getProperties())
{
keys.add(property);
}
super.visitJSObjectLiteralExpression(node);
}
});
return keys;
}
public PsiFile getFileContainingI18nKeys()
{
// get the list of defines
// find one that matches
// check to see if it's an i18n file
// resolve the reference to the file
List<PsiElement> defines = new ArrayList<PsiElement>();
List<PsiElement> parameters = new ArrayList<PsiElement>();
new DefineResolver().gatherDefineAndParameters(qualifier.getContainingFile(), defines, parameters);
PsiElement correctDefine = null;
for(int i=0;i<parameters.size();i++)
{
if(parameters.get(i).getText().equals(qualifier.getText()))
{
correctDefine = defines.get(i);
}
}
// didn't get a define, so there is no reference to an i18n item
if(correctDefine == null)
{
return null;
}
String defineText = correctDefine.getText();
defineText = defineText.substring(defineText.lastIndexOf("!") + 1).replaceAll("'", "");
// TODO find relative path etc.
PsiFile[] files = FilenameIndex.getFilesByName(correctDefine.getProject(), "dojo.js", GlobalSearchScope.projectScope(correctDefine.getProject()));
PsiFile dojoFile = null;
for(PsiFile file : files)
{
if(file.getContainingDirectory().getName().equals("dojo"))
{
dojoFile = file;
break;
}
}
VirtualFile i18nFile = dojoFile.getContainingDirectory().getParent().getVirtualFile().findFileByRelativePath("/" + defineText + ".js");
PsiFile templateFile = PsiManager.getInstance(dojoFile.getProject()).findFile(i18nFile);
return templateFile;
}
@Nullable
@Override
public PsiElement resolve() {
PsiFile templateFile = getFileContainingI18nKeys();
if(templateFile == null)
{
return null;
}
for(JSProperty property : getI18nKeys(templateFile))
{
String propertyText = accessor.getIndexExpression().getText();
propertyText = propertyText.substring(1, propertyText.length() - 1);
if(property.getName().equals(propertyText))
{
return property;
}
}
return null;
}
@NotNull
@Override
public Object[] getVariants() {
PsiFile file = getFileContainingI18nKeys();
if(file == null)
{
return new Object[0];
}
List<JSProperty> keys = getI18nKeys(file);
List<Object> keyStrings = new ArrayList<Object>();
for(JSProperty key : keys)
{
keyStrings.add(key.getName());
}
return keyStrings.toArray();
}
}
| only load psi file once
| src/com/chrisfolger/needsmoredojo/intellij/reference/NlsLookupReference.java | only load psi file once | <ide><path>rc/com/chrisfolger/needsmoredojo/intellij/reference/NlsLookupReference.java
<ide> public class NlsLookupReference extends PsiReferenceBase<JSLiteralExpression> {
<ide> private PsiElement qualifier;
<ide> private JSIndexedPropertyAccessExpression accessor;
<add> private PsiFile file;
<ide>
<ide> public NlsLookupReference(PsiElement qualifier, JSIndexedPropertyAccessExpression accessor, JSLiteralExpression sourceElement)
<ide> {
<ide>
<ide> public PsiFile getFileContainingI18nKeys()
<ide> {
<add> if(file != null)
<add> {
<add> return file;
<add> }
<add>
<ide> // get the list of defines
<ide> // find one that matches
<ide> // check to see if it's an i18n file
<ide> VirtualFile i18nFile = dojoFile.getContainingDirectory().getParent().getVirtualFile().findFileByRelativePath("/" + defineText + ".js");
<ide> PsiFile templateFile = PsiManager.getInstance(dojoFile.getProject()).findFile(i18nFile);
<ide>
<add> file = templateFile;
<ide> return templateFile;
<ide> }
<ide>
<ide> @NotNull
<ide> @Override
<ide> public Object[] getVariants() {
<del> PsiFile file = getFileContainingI18nKeys();
<del> if(file == null)
<add> PsiFile templateFile = getFileContainingI18nKeys();
<add> if(templateFile == null)
<ide> {
<ide> return new Object[0];
<ide> } |
|
Java | epl-1.0 | fdbc5c1af7f09464c24432c6ca45bb45153a139f | 0 | rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse | package com.redhat.ceylon.eclipse.code.hover;
/*******************************************************************************
* Copyright (c) 2000, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Genady Beryozkin <[email protected]> - [hovering] tooltip for constant string does not show constant value - https://bugs.eclipse.org/bugs/show_bug.cgi?id=85382
*******************************************************************************/
import static com.redhat.ceylon.eclipse.code.browser.BrowserInformationControl.isAvailable;
import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.addPageEpilog;
import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.convertToHTMLContent;
import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.insertPageProlog;
import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.toHex;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getLabel;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getModuleLabel;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getPackageLabel;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.findNode;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.gotoNode;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.CHARS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.COMMENTS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.IDENTIFIERS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.KEYWORDS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.NUMBERS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.PACKAGES;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.STRINGS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.TYPES;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.getCurrentThemeColor;
import static com.redhat.ceylon.eclipse.code.propose.CeylonContentProposer.getDescriptionFor;
import static com.redhat.ceylon.eclipse.code.resolve.CeylonReferenceResolver.getReferencedDeclaration;
import static com.redhat.ceylon.eclipse.code.resolve.CeylonReferenceResolver.getReferencedNode;
import static com.redhat.ceylon.eclipse.code.resolve.JavaHyperlinkDetector.getJavaElement;
import static com.redhat.ceylon.eclipse.code.resolve.JavaHyperlinkDetector.gotoJavaNode;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getModelLoader;
import static java.lang.Character.codePointCount;
import static java.lang.Float.parseFloat;
import static java.lang.Integer.parseInt;
import static org.eclipse.jdt.internal.ui.JavaPluginImages.setLocalImageDescriptors;
import static org.eclipse.jdt.ui.PreferenceConstants.APPEARANCE_JAVADOC_FONT;
import static org.eclipse.ui.ISharedImages.IMG_TOOL_BACK;
import static org.eclipse.ui.ISharedImages.IMG_TOOL_BACK_DISABLED;
import static org.eclipse.ui.ISharedImages.IMG_TOOL_FORWARD;
import static org.eclipse.ui.ISharedImages.IMG_TOOL_FORWARD_DISABLED;
import static org.eclipse.ui.PlatformUI.getWorkbench;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.Token;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.javadoc.JavadocContentAccess2;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.AbstractReusableInformationControlCreator;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IInputChangedListener;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextHoverExtension;
import org.eclipse.jface.text.ITextHoverExtension2;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Bundle;
import com.github.rjeschke.txtmark.BlockEmitter;
import com.github.rjeschke.txtmark.Configuration;
import com.github.rjeschke.txtmark.Configuration.Builder;
import com.github.rjeschke.txtmark.Processor;
import com.github.rjeschke.txtmark.SpanEmitter;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.cmr.api.ModuleSearchResult.ModuleDetails;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.NothingType;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Referenceable;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeAlias;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.model.UnknownType;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AnonymousAnnotation;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit;
import com.redhat.ceylon.eclipse.code.browser.BrowserInformationControl;
import com.redhat.ceylon.eclipse.code.browser.BrowserInput;
import com.redhat.ceylon.eclipse.code.editor.CeylonEditor;
import com.redhat.ceylon.eclipse.code.editor.Util;
import com.redhat.ceylon.eclipse.code.html.HTMLPrinter;
import com.redhat.ceylon.eclipse.code.parse.CeylonParseController;
import com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer;
import com.redhat.ceylon.eclipse.code.quickfix.ExtractFunctionProposal;
import com.redhat.ceylon.eclipse.code.quickfix.ExtractValueProposal;
import com.redhat.ceylon.eclipse.code.quickfix.SpecifyTypeProposal;
import com.redhat.ceylon.eclipse.code.search.FindAssignmentsAction;
import com.redhat.ceylon.eclipse.code.search.FindReferencesAction;
import com.redhat.ceylon.eclipse.code.search.FindRefinementsAction;
import com.redhat.ceylon.eclipse.code.search.FindSubtypesAction;
import com.redhat.ceylon.eclipse.core.model.loader.JDTModelLoader;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
/**
* Provides Javadoc as hover info for Java elements.
*
* @since 2.1
*/
public class DocumentationHover
implements ITextHover, ITextHoverExtension, ITextHoverExtension2 {
private CeylonEditor editor;
public DocumentationHover(CeylonEditor editor) {
this.editor = editor;
}
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
IDocument document = textViewer.getDocument();
int start= -2;
int end= -1;
try {
int pos= offset;
char c;
while (pos >= 0) {
c= document.getChar(pos);
if (!Character.isJavaIdentifierPart(c)) {
break;
}
--pos;
}
start= pos;
pos= offset;
int length= document.getLength();
while (pos < length) {
c= document.getChar(pos);
if (!Character.isJavaIdentifierPart(c)) {
break;
}
++pos;
}
end= pos;
} catch (BadLocationException x) {
}
if (start >= -1 && end > -1) {
if (start == offset && end == offset)
return new Region(offset, 0);
else if (start == offset)
return new Region(start, end - start);
else
return new Region(start + 1, end - start - 1);
}
return null;
}
final class CeylonLocationListener implements LocationListener {
private final BrowserInformationControl control;
CeylonLocationListener(BrowserInformationControl control) {
this.control = control;
}
@Override
public void changing(LocationEvent event) {
String location = event.location;
//necessary for windows environment (fix for blank page)
//somehow related to this: https://bugs.eclipse.org/bugs/show_bug.cgi?id=129236
if (!"about:blank".equals(location)) {
event.doit= false;
}
handleLink(location);
/*else if (location.startsWith("javadoc:")) {
final DocBrowserInformationControlInput input = (DocBrowserInformationControlInput) control.getInput();
int beginIndex = input.getHtml().indexOf("javadoc:")+8;
final String handle = input.getHtml().substring(beginIndex, input.getHtml().indexOf("\"",beginIndex));
new Job("Fetching Javadoc") {
@Override
protected IStatus run(IProgressMonitor monitor) {
final IJavaElement elem = JavaCore.create(handle);
try {
final String javadoc = JavadocContentAccess2.getHTMLContent((IMember) elem, true);
if (javadoc!=null) {
PlatformUI.getWorkbench().getProgressService()
.runInUI(editor.getSite().getWorkbenchWindow(), new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
StringBuffer sb = new StringBuffer();
HTMLPrinter.insertPageProlog(sb, 0, getStyleSheet());
appendJavadoc(elem, javadoc, sb);
HTMLPrinter.addPageEpilog(sb);
control.setInput(new DocBrowserInformationControlInput(input, null, sb.toString(), 0));
}
}, null);
}
}
catch (Exception e) {
e.printStackTrace();
}
return Status.OK_STATUS;
}
}.schedule();
}*/
}
private void handleLink(String location) {
if (location.startsWith("dec:")) {
Referenceable target = getLinkedModel(editor, location);
if (target!=null) {
close(control); //FIXME: should have protocol to hide, rather than dispose
gotoDeclaration(editor, target);
}
}
else if (location.startsWith("doc:")) {
Referenceable target = getLinkedModel(editor, location);
if (target!=null) {
control.setInput(getHoverInfo(target, control.getInput(), editor, null));
}
}
else if (location.startsWith("ref:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindReferencesAction(editor, (Declaration) target).run();
}
else if (location.startsWith("sub:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindSubtypesAction(editor, (Declaration) target).run();
}
else if (location.startsWith("act:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindRefinementsAction(editor, (Declaration) target).run();
}
else if (location.startsWith("ass:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindAssignmentsAction(editor, (Declaration) target).run();
}
else if (location.startsWith("stp:")) {
close(control);
CompilationUnit rn = editor.getParseController().getRootNode();
Node node = findNode(rn, Integer.parseInt(location.substring(4)));
SpecifyTypeProposal.create(rn, node, Util.getFile(editor.getEditorInput()))
.apply(editor.getParseController().getDocument());
}
else if (location.startsWith("exv:")) {
close(control);
new ExtractValueProposal(editor).apply(editor.getParseController().getDocument());
}
else if (location.startsWith("exf:")) {
close(control);
new ExtractFunctionProposal(editor).apply(editor.getParseController().getDocument());
}
}
@Override
public void changed(LocationEvent event) {}
}
/**
* Action to go back to the previous input in the hover control.
*/
static final class BackAction extends Action {
private final BrowserInformationControl fInfoControl;
public BackAction(BrowserInformationControl infoControl) {
fInfoControl= infoControl;
setText("Back");
ISharedImages images= getWorkbench().getSharedImages();
setImageDescriptor(images.getImageDescriptor(IMG_TOOL_BACK));
setDisabledImageDescriptor(images.getImageDescriptor(IMG_TOOL_BACK_DISABLED));
update();
}
@Override
public void run() {
BrowserInput previous= (BrowserInput) fInfoControl.getInput().getPrevious();
if (previous != null) {
fInfoControl.setInput(previous);
}
}
public void update() {
BrowserInput current= fInfoControl.getInput();
if (current != null && current.getPrevious() != null) {
BrowserInput previous= current.getPrevious();
setToolTipText("Back to " + previous.getInputName());
setEnabled(true);
} else {
setToolTipText("Back");
setEnabled(false);
}
}
}
/**
* Action to go forward to the next input in the hover control.
*/
static final class ForwardAction extends Action {
private final BrowserInformationControl fInfoControl;
public ForwardAction(BrowserInformationControl infoControl) {
fInfoControl= infoControl;
setText("Forward");
ISharedImages images= getWorkbench().getSharedImages();
setImageDescriptor(images.getImageDescriptor(IMG_TOOL_FORWARD));
setDisabledImageDescriptor(images.getImageDescriptor(IMG_TOOL_FORWARD_DISABLED));
update();
}
@Override
public void run() {
BrowserInput next= (BrowserInput) fInfoControl.getInput().getNext();
if (next != null) {
fInfoControl.setInput(next);
}
}
public void update() {
BrowserInput current= fInfoControl.getInput();
if (current != null && current.getNext() != null) {
setToolTipText("Forward to " + current.getNext().getInputName());
setEnabled(true);
} else {
setToolTipText("Forward");
setEnabled(false);
}
}
}
/**
* Action that shows the current hover contents in the Javadoc view.
*/
/*private static final class ShowInDocViewAction extends Action {
private final BrowserInformationControl fInfoControl;
public ShowInJavadocViewAction(BrowserInformationControl infoControl) {
fInfoControl= infoControl;
setText("Show in Ceylondoc View");
setImageDescriptor(JavaPluginImages.DESC_OBJS_JAVADOCTAG); //TODO: better image
}
@Override
public void run() {
DocBrowserInformationControlInput infoInput= (DocBrowserInformationControlInput) fInfoControl.getInput(); //TODO: check cast
fInfoControl.notifyDelayedInputChange(null);
fInfoControl.dispose(); //FIXME: should have protocol to hide, rather than dispose
try {
JavadocView view= (JavadocView) JavaPlugin.getActivePage().showView(JavaUI.ID_JAVADOC_VIEW);
view.setInput(infoInput);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
}
}*/
/**
* Action that opens the current hover input element.
*/
final class OpenDeclarationAction extends Action {
private final BrowserInformationControl fInfoControl;
public OpenDeclarationAction(BrowserInformationControl infoControl) {
fInfoControl = infoControl;
setText("Open Declaration");
setLocalImageDescriptors(this, "goto_input.gif");
}
@Override
public void run() {
close(fInfoControl); //FIXME: should have protocol to hide, rather than dispose
CeylonBrowserInput input = (CeylonBrowserInput) fInfoControl.getInput();
gotoDeclaration(editor, getLinkedModel(editor, input.getAddress()));
}
}
static void gotoDeclaration(CeylonEditor editor, Referenceable model) {
CeylonParseController cpc = editor.getParseController();
Node refNode = getReferencedNode(model, cpc);
if (refNode!=null) {
gotoNode(refNode, cpc.getProject(), cpc.getTypeChecker());
}
else if (model instanceof Declaration) {
gotoJavaNode((Declaration) model, cpc);
}
}
private static void close(BrowserInformationControl control) {
control.notifyDelayedInputChange(null);
control.dispose();
}
/**
* The style sheet (css).
*/
private static String fgStyleSheet;
/**
* The hover control creator.
*/
private IInformationControlCreator fHoverControlCreator;
/**
* The presentation control creator.
*/
private IInformationControlCreator fPresenterControlCreator;
private IInformationControlCreator getInformationPresenterControlCreator() {
if (fPresenterControlCreator == null)
fPresenterControlCreator= new PresenterControlCreator(this);
return fPresenterControlCreator;
}
@Override
public IInformationControlCreator getHoverControlCreator() {
return getHoverControlCreator("F2 for focus");
}
public IInformationControlCreator getHoverControlCreator(
String statusLineMessage) {
if (fHoverControlCreator == null) {
fHoverControlCreator= new HoverControlCreator(this,
getInformationPresenterControlCreator(),
statusLineMessage);
}
return fHoverControlCreator;
}
void addLinkListener(final BrowserInformationControl control) {
control.addLocationListener(new CeylonLocationListener(control));
}
public static Referenceable getLinkedModel(CeylonEditor editor, String location) {
TypeChecker tc = editor.getParseController().getTypeChecker();
String[] bits = location.split(":");
JDTModelLoader modelLoader = getModelLoader(tc);
String moduleName = bits[1];
Module module = modelLoader.getLoadedModule(moduleName);
if (module==null || bits.length==2) {
return module;
}
Referenceable target = module.getPackage(bits[2]);
for (int i=3; i<bits.length; i++) {
Scope scope;
if (target instanceof Scope) {
scope = (Scope) target;
}
else if (target instanceof TypedDeclaration) {
scope = ((TypedDeclaration) target).getType().getDeclaration();
}
else {
return null;
}
target = scope.getDirectMember(bits[i], null, false);
}
return target;
}
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
CeylonBrowserInput info = (CeylonBrowserInput) getHoverInfo2(textViewer, hoverRegion);
return info!=null ? info.getHtml() : null;
}
@Override
public CeylonBrowserInput getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
return internalGetHoverInfo(editor, hoverRegion);
}
static CeylonBrowserInput internalGetHoverInfo(final CeylonEditor editor,
IRegion hoverRegion) {
if (editor==null || editor.getSelectionProvider()==null) return null;
CeylonParseController parseController = editor.getParseController();
if (parseController==null) return null;
Tree.CompilationUnit rn = parseController.getRootNode();
if (rn!=null) {
int hoffset = hoverRegion.getOffset();
ITextSelection selection = getSelection(editor);
if (selection!=null &&
selection.getOffset()<=hoffset &&
selection.getOffset()+selection.getLength()>=hoffset) {
Node node = findNode(rn, selection.getOffset(),
selection.getOffset()+selection.getLength()-1);
if (node instanceof Tree.Expression) {
node = ((Tree.Expression) node).getTerm();
}
if (node instanceof Tree.Term) {
return getTermTypeHoverInfo(node, selection.getText(),
editor.getCeylonSourceViewer().getDocument(),
editor.getParseController().getProject());
}
}
Node node = findNode(rn, hoffset);
if (node instanceof Tree.ImportPath) {
Referenceable r = ((Tree.ImportPath) node).getModel();
if (r!=null) {
return getHoverInfo(r, null, editor, node);
}
}
else if (node instanceof Tree.LocalModifier) {
return getInferredTypeHoverInfo(node,
editor.getParseController().getProject());
}
else if (node instanceof Tree.Literal) {
return getTermTypeHoverInfo(node, null,
editor.getCeylonSourceViewer().getDocument(),
editor.getParseController().getProject());
}
else {
return getHoverInfo(getReferencedDeclaration(node),
null, editor, node);
}
}
return null;
}
private static ITextSelection getSelection(final CeylonEditor editor) {
final class GetSelection implements Runnable {
ITextSelection selection;
@Override
public void run() {
selection = (ITextSelection) editor.getSelectionProvider().getSelection();
}
ITextSelection getSelection() {
Display.getDefault().syncExec(this);
return selection;
}
}
return new GetSelection().getSelection();
}
private static CeylonBrowserInput getInferredTypeHoverInfo(Node node, IProject project) {
ProducedType t = ((Tree.LocalModifier) node).getTypeModel();
if (t==null) return null;
StringBuffer buffer = new StringBuffer();
HTMLPrinter.insertPageProlog(buffer, 0, DocumentationHover.getStyleSheet());
addImageAndLabel(buffer, null, fileUrl("types.gif").toExternalForm(),
16, 16, "<b><tt>" + highlightLine(t.getProducedTypeName()) + "</tt></b>",
20, 4);
buffer.append("<hr/>");
if (!t.containsUnknowns()) {
buffer.append("One quick assist available:<br/>");
addImageAndLabel(buffer, null, fileUrl("correction_change.gif").toExternalForm(),
16, 16, "<a href=\"stp:" + node.getStartIndex() + "\">Specify explicit type</a>",
20, 4);
}
//buffer.append(getDocumentationFor(editor.getParseController(), t.getDeclaration()));
HTMLPrinter.addPageEpilog(buffer);
return new CeylonBrowserInput(null, null, buffer.toString());
}
private static CeylonBrowserInput getTermTypeHoverInfo(Node node, String selectedText,
IDocument doc, IProject project) {
ProducedType t = ((Tree.Term) node).getTypeModel();
if (t==null) return null;
// String expr = "";
// try {
// expr = doc.get(node.getStartIndex(), node.getStopIndex()-node.getStartIndex()+1);
// }
// catch (BadLocationException e) {
// e.printStackTrace();
// }
StringBuffer buffer = new StringBuffer();
HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet());
String desc = node instanceof Tree.Literal ? "literal" : "expression";
addImageAndLabel(buffer, null, fileUrl("types.gif").toExternalForm(),
16, 16, "<b><tt>" + highlightLine(t.getProducedTypeName()) +
"</tt> "+desc+"</b>",
20, 4);
buffer.append( "<hr/>");
if (node instanceof Tree.StringLiteral) {
buffer.append("<code style='color:")
.append(toHex(getCurrentThemeColor(STRINGS)))
.append("'><pre>")
.append('\"')
.append(convertToHTMLContent(node.getText()))
.append('\"')
.append("</pre></code>")
.append("<hr/>");
// If a single char selection, then append info on that character too
if (selectedText != null
&& codePointCount(selectedText, 0, selectedText.length()) == 1) {
appendCharacterHoverInfo(buffer, selectedText);
}
}
else if (node instanceof Tree.CharLiteral) {
String character = node.getText();
if (character.length()>2) {
appendCharacterHoverInfo(buffer,
character.substring(1, character.length()-1));
}
}
else if (node instanceof Tree.NaturalLiteral) {
buffer.append("<code style='color:")
.append(toHex(getCurrentThemeColor(NUMBERS)))
.append("'>");
String text = node.getText().replace("_", "");
switch (text.charAt(0)) {
case '#':
buffer.append(parseInt(text.substring(1),16));
break;
case '$':
buffer.append(parseInt(text.substring(1),2));
break;
default:
buffer.append(parseInt(text));
}
buffer.append("</code>").append("<hr/>");
}
else if (node instanceof Tree.FloatLiteral) {
buffer.append("<code style='color:")
.append(toHex(getCurrentThemeColor(NUMBERS)))
.append("'>");
buffer.append(parseFloat(node.getText().replace("_", "")));
buffer.append("</code>").append("<hr/>");
}
buffer.append("Two quick assists available:<br/>");
addImageAndLabel(buffer, null, fileUrl("change.png").toExternalForm(),
16, 16, "<a href=\"exv:\">Extract value</a>",
20, 4);
addImageAndLabel(buffer, null, fileUrl("change.png").toExternalForm(),
16, 16, "<a href=\"exf:\">Extract function</a>",
20, 4);
HTMLPrinter.addPageEpilog(buffer);
return new CeylonBrowserInput(null, null, buffer.toString());
}
private static void appendCharacterHoverInfo(StringBuffer buffer, String character) {
buffer.append("<code style='color:")
.append(toHex(getCurrentThemeColor(CHARS)))
.append("'>")
.append('\'')
.append(convertToHTMLContent(character))
.append('\'')
.append("</code>");
int codepoint = Character.codePointAt(character, 0);
String name = Character.getName(codepoint);
buffer.append("<hr/>Unicode Name: <code>").append(name).append("</code>");
String hex = Integer.toHexString(codepoint).toUpperCase();
while (hex.length() < 4) {
hex = "0" + hex;
}
buffer.append("<br/>Codepoint: <code>").append("U+").append(hex).append("</code>");
buffer.append("<br/>General Category: <code>").append(getCodepointGeneralCategoryName(codepoint)).append("</code>");
Character.UnicodeScript script = Character.UnicodeScript.of(codepoint);
buffer.append("<br/>Script: <code>").append(script.name()).append("</code>");
Character.UnicodeBlock block = Character.UnicodeBlock.of(codepoint);
buffer.append("<br/>Block: <code>").append(block).append("<hr/>").append("</code>");
}
private static String getCodepointGeneralCategoryName(int codepoint) {
String gc;
switch (Character.getType(codepoint)) {
case Character.COMBINING_SPACING_MARK:
gc = "Mark, combining spacing"; break;
case Character.CONNECTOR_PUNCTUATION:
gc = "Punctuation, connector"; break;
case Character.CONTROL:
gc = "Other, control"; break;
case Character.CURRENCY_SYMBOL:
gc = "Symbol, currency"; break;
case Character.DASH_PUNCTUATION:
gc = "Punctuation, dash"; break;
case Character.DECIMAL_DIGIT_NUMBER:
gc = "Number, decimal digit"; break;
case Character.ENCLOSING_MARK:
gc = "Mark, enclosing"; break;
case Character.END_PUNCTUATION:
gc = "Punctuation, close"; break;
case Character.FINAL_QUOTE_PUNCTUATION:
gc = "Punctuation, final quote"; break;
case Character.FORMAT:
gc = "Other, format"; break;
case Character.INITIAL_QUOTE_PUNCTUATION:
gc = "Punctuation, initial quote"; break;
case Character.LETTER_NUMBER:
gc = "Number, letter"; break;
case Character.LINE_SEPARATOR:
gc = "Separator, line"; break;
case Character.LOWERCASE_LETTER:
gc = "Letter, lowercase"; break;
case Character.MATH_SYMBOL:
gc = "Symbol, math"; break;
case Character.MODIFIER_LETTER:
gc = "Letter, modifier"; break;
case Character.MODIFIER_SYMBOL:
gc = "Symbol, modifier"; break;
case Character.NON_SPACING_MARK:
gc = "Mark, nonspacing"; break;
case Character.OTHER_LETTER:
gc = "Letter, other"; break;
case Character.OTHER_NUMBER:
gc = "Number, other"; break;
case Character.OTHER_PUNCTUATION:
gc = "Punctuation, other"; break;
case Character.OTHER_SYMBOL:
gc = "Symbol, other"; break;
case Character.PARAGRAPH_SEPARATOR:
gc = "Separator, paragraph"; break;
case Character.PRIVATE_USE:
gc = "Other, private use"; break;
case Character.SPACE_SEPARATOR:
gc = "Separator, space"; break;
case Character.START_PUNCTUATION:
gc = "Punctuation, open"; break;
case Character.SURROGATE:
gc = "Other, surrogate"; break;
case Character.TITLECASE_LETTER:
gc = "Letter, titlecase"; break;
case Character.UNASSIGNED:
gc = "Other, unassigned"; break;
case Character.UPPERCASE_LETTER:
gc = "Letter, uppercase"; break;
default:
gc = "<Unknown>";
}
return gc;
}
private static String getIcon(Object obj) {
if (obj instanceof Module) {
return "jar_l_obj.gif";
}
else if (obj instanceof Package) {
return "package_obj.gif";
}
else if (obj instanceof Declaration) {
Declaration dec = (Declaration) obj;
if (dec instanceof Class) {
return dec.isShared() ?
"class_obj.gif" :
"innerclass_private_obj.gif";
}
else if (dec instanceof Interface) {
return dec.isShared() ?
"int_obj.gif" :
"innerinterface_private_obj.gif";
}
else if (dec instanceof TypeAlias||
dec instanceof NothingType) {
return "types.gif";
}
else if (dec.isParameter()) {
if (dec instanceof Method) {
return "methpro_obj.gif";
}
else {
return "field_protected_obj.gif";
}
}
else if (dec instanceof Method) {
return dec.isShared() ?
"public_co.gif" :
"private_co.gif";
}
else if (dec instanceof MethodOrValue) {
return dec.isShared() ?
"field_public_obj.gif" :
"field_private_obj.gif";
}
else if (dec instanceof TypeParameter) {
return "typevariable_obj.gif";
}
}
return null;
}
/**
* Computes the hover info.
* @param previousInput the previous input, or <code>null</code>
* @param node
* @param elements the resolved elements
* @param editorInputElement the editor input, or <code>null</code>
*
* @return the HTML hover info for the given element(s) or <code>null</code>
* if no information is available
* @since 3.4
*/
static CeylonBrowserInput getHoverInfo(Referenceable model,
BrowserInput previousInput, CeylonEditor editor, Node node) {
if (model instanceof Declaration) {
Declaration dec = (Declaration) model;
return new CeylonBrowserInput(previousInput, dec,
getDocumentationFor(editor.getParseController(), dec, node));
}
else if (model instanceof Package) {
Package dec = (Package) model;
return new CeylonBrowserInput(previousInput, dec,
getDocumentationFor(editor.getParseController(), dec));
}
else if (model instanceof Module) {
Module dec = (Module) model;
return new CeylonBrowserInput(previousInput, dec,
getDocumentationFor(editor.getParseController(), dec));
}
else {
return null;
}
}
private static void appendJavadoc(IJavaElement elem, StringBuffer sb) {
if (elem instanceof IMember) {
try {
//TODO: Javadoc @ icon?
IMember mem = (IMember) elem;
String jd = JavadocContentAccess2.getHTMLContent(mem, true);
if (jd!=null) {
sb.append("<br/>").append(jd);
String base = getBaseURL(mem, mem.isBinary());
int endHeadIdx= sb.indexOf("</head>");
sb.insert(endHeadIdx, "\n<base href='" + base + "'>\n");
}
}
catch (JavaModelException e) {
e.printStackTrace();
}
}
}
public static String getBaseURL(IJavaElement element, boolean isBinary) throws JavaModelException {
if (isBinary) {
// Source attachment usually does not include Javadoc resources
// => Always use the Javadoc location as base:
URL baseURL= JavaUI.getJavadocLocation(element, false);
if (baseURL != null) {
if (baseURL.getProtocol().equals("jar")) {
// It's a JarURLConnection, which is not known to the browser widget.
// Let's start the help web server:
URL baseURL2= PlatformUI.getWorkbench().getHelpSystem().resolve(baseURL.toExternalForm(), true);
if (baseURL2 != null) { // can be null if org.eclipse.help.ui is not available
baseURL= baseURL2;
}
}
return baseURL.toExternalForm();
}
} else {
IResource resource= element.getResource();
if (resource != null) {
/*
* Too bad: Browser widget knows nothing about EFS and custom URL handlers,
* so IResource#getLocationURI() does not work in all cases.
* We only support the local file system for now.
* A solution could be https://bugs.eclipse.org/bugs/show_bug.cgi?id=149022 .
*/
IPath location= resource.getLocation();
if (location != null)
return location.toFile().toURI().toString();
}
}
return null;
}
public static String getDocumentationFor(CeylonParseController cpc, Package pack) {
StringBuffer buffer= new StringBuffer();
addImageAndLabel(buffer, pack, fileUrl(getIcon(pack)).toExternalForm(),
16, 16, "<b><tt>" + highlightLine(description(pack)) +"</tt></b>", 20, 4);
buffer.append("<hr/>");
Module mod = pack.getModule();
addImageAndLabel(buffer, mod, fileUrl(getIcon(mod)).toExternalForm(),
16, 16, "in module <tt><a " + link(mod) + ">" +
getLabel(mod) +"</a></tt>", 20, 2);
PhasedUnit pu = cpc.getTypeChecker()
.getPhasedUnitFromRelativePath(pack.getNameAsString().replace('.', '/') + "/package.ceylon");
if (pu!=null) {
List<Tree.PackageDescriptor> packageDescriptors = pu.getCompilationUnit().getPackageDescriptors();
if (!packageDescriptors.isEmpty()) {
Tree.PackageDescriptor refnode = packageDescriptors.get(0);
if (refnode!=null) {
appendDocAnnotationContent(refnode.getAnnotationList(), buffer, pack);
appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, pack);
appendSeeAnnotationContent(refnode.getAnnotationList(), buffer);
}
}
}
if (mod.isJava()) {
buffer.append("<p>This package is implemented in Java.</p>");
}
if (JDKUtils.isJDKModule(mod.getNameAsString())) {
buffer.append("<p>This package forms part of the Java SDK.</p>");
}
boolean first = true;
for (Declaration dec: pack.getMembers()) {
if (dec instanceof Class && ((Class)dec).isOverloaded()) {
continue;
}
if (dec.isShared() && !dec.isAnonymous()) {
if (first) {
buffer.append("<hr/>Contains: ");
first = false;
}
else {
buffer.append(", ");
}
/*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(),
16, 16, "<tt><a " + link(dec) + ">" +
dec.getName() + "</a></tt>", 20, 2);*/
buffer.append("<tt><a " + link(dec) + ">" + dec.getName() + "</a></tt>");
}
}
if (!first) {
buffer.append(".<br/>");
}
insertPageProlog(buffer, 0, getStyleSheet());
addPageEpilog(buffer);
return buffer.toString();
}
private static String description(Package pack) {
return "package " + getLabel(pack);
}
public static String getDocumentationFor(ModuleDetails mod, String version) {
return getDocumentationForModule(mod.getName(), version, mod.getDoc());
}
public static String getDocumentationForModule(String name, String version, String doc) {
StringBuffer buffer= new StringBuffer();
addImageAndLabel(buffer, null, fileUrl("jar_l_obj.gif").toExternalForm(),
16, 16, "<b><tt>" + highlightLine(description(name, version)) + "</tt></b>", 20, 4);
buffer.append("<hr/>");
if (doc!=null) {
buffer.append(markdown(doc, null, null));
}
insertPageProlog(buffer, 0, getStyleSheet());
addPageEpilog(buffer);
return buffer.toString();
}
private static String description(String name, String version) {
return "module " + name + " \"" + version + "\"";
}
public static String getDocumentationFor(CeylonParseController cpc, Module mod) {
StringBuffer buffer= new StringBuffer();
addImageAndLabel(buffer, mod, fileUrl(getIcon(mod)).toExternalForm(),
16, 16, "<b><tt>" + highlightLine(description(mod)) + "</tt></b>", 20, 4);
buffer.append("<hr/>");
if (mod.isJava()) {
buffer.append("<p>This module is implemented in Java.</p>");
}
if (mod.isDefault()) {
buffer.append("<p>The default module for packages which do not belong to explicit module.</p>");
}
if (JDKUtils.isJDKModule(mod.getNameAsString())) {
buffer.append("<p>This module forms part of the Java SDK.</p>");
}
PhasedUnit pu = cpc.getTypeChecker()
.getPhasedUnitFromRelativePath(mod.getNameAsString().replace('.', '/') + "/module.ceylon");
if (pu!=null) {
List<Tree.ModuleDescriptor> moduleDescriptors = pu.getCompilationUnit().getModuleDescriptors();
if (!moduleDescriptors.isEmpty()) {
Tree.ModuleDescriptor refnode = moduleDescriptors.get(0);
if (refnode!=null) {
Scope linkScope = mod.getPackage(mod.getNameAsString());
appendDocAnnotationContent(refnode.getAnnotationList(), buffer, linkScope);
appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, linkScope);
appendSeeAnnotationContent(refnode.getAnnotationList(), buffer);
}
}
}
boolean first = true;
for (Package pack: mod.getPackages()) {
if (pack.isShared()) {
if (first) {
buffer.append("<hr/>Contains: ");
first = false;
}
else {
buffer.append(", ");
}
/*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(),
16, 16, "<tt><a " + link(dec) + ">" +
dec.getName() + "</a></tt>", 20, 2);*/
buffer.append("<tt><a " + link(pack) + ">" + pack.getNameAsString() + "</a></tt>");
}
}
if (!first) {
buffer.append(".<br/>");
}
insertPageProlog(buffer, 0, getStyleSheet());
addPageEpilog(buffer);
return buffer.toString();
}
private static String description(Module mod) {
return "module " + getLabel(mod) + " \"" + mod.getVersion() + "\"";
}
public static String getDocumentationFor(CeylonParseController cpc, Declaration dec) {
return getDocumentationFor(cpc, dec, null);
}
public static String getDocumentationFor(CeylonParseController cpc, Declaration dec, Node node) {
if (dec==null) return null;
StringBuffer buffer = new StringBuffer();
insertPageProlog(buffer, 0, getStyleSheet());
Package pack = dec.getUnit().getPackage();
addImageAndLabel(buffer, dec, fileUrl(getIcon(dec)).toExternalForm(),
16, 16, "<b><tt>" + (dec.isDeprecated() ? "<s>":"") +
highlightLine(description(dec, cpc)) +
(dec.isDeprecated() ? "</s>":"") + "</tt></b>", 20, 4);
buffer.append("<hr/>");
if (dec.isParameter()) {
Declaration pd = ((MethodOrValue) dec).getInitializerParameter().getDeclaration();
addImageAndLabel(buffer, pd, fileUrl(getIcon(pd)).toExternalForm(),
16, 16, "parameter of <tt><a " + link(pd) + ">" + pd.getName() +"</a></tt>", 20, 2);
}
else if (dec instanceof TypeParameter) {
Declaration pd = ((TypeParameter) dec).getDeclaration();
addImageAndLabel(buffer, pd, fileUrl(getIcon(pd)).toExternalForm(),
16, 16, "type parameter of <tt><a " + link(pd) + ">" + pd.getName() +"</a></tt>", 20, 2);
}
else {
if (dec.isClassOrInterfaceMember()) {
ClassOrInterface outer = (ClassOrInterface) dec.getContainer();
addImageAndLabel(buffer, outer, fileUrl(getIcon(outer)).toExternalForm(), 16, 16,
"member of <tt><a " + link(outer) + ">" +
convertToHTMLContent(outer.getType().getProducedTypeName()) + "</a></tt>", 20, 2);
}
if ((dec.isShared() || dec.isToplevel()) &&
!(dec instanceof NothingType)) {
String label;
if (pack.getNameAsString().isEmpty()) {
label = "in default package";
}
else {
label = "in package <tt><a " + link(pack) + ">" +
getPackageLabel(dec) +"</a></tt>";
}
addImageAndLabel(buffer, pack, fileUrl(getIcon(pack)).toExternalForm(),
16, 16, label, 20, 2);
Module mod = pack.getModule();
addImageAndLabel(buffer, mod, fileUrl(getIcon(mod)).toExternalForm(),
16, 16, "in module <tt><a " + link(mod) + ">" +
getModuleLabel(dec) +"</a></tt>", 20, 2);
}
}
boolean hasDoc = false;
Tree.Declaration refnode = (Tree.Declaration) getReferencedNode(dec, cpc);
if (refnode!=null) {
appendDeprecatedAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec));
int len = buffer.length();
appendDocAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec));
hasDoc = buffer.length()!=len;
appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec));
appendSeeAnnotationContent(refnode.getAnnotationList(), buffer);
}
appendJavadoc(dec, cpc.getProject(), buffer, node);
//boolean extraBreak = false;
boolean obj=false;
if (dec instanceof TypedDeclaration) {
TypeDeclaration td = ((TypedDeclaration) dec).getTypeDeclaration();
if (td!=null && td.isAnonymous()) {
obj=true;
documentInheritance(td, buffer);
}
}
else if (dec instanceof TypeDeclaration) {
documentInheritance((TypeDeclaration) dec, buffer);
}
Declaration rd = dec.getRefinedDeclaration();
if (dec!=rd) {
buffer.append("<p>");
addImageAndLabel(buffer, rd, fileUrl(rd.isFormal() ? "implm_co.gif" : "over_co.gif").toExternalForm(),
16, 16, "refines <tt><a " + link(rd) + ">" + rd.getName() +"</a></tt> declared by <tt>" +
convertToHTMLContent(((TypeDeclaration) rd.getContainer()).getType().getProducedTypeName()) +
"</tt>", 20, 2);
buffer.append("</p>");
if (!hasDoc) {
Tree.Declaration refnode2 = (Tree.Declaration) getReferencedNode(rd, cpc);
if (refnode2!=null) {
appendDocAnnotationContent(refnode2.getAnnotationList(), buffer, resolveScope(rd));
}
}
}
if (dec instanceof TypedDeclaration && !obj) {
ProducedType ret = ((TypedDeclaration) dec).getType();
if (ret!=null) {
buffer.append("<p>");
List<ProducedType> list;
if (ret.getDeclaration() instanceof UnionType) {
list = ret.getDeclaration().getCaseTypes();
}
else {
list = Arrays.asList(ret);
}
StringBuffer buf = new StringBuffer("returns <tt>");
for (ProducedType pt: list) {
if (pt.getDeclaration() instanceof ClassOrInterface ||
pt.getDeclaration() instanceof TypeParameter) {
buf.append("<a " + link(pt.getDeclaration()) + ">" +
convertToHTMLContent(pt.getProducedTypeName()) +"</a>");
}
else {
buf.append(convertToHTMLContent(pt.getProducedTypeName()));
}
buf.append("|");
}
buf.setLength(buf.length()-1);
buf.append("</tt>");
addImageAndLabel(buffer, ret.getDeclaration(), fileUrl("stepreturn_co.gif").toExternalForm(),
16, 16, buf.toString(), 20, 2);
buffer.append("</p>");
}
}
if (dec instanceof Functional) {
for (ParameterList pl: ((Functional) dec).getParameterLists()) {
if (!pl.getParameters().isEmpty()) {
buffer.append("<p>");
for (Parameter p: pl.getParameters()) {
StringBuffer doc = new StringBuffer();
Tree.Declaration refNode = (Tree.Declaration) getReferencedNode(p.getModel(), cpc);
if (refNode!=null) {
appendDocAnnotationContent(refNode.getAnnotationList(), doc, resolveScope(dec));
}
if (doc.length()!=0) {
doc.insert(0, ":");
}
ProducedType type = p.getType();
if (type==null) type = new UnknownType(dec.getUnit()).getType();
addImageAndLabel(buffer, p.getModel(), fileUrl("methpro_obj.gif"/*"stepinto_co.gif"*/).toExternalForm(),
16, 16, "accepts <tt><a " + link(type.getDeclaration()) + ">" +
convertToHTMLContent(type.getProducedTypeName()) +
"</a> <a " + link(p.getModel()) + ">"+ p.getName() +"</a></tt>" + doc, 20, 2);
}
buffer.append("</p>");
}
}
}
if (dec instanceof ClassOrInterface) {
if (!dec.getMembers().isEmpty()) {
boolean first = true;
for (Declaration mem: dec.getMembers()) {
if (mem instanceof Method && ((Method)mem).isOverloaded()) {
continue;
}
if (mem.isShared() && !dec.isAnonymous()) {
if (first) {
buffer.append("<hr/>Members: ");
first = false;
}
else {
buffer.append(", ");
}
/*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(),
16, 16, "<tt><a " + link(dec) + ">" + dec.getName() + "</a></tt>", 20, 2);*/
buffer.append("<tt><a " + link(mem) + ">" + mem.getName() + "</a></tt>");
}
}
if (!first) {
buffer.append(".<br/>");
//extraBreak = true;
}
}
}
if (dec instanceof NothingType) {
buffer.append("Special bottom type defined by the language. "
+ "<code>Nothing</code> is assignable to all types, but has no value. "
+ "A function or value of type <code>Nothing</code> either throws "
+ "an exception, or never returns.");
}
else {
//if (dec.getUnit().getFilename().endsWith(".ceylon")) {
//if (extraBreak)
appendExtraActions(dec, buffer);
}
addPageEpilog(buffer);
return buffer.toString();
}
public static void appendExtraActions(Declaration dec, StringBuffer buffer) {
buffer.append("<hr/>");
addImageAndLabel(buffer, null, fileUrl("unit.gif").toExternalForm(),
16, 16, "<a href='dec:" + declink(dec) + "'>declared</a> in unit <tt>"+
dec.getUnit().getFilename() + "</tt>", 20, 2);
//}
buffer.append("<hr/>");
addImageAndLabel(buffer, null, fileUrl("search_ref_obj.png").toExternalForm(),
16, 16, "<a href='ref:" + declink(dec) + "'>find references</a> to <tt>" +
dec.getName() + "</tt>", 20, 2);
if (dec instanceof ClassOrInterface) {
addImageAndLabel(buffer, null, fileUrl("search_decl_obj.png").toExternalForm(),
16, 16, "<a href='sub:" + declink(dec) + "'>find subtypes</a> of <tt>" +
dec.getName() + "</tt>", 20, 2);
}
if (dec instanceof Value) {
addImageAndLabel(buffer, null, fileUrl("search_ref_obj.png").toExternalForm(),
16, 16, "<a href='ass:" + declink(dec) + "'>find assignments</a> to <tt>" +
dec.getName() + "</tt>", 20, 2);
}
if (dec.isFormal()||dec.isDefault()) {
addImageAndLabel(buffer, null, fileUrl("search_decl_obj.png").toExternalForm(),
16, 16, "<a href='act:" + declink(dec) + "'>find refinements</a> of <tt>" +
dec.getName() + "</tt>", 20, 2);
}
}
private static void documentInheritance(TypeDeclaration dec, StringBuffer buffer) {
if (dec instanceof Class) {
ProducedType sup = ((Class) dec).getExtendedType();
if (sup!=null) {
buffer.append("<p>");
addImageAndLabel(buffer, sup.getDeclaration(), fileUrl("super_co.gif").toExternalForm(),
16, 16, "extends <tt><a " + link(sup.getDeclaration()) + ">" +
HTMLPrinter.convertToHTMLContent(sup.getProducedTypeName()) +"</a></tt>", 20, 2);
buffer.append("</p>");
//extraBreak = true;
}
}
// if (dec instanceof TypeDeclaration) {
List<ProducedType> sts = ((TypeDeclaration) dec).getSatisfiedTypes();
if (!sts.isEmpty()) {
buffer.append("<p>");
for (ProducedType td: sts) {
addImageAndLabel(buffer, td.getDeclaration(), fileUrl("super_co.gif").toExternalForm(),
16, 16, "satisfies <tt><a " + link(td.getDeclaration()) + ">" +
convertToHTMLContent(td.getProducedTypeName()) +"</a></tt>", 20, 2);
//extraBreak = true;
}
buffer.append("</p>");
}
List<ProducedType> cts = ((TypeDeclaration) dec).getCaseTypes();
if (cts!=null) {
buffer.append("<p>");
for (ProducedType td: cts) {
addImageAndLabel(buffer, td.getDeclaration(), fileUrl("sub_co.gif").toExternalForm(),
16, 16, (td.getDeclaration().isSelfType() ? "has self type" : "has case") +
" <tt><a " + link(td.getDeclaration()) + ">" +
convertToHTMLContent(td.getProducedTypeName()) +"</a></tt>", 20, 2);
//extraBreak = true;
}
buffer.append("</p>");
}
// }
}
private static String description(Declaration dec, CeylonParseController cpc) {
String result = getDescriptionFor(dec);
if (dec instanceof TypeDeclaration) {
TypeDeclaration td = (TypeDeclaration) dec;
if (td.isAlias() && td.getExtendedType()!=null) {
result += " => ";
result += td.getExtendedType().getProducedTypeName();
}
}
else if (dec instanceof Value) {
if (!((Value) dec).isVariable()) {
Tree.Declaration refnode = (Tree.Declaration) getReferencedNode(dec, cpc);
if (refnode instanceof Tree.AttributeDeclaration) {
Tree.SpecifierOrInitializerExpression sie = ((Tree.AttributeDeclaration) refnode).getSpecifierOrInitializerExpression();
if (sie!=null) {
if (sie.getExpression()!=null) {
Tree.Term term = sie.getExpression().getTerm();
if (term instanceof Tree.Literal) {
result += " = ";
result += term.getToken().getText();
}
}
}
}
}
}
/*else if (dec instanceof ValueParameter) {
Tree.Declaration refnode = (Tree.Declaration) getReferencedNode(dec, cpc);
if (refnode instanceof Tree.ValueParameterDeclaration) {
Tree.DefaultArgument da = ((Tree.ValueParameterDeclaration) refnode).getDefaultArgument();
if (da!=null) {
Tree.Expression e = da.getSpecifierExpression().getExpression();
if (e!=null) {
Tree.Term term = e.getTerm();
if (term instanceof Tree.Literal) {
result += " = ";
result += term.getText();
}
else {
result += " =";
}
}
}
}
}*/
return result;
}
static String getAddress(Referenceable model) {
if (model==null) return null;
return "dec:" + declink(model);
}
private static String link(Referenceable model) {
return "href='doc:" + declink(model) + "'";
}
private static String declink(Referenceable model) {
if (model instanceof Package) {
Package p = (Package) model;
return declink(p.getModule()) + ":" + p.getNameAsString();
}
if (model instanceof Module) {
return ((Module) model).getNameAsString();
}
else if (model instanceof Declaration) {
String result = ":" + ((Declaration) model).getName();
Scope container = ((Declaration) model).getContainer();
if (container instanceof Referenceable) {
return declink((Referenceable) container)
+ result;
}
else {
return result;
}
}
else {
return "";
}
}
private static void appendJavadoc(Declaration model, IProject project,
StringBuffer buffer, Node node) {
IJavaProject jp = JavaCore.create(project);
if (jp!=null) {
try {
appendJavadoc(getJavaElement(model, jp, node), buffer);
}
catch (JavaModelException jme) {
jme.printStackTrace();
}
}
}
private static void appendDocAnnotationContent(Tree.AnnotationList annotationList,
StringBuffer documentation, Scope linkScope) {
if (annotationList!=null) {
AnonymousAnnotation aa = annotationList.getAnonymousAnnotation();
if (aa!=null) {
documentation.append(markdown(aa.getStringLiteral().getText(), linkScope,
annotationList.getUnit()));
}
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("doc".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
if (!args.isEmpty()) {
Tree.PositionalArgument a = args.get(0);
if (a instanceof Tree.ListedArgument) {
String text = ((Tree.ListedArgument) a).getExpression()
.getTerm().getText();
if (text!=null) {
documentation.append(markdown(text, linkScope,
annotationList.getUnit()));
}
}
}
}
}
}
}
}
}
private static void appendDeprecatedAnnotationContent(Tree.AnnotationList annotationList,
StringBuffer documentation, Scope linkScope) {
if (annotationList!=null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("deprecated".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
if (!args.isEmpty()) {
Tree.PositionalArgument a = args.get(0);
if (a instanceof Tree.ListedArgument) {
String text = ((Tree.ListedArgument) a).getExpression()
.getTerm().getText();
if (text!=null) {
documentation.append(markdown("_(This is a deprecated program element.)_\n\n" + text,
linkScope, annotationList.getUnit()));
}
}
}
}
}
}
}
}
}
private static void appendSeeAnnotationContent(Tree.AnnotationList annotationList,
StringBuffer documentation) {
if (annotationList!=null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("see".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
for (Tree.PositionalArgument arg: args) {
if (arg instanceof Tree.ListedArgument) {
Tree.Term term = ((Tree.ListedArgument) arg).getExpression().getTerm();
if (term instanceof Tree.MetaLiteral) {
Declaration dec = ((Tree.MetaLiteral) term).getDeclaration();
if (dec!=null) {
String dn = dec.getName();
if (dec.isClassOrInterfaceMember()) {
dn = ((ClassOrInterface) dec.getContainer()).getName() + "." + dn;
}
addImageAndLabel(documentation, dec, fileUrl("link_obj.gif"/*getIcon(dec)*/).toExternalForm(), 16, 16,
"see <tt><a "+link(dec)+">"+dn+"</a></tt>", 20, 2);
}
}
}
}
}
}
}
}
}
}
private static void appendThrowAnnotationContent(Tree.AnnotationList annotationList,
StringBuffer documentation, Scope linkScope) {
if (annotationList!=null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("throws".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
if (args.isEmpty()) continue;
Tree.PositionalArgument typeArg = args.get(0);
Tree.PositionalArgument textArg = args.size()>1 ? args.get(1) : null;
if (typeArg instanceof Tree.ListedArgument &&
(textArg==null || textArg instanceof Tree.ListedArgument)) {
Tree.Term typeArgTerm = ((Tree.ListedArgument) typeArg).getExpression().getTerm();
Tree.Term textArgTerm = textArg==null ? null : ((Tree.ListedArgument) textArg).getExpression().getTerm();
String text = textArgTerm instanceof Tree.StringLiteral ?
textArgTerm.getText() : "";
if (typeArgTerm instanceof Tree.MetaLiteral) {
Declaration dec = ((Tree.MetaLiteral) typeArgTerm).getDeclaration();
if (dec!=null) {
String dn = dec.getName();
if (typeArgTerm instanceof Tree.QualifiedMemberOrTypeExpression) {
Tree.Primary p = ((Tree.QualifiedMemberOrTypeExpression) typeArgTerm).getPrimary();
if (p instanceof Tree.MemberOrTypeExpression) {
dn = ((Tree.MemberOrTypeExpression) p).getDeclaration().getName()
+ "." + dn;
}
}
addImageAndLabel(documentation, dec, fileUrl("ihigh_obj.gif"/*getIcon(dec)*/).toExternalForm(), 16, 16,
"throws <tt><a "+link(dec)+">"+dn+"</a></tt>" +
markdown(text, linkScope, annotationList.getUnit()), 20, 2);
}
}
}
}
}
}
}
}
}
public static URL fileUrl(String icon) {
try {
return FileLocator.toFileURL(FileLocator.find(CeylonPlugin.getInstance().getBundle(),
new Path("icons/").append(icon), null));
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Returns the Javadoc hover style sheet with the current Javadoc font from the preferences.
* @return the updated style sheet
* @since 3.4
*/
public static String getStyleSheet() {
if (fgStyleSheet == null)
fgStyleSheet = loadStyleSheet();
//Color c = CeylonTokenColorer.getCurrentThemeColor("docHover");
//String color = toHexString(c.getRed()) + toHexString(c.getGreen()) + toHexString(c.getBlue());
String css= fgStyleSheet;// + "body { background-color: #" + color+ " }";
if (css != null) {
FontData fontData= JFaceResources.getFontRegistry()
.getFontData(PreferenceConstants.APPEARANCE_JAVADOC_FONT)[0];
css= HTMLPrinter.convertTopLevelFont(css, fontData);
}
return css;
}
/**
* Loads and returns the Javadoc hover style sheet.
* @return the style sheet, or <code>null</code> if unable to load
* @since 3.4
*/
public static String loadStyleSheet() {
Bundle bundle= Platform.getBundle(JavaPlugin.getPluginId());
URL styleSheetURL= bundle.getEntry("/JavadocHoverStyleSheet.css");
if (styleSheetURL != null) {
BufferedReader reader= null;
try {
reader= new BufferedReader(new InputStreamReader(styleSheetURL.openStream()));
StringBuffer buffer= new StringBuffer(1500);
String line= reader.readLine();
while (line != null) {
buffer.append(line);
buffer.append('\n');
line= reader.readLine();
}
return buffer.toString();
} catch (IOException ex) {
JavaPlugin.log(ex);
return "";
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
}
return null;
}
public static void addImageAndLabel(StringBuffer buf, Referenceable model, String imageSrcPath,
int imageWidth, int imageHeight, String label, int labelLeft, int labelTop) {
buf.append("<div style='word-wrap: break-word; position: relative; ");
if (imageSrcPath != null) {
buf.append("margin-left: ").append(labelLeft).append("px; ");
buf.append("padding-top: ").append(labelTop).append("px; ");
}
buf.append("'>");
if (imageSrcPath != null) {
if (model!=null) {
buf.append("<a ").append(link(model)).append(">");
}
addImage(buf, imageSrcPath, imageWidth, imageHeight,
labelLeft);
if (model!=null) {
buf.append("</a>");
}
}
buf.append(label);
buf.append("</div>");
}
public static void addImage(StringBuffer buf, String imageSrcPath,
int imageWidth, int imageHeight, int labelLeft) {
StringBuffer imageStyle= new StringBuffer("border:none; position: absolute; ");
imageStyle.append("width: ").append(imageWidth).append("px; ");
imageStyle.append("height: ").append(imageHeight).append("px; ");
imageStyle.append("left: ").append(- labelLeft - 1).append("px; ");
// hack for broken transparent PNG support in IE 6, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=223900 :
buf.append("<!--[if lte IE 6]><![if gte IE 5.5]>\n");
//String tooltip= element == null ? "" : "alt='" + "Open Declaration" + "' ";
buf.append("<span ").append("style=\"").append(imageStyle)
.append("filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='")
.append(imageSrcPath).append("')\"></span>\n");
buf.append("<![endif]><![endif]-->\n");
buf.append("<!--[if !IE]>-->\n");
buf.append("<img ").append("style='").append(imageStyle).append("' src='")
.append(imageSrcPath).append("'/>\n");
buf.append("<!--<![endif]-->\n");
buf.append("<!--[if gte IE 7]>\n");
buf.append("<img ").append("style='").append(imageStyle).append("' src='")
.append(imageSrcPath).append("'/>\n");
buf.append("<![endif]-->\n");
}
private static String markdown(String text, final Scope linkScope, final Unit unit) {
if( text == null || text.length() == 0 ) {
return text;
}
// String unquotedText = text.substring(1, text.length()-1);
Builder builder = Configuration.builder().forceExtentedProfile();
builder.setCodeBlockEmitter(new CeylonBlockEmitter());
if (linkScope!=null) {
builder.setSpecialLinkEmitter(new SpanEmitter() {
@Override
public void emitSpan(StringBuilder out, String content) {
String linkName;
String linkTarget;
int indexOf = content.indexOf("|");
if( indexOf == -1 ) {
linkName = content;
linkTarget = content;
} else {
linkName = content.substring(0, indexOf);
linkTarget = content.substring(indexOf+1, content.length());
}
String href = resolveLink(linkTarget, linkScope, unit);
if (href != null) {
out.append("<a ").append(href).append(">");
}
out.append("<code>");
int sep = linkName.indexOf("::");
out.append(sep<0?linkName:linkName.substring(sep+2));
out.append("</code>");
if (href != null) {
out.append("</a>");
}
}
});
}
return Processor.process(text, builder.build());
}
private static String resolveLink(String linkTarget, Scope linkScope, Unit unit) {
String declName;
Scope scope = null;
int pkgSeparatorIndex = linkTarget.indexOf("::");
if( pkgSeparatorIndex == -1 ) {
declName = linkTarget;
scope = linkScope;
}
else {
String pkgName = linkTarget.substring(0, pkgSeparatorIndex);
declName = linkTarget.substring(pkgSeparatorIndex+2, linkTarget.length());
Module module = resolveModule(linkScope);
if( module != null ) {
scope = module.getPackage(pkgName);
}
}
if (scope==null || declName == null || "".equals(declName)) {
return null; // no point in continuing. Required for non-token auto-complete.
}
String[] declNames = declName.split("\\.");
Declaration decl = scope.getMemberOrParameter(unit, declNames[0], null, false);
for (int i=1; i<declNames.length; i++) {
if (decl instanceof Scope) {
scope = (Scope) decl;
decl = scope.getMember(declNames[i], null, false);
}
else {
decl = null;
break;
}
}
if (decl != null) {
String href = link(decl);
return href;
}
else {
return null;
}
}
private static Scope resolveScope(Declaration decl) {
if (decl == null) {
return null;
} else if (decl instanceof Scope) {
return (Scope) decl;
} else {
return decl.getContainer();
}
}
private static Module resolveModule(Scope scope) {
if (scope == null) {
return null;
} else if (scope instanceof Package) {
return ((Package) scope).getModule();
} else {
return resolveModule(scope.getContainer());
}
}
public static final class CeylonBlockEmitter implements BlockEmitter {
@Override
public void emitBlock(StringBuilder out, List<String> lines, String meta) {
if (!lines.isEmpty()) {
out.append("<pre>");
/*if (meta == null || meta.length() == 0) {
out.append("<pre>");
} else {
out.append("<pre class=\"brush: ").append(meta).append("\">");
}*/
StringBuilder code = new StringBuilder();
for (String s: lines) {
code.append(s).append('\n');
}
String highlighted;
if (meta == null || meta.length() == 0 || "ceylon".equals(meta)) {
highlighted = highlightLine(code.toString());
}
else {
highlighted = code.toString();
}
out.append(highlighted);
out.append("</pre>\n");
}
}
}
public static String highlightLine(String line) {
String kwc = toHex(getCurrentThemeColor(KEYWORDS));
String tc = toHex(getCurrentThemeColor(TYPES));
String ic = toHex(getCurrentThemeColor(IDENTIFIERS));
String sc = toHex(getCurrentThemeColor(STRINGS));
String nc = toHex(getCurrentThemeColor(NUMBERS));
String cc = toHex(getCurrentThemeColor(CHARS));
String pc = toHex(getCurrentThemeColor(PACKAGES));
String lcc = toHex(getCurrentThemeColor(COMMENTS));
CeylonLexer lexer = new CeylonLexer(new ANTLRStringStream(line));
Token token;
boolean inPackageName = false;
StringBuilder result = new StringBuilder();
while ((token=lexer.nextToken()).getType()!=CeylonLexer.EOF) {
String s = convertToHTMLContent(token.getText());
int type = token.getType();
if (type!=CeylonLexer.LIDENTIFIER &&
type!=CeylonLexer.MEMBER_OP) {
inPackageName = false;
}
else if (inPackageName) {
result.append("<span style='color:"+pc+"'>").append(s).append("</span>");
continue;
}
switch (type) {
case CeylonLexer.FLOAT_LITERAL:
case CeylonLexer.NATURAL_LITERAL:
result.append("<span style='color:"+nc+"'>").append(s).append("</span>");
break;
case CeylonLexer.CHAR_LITERAL:
result.append("<span style='color:"+cc+"'>").append(s).append("</span>");
break;
case CeylonLexer.STRING_LITERAL:
case CeylonLexer.STRING_START:
case CeylonLexer.STRING_MID:
case CeylonLexer.VERBATIM_STRING:
result.append("<span style='color:"+sc+"'>").append(s).append("</span>");
break;
case CeylonLexer.UIDENTIFIER:
result.append("<span style='color:"+tc+"'>").append(s).append("</span>");
break;
case CeylonLexer.LIDENTIFIER:
result.append("<span style='color:"+ic+"'>").append(s).append("</span>");
break;
case CeylonLexer.MULTI_COMMENT:
case CeylonLexer.LINE_COMMENT:
result.append("<span style='color:"+lcc+"'>").append(s).append("</span>");
break;
case CeylonLexer.IMPORT:
case CeylonLexer.PACKAGE:
case CeylonLexer.MODULE:
inPackageName = true; //then fall through!
default:
if (CeylonTokenColorer.keywords.contains(s)) {
result.append("<span style='color:"+kwc+"'>").append(s).append("</span>");
}
else {
result.append(s);
}
}
}
return result.toString();
}
/**
* Creates the "enriched" control.
*/
private final class PresenterControlCreator extends AbstractReusableInformationControlCreator {
private final DocumentationHover docHover;
PresenterControlCreator(DocumentationHover docHover) {
this.docHover = docHover;
}
@Override
public IInformationControl doCreateInformationControl(Shell parent) {
if (isAvailable(parent)) {
ToolBarManager tbm = new ToolBarManager(SWT.FLAT);
BrowserInformationControl control = new BrowserInformationControl(parent,
APPEARANCE_JAVADOC_FONT, tbm);
final BackAction backAction = new BackAction(control);
backAction.setEnabled(false);
tbm.add(backAction);
final ForwardAction forwardAction = new ForwardAction(control);
tbm.add(forwardAction);
forwardAction.setEnabled(false);
//final ShowInJavadocViewAction showInJavadocViewAction= new ShowInJavadocViewAction(iControl);
//tbm.add(showInJavadocViewAction);
final OpenDeclarationAction openDeclarationAction = new OpenDeclarationAction(control);
tbm.add(openDeclarationAction);
// final SimpleSelectionProvider selectionProvider = new SimpleSelectionProvider();
//TODO: an action to open the generated ceylondoc
// from the doc archive, in a browser window
/*if (fSite != null) {
OpenAttachedJavadocAction openAttachedJavadocAction= new OpenAttachedJavadocAction(fSite);
openAttachedJavadocAction.setSpecialSelectionProvider(selectionProvider);
openAttachedJavadocAction.setImageDescriptor(DESC_ELCL_OPEN_BROWSER);
openAttachedJavadocAction.setDisabledImageDescriptor(DESC_DLCL_OPEN_BROWSER);
selectionProvider.addSelectionChangedListener(openAttachedJavadocAction);
selectionProvider.setSelection(new StructuredSelection());
tbm.add(openAttachedJavadocAction);
}*/
IInputChangedListener inputChangeListener = new IInputChangedListener() {
public void inputChanged(Object newInput) {
backAction.update();
forwardAction.update();
// if (newInput == null) {
// selectionProvider.setSelection(new StructuredSelection());
// }
// else
boolean isDeclaration = false;
if (newInput instanceof CeylonBrowserInput) {
// Object inputElement = ((CeylonBrowserInput) newInput).getInputElement();
// selectionProvider.setSelection(new StructuredSelection(inputElement));
//showInJavadocViewAction.setEnabled(isJavaElementInput);
isDeclaration = ((CeylonBrowserInput) newInput).getAddress()!=null;
}
openDeclarationAction.setEnabled(isDeclaration);
}
};
control.addInputChangeListener(inputChangeListener);
tbm.update(true);
docHover.addLinkListener(control);
return control;
}
else {
return new DefaultInformationControl(parent, true);
}
}
}
private final class HoverControlCreator extends AbstractReusableInformationControlCreator {
private final DocumentationHover docHover;
private String statusLineMessage;
private final IInformationControlCreator enrichedControlCreator;
HoverControlCreator(DocumentationHover docHover,
IInformationControlCreator enrichedControlCreator,
String statusLineMessage) {
this.docHover = docHover;
this.enrichedControlCreator = enrichedControlCreator;
this.statusLineMessage = statusLineMessage;
}
@Override
public IInformationControl doCreateInformationControl(Shell parent) {
if (enrichedControlCreator!=null && isAvailable(parent)) {
BrowserInformationControl control = new BrowserInformationControl(parent,
APPEARANCE_JAVADOC_FONT, statusLineMessage) {
@Override
public IInformationControlCreator getInformationPresenterControlCreator() {
return enrichedControlCreator;
}
};
if (docHover!=null) {
docHover.addLinkListener(control);
}
return control;
}
else {
return new DefaultInformationControl(parent, statusLineMessage);
}
}
}
} | plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/hover/DocumentationHover.java | package com.redhat.ceylon.eclipse.code.hover;
/*******************************************************************************
* Copyright (c) 2000, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Genady Beryozkin <[email protected]> - [hovering] tooltip for constant string does not show constant value - https://bugs.eclipse.org/bugs/show_bug.cgi?id=85382
*******************************************************************************/
import static com.redhat.ceylon.eclipse.code.browser.BrowserInformationControl.isAvailable;
import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.addPageEpilog;
import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.convertToHTMLContent;
import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.insertPageProlog;
import static com.redhat.ceylon.eclipse.code.html.HTMLPrinter.toHex;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getLabel;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getModuleLabel;
import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.getPackageLabel;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.findNode;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.gotoNode;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.CHARS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.COMMENTS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.IDENTIFIERS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.KEYWORDS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.NUMBERS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.PACKAGES;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.STRINGS;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.TYPES;
import static com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer.getCurrentThemeColor;
import static com.redhat.ceylon.eclipse.code.propose.CeylonContentProposer.getDescriptionFor;
import static com.redhat.ceylon.eclipse.code.resolve.CeylonReferenceResolver.getReferencedDeclaration;
import static com.redhat.ceylon.eclipse.code.resolve.CeylonReferenceResolver.getReferencedNode;
import static com.redhat.ceylon.eclipse.code.resolve.JavaHyperlinkDetector.getJavaElement;
import static com.redhat.ceylon.eclipse.code.resolve.JavaHyperlinkDetector.gotoJavaNode;
import static com.redhat.ceylon.eclipse.core.builder.CeylonBuilder.getModelLoader;
import static java.lang.Character.codePointCount;
import static java.lang.Float.parseFloat;
import static java.lang.Integer.parseInt;
import static org.eclipse.jdt.internal.ui.JavaPluginImages.setLocalImageDescriptors;
import static org.eclipse.jdt.ui.PreferenceConstants.APPEARANCE_JAVADOC_FONT;
import static org.eclipse.ui.ISharedImages.IMG_TOOL_BACK;
import static org.eclipse.ui.ISharedImages.IMG_TOOL_BACK_DISABLED;
import static org.eclipse.ui.ISharedImages.IMG_TOOL_FORWARD;
import static org.eclipse.ui.ISharedImages.IMG_TOOL_FORWARD_DISABLED;
import static org.eclipse.ui.PlatformUI.getWorkbench;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.Token;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.javadoc.JavadocContentAccess2;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.AbstractReusableInformationControlCreator;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IInputChangedListener;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextHoverExtension;
import org.eclipse.jface.text.ITextHoverExtension2;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.LocationListener;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Bundle;
import com.github.rjeschke.txtmark.BlockEmitter;
import com.github.rjeschke.txtmark.Configuration;
import com.github.rjeschke.txtmark.Configuration.Builder;
import com.github.rjeschke.txtmark.Processor;
import com.github.rjeschke.txtmark.SpanEmitter;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.cmr.api.ModuleSearchResult.ModuleDetails;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.NothingType;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Referenceable;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeAlias;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.model.UnknownType;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.AnonymousAnnotation;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit;
import com.redhat.ceylon.eclipse.code.browser.BrowserInformationControl;
import com.redhat.ceylon.eclipse.code.browser.BrowserInput;
import com.redhat.ceylon.eclipse.code.editor.CeylonEditor;
import com.redhat.ceylon.eclipse.code.editor.Util;
import com.redhat.ceylon.eclipse.code.html.HTMLPrinter;
import com.redhat.ceylon.eclipse.code.parse.CeylonParseController;
import com.redhat.ceylon.eclipse.code.parse.CeylonTokenColorer;
import com.redhat.ceylon.eclipse.code.quickfix.ExtractFunctionProposal;
import com.redhat.ceylon.eclipse.code.quickfix.ExtractValueProposal;
import com.redhat.ceylon.eclipse.code.quickfix.SpecifyTypeProposal;
import com.redhat.ceylon.eclipse.code.search.FindAssignmentsAction;
import com.redhat.ceylon.eclipse.code.search.FindReferencesAction;
import com.redhat.ceylon.eclipse.code.search.FindRefinementsAction;
import com.redhat.ceylon.eclipse.code.search.FindSubtypesAction;
import com.redhat.ceylon.eclipse.core.model.loader.JDTModelLoader;
import com.redhat.ceylon.eclipse.ui.CeylonPlugin;
/**
* Provides Javadoc as hover info for Java elements.
*
* @since 2.1
*/
public class DocumentationHover
implements ITextHover, ITextHoverExtension, ITextHoverExtension2 {
private CeylonEditor editor;
public DocumentationHover(CeylonEditor editor) {
this.editor = editor;
}
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
IDocument document = textViewer.getDocument();
int start= -2;
int end= -1;
try {
int pos= offset;
char c;
while (pos >= 0) {
c= document.getChar(pos);
if (!Character.isJavaIdentifierPart(c)) {
break;
}
--pos;
}
start= pos;
pos= offset;
int length= document.getLength();
while (pos < length) {
c= document.getChar(pos);
if (!Character.isJavaIdentifierPart(c)) {
break;
}
++pos;
}
end= pos;
} catch (BadLocationException x) {
}
if (start >= -1 && end > -1) {
if (start == offset && end == offset)
return new Region(offset, 0);
else if (start == offset)
return new Region(start, end - start);
else
return new Region(start + 1, end - start - 1);
}
return null;
}
final class CeylonLocationListener implements LocationListener {
private final BrowserInformationControl control;
CeylonLocationListener(BrowserInformationControl control) {
this.control = control;
}
@Override
public void changing(LocationEvent event) {
String location = event.location;
//necessary for windows environment (fix for blank page)
//somehow related to this: https://bugs.eclipse.org/bugs/show_bug.cgi?id=129236
if (!"about:blank".equals(location)) {
event.doit= false;
}
handleLink(location);
/*else if (location.startsWith("javadoc:")) {
final DocBrowserInformationControlInput input = (DocBrowserInformationControlInput) control.getInput();
int beginIndex = input.getHtml().indexOf("javadoc:")+8;
final String handle = input.getHtml().substring(beginIndex, input.getHtml().indexOf("\"",beginIndex));
new Job("Fetching Javadoc") {
@Override
protected IStatus run(IProgressMonitor monitor) {
final IJavaElement elem = JavaCore.create(handle);
try {
final String javadoc = JavadocContentAccess2.getHTMLContent((IMember) elem, true);
if (javadoc!=null) {
PlatformUI.getWorkbench().getProgressService()
.runInUI(editor.getSite().getWorkbenchWindow(), new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
StringBuffer sb = new StringBuffer();
HTMLPrinter.insertPageProlog(sb, 0, getStyleSheet());
appendJavadoc(elem, javadoc, sb);
HTMLPrinter.addPageEpilog(sb);
control.setInput(new DocBrowserInformationControlInput(input, null, sb.toString(), 0));
}
}, null);
}
}
catch (Exception e) {
e.printStackTrace();
}
return Status.OK_STATUS;
}
}.schedule();
}*/
}
private void handleLink(String location) {
if (location.startsWith("dec:")) {
Referenceable target = getLinkedModel(editor, location);
if (target!=null) {
close(control); //FIXME: should have protocol to hide, rather than dispose
gotoDeclaration(editor, target);
}
}
else if (location.startsWith("doc:")) {
Referenceable target = getLinkedModel(editor, location);
if (target!=null) {
control.setInput(getHoverInfo(target, control.getInput(), editor, null));
}
}
else if (location.startsWith("ref:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindReferencesAction(editor, (Declaration) target).run();
}
else if (location.startsWith("sub:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindSubtypesAction(editor, (Declaration) target).run();
}
else if (location.startsWith("act:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindRefinementsAction(editor, (Declaration) target).run();
}
else if (location.startsWith("ass:")) {
Referenceable target = getLinkedModel(editor, location);
close(control);
new FindAssignmentsAction(editor, (Declaration) target).run();
}
else if (location.startsWith("stp:")) {
close(control);
CompilationUnit rn = editor.getParseController().getRootNode();
Node node = findNode(rn, Integer.parseInt(location.substring(4)));
SpecifyTypeProposal.create(rn, node, Util.getFile(editor.getEditorInput()))
.apply(editor.getParseController().getDocument());
}
else if (location.startsWith("exv:")) {
close(control);
new ExtractValueProposal(editor).apply(editor.getParseController().getDocument());
}
else if (location.startsWith("exf:")) {
close(control);
new ExtractFunctionProposal(editor).apply(editor.getParseController().getDocument());
}
}
@Override
public void changed(LocationEvent event) {}
}
/**
* Action to go back to the previous input in the hover control.
*/
static final class BackAction extends Action {
private final BrowserInformationControl fInfoControl;
public BackAction(BrowserInformationControl infoControl) {
fInfoControl= infoControl;
setText("Back");
ISharedImages images= getWorkbench().getSharedImages();
setImageDescriptor(images.getImageDescriptor(IMG_TOOL_BACK));
setDisabledImageDescriptor(images.getImageDescriptor(IMG_TOOL_BACK_DISABLED));
update();
}
@Override
public void run() {
BrowserInput previous= (BrowserInput) fInfoControl.getInput().getPrevious();
if (previous != null) {
fInfoControl.setInput(previous);
}
}
public void update() {
BrowserInput current= fInfoControl.getInput();
if (current != null && current.getPrevious() != null) {
BrowserInput previous= current.getPrevious();
setToolTipText("Back to " + previous.getInputName());
setEnabled(true);
} else {
setToolTipText("Back");
setEnabled(false);
}
}
}
/**
* Action to go forward to the next input in the hover control.
*/
static final class ForwardAction extends Action {
private final BrowserInformationControl fInfoControl;
public ForwardAction(BrowserInformationControl infoControl) {
fInfoControl= infoControl;
setText("Forward");
ISharedImages images= getWorkbench().getSharedImages();
setImageDescriptor(images.getImageDescriptor(IMG_TOOL_FORWARD));
setDisabledImageDescriptor(images.getImageDescriptor(IMG_TOOL_FORWARD_DISABLED));
update();
}
@Override
public void run() {
BrowserInput next= (BrowserInput) fInfoControl.getInput().getNext();
if (next != null) {
fInfoControl.setInput(next);
}
}
public void update() {
BrowserInput current= fInfoControl.getInput();
if (current != null && current.getNext() != null) {
setToolTipText("Forward to " + current.getNext().getInputName());
setEnabled(true);
} else {
setToolTipText("Forward");
setEnabled(false);
}
}
}
/**
* Action that shows the current hover contents in the Javadoc view.
*/
/*private static final class ShowInDocViewAction extends Action {
private final BrowserInformationControl fInfoControl;
public ShowInJavadocViewAction(BrowserInformationControl infoControl) {
fInfoControl= infoControl;
setText("Show in Ceylondoc View");
setImageDescriptor(JavaPluginImages.DESC_OBJS_JAVADOCTAG); //TODO: better image
}
@Override
public void run() {
DocBrowserInformationControlInput infoInput= (DocBrowserInformationControlInput) fInfoControl.getInput(); //TODO: check cast
fInfoControl.notifyDelayedInputChange(null);
fInfoControl.dispose(); //FIXME: should have protocol to hide, rather than dispose
try {
JavadocView view= (JavadocView) JavaPlugin.getActivePage().showView(JavaUI.ID_JAVADOC_VIEW);
view.setInput(infoInput);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
}
}*/
/**
* Action that opens the current hover input element.
*/
final class OpenDeclarationAction extends Action {
private final BrowserInformationControl fInfoControl;
public OpenDeclarationAction(BrowserInformationControl infoControl) {
fInfoControl = infoControl;
setText("Open Declaration");
setLocalImageDescriptors(this, "goto_input.gif");
}
@Override
public void run() {
close(fInfoControl); //FIXME: should have protocol to hide, rather than dispose
CeylonBrowserInput input = (CeylonBrowserInput) fInfoControl.getInput();
gotoDeclaration(editor, getLinkedModel(editor, input.getAddress()));
}
}
static void gotoDeclaration(CeylonEditor editor, Referenceable model) {
CeylonParseController cpc = editor.getParseController();
Node refNode = getReferencedNode(model, cpc);
if (refNode!=null) {
gotoNode(refNode, cpc.getProject(), cpc.getTypeChecker());
}
else if (model instanceof Declaration) {
gotoJavaNode((Declaration) model, cpc);
}
}
private static void close(BrowserInformationControl control) {
control.notifyDelayedInputChange(null);
control.dispose();
}
/**
* The style sheet (css).
*/
private static String fgStyleSheet;
/**
* The hover control creator.
*/
private IInformationControlCreator fHoverControlCreator;
/**
* The presentation control creator.
*/
private IInformationControlCreator fPresenterControlCreator;
private IInformationControlCreator getInformationPresenterControlCreator() {
if (fPresenterControlCreator == null)
fPresenterControlCreator= new PresenterControlCreator(this);
return fPresenterControlCreator;
}
@Override
public IInformationControlCreator getHoverControlCreator() {
return getHoverControlCreator("F2 for focus");
}
public IInformationControlCreator getHoverControlCreator(
String statusLineMessage) {
if (fHoverControlCreator == null) {
fHoverControlCreator= new HoverControlCreator(this,
getInformationPresenterControlCreator(),
statusLineMessage);
}
return fHoverControlCreator;
}
void addLinkListener(final BrowserInformationControl control) {
control.addLocationListener(new CeylonLocationListener(control));
}
public static Referenceable getLinkedModel(CeylonEditor editor, String location) {
TypeChecker tc = editor.getParseController().getTypeChecker();
String[] bits = location.split(":");
JDTModelLoader modelLoader = getModelLoader(tc);
String moduleName = bits[1];
Module module = modelLoader.getLoadedModule(moduleName);
if (module==null || bits.length==2) {
return module;
}
Referenceable target = module.getPackage(bits[2]);
for (int i=3; i<bits.length; i++) {
Scope scope;
if (target instanceof Scope) {
scope = (Scope) target;
}
else if (target instanceof TypedDeclaration) {
scope = ((TypedDeclaration) target).getType().getDeclaration();
}
else {
return null;
}
target = scope.getDirectMember(bits[i], null, false);
}
return target;
}
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
CeylonBrowserInput info = (CeylonBrowserInput) getHoverInfo2(textViewer, hoverRegion);
return info!=null ? info.getHtml() : null;
}
@Override
public CeylonBrowserInput getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
return internalGetHoverInfo(editor, hoverRegion);
}
static CeylonBrowserInput internalGetHoverInfo(final CeylonEditor editor,
IRegion hoverRegion) {
if (editor==null || editor.getSelectionProvider()==null) return null;
CeylonParseController parseController = editor.getParseController();
if (parseController==null) return null;
Tree.CompilationUnit rn = parseController.getRootNode();
if (rn!=null) {
int hoffset = hoverRegion.getOffset();
ITextSelection selection = getSelection(editor);
if (selection!=null &&
selection.getOffset()<=hoffset &&
selection.getOffset()+selection.getLength()>=hoffset) {
Node node = findNode(rn, selection.getOffset(),
selection.getOffset()+selection.getLength()-1);
if (node instanceof Tree.Expression) {
node = ((Tree.Expression) node).getTerm();
}
if (node instanceof Tree.Term) {
return getTermTypeHoverInfo(node, selection.getText(),
editor.getCeylonSourceViewer().getDocument(),
editor.getParseController().getProject());
}
}
Node node = findNode(rn, hoffset);
if (node instanceof Tree.ImportPath) {
Referenceable r = ((Tree.ImportPath) node).getModel();
if (r!=null) {
return getHoverInfo(r, null, editor, node);
}
}
else if (node instanceof Tree.LocalModifier) {
return getInferredTypeHoverInfo(node,
editor.getParseController().getProject());
}
else if (node instanceof Tree.Literal) {
return getTermTypeHoverInfo(node, null,
editor.getCeylonSourceViewer().getDocument(),
editor.getParseController().getProject());
}
else {
return getHoverInfo(getReferencedDeclaration(node),
null, editor, node);
}
}
return null;
}
private static ITextSelection getSelection(final CeylonEditor editor) {
final class GetSelection implements Runnable {
ITextSelection selection;
@Override
public void run() {
selection = (ITextSelection) editor.getSelectionProvider().getSelection();
}
ITextSelection getSelection() {
Display.getDefault().syncExec(this);
return selection;
}
}
return new GetSelection().getSelection();
}
private static CeylonBrowserInput getInferredTypeHoverInfo(Node node, IProject project) {
ProducedType t = ((Tree.LocalModifier) node).getTypeModel();
if (t==null) return null;
StringBuffer buffer = new StringBuffer();
HTMLPrinter.insertPageProlog(buffer, 0, DocumentationHover.getStyleSheet());
addImageAndLabel(buffer, null, fileUrl("types.gif").toExternalForm(),
16, 16, "<b><tt>" + highlightLine(t.getProducedTypeName()) + "</tt></b>",
20, 4);
buffer.append("<hr/>");
if (!t.containsUnknowns()) {
buffer.append("One quick assist available:<br/>");
addImageAndLabel(buffer, null, fileUrl("correction_change.gif").toExternalForm(),
16, 16, "<a href=\"stp:" + node.getStartIndex() + "\">Specify explicit type</a>",
20, 4);
}
//buffer.append(getDocumentationFor(editor.getParseController(), t.getDeclaration()));
HTMLPrinter.addPageEpilog(buffer);
return new CeylonBrowserInput(null, null, buffer.toString());
}
private static CeylonBrowserInput getTermTypeHoverInfo(Node node, String selectedText,
IDocument doc, IProject project) {
ProducedType t = ((Tree.Term) node).getTypeModel();
if (t==null) return null;
// String expr = "";
// try {
// expr = doc.get(node.getStartIndex(), node.getStopIndex()-node.getStartIndex()+1);
// }
// catch (BadLocationException e) {
// e.printStackTrace();
// }
StringBuffer buffer = new StringBuffer();
HTMLPrinter.insertPageProlog(buffer, 0, getStyleSheet());
String desc = node instanceof Tree.Literal ? "literal" : "expression";
addImageAndLabel(buffer, null, fileUrl("types.gif").toExternalForm(),
16, 16, "<b><tt>" + highlightLine(t.getProducedTypeName()) +
"</tt> "+desc+"</b>",
20, 4);
buffer.append( "<hr/>");
if (node instanceof Tree.StringLiteral) {
buffer.append("<code style='color:")
.append(toHex(getCurrentThemeColor(STRINGS)))
.append("'><pre>")
.append('\"')
.append(convertToHTMLContent(node.getText()))
.append('\"')
.append("</pre></code>")
.append("<hr/>");
// If a single char selection, then append info on that character too
if (selectedText != null
&& codePointCount(selectedText, 0, selectedText.length()) == 1) {
appendCharacterHoverInfo(buffer, selectedText);
}
}
else if (node instanceof Tree.CharLiteral) {
String character = node.getText();
if (character.length()>2) {
appendCharacterHoverInfo(buffer,
character.substring(1, character.length()-1));
}
}
else if (node instanceof Tree.NaturalLiteral) {
buffer.append("<code style='color:")
.append(toHex(getCurrentThemeColor(NUMBERS)))
.append("'>");
String text = node.getText().replace("_", "");
switch (text.charAt(0)) {
case '#':
buffer.append(parseInt(text.substring(1),16));
break;
case '$':
buffer.append(parseInt(text.substring(1),2));
break;
default:
buffer.append(parseInt(text));
}
buffer.append("</code>").append("<hr/>");
}
else if (node instanceof Tree.FloatLiteral) {
buffer.append("<code style='color:")
.append(toHex(getCurrentThemeColor(NUMBERS)))
.append("'>");
buffer.append(parseFloat(node.getText().replace("_", "")));
buffer.append("</code>").append("<hr/>");
}
buffer.append("Two quick assists available:<br/>");
addImageAndLabel(buffer, null, fileUrl("change.png").toExternalForm(),
16, 16, "<a href=\"exv:\">Extract value</a>",
20, 4);
addImageAndLabel(buffer, null, fileUrl("change.png").toExternalForm(),
16, 16, "<a href=\"exf:\">Extract function</a>",
20, 4);
HTMLPrinter.addPageEpilog(buffer);
return new CeylonBrowserInput(null, null, buffer.toString());
}
private static void appendCharacterHoverInfo(StringBuffer buffer, String character) {
buffer.append("<code style='color:")
.append(toHex(getCurrentThemeColor(CHARS)))
.append("'>")
.append('\'')
.append(convertToHTMLContent(character))
.append('\'')
.append("</code>");
int codepoint = Character.codePointAt(character, 0);
String name = Character.getName(codepoint);
buffer.append("<hr/>Unicode Name: <code>").append(name).append("</code>");
String hex = Integer.toHexString(codepoint).toUpperCase();
while (hex.length() < 4) {
hex = "0" + hex;
}
buffer.append("<br/>Codepoint: <code>").append("U+").append(hex).append("</code>");
buffer.append("<br/>General Category: <code>").append(getCodepointGeneralCategoryName(codepoint)).append("</code>");
Character.UnicodeScript script = Character.UnicodeScript.of(codepoint);
buffer.append("<br/>Script: <code>").append(script.name()).append("</code>");
Character.UnicodeBlock block = Character.UnicodeBlock.of(codepoint);
buffer.append("<br/>Block: <code>").append(block).append("<hr/>").append("</code>");
}
private static String getCodepointGeneralCategoryName(int codepoint) {
String gc;
switch (Character.getType(codepoint)) {
case Character.COMBINING_SPACING_MARK:
gc = "Mark, combining spacing"; break;
case Character.CONNECTOR_PUNCTUATION:
gc = "Punctuation, connector"; break;
case Character.CONTROL:
gc = "Other, control"; break;
case Character.CURRENCY_SYMBOL:
gc = "Symbol, currency"; break;
case Character.DASH_PUNCTUATION:
gc = "Punctuation, dash"; break;
case Character.DECIMAL_DIGIT_NUMBER:
gc = "Number, decimal digit"; break;
case Character.ENCLOSING_MARK:
gc = "Mark, enclosing"; break;
case Character.END_PUNCTUATION:
gc = "Punctuation, close"; break;
case Character.FINAL_QUOTE_PUNCTUATION:
gc = "Punctuation, final quote"; break;
case Character.FORMAT:
gc = "Other, format"; break;
case Character.INITIAL_QUOTE_PUNCTUATION:
gc = "Punctuation, initial quote"; break;
case Character.LETTER_NUMBER:
gc = "Number, letter"; break;
case Character.LINE_SEPARATOR:
gc = "Separator, line"; break;
case Character.LOWERCASE_LETTER:
gc = "Letter, lowercase"; break;
case Character.MATH_SYMBOL:
gc = "Symbol, math"; break;
case Character.MODIFIER_LETTER:
gc = "Letter, modifier"; break;
case Character.MODIFIER_SYMBOL:
gc = "Symbol, modifier"; break;
case Character.NON_SPACING_MARK:
gc = "Mark, nonspacing"; break;
case Character.OTHER_LETTER:
gc = "Letter, other"; break;
case Character.OTHER_NUMBER:
gc = "Number, other"; break;
case Character.OTHER_PUNCTUATION:
gc = "Punctuation, other"; break;
case Character.OTHER_SYMBOL:
gc = "Symbol, other"; break;
case Character.PARAGRAPH_SEPARATOR:
gc = "Separator, paragraph"; break;
case Character.PRIVATE_USE:
gc = "Other, private use"; break;
case Character.SPACE_SEPARATOR:
gc = "Separator, space"; break;
case Character.START_PUNCTUATION:
gc = "Punctuation, open"; break;
case Character.SURROGATE:
gc = "Other, surrogate"; break;
case Character.TITLECASE_LETTER:
gc = "Letter, titlecase"; break;
case Character.UNASSIGNED:
gc = "Other, unassigned"; break;
case Character.UPPERCASE_LETTER:
gc = "Letter, uppercase"; break;
default:
gc = "<Unknown>";
}
return gc;
}
private static String getIcon(Object obj) {
if (obj instanceof Module) {
return "jar_l_obj.gif";
}
else if (obj instanceof Package) {
return "package_obj.gif";
}
else if (obj instanceof Declaration) {
Declaration dec = (Declaration) obj;
if (dec instanceof Class) {
return dec.isShared() ?
"class_obj.gif" :
"innerclass_private_obj.gif";
}
else if (dec instanceof Interface) {
return dec.isShared() ?
"int_obj.gif" :
"innerinterface_private_obj.gif";
}
else if (dec instanceof TypeAlias||
dec instanceof NothingType) {
return "types.gif";
}
else if (dec.isParameter()) {
if (dec instanceof Method) {
return "methpro_obj.gif";
}
else {
return "field_protected_obj.gif";
}
}
else if (dec instanceof Method) {
return dec.isShared() ?
"public_co.gif" :
"private_co.gif";
}
else if (dec instanceof MethodOrValue) {
return dec.isShared() ?
"field_public_obj.gif" :
"field_private_obj.gif";
}
else if (dec instanceof TypeParameter) {
return "typevariable_obj.gif";
}
}
return null;
}
/**
* Computes the hover info.
* @param previousInput the previous input, or <code>null</code>
* @param node
* @param elements the resolved elements
* @param editorInputElement the editor input, or <code>null</code>
*
* @return the HTML hover info for the given element(s) or <code>null</code>
* if no information is available
* @since 3.4
*/
static CeylonBrowserInput getHoverInfo(Referenceable model,
BrowserInput previousInput, CeylonEditor editor, Node node) {
if (model instanceof Declaration) {
Declaration dec = (Declaration) model;
return new CeylonBrowserInput(previousInput, dec,
getDocumentationFor(editor.getParseController(), dec, node));
}
else if (model instanceof Package) {
Package dec = (Package) model;
return new CeylonBrowserInput(previousInput, dec,
getDocumentationFor(editor.getParseController(), dec));
}
else if (model instanceof Module) {
Module dec = (Module) model;
return new CeylonBrowserInput(previousInput, dec,
getDocumentationFor(editor.getParseController(), dec));
}
else {
return null;
}
}
private static void appendJavadoc(IJavaElement elem, StringBuffer sb) {
if (elem instanceof IMember) {
try {
//TODO: Javadoc @ icon?
IMember mem = (IMember) elem;
String jd = JavadocContentAccess2.getHTMLContent(mem, true);
if (jd!=null) {
sb.append("<br/>").append(jd);
String base = getBaseURL(mem, mem.isBinary());
int endHeadIdx= sb.indexOf("</head>");
sb.insert(endHeadIdx, "\n<base href='" + base + "'>\n");
}
}
catch (JavaModelException e) {
e.printStackTrace();
}
}
}
public static String getBaseURL(IJavaElement element, boolean isBinary) throws JavaModelException {
if (isBinary) {
// Source attachment usually does not include Javadoc resources
// => Always use the Javadoc location as base:
URL baseURL= JavaUI.getJavadocLocation(element, false);
if (baseURL != null) {
if (baseURL.getProtocol().equals("jar")) {
// It's a JarURLConnection, which is not known to the browser widget.
// Let's start the help web server:
URL baseURL2= PlatformUI.getWorkbench().getHelpSystem().resolve(baseURL.toExternalForm(), true);
if (baseURL2 != null) { // can be null if org.eclipse.help.ui is not available
baseURL= baseURL2;
}
}
return baseURL.toExternalForm();
}
} else {
IResource resource= element.getResource();
if (resource != null) {
/*
* Too bad: Browser widget knows nothing about EFS and custom URL handlers,
* so IResource#getLocationURI() does not work in all cases.
* We only support the local file system for now.
* A solution could be https://bugs.eclipse.org/bugs/show_bug.cgi?id=149022 .
*/
IPath location= resource.getLocation();
if (location != null)
return location.toFile().toURI().toString();
}
}
return null;
}
public static String getDocumentationFor(CeylonParseController cpc, Package pack) {
StringBuffer buffer= new StringBuffer();
addImageAndLabel(buffer, pack, fileUrl(getIcon(pack)).toExternalForm(),
16, 16, "<b><tt>" + highlightLine(description(pack)) +"</tt></b>", 20, 4);
buffer.append("<hr/>");
Module mod = pack.getModule();
addImageAndLabel(buffer, mod, fileUrl(getIcon(mod)).toExternalForm(),
16, 16, "in module <tt><a " + link(mod) + ">" +
getLabel(mod) +"</a></tt>", 20, 2);
PhasedUnit pu = cpc.getTypeChecker()
.getPhasedUnitFromRelativePath(pack.getNameAsString().replace('.', '/') + "/package.ceylon");
if (pu!=null) {
List<Tree.PackageDescriptor> packageDescriptors = pu.getCompilationUnit().getPackageDescriptors();
if (!packageDescriptors.isEmpty()) {
Tree.PackageDescriptor refnode = packageDescriptors.get(0);
if (refnode!=null) {
appendDocAnnotationContent(refnode.getAnnotationList(), buffer, pack);
appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, pack);
appendSeeAnnotationContent(refnode.getAnnotationList(), buffer);
}
}
}
if (mod.isJava()) {
buffer.append("<p>This package is implemented in Java.</p>");
}
if (JDKUtils.isJDKModule(mod.getNameAsString())) {
buffer.append("<p>This package forms part of the Java SDK.</p>");
}
boolean first = true;
for (Declaration dec: pack.getMembers()) {
if (dec instanceof Class && ((Class)dec).isOverloaded()) {
continue;
}
if (dec.isShared() && !dec.isAnonymous()) {
if (first) {
buffer.append("<hr/>Contains: ");
first = false;
}
else {
buffer.append(", ");
}
/*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(),
16, 16, "<tt><a " + link(dec) + ">" +
dec.getName() + "</a></tt>", 20, 2);*/
buffer.append("<tt><a " + link(dec) + ">" + dec.getName() + "</a></tt>");
}
}
if (!first) {
buffer.append(".<br/>");
}
insertPageProlog(buffer, 0, getStyleSheet());
addPageEpilog(buffer);
return buffer.toString();
}
private static String description(Package pack) {
return "package " + getLabel(pack);
}
public static String getDocumentationFor(ModuleDetails mod, String version) {
return getDocumentationForModule(mod.getName(), version, mod.getDoc());
}
public static String getDocumentationForModule(String name, String version, String doc) {
StringBuffer buffer= new StringBuffer();
addImageAndLabel(buffer, null, fileUrl("jar_l_obj.gif").toExternalForm(),
16, 16, "<b><tt>" + highlightLine(description(name, version)) + "</tt></b>", 20, 4);
buffer.append("<hr/>");
if (doc!=null) {
buffer.append(markdown(doc, null, null));
}
insertPageProlog(buffer, 0, getStyleSheet());
addPageEpilog(buffer);
return buffer.toString();
}
private static String description(String name, String version) {
return "module " + name + " \"" + version + "\"";
}
public static String getDocumentationFor(CeylonParseController cpc, Module mod) {
StringBuffer buffer= new StringBuffer();
addImageAndLabel(buffer, mod, fileUrl(getIcon(mod)).toExternalForm(),
16, 16, "<b><tt>" + highlightLine(description(mod)) + "</tt></b>", 20, 4);
buffer.append("<hr/>");
if (mod.isJava()) {
buffer.append("<p>This module is implemented in Java.</p>");
}
if (mod.isDefault()) {
buffer.append("<p>The default module for packages which do not belong to explicit module.</p>");
}
if (JDKUtils.isJDKModule(mod.getNameAsString())) {
buffer.append("<p>This module forms part of the Java SDK.</p>");
}
PhasedUnit pu = cpc.getTypeChecker()
.getPhasedUnitFromRelativePath(mod.getNameAsString().replace('.', '/') + "/module.ceylon");
if (pu!=null) {
List<Tree.ModuleDescriptor> moduleDescriptors = pu.getCompilationUnit().getModuleDescriptors();
if (!moduleDescriptors.isEmpty()) {
Tree.ModuleDescriptor refnode = moduleDescriptors.get(0);
if (refnode!=null) {
Scope linkScope = mod.getPackage(mod.getNameAsString());
appendDocAnnotationContent(refnode.getAnnotationList(), buffer, linkScope);
appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, linkScope);
appendSeeAnnotationContent(refnode.getAnnotationList(), buffer);
}
}
}
boolean first = true;
for (Package pack: mod.getPackages()) {
if (pack.isShared()) {
if (first) {
buffer.append("<hr/>Contains: ");
first = false;
}
else {
buffer.append(", ");
}
/*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(),
16, 16, "<tt><a " + link(dec) + ">" +
dec.getName() + "</a></tt>", 20, 2);*/
buffer.append("<tt><a " + link(pack) + ">" + pack.getNameAsString() + "</a></tt>");
}
}
if (!first) {
buffer.append(".<br/>");
}
insertPageProlog(buffer, 0, getStyleSheet());
addPageEpilog(buffer);
return buffer.toString();
}
private static String description(Module mod) {
return "module " + getLabel(mod) + " \"" + mod.getVersion() + "\"";
}
public static String getDocumentationFor(CeylonParseController cpc, Declaration dec) {
return getDocumentationFor(cpc, dec, null);
}
public static String getDocumentationFor(CeylonParseController cpc, Declaration dec, Node node) {
if (dec==null) return null;
StringBuffer buffer = new StringBuffer();
insertPageProlog(buffer, 0, getStyleSheet());
Package pack = dec.getUnit().getPackage();
addImageAndLabel(buffer, dec, fileUrl(getIcon(dec)).toExternalForm(),
16, 16, "<b><tt>" + (dec.isDeprecated() ? "<s>":"") +
highlightLine(description(dec, cpc)) +
(dec.isDeprecated() ? "</s>":"") + "</tt></b>", 20, 4);
buffer.append("<hr/>");
if (dec.isParameter()) {
Declaration pd = ((MethodOrValue) dec).getInitializerParameter().getDeclaration();
addImageAndLabel(buffer, pd, fileUrl(getIcon(pd)).toExternalForm(),
16, 16, "parameter of <tt><a " + link(pd) + ">" + pd.getName() +"</a></tt>", 20, 2);
}
else if (dec instanceof TypeParameter) {
Declaration pd = ((TypeParameter) dec).getDeclaration();
addImageAndLabel(buffer, pd, fileUrl(getIcon(pd)).toExternalForm(),
16, 16, "type parameter of <tt><a " + link(pd) + ">" + pd.getName() +"</a></tt>", 20, 2);
}
else {
if (dec.isClassOrInterfaceMember()) {
ClassOrInterface outer = (ClassOrInterface) dec.getContainer();
addImageAndLabel(buffer, outer, fileUrl(getIcon(outer)).toExternalForm(), 16, 16,
"member of <tt><a " + link(outer) + ">" +
convertToHTMLContent(outer.getType().getProducedTypeName()) + "</a></tt>", 20, 2);
}
if ((dec.isShared() || dec.isToplevel()) &&
!(dec instanceof NothingType)) {
String label;
if (pack.getNameAsString().isEmpty()) {
label = "in default package";
}
else {
label = "in package <tt><a " + link(pack) + ">" +
getPackageLabel(dec) +"</a></tt>";
}
addImageAndLabel(buffer, pack, fileUrl(getIcon(pack)).toExternalForm(),
16, 16, label, 20, 2);
Module mod = pack.getModule();
addImageAndLabel(buffer, mod, fileUrl(getIcon(mod)).toExternalForm(),
16, 16, "in module <tt><a " + link(mod) + ">" +
getModuleLabel(dec) +"</a></tt>", 20, 2);
}
}
boolean hasDoc = false;
Tree.Declaration refnode = (Tree.Declaration) getReferencedNode(dec, cpc);
if (refnode!=null) {
appendDeprecatedAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec));
int len = buffer.length();
appendDocAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec));
hasDoc = buffer.length()!=len;
appendThrowAnnotationContent(refnode.getAnnotationList(), buffer, resolveScope(dec));
appendSeeAnnotationContent(refnode.getAnnotationList(), buffer);
}
appendJavadoc(dec, cpc.getProject(), buffer, node);
//boolean extraBreak = false;
boolean obj=false;
if (dec instanceof TypedDeclaration) {
TypeDeclaration td = ((TypedDeclaration) dec).getTypeDeclaration();
if (td!=null && td.isAnonymous()) {
obj=true;
documentInheritance(td, buffer);
}
}
else if (dec instanceof TypeDeclaration) {
documentInheritance((TypeDeclaration) dec, buffer);
}
Declaration rd = dec.getRefinedDeclaration();
if (dec!=rd) {
buffer.append("<p>");
addImageAndLabel(buffer, rd, fileUrl(rd.isFormal() ? "implm_co.gif" : "over_co.gif").toExternalForm(),
16, 16, "refines <tt><a " + link(rd) + ">" + rd.getName() +"</a></tt> declared by <tt>" +
convertToHTMLContent(((TypeDeclaration) rd.getContainer()).getType().getProducedTypeName()) +
"</tt>", 20, 2);
buffer.append("</p>");
if (!hasDoc) {
Tree.Declaration refnode2 = (Tree.Declaration) getReferencedNode(rd, cpc);
if (refnode2!=null) {
appendDocAnnotationContent(refnode2.getAnnotationList(), buffer, resolveScope(rd));
}
}
}
if (dec instanceof TypedDeclaration && !obj) {
ProducedType ret = ((TypedDeclaration) dec).getType();
if (ret!=null) {
buffer.append("<p>");
List<ProducedType> list;
if (ret.getDeclaration() instanceof UnionType) {
list = ret.getDeclaration().getCaseTypes();
}
else {
list = Arrays.asList(ret);
}
StringBuffer buf = new StringBuffer("returns <tt>");
for (ProducedType pt: list) {
if (pt.getDeclaration() instanceof ClassOrInterface ||
pt.getDeclaration() instanceof TypeParameter) {
buf.append("<a " + link(pt.getDeclaration()) + ">" +
convertToHTMLContent(pt.getProducedTypeName()) +"</a>");
}
else {
buf.append(convertToHTMLContent(pt.getProducedTypeName()));
}
buf.append("|");
}
buf.setLength(buf.length()-1);
buf.append("</tt>");
addImageAndLabel(buffer, ret.getDeclaration(), fileUrl("stepreturn_co.gif").toExternalForm(),
16, 16, buf.toString(), 20, 2);
buffer.append("</p>");
}
}
if (dec instanceof Functional) {
for (ParameterList pl: ((Functional) dec).getParameterLists()) {
if (!pl.getParameters().isEmpty()) {
buffer.append("<p>");
for (Parameter p: pl.getParameters()) {
StringBuffer doc = new StringBuffer();
Tree.Declaration refNode = (Tree.Declaration) getReferencedNode(p.getModel(), cpc);
if (refNode!=null) {
appendDocAnnotationContent(refNode.getAnnotationList(), doc, resolveScope(dec));
}
if (doc.length()!=0) {
doc.insert(0, ":");
}
ProducedType type = p.getType();
if (type==null) type = new UnknownType(dec.getUnit()).getType();
addImageAndLabel(buffer, p.getModel(), fileUrl("methpro_obj.gif"/*"stepinto_co.gif"*/).toExternalForm(),
16, 16, "accepts <tt><a " + link(type.getDeclaration()) + ">" +
convertToHTMLContent(type.getProducedTypeName()) +
"</a> <a " + link(p.getModel()) + ">"+ p.getName() +"</a></tt>" + doc, 20, 2);
}
buffer.append("</p>");
}
}
}
if (dec instanceof ClassOrInterface) {
if (!dec.getMembers().isEmpty()) {
boolean first = true;
for (Declaration mem: dec.getMembers()) {
if (mem instanceof Method && ((Method)mem).isOverloaded()) {
continue;
}
if (mem.isShared() && !dec.isAnonymous()) {
if (first) {
buffer.append("<hr/>Members: ");
first = false;
}
else {
buffer.append(", ");
}
/*addImageAndLabel(buffer, null, fileUrl(getIcon(dec)).toExternalForm(),
16, 16, "<tt><a " + link(dec) + ">" + dec.getName() + "</a></tt>", 20, 2);*/
buffer.append("<tt><a " + link(mem) + ">" + mem.getName() + "</a></tt>");
}
}
if (!first) {
buffer.append(".<br/>");
//extraBreak = true;
}
}
}
if (dec instanceof NothingType) {
buffer.append("Special bottom type defined by the language. "
+ "<code>Nothing</code> is assignable to all types, but has no value. "
+ "A function or value of type <code>Nothing</code> either throws "
+ "an exception, or never returns.");
}
else {
//if (dec.getUnit().getFilename().endsWith(".ceylon")) {
//if (extraBreak)
appendExtraActions(dec, buffer);
}
addPageEpilog(buffer);
return buffer.toString();
}
public static void appendExtraActions(Declaration dec, StringBuffer buffer) {
buffer.append("<hr/>");
addImageAndLabel(buffer, null, fileUrl("unit.gif").toExternalForm(),
16, 16, "<a href='dec:" + declink(dec) + "'>declared</a> in unit <tt>"+
dec.getUnit().getFilename() + "</tt>", 20, 2);
//}
buffer.append("<hr/>");
addImageAndLabel(buffer, null, fileUrl("search_ref_obj.png").toExternalForm(),
16, 16, "<a href='ref:" + declink(dec) + "'>find references</a> to <tt>" +
dec.getName() + "</tt>", 20, 2);
if (dec instanceof ClassOrInterface) {
addImageAndLabel(buffer, null, fileUrl("search_decl_obj.png").toExternalForm(),
16, 16, "<a href='sub:" + declink(dec) + "'>find subtypes</a> of <tt>" +
dec.getName() + "</tt>", 20, 2);
}
if (dec instanceof Value) {
addImageAndLabel(buffer, null, fileUrl("search_ref_obj.png").toExternalForm(),
16, 16, "<a href='ass:" + declink(dec) + "'>find assignments</a> to <tt>" +
dec.getName() + "</tt>", 20, 2);
}
if (dec.isFormal()||dec.isDefault()) {
addImageAndLabel(buffer, null, fileUrl("search_decl_obj.png").toExternalForm(),
16, 16, "<a href='act:" + declink(dec) + "'>find refinements</a> of <tt>" +
dec.getName() + "</tt>", 20, 2);
}
}
private static void documentInheritance(TypeDeclaration dec, StringBuffer buffer) {
if (dec instanceof Class) {
ProducedType sup = ((Class) dec).getExtendedType();
if (sup!=null) {
buffer.append("<p>");
addImageAndLabel(buffer, sup.getDeclaration(), fileUrl("super_co.gif").toExternalForm(),
16, 16, "extends <tt><a " + link(sup.getDeclaration()) + ">" +
HTMLPrinter.convertToHTMLContent(sup.getProducedTypeName()) +"</a></tt>", 20, 2);
buffer.append("</p>");
//extraBreak = true;
}
}
// if (dec instanceof TypeDeclaration) {
List<ProducedType> sts = ((TypeDeclaration) dec).getSatisfiedTypes();
if (!sts.isEmpty()) {
buffer.append("<p>");
for (ProducedType td: sts) {
addImageAndLabel(buffer, td.getDeclaration(), fileUrl("super_co.gif").toExternalForm(),
16, 16, "satisfies <tt><a " + link(td.getDeclaration()) + ">" +
convertToHTMLContent(td.getProducedTypeName()) +"</a></tt>", 20, 2);
//extraBreak = true;
}
buffer.append("</p>");
}
List<ProducedType> cts = ((TypeDeclaration) dec).getCaseTypes();
if (cts!=null) {
buffer.append("<p>");
for (ProducedType td: cts) {
addImageAndLabel(buffer, td.getDeclaration(), fileUrl("sub_co.gif").toExternalForm(),
16, 16, (td.getDeclaration().isSelfType() ? "has self type" : "has case") +
" <tt><a " + link(td.getDeclaration()) + ">" +
convertToHTMLContent(td.getProducedTypeName()) +"</a></tt>", 20, 2);
//extraBreak = true;
}
buffer.append("</p>");
}
// }
}
private static String description(Declaration dec, CeylonParseController cpc) {
String result = getDescriptionFor(dec);
if (dec instanceof TypeDeclaration) {
TypeDeclaration td = (TypeDeclaration) dec;
if (td.isAlias() && td.getExtendedType()!=null) {
result += " => ";
result += td.getExtendedType().getProducedTypeName();
}
}
else if (dec instanceof Value) {
if (!((Value) dec).isVariable()) {
Tree.Declaration refnode = (Tree.Declaration) getReferencedNode(dec, cpc);
if (refnode instanceof Tree.AttributeDeclaration) {
Tree.SpecifierOrInitializerExpression sie = ((Tree.AttributeDeclaration) refnode).getSpecifierOrInitializerExpression();
if (sie!=null) {
if (sie.getExpression()!=null) {
Tree.Term term = sie.getExpression().getTerm();
if (term instanceof Tree.Literal) {
result += " = ";
result += term.getToken().getText();
}
}
}
}
}
}
/*else if (dec instanceof ValueParameter) {
Tree.Declaration refnode = (Tree.Declaration) getReferencedNode(dec, cpc);
if (refnode instanceof Tree.ValueParameterDeclaration) {
Tree.DefaultArgument da = ((Tree.ValueParameterDeclaration) refnode).getDefaultArgument();
if (da!=null) {
Tree.Expression e = da.getSpecifierExpression().getExpression();
if (e!=null) {
Tree.Term term = e.getTerm();
if (term instanceof Tree.Literal) {
result += " = ";
result += term.getText();
}
else {
result += " =";
}
}
}
}
}*/
return result;
}
static String getAddress(Referenceable model) {
if (model==null) return null;
return "dec:" + declink(model);
}
private static String link(Referenceable model) {
return "href='doc:" + declink(model) + "'";
}
private static String declink(Referenceable model) {
if (model instanceof Package) {
Package p = (Package) model;
return declink(p.getModule()) + ":" + p.getNameAsString();
}
if (model instanceof Module) {
return ((Module) model).getNameAsString();
}
else if (model instanceof Declaration) {
String result = ":" + ((Declaration) model).getName();
Scope container = ((Declaration) model).getContainer();
if (container instanceof Referenceable) {
return declink((Referenceable) container)
+ result;
}
else {
return result;
}
}
else {
return "";
}
}
private static void appendJavadoc(Declaration model, IProject project,
StringBuffer buffer, Node node) {
IJavaProject jp = JavaCore.create(project);
if (jp!=null) {
try {
appendJavadoc(getJavaElement(model, jp, node), buffer);
}
catch (JavaModelException jme) {
jme.printStackTrace();
}
}
}
private static void appendDocAnnotationContent(Tree.AnnotationList annotationList,
StringBuffer documentation, Scope linkScope) {
if (annotationList!=null) {
AnonymousAnnotation aa = annotationList.getAnonymousAnnotation();
if (aa!=null) {
documentation.append(markdown(aa.getStringLiteral().getText(), linkScope,
annotationList.getUnit()));
}
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("doc".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
if (!args.isEmpty()) {
Tree.PositionalArgument a = args.get(0);
if (a instanceof Tree.ListedArgument) {
String text = ((Tree.ListedArgument) a).getExpression()
.getTerm().getText();
if (text!=null) {
documentation.append(markdown(text, linkScope,
annotationList.getUnit()));
}
}
}
}
}
}
}
}
}
private static void appendDeprecatedAnnotationContent(Tree.AnnotationList annotationList,
StringBuffer documentation, Scope linkScope) {
if (annotationList!=null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("deprecated".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
if (!args.isEmpty()) {
Tree.PositionalArgument a = args.get(0);
if (a instanceof Tree.ListedArgument) {
String text = ((Tree.ListedArgument) a).getExpression()
.getTerm().getText();
if (text!=null) {
documentation.append(markdown("_(This is a deprecated program element.)_\n\n" + text,
linkScope, annotationList.getUnit()));
}
}
}
}
}
}
}
}
}
private static void appendSeeAnnotationContent(Tree.AnnotationList annotationList,
StringBuffer documentation) {
if (annotationList!=null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("see".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
for (Tree.PositionalArgument arg: args) {
if (arg instanceof Tree.ListedArgument) {
Tree.Term term = ((Tree.ListedArgument) arg).getExpression().getTerm();
if (term instanceof Tree.MetaLiteral) {
Declaration dec = ((Tree.MetaLiteral) term).getDeclaration();
if (dec!=null) {
String dn = dec.getName();
if (dec.isClassOrInterfaceMember()) {
dn = ((ClassOrInterface) dec.getContainer()).getName() + "." + dn;
}
addImageAndLabel(documentation, dec, fileUrl("link_obj.gif"/*getIcon(dec)*/).toExternalForm(), 16, 16,
"see <tt><a "+link(dec)+">"+dn+"</a></tt>", 20, 2);
}
}
}
}
}
}
}
}
}
}
private static void appendThrowAnnotationContent(Tree.AnnotationList annotationList,
StringBuffer documentation, Scope linkScope) {
if (annotationList!=null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
Tree.Primary annotPrim = annotation.getPrimary();
if (annotPrim instanceof Tree.BaseMemberExpression) {
String name = ((Tree.BaseMemberExpression) annotPrim).getIdentifier().getText();
if ("throws".equals(name)) {
Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList();
if (argList!=null) {
List<Tree.PositionalArgument> args = argList.getPositionalArguments();
if (args.isEmpty()) continue;
Tree.PositionalArgument typeArg = args.get(0);
Tree.PositionalArgument textArg = args.size()>1 ? args.get(1) : null;
if (typeArg instanceof Tree.ListedArgument &&
(textArg==null || textArg instanceof Tree.ListedArgument)) {
Tree.Term typeArgTerm = ((Tree.ListedArgument) typeArg).getExpression().getTerm();
Tree.Term textArgTerm = textArg==null ? null : ((Tree.ListedArgument) textArg).getExpression().getTerm();
String text = textArgTerm instanceof Tree.StringLiteral ?
textArgTerm.getText() : "";
if (typeArgTerm instanceof Tree.MetaLiteral) {
Declaration dec = ((Tree.MetaLiteral) typeArgTerm).getDeclaration();
if (dec!=null) {
String dn = dec.getName();
if (typeArgTerm instanceof Tree.QualifiedMemberOrTypeExpression) {
Tree.Primary p = ((Tree.QualifiedMemberOrTypeExpression) typeArgTerm).getPrimary();
if (p instanceof Tree.MemberOrTypeExpression) {
dn = ((Tree.MemberOrTypeExpression) p).getDeclaration().getName()
+ "." + dn;
}
}
addImageAndLabel(documentation, dec, fileUrl("ihigh_obj.gif"/*getIcon(dec)*/).toExternalForm(), 16, 16,
"throws <tt><a "+link(dec)+">"+dn+"</a></tt>" +
markdown(text, linkScope, annotationList.getUnit()), 20, 2);
}
}
}
}
}
}
}
}
}
public static URL fileUrl(String icon) {
try {
return FileLocator.toFileURL(FileLocator.find(CeylonPlugin.getInstance().getBundle(),
new Path("icons/").append(icon), null));
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Returns the Javadoc hover style sheet with the current Javadoc font from the preferences.
* @return the updated style sheet
* @since 3.4
*/
public static String getStyleSheet() {
if (fgStyleSheet == null)
fgStyleSheet = loadStyleSheet();
//Color c = CeylonTokenColorer.getCurrentThemeColor("docHover");
//String color = toHexString(c.getRed()) + toHexString(c.getGreen()) + toHexString(c.getBlue());
String css= fgStyleSheet;// + "body { background-color: #" + color+ " }";
if (css != null) {
FontData fontData= JFaceResources.getFontRegistry()
.getFontData(PreferenceConstants.APPEARANCE_JAVADOC_FONT)[0];
css= HTMLPrinter.convertTopLevelFont(css, fontData);
}
return css;
}
/**
* Loads and returns the Javadoc hover style sheet.
* @return the style sheet, or <code>null</code> if unable to load
* @since 3.4
*/
public static String loadStyleSheet() {
Bundle bundle= Platform.getBundle(JavaPlugin.getPluginId());
URL styleSheetURL= bundle.getEntry("/JavadocHoverStyleSheet.css");
if (styleSheetURL != null) {
BufferedReader reader= null;
try {
reader= new BufferedReader(new InputStreamReader(styleSheetURL.openStream()));
StringBuffer buffer= new StringBuffer(1500);
String line= reader.readLine();
while (line != null) {
buffer.append(line);
buffer.append('\n');
line= reader.readLine();
}
return buffer.toString();
} catch (IOException ex) {
JavaPlugin.log(ex);
return "";
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
}
return null;
}
public static void addImageAndLabel(StringBuffer buf, Referenceable model, String imageSrcPath,
int imageWidth, int imageHeight, String label, int labelLeft, int labelTop) {
buf.append("<div style='word-wrap: break-word; position: relative; ");
if (imageSrcPath != null) {
buf.append("margin-left: ").append(labelLeft).append("px; ");
buf.append("padding-top: ").append(labelTop).append("px; ");
}
buf.append("'>");
if (imageSrcPath != null) {
if (model!=null) {
buf.append("<a ").append(link(model)).append(">");
}
addImage(buf, imageSrcPath, imageWidth, imageHeight,
labelLeft);
if (model!=null) {
buf.append("</a>");
}
}
buf.append(label);
buf.append("</div>");
}
public static void addImage(StringBuffer buf, String imageSrcPath,
int imageWidth, int imageHeight, int labelLeft) {
StringBuffer imageStyle= new StringBuffer("border:none; position: absolute; ");
imageStyle.append("width: ").append(imageWidth).append("px; ");
imageStyle.append("height: ").append(imageHeight).append("px; ");
imageStyle.append("left: ").append(- labelLeft - 1).append("px; ");
// hack for broken transparent PNG support in IE 6, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=223900 :
buf.append("<!--[if lte IE 6]><![if gte IE 5.5]>\n");
//String tooltip= element == null ? "" : "alt='" + "Open Declaration" + "' ";
buf.append("<span ").append("style=\"").append(imageStyle)
.append("filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='")
.append(imageSrcPath).append("')\"></span>\n");
buf.append("<![endif]><![endif]-->\n");
buf.append("<!--[if !IE]>-->\n");
buf.append("<img ").append("style='").append(imageStyle).append("' src='")
.append(imageSrcPath).append("'/>\n");
buf.append("<!--<![endif]-->\n");
buf.append("<!--[if gte IE 7]>\n");
buf.append("<img ").append("style='").append(imageStyle).append("' src='")
.append(imageSrcPath).append("'/>\n");
buf.append("<![endif]-->\n");
}
private static String markdown(String text, final Scope linkScope, final Unit unit) {
if( text == null || text.length() == 0 ) {
return text;
}
// String unquotedText = text.substring(1, text.length()-1);
Builder builder = Configuration.builder().forceExtentedProfile();
builder.setCodeBlockEmitter(new CeylonBlockEmitter());
if (linkScope!=null) {
builder.setSpecialLinkEmitter(new SpanEmitter() {
@Override
public void emitSpan(StringBuilder out, String content) {
String linkName;
String linkTarget;
int indexOf = content.indexOf("|");
if( indexOf == -1 ) {
linkName = content;
linkTarget = content;
} else {
linkName = content.substring(0, indexOf);
linkTarget = content.substring(indexOf+1, content.length());
}
String href = resolveLink(linkTarget, linkScope, unit);
if (href != null) {
out.append("<a ").append(href).append(">");
}
out.append("<code>");
int sep = linkName.indexOf("::");
out.append(sep<0?linkName:linkName.substring(sep+2));
out.append("</code>");
if (href != null) {
out.append("</a>");
}
}
});
}
return Processor.process(text, builder.build());
}
private static String resolveLink(String linkTarget, Scope linkScope, Unit unit) {
String declName;
Scope scope = null;
int pkgSeparatorIndex = linkTarget.indexOf("::");
if( pkgSeparatorIndex == -1 ) {
declName = linkTarget;
scope = linkScope;
}
else {
String pkgName = linkTarget.substring(0, pkgSeparatorIndex);
declName = linkTarget.substring(pkgSeparatorIndex+2, linkTarget.length());
Module module = resolveModule(linkScope);
if( module != null ) {
scope = module.getPackage(pkgName);
}
}
if (scope==null || declName == null || "".equals(declName)) {
return null; // no point in continuing. Required for non-token auto-complete.
}
String[] declNames = declName.split("\\.");
Declaration decl = scope.getMemberOrParameter(unit, declNames[0], null, false);
for (int i=1; i<declNames.length; i++) {
if (decl instanceof Scope) {
scope = (Scope) decl;
decl = scope.getMember(declNames[i], null, false);
}
else {
decl = null;
break;
}
}
if (decl != null) {
String href = link(decl);
return href;
}
else {
return null;
}
}
private static Scope resolveScope(Declaration decl) {
if (decl == null) {
return null;
} else if (decl instanceof Scope) {
return (Scope) decl;
} else {
return decl.getContainer();
}
}
private static Module resolveModule(Scope scope) {
if (scope == null) {
return null;
} else if (scope instanceof Package) {
return ((Package) scope).getModule();
} else {
return resolveModule(scope.getContainer());
}
}
public static final class CeylonBlockEmitter implements BlockEmitter {
@Override
public void emitBlock(StringBuilder out, List<String> lines, String meta) {
if (!lines.isEmpty()) {
if (meta == null || meta.length() == 0) {
out.append("<pre>");
} else {
out.append("<pre class=\"brush: ").append(meta).append("\">");
}
StringBuilder code = new StringBuilder();
for (String s: lines) {
code.append(s).append('\n');
}
out.append(highlightLine(code.toString()));
out.append("</pre>\n");
}
}
}
public static String highlightLine(String line) {
String kwc = toHex(getCurrentThemeColor(KEYWORDS));
String tc = toHex(getCurrentThemeColor(TYPES));
String ic = toHex(getCurrentThemeColor(IDENTIFIERS));
String sc = toHex(getCurrentThemeColor(STRINGS));
String nc = toHex(getCurrentThemeColor(NUMBERS));
String cc = toHex(getCurrentThemeColor(CHARS));
String pc = toHex(getCurrentThemeColor(PACKAGES));
String lcc = toHex(getCurrentThemeColor(COMMENTS));
CeylonLexer lexer = new CeylonLexer(new ANTLRStringStream(line));
Token token;
boolean inPackageName = false;
StringBuilder result = new StringBuilder();
while ((token=lexer.nextToken()).getType()!=CeylonLexer.EOF) {
String s = convertToHTMLContent(token.getText());
int type = token.getType();
if (type!=CeylonLexer.LIDENTIFIER &&
type!=CeylonLexer.MEMBER_OP) {
inPackageName = false;
}
else if (inPackageName) {
result.append("<span style='color:"+pc+"'>").append(s).append("</span>");
continue;
}
switch (type) {
case CeylonLexer.FLOAT_LITERAL:
case CeylonLexer.NATURAL_LITERAL:
result.append("<span style='color:"+nc+"'>").append(s).append("</span>");
break;
case CeylonLexer.CHAR_LITERAL:
result.append("<span style='color:"+cc+"'>").append(s).append("</span>");
break;
case CeylonLexer.STRING_LITERAL:
case CeylonLexer.STRING_START:
case CeylonLexer.STRING_MID:
case CeylonLexer.VERBATIM_STRING:
result.append("<span style='color:"+sc+"'>").append(s).append("</span>");
break;
case CeylonLexer.UIDENTIFIER:
result.append("<span style='color:"+tc+"'>").append(s).append("</span>");
break;
case CeylonLexer.LIDENTIFIER:
result.append("<span style='color:"+ic+"'>").append(s).append("</span>");
break;
case CeylonLexer.MULTI_COMMENT:
case CeylonLexer.LINE_COMMENT:
result.append("<span style='color:"+lcc+"'>").append(s).append("</span>");
break;
case CeylonLexer.IMPORT:
case CeylonLexer.PACKAGE:
case CeylonLexer.MODULE:
inPackageName = true; //then fall through!
default:
if (CeylonTokenColorer.keywords.contains(s)) {
result.append("<span style='color:"+kwc+"'>").append(s).append("</span>");
}
else {
result.append(s);
}
}
}
return result.toString();
}
/**
* Creates the "enriched" control.
*/
private final class PresenterControlCreator extends AbstractReusableInformationControlCreator {
private final DocumentationHover docHover;
PresenterControlCreator(DocumentationHover docHover) {
this.docHover = docHover;
}
@Override
public IInformationControl doCreateInformationControl(Shell parent) {
if (isAvailable(parent)) {
ToolBarManager tbm = new ToolBarManager(SWT.FLAT);
BrowserInformationControl control = new BrowserInformationControl(parent,
APPEARANCE_JAVADOC_FONT, tbm);
final BackAction backAction = new BackAction(control);
backAction.setEnabled(false);
tbm.add(backAction);
final ForwardAction forwardAction = new ForwardAction(control);
tbm.add(forwardAction);
forwardAction.setEnabled(false);
//final ShowInJavadocViewAction showInJavadocViewAction= new ShowInJavadocViewAction(iControl);
//tbm.add(showInJavadocViewAction);
final OpenDeclarationAction openDeclarationAction = new OpenDeclarationAction(control);
tbm.add(openDeclarationAction);
// final SimpleSelectionProvider selectionProvider = new SimpleSelectionProvider();
//TODO: an action to open the generated ceylondoc
// from the doc archive, in a browser window
/*if (fSite != null) {
OpenAttachedJavadocAction openAttachedJavadocAction= new OpenAttachedJavadocAction(fSite);
openAttachedJavadocAction.setSpecialSelectionProvider(selectionProvider);
openAttachedJavadocAction.setImageDescriptor(DESC_ELCL_OPEN_BROWSER);
openAttachedJavadocAction.setDisabledImageDescriptor(DESC_DLCL_OPEN_BROWSER);
selectionProvider.addSelectionChangedListener(openAttachedJavadocAction);
selectionProvider.setSelection(new StructuredSelection());
tbm.add(openAttachedJavadocAction);
}*/
IInputChangedListener inputChangeListener = new IInputChangedListener() {
public void inputChanged(Object newInput) {
backAction.update();
forwardAction.update();
// if (newInput == null) {
// selectionProvider.setSelection(new StructuredSelection());
// }
// else
boolean isDeclaration = false;
if (newInput instanceof CeylonBrowserInput) {
// Object inputElement = ((CeylonBrowserInput) newInput).getInputElement();
// selectionProvider.setSelection(new StructuredSelection(inputElement));
//showInJavadocViewAction.setEnabled(isJavaElementInput);
isDeclaration = ((CeylonBrowserInput) newInput).getAddress()!=null;
}
openDeclarationAction.setEnabled(isDeclaration);
}
};
control.addInputChangeListener(inputChangeListener);
tbm.update(true);
docHover.addLinkListener(control);
return control;
}
else {
return new DefaultInformationControl(parent, true);
}
}
}
private final class HoverControlCreator extends AbstractReusableInformationControlCreator {
private final DocumentationHover docHover;
private String statusLineMessage;
private final IInformationControlCreator enrichedControlCreator;
HoverControlCreator(DocumentationHover docHover,
IInformationControlCreator enrichedControlCreator,
String statusLineMessage) {
this.docHover = docHover;
this.enrichedControlCreator = enrichedControlCreator;
this.statusLineMessage = statusLineMessage;
}
@Override
public IInformationControl doCreateInformationControl(Shell parent) {
if (enrichedControlCreator!=null && isAvailable(parent)) {
BrowserInformationControl control = new BrowserInformationControl(parent,
APPEARANCE_JAVADOC_FONT, statusLineMessage) {
@Override
public IInformationControlCreator getInformationPresenterControlCreator() {
return enrichedControlCreator;
}
};
if (docHover!=null) {
docHover.addLinkListener(control);
}
return control;
}
else {
return new DefaultInformationControl(parent, statusLineMessage);
}
}
}
} | fix #730, disable syntax highlighting when code block is not "ceylon" | plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/hover/DocumentationHover.java | fix #730, disable syntax highlighting when code block is not "ceylon" | <ide><path>lugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/hover/DocumentationHover.java
<ide> @Override
<ide> public void emitBlock(StringBuilder out, List<String> lines, String meta) {
<ide> if (!lines.isEmpty()) {
<del> if (meta == null || meta.length() == 0) {
<add> out.append("<pre>");
<add> /*if (meta == null || meta.length() == 0) {
<ide> out.append("<pre>");
<ide> } else {
<ide> out.append("<pre class=\"brush: ").append(meta).append("\">");
<del> }
<add> }*/
<ide> StringBuilder code = new StringBuilder();
<ide> for (String s: lines) {
<ide> code.append(s).append('\n');
<ide> }
<del> out.append(highlightLine(code.toString()));
<add> String highlighted;
<add> if (meta == null || meta.length() == 0 || "ceylon".equals(meta)) {
<add> highlighted = highlightLine(code.toString());
<add> }
<add> else {
<add> highlighted = code.toString();
<add> }
<add> out.append(highlighted);
<ide> out.append("</pre>\n");
<ide> }
<ide> } |
|
JavaScript | mit | 69748a5a162ae82319ebccf1eabff382fc826d14 | 0 | dsebastien/angularjs-webpack-starter,dsebastien/angularjs-webpack-starter,dsebastien/angularjs-webpack-starter | "use strict";
const fs = require("fs");
const path = require("path");
const seleniumFolder = "node_modules/protractor/selenium";
const seleniumFiles = fs.readdirSync(seleniumFolder);
let seleniumJarFile = "";
for(let i in seleniumFiles) {
if(path.extname(seleniumFiles[i]) === ".jar") {
seleniumJarFile = seleniumFiles[i];
break;
}
}
if(seleniumJarFile === null || seleniumJarFile === "") {
throw new Error("The Selenium jar file could not be located in ["+seleniumFolder+"]. Please make sure that Protactor is correctly installed!");
}
exports.config = {
baseUrl: "http://localhost:3000/",
// use `npm run e2e`
specs: [
"src/**/**.e2e.ts",
"src/**/*.e2e.ts"
],
exclude: [],
allScriptsTimeout: 110000,
framework: "jasmine",
jasmineNodeOpts: {
defaultTimeoutInterval: 600000,
showTiming: true,
showColors: true,
isVerbose: false,
includeStackTrace: false
},
capabilities: {
"browserName": "chrome",
"chromeOptions": {
"args": [
"show-fps-counter=true"
]
}
},
onPrepare: function () {
browser.ignoreSynchronization = true;
},
directConnect: true,
seleniumServerJar: seleniumJarFile
};
| protractor.conf.js | "use strict";
let fs = require("fs");
let path = require("path");
const seleniumFolder = "node_modules/protractor/selenium";
let seleniumFiles = fs.readdirSync(seleniumFolder);
let seleniumJarFile = "";
for(let i in seleniumFiles) {
if(path.extname(seleniumFiles[i]) === ".jar") {
seleniumJarFile = seleniumFiles[i];
break;
}
}
if(seleniumJarFile === null || seleniumJarFile === "") {
throw new Error("The Selenium jar file could not be located in ["+seleniumFolder+"]. Please make sure that Protactor is correctly installed!");
}
exports.config = {
baseUrl: "http://localhost:3000/",
// use `npm run e2e`
specs: [
"src/**/**.e2e.ts",
"src/**/*.e2e.ts"
],
exclude: [],
allScriptsTimeout: 110000,
framework: "jasmine",
jasmineNodeOpts: {
defaultTimeoutInterval: 600000,
showTiming: true,
showColors: true,
isVerbose: false,
includeStackTrace: false
},
capabilities: {
"browserName": "chrome",
"chromeOptions": {
"args": [
"show-fps-counter=true"
]
}
},
onPrepare: function () {
browser.ignoreSynchronization = true;
},
directConnect: true,
seleniumServerJar: seleniumJarFile
};
| let the const rule the place
| protractor.conf.js | let the const rule the place | <ide><path>rotractor.conf.js
<ide> "use strict";
<ide>
<del>let fs = require("fs");
<del>let path = require("path");
<add>const fs = require("fs");
<add>const path = require("path");
<ide>
<ide> const seleniumFolder = "node_modules/protractor/selenium";
<del>let seleniumFiles = fs.readdirSync(seleniumFolder);
<add>const seleniumFiles = fs.readdirSync(seleniumFolder);
<ide> let seleniumJarFile = "";
<ide> for(let i in seleniumFiles) {
<ide> if(path.extname(seleniumFiles[i]) === ".jar") {
<ide> if(seleniumJarFile === null || seleniumJarFile === "") {
<ide> throw new Error("The Selenium jar file could not be located in ["+seleniumFolder+"]. Please make sure that Protactor is correctly installed!");
<ide> }
<del>
<ide>
<ide> exports.config = {
<ide> baseUrl: "http://localhost:3000/", |
|
Java | apache-2.0 | 6c1a1abe0002018d282fb366b94b00ebb366de11 | 0 | davidmoten/RxJava,jbripley/RxJava,nurkiewicz/RxJava,AmberWhiteSky/RxJava,sunfei/RxJava,suclike/RxJava,pitatensai/RxJava,nkhuyu/RxJava,shekarrex/RxJava,hzysoft/RxJava,mattrjacobs/RxJava,aditya-chaturvedi/RxJava,Bobjoy/RxJava,yuhuayi/RxJava,devagul93/RxJava,frodoking/RxJava,ashwary/RxJava,picnic106/RxJava,Eagles2F/RxJava,HuangWenhuan0/RxJava,androidyue/RxJava,runt18/RxJava,rabbitcount/RxJava,simonbasle/RxJava,nurkiewicz/RxJava,randall-mo/RxJava,devagul93/RxJava,hyleung/RxJava,lncosie/RxJava,southwolf/RxJava,hyarlagadda/RxJava,sposam/RxJava,Ryan800/RxJava,onepavel/RxJava,xfumihiro/RxJava,nkhuyu/RxJava,YlJava110/RxJava,klemzy/RxJava,Turbo87/RxJava,zhongdj/RxJava,picnic106/RxJava,cloudbearings/RxJava,ppiech/RxJava,yuhuayi/RxJava,cgpllx/RxJava,hyarlagadda/RxJava,abersnaze/RxJava,sunfei/RxJava,ChenWenHuan/RxJava,jbripley/RxJava,lijunhuayc/RxJava,cloudbearings/RxJava,wlrhnh-David/RxJava,ppiech/RxJava,duqiao/RxJava,lncosie/RxJava,ReactiveX/RxJava,nvoron23/RxJava,hyleung/RxJava,duqiao/RxJava,Eagles2F/RxJava,abersnaze/RxJava,stevegury/RxJava,benjchristensen/RxJava,ypresto/RxJava,ayushnvijay/RxJava,Godchin1990/RxJava,ronenhamias/RxJava,simonbasle/RxJava,KevinTCoughlin/RxJava,rabbitcount/RxJava,suclike/RxJava,jbripley/RxJava,sposam/RxJava,Ribeiro/RxJava,Eagles2F/RxJava,pitatensai/RxJava,eduardotrandafilov/RxJava,mttkay/RxJava,AttwellBrian/RxJava,takecy/RxJava,randall-mo/RxJava,weikipeng/RxJava,wrightm/RxJava,ronenhamias/RxJava,jacek-rzrz/RxJava,AmberWhiteSky/RxJava,devisnik/RxJava,southwolf/RxJava,rabbitcount/RxJava,lijunhuayc/RxJava,msdgwzhy6/RxJava,ReactiveX/RxJava,ibaca/RxJava,marcogarcia23/RxJava,ibaca/RxJava,srayhunter/RxJava,zhongdj/RxJava,cgpllx/RxJava,b-cuts/RxJava,A-w-K/RxJava,java02014/RxJava,gjesse/RxJava,kuanghao/RxJava,jtulach/RxJava,mobilist/RxJava,Siddartha07/RxJava,lncosie/RxJava,klemzy/RxJava,xfumihiro/RxJava,HuangWenhuan0/RxJava,Siddartha07/RxJava,androidgilbert/RxJava,java02014/RxJava,devisnik/RxJava,yuhuayi/RxJava,ppiech/RxJava,NiteshKant/RxJava,takecy/RxJava,A-w-K/RxJava,Godchin1990/RxJava,kuanghao/RxJava,jacek-rzrz/RxJava,cloudbearings/RxJava,frodoking/RxJava,tilal6991/RxJava,ashwary/RxJava,spoon-bot/RxJava,sitexa/RxJava,onepavel/RxJava,tombujok/RxJava,ruhkopf/RxJava,southwolf/RxJava,marcogarcia23/RxJava,AttwellBrian/RxJava,ChenWenHuan/RxJava,zjrstar/RxJava,fjg1989/RxJava,gjesse/RxJava,sunfei/RxJava,ypresto/RxJava,Shedings/RxJava,shekarrex/RxJava,devisnik/RxJava,java02014/RxJava,wehjin/RxJava,cgpllx/RxJava,dromato/RxJava,Siddartha07/RxJava,mttkay/RxJava,nvoron23/RxJava,bboyfeiyu/RxJava,mattrjacobs/RxJava,Shedings/RxJava,shekarrex/RxJava,abersnaze/RxJava,forsail/RxJava,zsxwing/RxJava,wlrhnh-David/RxJava,ibaca/RxJava,sanxieryu/RxJava,tilal6991/RxJava,srayhunter/RxJava,davidmoten/RxJava,ChenWenHuan/RxJava,takecy/RxJava,picnic106/RxJava,ayushnvijay/RxJava,KevinTCoughlin/RxJava,eduardotrandafilov/RxJava,sposam/RxJava,TracyLu/RxJava,b-cuts/RxJava,bboyfeiyu/RxJava,puniverse/RxJava,androidyue/RxJava,androidgilbert/RxJava,puniverse/RxJava,maugomez77/RxJava,hyarlagadda/RxJava,zjrstar/RxJava,markrietveld/RxJava,tilal6991/RxJava,xfumihiro/RxJava,zjrstar/RxJava,ashwary/RxJava,runt18/RxJava,sitexa/RxJava,Ribeiro/RxJava,simonbasle/RxJava,elijah513/RxJava,artem-zinnatullin/RxJava,reactivex/rxjava,klemzy/RxJava,eduardotrandafilov/RxJava,elijah513/RxJava,androidyue/RxJava,duqiao/RxJava,ruhkopf/RxJava,hyleung/RxJava,jacek-rzrz/RxJava,dromato/RxJava,akarnokd/RxJava,sitexa/RxJava,NiteshKant/RxJava,randall-mo/RxJava,wlrhnh-David/RxJava,KevinTCoughlin/RxJava,Bobjoy/RxJava,ruhkopf/RxJava,vqvu/RxJava,pitatensai/RxJava,mttkay/RxJava,dromato/RxJava,mobilist/RxJava,YlJava110/RxJava,runt18/RxJava,TracyLu/RxJava,ypresto/RxJava,Turbo87/RxJava,stevegury/RxJava,wehjin/RxJava,Shedings/RxJava,akarnokd/RxJava,weikipeng/RxJava,nkhuyu/RxJava,reactivex/rxjava,msdgwzhy6/RxJava,Ryan800/RxJava,Ryan800/RxJava,devagul93/RxJava,fjg1989/RxJava,hzysoft/RxJava,onepavel/RxJava,hzysoft/RxJava,jtulach/RxJava,sanxieryu/RxJava,kuanghao/RxJava,YlJava110/RxJava,forsail/RxJava,A-w-K/RxJava,wrightm/RxJava,abersnaze/RxJava,tombujok/RxJava,Godchin1990/RxJava,spoon-bot/RxJava,aditya-chaturvedi/RxJava,nvoron23/RxJava,zsxwing/RxJava,maugomez77/RxJava,wrightm/RxJava,vqvu/RxJava,ronenhamias/RxJava,suclike/RxJava,davidmoten/RxJava,maugomez77/RxJava,mattrjacobs/RxJava,vqvu/RxJava,gjesse/RxJava,elijah513/RxJava,ayushnvijay/RxJava,frodoking/RxJava,markrietveld/RxJava,markrietveld/RxJava,srayhunter/RxJava,artem-zinnatullin/RxJava,aditya-chaturvedi/RxJava,devisnik/RxJava,AmberWhiteSky/RxJava,androidgilbert/RxJava,zsxwing/RxJava,b-cuts/RxJava,weikipeng/RxJava,nurkiewicz/RxJava,Bobjoy/RxJava,stevegury/RxJava,sanxieryu/RxJava,puniverse/RxJava,msdgwzhy6/RxJava,lijunhuayc/RxJava,Turbo87/RxJava,wehjin/RxJava,HuangWenhuan0/RxJava,TracyLu/RxJava,zhongdj/RxJava,marcogarcia23/RxJava,forsail/RxJava,fjg1989/RxJava,Ribeiro/RxJava,tombujok/RxJava | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.operators;
import org.junit.Test;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.subscriptions.Subscriptions;
import rx.util.AtomicObservableSubscription;
import rx.util.functions.Func1;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static rx.testing.TrustedObservableTester.assertTrustedObservable;
/**
* Returns a specified number of contiguous values from the start of an observable sequence.
*/
public final class OperationTake {
/**
* Returns a specified number of contiguous values from the start of an observable sequence.
*
* @param items
* @param num
* @return
*/
public static <T> Func1<Observer<T>, Subscription> take(final Observable<T> items, final int num) {
// wrap in a Func so that if a chain is built up, then asynchronously subscribed to twice we will have 2 instances of Take<T> rather than 1 handing both, which is not thread-safe.
return new Func1<Observer<T>, Subscription>() {
@Override
public Subscription call(Observer<T> observer) {
return new Take<T>(items, num).call(observer);
}
};
}
/**
* This class is NOT thread-safe if invoked and referenced multiple times. In other words, don't subscribe to it multiple times from different threads.
* <p>
* It IS thread-safe from within it while receiving onNext events from multiple threads.
* <p>
* This should all be fine as long as it's kept as a private class and a new instance created from static factory method above.
* <p>
* Note how the take() factory method above protects us from a single instance being exposed with the Observable wrapper handling the subscribe flow.
*
* @param <T>
*/
private static class Take<T> implements Func1<Observer<T>, Subscription> {
private final AtomicInteger counter = new AtomicInteger();
private final Observable<T> items;
private final int num;
private final AtomicObservableSubscription subscription = new AtomicObservableSubscription();
private Take(Observable<T> items, int num) {
this.items = items;
this.num = num;
}
@Override
public Subscription call(Observer<T> observer) {
if (num < 1) {
items.subscribe(new Observer<T>()
{
@Override
public void onCompleted()
{
}
@Override
public void onError(Exception e)
{
}
@Override
public void onNext(T args)
{
}
}).unsubscribe();
observer.onCompleted();
return Subscriptions.empty();
}
return subscription.wrap(items.subscribe(new ItemObserver(observer)));
}
private class ItemObserver implements Observer<T> {
private final Observer<T> observer;
public ItemObserver(Observer<T> observer) {
this.observer = observer;
}
@Override
public void onCompleted() {
if (counter.getAndSet(num) < num) {
observer.onCompleted();
}
}
@Override
public void onError(Exception e) {
if (counter.getAndSet(num) < num) {
observer.onError(e);
}
}
@Override
public void onNext(T args) {
final int count = counter.incrementAndGet();
if (count <= num) {
observer.onNext(args);
if (count == num) {
observer.onCompleted();
}
}
if (count >= num) {
// this will work if the sequence is asynchronous, it will have no effect on a synchronous observable
subscription.unsubscribe();
}
}
}
}
public static class UnitTest {
@Test
public void testTake1() {
Observable<String> w = Observable.toObservable("one", "two", "three");
Observable<String> take = Observable.create(assertTrustedObservable(take(w, 2)));
@SuppressWarnings("unchecked")
Observer<String> aObserver = mock(Observer.class);
take.subscribe(aObserver);
verify(aObserver, times(1)).onNext("one");
verify(aObserver, times(1)).onNext("two");
verify(aObserver, never()).onNext("three");
verify(aObserver, never()).onError(any(Exception.class));
verify(aObserver, times(1)).onCompleted();
}
@Test
public void testTake2() {
Observable<String> w = Observable.toObservable("one", "two", "three");
Observable<String> take = Observable.create(assertTrustedObservable(take(w, 1)));
@SuppressWarnings("unchecked")
Observer<String> aObserver = mock(Observer.class);
take.subscribe(aObserver);
verify(aObserver, times(1)).onNext("one");
verify(aObserver, never()).onNext("two");
verify(aObserver, never()).onNext("three");
verify(aObserver, never()).onError(any(Exception.class));
verify(aObserver, times(1)).onCompleted();
}
@Test
public void testTakeDoesntLeakErrors() {
Observable<String> source = Observable.create(new Func1<Observer<String>, Subscription>()
{
@Override
public Subscription call(Observer<String> observer)
{
observer.onNext("one");
observer.onError(new Exception("test failed"));
return Subscriptions.empty();
}
});
Observable.create(assertTrustedObservable(take(source, 1))).last();
}
@Test
public void testTakeZeroDoesntLeakError() {
final AtomicBoolean subscribed = new AtomicBoolean(false);
final AtomicBoolean unSubscribed = new AtomicBoolean(false);
Observable<String> source = Observable.create(new Func1<Observer<String>, Subscription>()
{
@Override
public Subscription call(Observer<String> observer)
{
subscribed.set(true);
observer.onError(new Exception("test failed"));
return new Subscription()
{
@Override
public void unsubscribe()
{
unSubscribed.set(true);
}
};
}
});
Observable.create(assertTrustedObservable(take(source, 0))).lastOrDefault("ok");
assertTrue("source subscribed", subscribed.get());
assertTrue("source unsubscribed", unSubscribed.get());
}
@Test
public void testUnsubscribeAfterTake() {
Subscription s = mock(Subscription.class);
TestObservable w = new TestObservable(s, "one", "two", "three");
@SuppressWarnings("unchecked")
Observer<String> aObserver = mock(Observer.class);
Observable<String> take = Observable.create(assertTrustedObservable(take(w, 1)));
take.subscribe(aObserver);
// wait for the Observable to complete
try {
w.t.join();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
System.out.println("TestObservable thread finished");
verify(aObserver, times(1)).onNext("one");
verify(aObserver, never()).onNext("two");
verify(aObserver, never()).onNext("three");
verify(s, times(1)).unsubscribe();
}
private static class TestObservable extends Observable<String> {
final Subscription s;
final String[] values;
Thread t = null;
public TestObservable(Subscription s, String... values) {
this.s = s;
this.values = values;
}
@Override
public Subscription subscribe(final Observer<String> observer) {
System.out.println("TestObservable subscribed to ...");
t = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("running TestObservable thread");
for (String s : values) {
System.out.println("TestObservable onNext: " + s);
observer.onNext(s);
}
observer.onCompleted();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
System.out.println("starting TestObservable thread");
t.start();
System.out.println("done starting TestObservable thread");
return s;
}
}
}
}
| rxjava-core/src/main/java/rx/operators/OperationTake.java | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.operators;
import org.junit.Test;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.subscriptions.Subscriptions;
import rx.util.AtomicObservableSubscription;
import rx.util.functions.Func1;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static rx.testing.TrustedObservableTester.assertTrustedObservable;
/**
* Returns a specified number of contiguous values from the start of an observable sequence.
*/
public final class OperationTake {
/**
* Returns a specified number of contiguous values from the start of an observable sequence.
*
* @param items
* @param num
* @return
*/
public static <T> Func1<Observer<T>, Subscription> take(final Observable<T> items, final int num) {
// wrap in a Func so that if a chain is built up, then asynchronously subscribed to twice we will have 2 instances of Take<T> rather than 1 handing both, which is not thread-safe.
return new Func1<Observer<T>, Subscription>() {
@Override
public Subscription call(Observer<T> observer) {
return new Take<T>(items, num).call(observer);
}
};
}
/**
* This class is NOT thread-safe if invoked and referenced multiple times. In other words, don't subscribe to it multiple times from different threads.
* <p>
* It IS thread-safe from within it while receiving onNext events from multiple threads.
* <p>
* This should all be fine as long as it's kept as a private class and a new instance created from static factory method above.
* <p>
* Note how the take() factory method above protects us from a single instance being exposed with the Observable wrapper handling the subscribe flow.
*
* @param <T>
*/
private static class Take<T> implements Func1<Observer<T>, Subscription> {
private final AtomicInteger counter = new AtomicInteger();
private final Observable<T> items;
private final int num;
private final AtomicObservableSubscription subscription = new AtomicObservableSubscription();
private Take(Observable<T> items, int num) {
this.items = items;
this.num = num;
}
@Override
public Subscription call(Observer<T> observer) {
if (num < 1) {
observer.onCompleted();
return Subscriptions.empty();
}
return subscription.wrap(items.subscribe(new ItemObserver(observer)));
}
private class ItemObserver implements Observer<T> {
private final Observer<T> observer;
public ItemObserver(Observer<T> observer) {
this.observer = observer;
}
@Override
public void onCompleted() {
if (counter.getAndSet(num) < num) {
observer.onCompleted();
}
}
@Override
public void onError(Exception e) {
if (counter.getAndSet(num) < num) {
observer.onError(e);
}
}
@Override
public void onNext(T args) {
final int count = counter.incrementAndGet();
if (count <= num) {
observer.onNext(args);
if (count == num) {
observer.onCompleted();
}
}
if (count >= num) {
// this will work if the sequence is asynchronous, it will have no effect on a synchronous observable
subscription.unsubscribe();
}
}
}
}
public static class UnitTest {
@Test
public void testTake1() {
Observable<String> w = Observable.toObservable("one", "two", "three");
Observable<String> take = Observable.create(assertTrustedObservable(take(w, 2)));
@SuppressWarnings("unchecked")
Observer<String> aObserver = mock(Observer.class);
take.subscribe(aObserver);
verify(aObserver, times(1)).onNext("one");
verify(aObserver, times(1)).onNext("two");
verify(aObserver, never()).onNext("three");
verify(aObserver, never()).onError(any(Exception.class));
verify(aObserver, times(1)).onCompleted();
}
@Test
public void testTake2() {
Observable<String> w = Observable.toObservable("one", "two", "three");
Observable<String> take = Observable.create(assertTrustedObservable(take(w, 1)));
@SuppressWarnings("unchecked")
Observer<String> aObserver = mock(Observer.class);
take.subscribe(aObserver);
verify(aObserver, times(1)).onNext("one");
verify(aObserver, never()).onNext("two");
verify(aObserver, never()).onNext("three");
verify(aObserver, never()).onError(any(Exception.class));
verify(aObserver, times(1)).onCompleted();
}
@Test
public void testTakeDoesntLeakErrors() {
Observable<String> source = Observable.create(new Func1<Observer<String>, Subscription>()
{
@Override
public Subscription call(Observer<String> observer)
{
observer.onNext("one");
observer.onError(new Exception("test failed"));
return Subscriptions.empty();
}
});
Observable.create(assertTrustedObservable(take(source, 1))).last();
}
@Test
public void testTakeZeroDoesntLeakError() {
Observable<String> source = Observable.error(new Exception("test failed"));
Observable.create(assertTrustedObservable(take(source, 0))).lastOrDefault("ok");
}
@Test
public void testUnsubscribeAfterTake() {
Subscription s = mock(Subscription.class);
TestObservable w = new TestObservable(s, "one", "two", "three");
@SuppressWarnings("unchecked")
Observer<String> aObserver = mock(Observer.class);
Observable<String> take = Observable.create(assertTrustedObservable(take(w, 1)));
take.subscribe(aObserver);
// wait for the Observable to complete
try {
w.t.join();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
System.out.println("TestObservable thread finished");
verify(aObserver, times(1)).onNext("one");
verify(aObserver, never()).onNext("two");
verify(aObserver, never()).onNext("three");
verify(s, times(1)).unsubscribe();
}
private static class TestObservable extends Observable<String> {
final Subscription s;
final String[] values;
Thread t = null;
public TestObservable(Subscription s, String... values) {
this.s = s;
this.values = values;
}
@Override
public Subscription subscribe(final Observer<String> observer) {
System.out.println("TestObservable subscribed to ...");
t = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("running TestObservable thread");
for (String s : values) {
System.out.println("TestObservable onNext: " + s);
observer.onNext(s);
}
observer.onCompleted();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
System.out.println("starting TestObservable thread");
t.start();
System.out.println("done starting TestObservable thread");
return s;
}
}
}
}
| take(0) subscribes to its source
| rxjava-core/src/main/java/rx/operators/OperationTake.java | take(0) subscribes to its source | <ide><path>xjava-core/src/main/java/rx/operators/OperationTake.java
<ide> import rx.util.AtomicObservableSubscription;
<ide> import rx.util.functions.Func1;
<ide>
<add>import java.util.concurrent.atomic.AtomicBoolean;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<add>import static org.junit.Assert.assertTrue;
<ide> import static org.junit.Assert.fail;
<ide> import static org.mockito.Matchers.any;
<ide> import static org.mockito.Mockito.mock;
<ide> @Override
<ide> public Subscription call(Observer<T> observer) {
<ide> if (num < 1) {
<add> items.subscribe(new Observer<T>()
<add> {
<add> @Override
<add> public void onCompleted()
<add> {
<add> }
<add>
<add> @Override
<add> public void onError(Exception e)
<add> {
<add> }
<add>
<add> @Override
<add> public void onNext(T args)
<add> {
<add> }
<add> }).unsubscribe();
<ide> observer.onCompleted();
<ide> return Subscriptions.empty();
<ide> }
<ide>
<ide> @Test
<ide> public void testTakeZeroDoesntLeakError() {
<del> Observable<String> source = Observable.error(new Exception("test failed"));
<add> final AtomicBoolean subscribed = new AtomicBoolean(false);
<add> final AtomicBoolean unSubscribed = new AtomicBoolean(false);
<add> Observable<String> source = Observable.create(new Func1<Observer<String>, Subscription>()
<add> {
<add> @Override
<add> public Subscription call(Observer<String> observer)
<add> {
<add> subscribed.set(true);
<add> observer.onError(new Exception("test failed"));
<add> return new Subscription()
<add> {
<add> @Override
<add> public void unsubscribe()
<add> {
<add> unSubscribed.set(true);
<add> }
<add> };
<add> }
<add> });
<ide> Observable.create(assertTrustedObservable(take(source, 0))).lastOrDefault("ok");
<add> assertTrue("source subscribed", subscribed.get());
<add> assertTrue("source unsubscribed", unSubscribed.get());
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | e141d720598629f9081e445eefae72ef82aed6ea | 0 | andrewinblue/nebulae,andrewinblue/nebulae | package com.nebuale.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ConsoleApplicationTests {
@Test
public void contextLoads() {
System.out.println("Test Message 01");
}
@Test
public void testMethod02() {
System.out.println("Test message 02");
}
}
| src/test/java/com/nebuale/web/ConsoleApplicationTests.java | package com.nebuale.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ConsoleApplicationTests {
@Test
public void contextLoads() {
System.out.println("Test Message 01");
}
@Test
public void testMethod02() {
}
}
| andrche added new test message
| src/test/java/com/nebuale/web/ConsoleApplicationTests.java | andrche added new test message | <ide><path>rc/test/java/com/nebuale/web/ConsoleApplicationTests.java
<ide>
<ide> @Test
<ide> public void testMethod02() {
<add> System.out.println("Test message 02");
<ide> }
<ide>
<ide> } |
|
Java | mpl-2.0 | 4bd9883bb51cfd58fda3a84fd9bd5c3a396a6f80 | 0 | pamval/cfr,pamval/cfr,diogofscmariano/cfr,davidmsantos90/cfr,webdetails/cfr,jvelasques/cfr,jvelasques/cfr,bluezio/cfr,bluezio/cfr,davidmsantos90/cfr,diogofscmariano/cfr,webdetails/cfr | /*!
* Copyright 2002 - 2013 Webdetails, a Pentaho company. All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package pt.webdetails.cfr;
import java.io.*;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import pt.webdetails.cfr.auth.FilePermissionEnum;
import pt.webdetails.cfr.auth.FilePermissionMetadata;
import pt.webdetails.cfr.file.CfrFile;
import pt.webdetails.cfr.file.FileStorer;
import pt.webdetails.cfr.file.IFile;
import pt.webdetails.cfr.file.MetadataReader;
import pt.webdetails.cfr.repository.IFileRepository;
import pt.webdetails.cpf.InvalidOperationException;
import pt.webdetails.cpf.persistence.PersistenceEngine;
import pt.webdetails.cpf.utils.CharsetHelper;
import pt.webdetails.cpf.VersionChecker;
import pt.webdetails.cpf.utils.MimeTypes;
import com.sun.jersey.multipart.FormDataParam;
import com.sun.jersey.core.header.FormDataContentDisposition;
@Path( "cfr/api" )
public class CfrApi {
private static final Log logger = LogFactory.getLog( CfrApi.class );
private CfrService service = new CfrService();
private MetadataReader mr = new MetadataReader( service );
private static final String UI_PATH = "cfr/presentation/";
static String checkRelativePathSanity( String path ) {
String result = path;
if ( path != null ) {
if ( result.startsWith( "./" ) ) {
result = result.replaceFirst( "./", "" );
}
if ( result.startsWith( "." ) ) {
result = result.replaceFirst( ".", "" );
}
if ( result.startsWith( "/" ) ) {
result = result.replaceFirst( "/", "" );
}
if ( result.endsWith( "/" ) ) {
result = result.substring( 0, result.length() - 1 );
}
}
return result;
}
static String relativeFilePath( String baseDir, String file ) {
String _baseDir = checkRelativePathSanity( baseDir );
String _file = checkRelativePathSanity( file );
String result = null;
if ( _baseDir == null || _baseDir.length() == 0 ) {
return _file;
} else {
if ( _baseDir.endsWith( "/" ) ) {
result = new StringBuilder( _baseDir ).append( _file ).toString();
} else {
result = new StringBuilder( _baseDir ).append( '/' ).append( _file ).toString();
}
}
return result;
}
@GET
@Path( "/home" )
public void home( @Context HttpServletRequest request,
@Context HttpServletResponse response ) throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
params.put( "solution", "system" );
params.put( "path", "cfr/presentation/" );
params.put( "file", "cfr.wcdf" );
params.put( "absolute", "false" );
params.put( "inferScheme", "false" );
if ( Boolean.parseBoolean( request.getParameter( "debug" ) ) ) {
params.put( "debug", "true" );
}
renderInCde( response, params );
}
@GET
@Path( "/createFolder" )
public void createFolder( @Context HttpServletRequest request,
@Context HttpServletResponse response ) throws Exception {
String path = checkRelativePathSanity( getParameter( "path", request ) );
if ( path == null || StringUtils.isBlank( path ) ) {
throw new Exception( "path is null or empty" );
}
boolean createResult = service.getRepository().createFolder( path );
writeMessage( new JSONObject().put( "result", createResult ).toString(), response.getOutputStream() );
}
@POST
@Path( "/remove" )
public void remove( @Context HttpServletRequest request, @Context HttpServletResponse response ) throws Exception {
String fullFileName =
checkRelativePathSanity( getParameter( "fileName", request ) );
if ( fullFileName == null || StringUtils.isBlank( fullFileName ) ) {
throw new Exception( "fileName is null or empty" );
}
boolean removeResult = service.getRepository().deleteFile( fullFileName );
boolean result = false;
if ( removeResult ) {
FileStorer.deletePermissions( fullFileName, null );
result = FileStorer.removeFile( fullFileName, null );
}
writeMessage( new JSONObject().put( "result", result ).toString(), response.getOutputStream() );
}
@POST
@Path( "/store" )
@Consumes( "multipart/form-data" )
public void store( @FormDataParam( "file" ) InputStream uploadedInputStream,
@FormDataParam( "file" ) FormDataContentDisposition fileDetail,
@FormDataParam( "path" ) String path,
@Context HttpServletRequest request, @Context HttpServletResponse response )
throws IOException, InvalidOperationException, Exception {
String fileName = fileDetail.getFileName(), savePath = path;
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
IOUtils.copy( uploadedInputStream, oStream );
oStream.flush();
byte[] contents = oStream.toByteArray();
oStream.close();
if ( fileName == null ) {
logger.error( "parameter fileName must not be null" );
throw new Exception( "parameter fileName must not be null" );
}
if ( savePath == null ) {
logger.error( "parameter path must not be null" );
throw new Exception( "parameter path must not be null" );
}
if ( contents == null ) {
logger.error( "File content must not be null" );
throw new Exception( "File content must not be null" );
}
FileStorer fileStorer = new FileStorer( service.getRepository() );
boolean stored =
fileStorer
.storeFile( checkRelativePathSanity( fileName ), checkRelativePathSanity( savePath ), contents,
service.getCurrentUserName() );
JSONObject result = new JSONObject().put( "result", stored );
writeMessage( result.toString(), response.getOutputStream() );
}
@POST
@Path( "/listFiles" )
public void listFiles( @FormParam( "dir" ) @DefaultValue( "" ) String baseDir,
@Context HttpServletRequest request, @Context HttpServletResponse response )
throws IOException {
//String baseDir = URLDecoder.decode( getParameter( "dir", request ), "ISO-8859-1" );
IFile[] files = service.getRepository().listFiles( baseDir );
List<IFile> allowedFiles = new ArrayList<IFile>( files.length );
String extensions = getParameter( "fileExtensions", request );
// checks permissions
/*
* remarks: ideally the repository must list only the files that the current user is allowed to access?
*/
for ( IFile file : files ) {
String relativePath = relativeFilePath( baseDir, file.getName() );
if ( mr.isCurrentUserAllowed( FilePermissionEnum.READ, relativePath ) ) {
allowedFiles.add( file );
}
}
String[] exts = null;
if ( !StringUtils.isBlank( extensions ) ) {
exts = extensions.split( " " );
}
IFile[] allowedFilesArray = new IFile[ allowedFiles.size() ];
response.setContentType( MimeTypes.HTML );
writeMessage( toJQueryFileTree( baseDir, allowedFiles.toArray( allowedFilesArray ), exts ),
response.getOutputStream() );
}
@GET
@Path( "/getFile" )
public void getFile( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws IOException, JSONException, Exception {
String fullFileName = checkRelativePathSanity( getParameter( "fileName", null, request ) );
if ( fullFileName == null ) {
logger.error( "request query parameter fileName must not be null" );
throw new Exception( "request query parameter fileName must not be null" );
}
if ( mr.isCurrentUserAllowed( FilePermissionEnum.READ, fullFileName ) ) {
CfrFile file = service.getRepository().getFile( fullFileName );
setResponseHeaders( getMimeType( file.getFileName() ), -1, URLEncoder.encode( file.getFileName(),
CharsetHelper.getEncoding() ), response );
ByteArrayInputStream bais = new ByteArrayInputStream( file.getContent() );
IOUtils.copy( bais, response.getOutputStream() );
response.getOutputStream().flush();
IOUtils.closeQuietly( bais );
} else {
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "you don't have permissions to access the file" );
}
}
@GET
@Path( "/viewFile" )
public void viewFile( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws Exception {
String fullFileName =
checkRelativePathSanity( getParameter( "fileName", null, request ) );
if ( fullFileName == null ) {
logger.error( "request query parameter fileName must not be null" );
throw new Exception( "request query parameter fileName must not be null" );
}
if ( mr.isCurrentUserAllowed( FilePermissionEnum.READ, fullFileName ) ) {
CfrFile file = service.getRepository().getFile( fullFileName );
setResponseHeaders( getMimeType( file.getFileName() ), -1, null, response );
ByteArrayInputStream bais = new ByteArrayInputStream( file.getContent() );
IOUtils.copy( bais, response.getOutputStream() );
response.getOutputStream().flush();
IOUtils.closeQuietly( bais );
} else {
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "you don't have permissions to access the file" );
}
}
@GET
@Path( "/listFilesJson" )
public void listFilesJSON( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws IOException, JSONException {
String baseDir = checkRelativePathSanity( getParameter( "dir", request ) );
IFile[] files = service.getRepository().listFiles( baseDir );
JSONArray arr = new JSONArray();
if ( files != null ) {
for ( IFile file : files ) {
if ( mr.isCurrentUserAllowed( FilePermissionEnum.READ, relativeFilePath( baseDir, file.getName() ) ) ) {
JSONObject obj = new JSONObject();
obj.put( "fileName", file.getName() );
obj.put( "isDirectory", file.isDirectory() );
obj.put( "path", baseDir );
arr.put( obj );
}
}
}
writeMessage( arr.toString( 2 ), response.getOutputStream() );
}
@GET
@Path( "/listUploads" )
public void listUploads( @Context HttpServletRequest request,
@Context HttpServletResponse response )
throws IOException, JSONException {
String path = checkRelativePathSanity( getParameter( "fileName", request ) );
writeMessage( mr.listFiles( path, getParameter( "user", request ), getParameter( "startDate", request ),
getParameter( "endDate", request ) ).toString(), response.getOutputStream() );
}
@GET
@Path( "/listUploadsFlat" )
public void listUploadsFlat( @Context HttpServletRequest request,
@Context HttpServletResponse response )
throws IOException, JSONException {
String path = checkRelativePathSanity( getParameter( "fileName", request ) );
writeMessage( mr.listFilesFlat( path, getParameter( "user", request ), getParameter( "startDate", request ),
getParameter( "endDate", request ) ).toString(), response.getOutputStream() );
}
private static String toJQueryFileTree( String baseDir, IFile[] files, String[] extensions ) {
StringBuilder out = new StringBuilder();
out.append( "<ul class=\"jqueryFileTree\" style=\"display: none;\">" );
for ( IFile file : files ) {
if ( file.isDirectory() ) {
out.append( "<li class=\"directory collapsed\"><a href=\"#\" rel=\"" + baseDir + file.getName() + "/\">"
+ file.getName() + "</a></li>" );
}
}
for ( IFile file : files ) {
if ( !file.isDirectory() ) {
int dotIndex = file.getName().lastIndexOf( '.' );
String ext = dotIndex > 0 ? file.getName().substring( dotIndex + 1 ) : "";
boolean accepted = ext.equals( "" );
if ( !ext.equals( "" ) ) {
if ( extensions == null || extensions.length == 0 ) {
accepted = true;
} else {
for ( String acceptedExtension : extensions ) {
if ( ext.equals( acceptedExtension ) ) {
accepted = true;
break;
}
}
}
}
if ( accepted ) {
out.append( "<li class=\"file ext_" + ext + "\"><a href=\"#\" rel=\"" + baseDir + file.getName() + "\">"
+ file.getName() + "</a></li>" );
}
}
}
out.append( "</ul>" );
return out.toString();
}
@GET
@Path( "/setPermissions" )
public void setPermissions( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws JSONException, IOException {
String path = checkRelativePathSanity( getParameter( pathParameterPath, null, request ) );
String[] userOrGroupId = getStringArrayParameter( pathParameterGroupOrUserId, request );
String[] _permissions = getStringArrayParameter( pathParameterPermission, request );
boolean recursive = Boolean.parseBoolean( getParameter( pathParameterRecursive, "false", request ) );
JSONObject result = new JSONObject();
if ( path != null && userOrGroupId.length > 0 && _permissions.length > 0 ) {
List<String> files = new ArrayList<String>();
if ( recursive ) {
files = getFileNameTree( path );
} else {
files.add( path );
}
// build valid permissions set
Set<FilePermissionEnum> validPermissions = new TreeSet<FilePermissionEnum>();
for ( String permission : _permissions ) {
FilePermissionEnum perm = FilePermissionEnum.resolve( permission );
if ( perm != null ) {
validPermissions.add( perm );
}
}
JSONArray permissionAddResultArray = new JSONArray();
for ( String file : files ) {
for ( String id : userOrGroupId ) {
JSONObject individualResult = new JSONObject();
boolean storeResult =
FileStorer.storeFilePermissions( new FilePermissionMetadata( file, id, validPermissions ) );
if ( storeResult ) {
individualResult
.put( "status", String.format( "Added permission for path %s and user/role %s", file, id ) );
} else {
individualResult
.put( "status", String.format( "Failed to add permission for path %s and user/role %s", file,
id ) );
}
permissionAddResultArray.put( individualResult );
}
}
result.put( "status", "Operation finished. Check statusArray for details." );
result.put( "statusArray", permissionAddResultArray );
} else {
result.put( "status", "Path or user group parameters not found" );
}
writeMessage( result.toString( 2 ), response.getOutputStream() );
}
@GET
@Path( "/deletePermissions" )
public void deletePermissions( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws JSONException, IOException {
String path = checkRelativePathSanity( getParameter( pathParameterPath, null, request ) );
String[] userOrGroupId = getStringArrayParameter( pathParameterGroupOrUserId, request );
JSONObject result = new JSONObject();
if ( path != null || ( userOrGroupId != null && userOrGroupId.length > 0 ) ) {
if ( userOrGroupId == null || userOrGroupId.length == 0 ) {
if ( FileStorer.deletePermissions( path, null ) ) {
result.put( "status", "Permissions deleted" );
} else {
result.put( "status", "Error deleting permissions" );
}
} else {
JSONArray permissionDeleteResultArray = new JSONArray();
for ( String id : userOrGroupId ) {
JSONObject individualResult = new JSONObject();
boolean deleteResult = FileStorer.deletePermissions( path, id );
if ( deleteResult ) {
individualResult.put( "status", String.format( "Permission for %s and path %s deleted.", id, path ) );
} else {
individualResult
.put( "status", String.format( "Failed to delete permission for %s and path %s.", id, path ) );
}
permissionDeleteResultArray.put( individualResult );
}
result.put( "status", "Multiple permission deletion. Check Status array" );
result.put( "statusArray", permissionDeleteResultArray );
}
} else {
result.put( "status", "Required arguments user/role and path not found" );
}
writeMessage( result.toString( 2 ), response.getOutputStream() );
}
@GET
@Path( "/getPermissions" )
public void getPermissions( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws IOException, JSONException {
String path = checkRelativePathSanity( getParameter( pathParameterPath, null, request ) );
String id = getParameter( pathParameterGroupOrUserId, null, request );
if ( path != null || id != null ) {
JSONArray permissions = mr.getPermissions( path, id, FilePermissionMetadata.DEFAULT_PERMISSIONS );
writeMessage( permissions.toString( 0 ), response.getOutputStream() );
}
}
@GET
@Path( "/resetRepository" )
public String resetRepository() {
if ( !this.service.isCurrentUserAdmin() ) {
logger.warn( "Reset repository called by a non admin user. Aborting" );
return "User has no access to this endpoint";
}
PersistenceEngine.getInstance().dropClass( FileStorer.FILE_METADATA_STORE_CLASS );
PersistenceEngine.getInstance().initializeClass( FileStorer.FILE_METADATA_STORE_CLASS );
PersistenceEngine.getInstance().dropClass( FileStorer.FILE_PERMISSIONS_METADATA_STORE_CLASS );
PersistenceEngine.getInstance().initializeClass( FileStorer.FILE_PERMISSIONS_METADATA_STORE_CLASS );
IFileRepository repo = new CfrService().getRepository();
for ( IFile file : repo.listFiles( "" ) ) {
repo.deleteFile( file.getFullPath() );
}
return "Repository Reset complete";
}
private static final String pathParameterGroupOrUserId = "id";
private static final String pathParameterPath = "path";
private static final String pathParameterPermission = "permission";
private static final String pathParameterRecursive = "recursive";
@GET
@Path( "/checkVersion" )
public void checkVersion( @Context HttpServletResponse response ) throws IOException, JSONException {
writeMessage( getVersionChecker().checkVersion().toJSON().toString(), response.getOutputStream() );
}
@GET
@Path( "/getVersion" )
public void getVersion( @Context HttpServletResponse response ) throws IOException, JSONException {
writeMessage( getVersionChecker().getVersion(), response.getOutputStream() );
}
@GET
@Path( "/about" )
public void about( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws Exception {
renderInCde( response, getRenderRequestParameters( "cfrAbout.wcdf", request ) );
}
@GET
@Path( "/browser" )
public void browser( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws Exception {
renderInCde( response, getRenderRequestParameters( "cfrBrowser.wcdf", request ) );
}
public VersionChecker getVersionChecker() {
return new VersionChecker( new CfrPluginSettings() ) {
@Override
protected String getVersionCheckUrl( VersionChecker.Branch branch ) {
switch( branch ) {
case TRUNK:
return "http://ci.pentaho.com/job/pentaho-cfr/lastSuccessfulBuild/artifact/cfr-pentaho5/dist/marketplace.xml";
// case STABLE:
// return "http://ci.analytical-labs.com/job/Webdetails-CFR-Release/"
// + "lastSuccessfulBuild/artifact/dist/marketplace.xml";
default:
return null;
}
}
};
}
private void renderInCde( HttpServletResponse response, Map<String, Object> params ) throws Exception {
InterPluginBroker.run( params, response.getOutputStream() );
}
private Map<String, Object> getRenderRequestParameters( String dashboardName, HttpServletRequest request ) {
Map<String, Object> params = new HashMap<String, Object>();
params.put( "solution", "system" );
params.put( "path", UI_PATH );
params.put( "file", dashboardName );
params.put( "bypassCache", "true" );
params.put( "absolute", "false" );
params.put( "inferScheme", "false" );
// add request parameters
Enumeration<String> originalParams = request.getParameterNames();
// Iterate and put the values there
while ( originalParams.hasMoreElements() ) {
String originalParam = originalParams.nextElement();
params.put( originalParam, request.getParameter( originalParam ) );
}
return params;
}
private String getParameter( String param, HttpServletRequest request ) {
return getParameter( param, "", request );
}
private String getParameter( String param, String dflt, HttpServletRequest request ) {
return request.getParameter( param ) != null ? request.getParameter( param ) : dflt;
}
private String[] getStringArrayParameter( String param, HttpServletRequest request ) {
String[] result = (String[]) request.getParameterMap().get( param );
return result;
}
private void setResponseHeaders( String mimeType, int cacheDuration, String attachmentName,
HttpServletResponse response ) {
if ( response == null ) {
logger.warn( "Parameter 'httpresponse' not found!" );
return;
}
response.setHeader( "Content-Type", mimeType );
if ( attachmentName != null ) {
response.setHeader( "content-disposition", "attachment; filename=" + attachmentName );
} // Cache?
if ( cacheDuration > 0 ) {
response.setHeader( "Cache-Control", "max-age=" + cacheDuration );
} else {
response.setHeader( "Cache-Control", "max-age=0, no-store" );
}
}
private String getMimeType( String fileName ) {
String[] fileNameSplit = StringUtils.split( fileName, '.' );
return MimeTypes.getMimeType( fileNameSplit[ fileNameSplit.length - 1 ].toUpperCase() );
}
private void writeMessage( String message, OutputStream out ) throws IOException {
IOUtils.write( message, out );
out.flush();
}
private List<String> getFileNameTree( String path ) {
List<String> files = new ArrayList<String>();
if ( !StringUtils.isEmpty( path ) ) {
files.add( path );
}
files.addAll( buildFileNameTree( path, getFileNames( service.getRepository().listFiles( path ) ) ) );
List<String> treatedFileNames = new ArrayList<String>();
for (String file : files ) {
if (file.startsWith( "/" )) {
treatedFileNames.add( file.replaceFirst( "/", "" ) );
} else {
treatedFileNames.add( file );
}
}
return treatedFileNames;
}
private List<String> buildFileNameTree( String basePath, List<String> children ) {
List<String> result = new ArrayList<String>();
for ( String child : children ) {
String newEntry = basePath + "/" + child;
result.add( newEntry );
result.addAll( buildFileNameTree( newEntry, getFileNames( service.getRepository().listFiles( newEntry ) ) ) );
}
return result;
}
private List<String> getFileNames( IFile[] files ) {
List<String> names = new ArrayList<String>();
for ( IFile file : files ) {
names.add( file.getName() );
}
return names;
}
}
| cfr-pentaho5/src/pt/webdetails/cfr/CfrApi.java | /*!
* Copyright 2002 - 2013 Webdetails, a Pentaho company. All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package pt.webdetails.cfr;
import java.io.*;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import pt.webdetails.cfr.auth.FilePermissionEnum;
import pt.webdetails.cfr.auth.FilePermissionMetadata;
import pt.webdetails.cfr.file.CfrFile;
import pt.webdetails.cfr.file.FileStorer;
import pt.webdetails.cfr.file.IFile;
import pt.webdetails.cfr.file.MetadataReader;
import pt.webdetails.cfr.repository.IFileRepository;
import pt.webdetails.cpf.InvalidOperationException;
import pt.webdetails.cpf.persistence.PersistenceEngine;
import pt.webdetails.cpf.utils.CharsetHelper;
import pt.webdetails.cpf.VersionChecker;
import pt.webdetails.cpf.utils.MimeTypes;
import com.sun.jersey.multipart.FormDataParam;
import com.sun.jersey.core.header.FormDataContentDisposition;
@Path( "cfr/api" )
public class CfrApi {
private static final Log logger = LogFactory.getLog( CfrApi.class );
private CfrService service = new CfrService();
private MetadataReader mr = new MetadataReader( service );
private static final String UI_PATH = "cfr/presentation/";
static String checkRelativePathSanity( String path ) {
String result = path;
if ( path != null ) {
if ( result.startsWith( "./" ) ) {
result = result.replaceFirst( "./", "" );
}
if ( result.startsWith( "." ) ) {
result = result.replaceFirst( ".", "" );
}
if ( result.startsWith( "/" ) ) {
result = result.replaceFirst( ".", "" );
}
if ( result.endsWith( "/" ) ) {
result = result.substring( 0, result.length() - 1 );
}
}
return result;
}
static String relativeFilePath( String baseDir, String file ) {
String _baseDir = checkRelativePathSanity( baseDir );
String _file = checkRelativePathSanity( file );
String result = null;
if ( _baseDir == null || _baseDir.length() == 0 ) {
return _file;
} else {
if ( _baseDir.endsWith( "/" ) ) {
result = new StringBuilder( _baseDir ).append( _file ).toString();
} else {
result = new StringBuilder( _baseDir ).append( '/' ).append( _file ).toString();
}
}
return result;
}
@GET
@Path( "/home" )
public void home( @Context HttpServletRequest request,
@Context HttpServletResponse response ) throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
params.put( "solution", "system" );
params.put( "path", "cfr/presentation/" );
params.put( "file", "cfr.wcdf" );
params.put( "absolute", "false" );
params.put( "inferScheme", "false" );
if ( Boolean.parseBoolean( request.getParameter( "debug" ) ) ) {
params.put( "debug", "true" );
}
renderInCde( response, params );
}
@GET
@Path( "/createFolder" )
public void createFolder( @Context HttpServletRequest request,
@Context HttpServletResponse response ) throws Exception {
String path = checkRelativePathSanity( getParameter( "path", request ) );
if ( path == null || StringUtils.isBlank( path ) ) {
throw new Exception( "path is null or empty" );
}
boolean createResult = service.getRepository().createFolder( path );
writeMessage( new JSONObject().put( "result", createResult ).toString(), response.getOutputStream() );
}
@POST
@Path( "/remove" )
public void remove( @Context HttpServletRequest request, @Context HttpServletResponse response ) throws Exception {
String fullFileName =
checkRelativePathSanity( getParameter( "fileName", request ) );
if ( fullFileName == null || StringUtils.isBlank( fullFileName ) ) {
throw new Exception( "fileName is null or empty" );
}
boolean removeResult = service.getRepository().deleteFile( fullFileName );
boolean result = false;
if ( removeResult ) {
FileStorer.deletePermissions( fullFileName, null );
result = FileStorer.removeFile( fullFileName, null );
}
writeMessage( new JSONObject().put( "result", result ).toString(), response.getOutputStream() );
}
@POST
@Path( "/store" )
@Consumes( "multipart/form-data" )
public void store( @FormDataParam( "file" ) InputStream uploadedInputStream,
@FormDataParam( "file" ) FormDataContentDisposition fileDetail,
@FormDataParam( "path" ) String path,
@Context HttpServletRequest request, @Context HttpServletResponse response )
throws IOException, InvalidOperationException, Exception {
String fileName = fileDetail.getFileName(), savePath = path;
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
IOUtils.copy( uploadedInputStream, oStream );
oStream.flush();
byte[] contents = oStream.toByteArray();
oStream.close();
if ( fileName == null ) {
logger.error( "parameter fileName must not be null" );
throw new Exception( "parameter fileName must not be null" );
}
if ( savePath == null ) {
logger.error( "parameter path must not be null" );
throw new Exception( "parameter path must not be null" );
}
if ( contents == null ) {
logger.error( "File content must not be null" );
throw new Exception( "File content must not be null" );
}
FileStorer fileStorer = new FileStorer( service.getRepository() );
boolean stored =
fileStorer
.storeFile( checkRelativePathSanity( fileName ), checkRelativePathSanity( savePath ), contents,
service.getCurrentUserName() );
JSONObject result = new JSONObject().put( "result", stored );
writeMessage( result.toString(), response.getOutputStream() );
}
@POST
@Path( "/listFiles" )
public void listFiles( @FormParam( "dir" ) @DefaultValue( "" ) String baseDir,
@Context HttpServletRequest request, @Context HttpServletResponse response )
throws IOException {
//String baseDir = URLDecoder.decode( getParameter( "dir", request ), "ISO-8859-1" );
IFile[] files = service.getRepository().listFiles( baseDir );
List<IFile> allowedFiles = new ArrayList<IFile>( files.length );
String extensions = getParameter( "fileExtensions", request );
// checks permissions
/*
* remarks: ideally the repository must list only the files that the current user is allowed to access?
*/
for ( IFile file : files ) {
String relativePath = relativeFilePath( baseDir, file.getName() );
if ( mr.isCurrentUserAllowed( FilePermissionEnum.READ, relativePath ) ) {
allowedFiles.add( file );
}
}
String[] exts = null;
if ( !StringUtils.isBlank( extensions ) ) {
exts = extensions.split( " " );
}
IFile[] allowedFilesArray = new IFile[ allowedFiles.size() ];
response.setContentType( MimeTypes.HTML );
writeMessage( toJQueryFileTree( baseDir, allowedFiles.toArray( allowedFilesArray ), exts ),
response.getOutputStream() );
}
@GET
@Path( "/getFile" )
public void getFile( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws IOException, JSONException, Exception {
String fullFileName = checkRelativePathSanity( getParameter( "fileName", null, request ) );
if ( fullFileName == null ) {
logger.error( "request query parameter fileName must not be null" );
throw new Exception( "request query parameter fileName must not be null" );
}
if ( mr.isCurrentUserAllowed( FilePermissionEnum.READ, fullFileName ) ) {
CfrFile file = service.getRepository().getFile( fullFileName );
setResponseHeaders( getMimeType( file.getFileName() ), -1, URLEncoder.encode( file.getFileName(),
CharsetHelper.getEncoding() ), response );
ByteArrayInputStream bais = new ByteArrayInputStream( file.getContent() );
IOUtils.copy( bais, response.getOutputStream() );
response.getOutputStream().flush();
IOUtils.closeQuietly( bais );
} else {
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "you don't have permissions to access the file" );
}
}
@GET
@Path( "/viewFile" )
public void viewFile( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws Exception {
String fullFileName =
checkRelativePathSanity( getParameter( "fileName", null, request ) );
if ( fullFileName == null ) {
logger.error( "request query parameter fileName must not be null" );
throw new Exception( "request query parameter fileName must not be null" );
}
if ( mr.isCurrentUserAllowed( FilePermissionEnum.READ, fullFileName ) ) {
CfrFile file = service.getRepository().getFile( fullFileName );
setResponseHeaders( getMimeType( file.getFileName() ), -1, null, response );
ByteArrayInputStream bais = new ByteArrayInputStream( file.getContent() );
IOUtils.copy( bais, response.getOutputStream() );
response.getOutputStream().flush();
IOUtils.closeQuietly( bais );
} else {
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "you don't have permissions to access the file" );
}
}
@GET
@Path( "/listFilesJson" )
public void listFilesJSON( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws IOException, JSONException {
String baseDir = checkRelativePathSanity( getParameter( "dir", request ) );
IFile[] files = service.getRepository().listFiles( baseDir );
JSONArray arr = new JSONArray();
if ( files != null ) {
for ( IFile file : files ) {
if ( mr.isCurrentUserAllowed( FilePermissionEnum.READ, relativeFilePath( baseDir, file.getName() ) ) ) {
JSONObject obj = new JSONObject();
obj.put( "fileName", file.getName() );
obj.put( "isDirectory", file.isDirectory() );
obj.put( "path", baseDir );
arr.put( obj );
}
}
}
writeMessage( arr.toString( 2 ), response.getOutputStream() );
}
@GET
@Path( "/listUploads" )
public void listUploads( @Context HttpServletRequest request,
@Context HttpServletResponse response )
throws IOException, JSONException {
String path = checkRelativePathSanity( getParameter( "fileName", request ) );
writeMessage( mr.listFiles( path, getParameter( "user", request ), getParameter( "startDate", request ),
getParameter( "endDate", request ) ).toString(), response.getOutputStream() );
}
@GET
@Path( "/listUploadsFlat" )
public void listUploadsFlat( @Context HttpServletRequest request,
@Context HttpServletResponse response )
throws IOException, JSONException {
String path = checkRelativePathSanity( getParameter( "fileName", request ) );
writeMessage( mr.listFilesFlat( path, getParameter( "user", request ), getParameter( "startDate", request ),
getParameter( "endDate", request ) ).toString(), response.getOutputStream() );
}
private static String toJQueryFileTree( String baseDir, IFile[] files, String[] extensions ) {
StringBuilder out = new StringBuilder();
out.append( "<ul class=\"jqueryFileTree\" style=\"display: none;\">" );
for ( IFile file : files ) {
if ( file.isDirectory() ) {
out.append( "<li class=\"directory collapsed\"><a href=\"#\" rel=\"" + baseDir + file.getName() + "/\">"
+ file.getName() + "</a></li>" );
}
}
for ( IFile file : files ) {
if ( !file.isDirectory() ) {
int dotIndex = file.getName().lastIndexOf( '.' );
String ext = dotIndex > 0 ? file.getName().substring( dotIndex + 1 ) : "";
boolean accepted = ext.equals( "" );
if ( !ext.equals( "" ) ) {
if ( extensions == null || extensions.length == 0 ) {
accepted = true;
} else {
for ( String acceptedExtension : extensions ) {
if ( ext.equals( acceptedExtension ) ) {
accepted = true;
break;
}
}
}
}
if ( accepted ) {
out.append( "<li class=\"file ext_" + ext + "\"><a href=\"#\" rel=\"" + baseDir + file.getName() + "\">"
+ file.getName() + "</a></li>" );
}
}
}
out.append( "</ul>" );
return out.toString();
}
@GET
@Path( "/setPermissions" )
public void setPermissions( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws JSONException, IOException {
String path = checkRelativePathSanity( getParameter( pathParameterPath, null, request ) );
String[] userOrGroupId = getStringArrayParameter( pathParameterGroupOrUserId, request );
String[] _permissions = getStringArrayParameter( pathParameterPermission, request );
JSONObject result = new JSONObject();
if ( path != null && userOrGroupId.length > 0 && _permissions.length > 0 ) {
// build valid permissions set
Set<FilePermissionEnum> validPermissions = new TreeSet<FilePermissionEnum>();
for ( String permission : _permissions ) {
FilePermissionEnum perm = FilePermissionEnum.resolve( permission );
if ( perm != null ) {
validPermissions.add( perm );
}
}
JSONArray permissionAddResultArray = new JSONArray();
for ( String id : userOrGroupId ) {
JSONObject individualResult = new JSONObject();
boolean storeResult =
FileStorer.storeFilePermissions( new FilePermissionMetadata( path, id, validPermissions ) );
if ( storeResult ) {
individualResult.put( "status", String.format( "Added permission for path %s and user/role %s", path, id ) );
} else {
individualResult.put( "status", String.format( "Failed to add permission for path %s and user/role %s", path,
id ) );
}
permissionAddResultArray.put( individualResult );
}
result.put( "status", "Operation finished. Check statusArray for details." );
result.put( "statusArray", permissionAddResultArray );
} else {
result.put( "status", "Path or user group parameters not found" );
}
writeMessage( result.toString( 2 ), response.getOutputStream() );
}
@GET
@Path( "/deletePermissions" )
public void deletePermissions( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws JSONException, IOException {
String path = checkRelativePathSanity( getParameter( pathParameterPath, null, request ) );
String[] userOrGroupId = getStringArrayParameter( pathParameterGroupOrUserId, request );
JSONObject result = new JSONObject();
if ( path != null || ( userOrGroupId != null && userOrGroupId.length > 0 ) ) {
if ( userOrGroupId == null || userOrGroupId.length == 0 ) {
if ( FileStorer.deletePermissions( path, null ) ) {
result.put( "status", "Permissions deleted" );
} else {
result.put( "status", "Error deleting permissions" );
}
} else {
JSONArray permissionDeleteResultArray = new JSONArray();
for ( String id : userOrGroupId ) {
JSONObject individualResult = new JSONObject();
boolean deleteResult = FileStorer.deletePermissions( path, id );
if ( deleteResult ) {
individualResult.put( "status", String.format( "Permission for %s and path %s deleted.", id, path ) );
} else {
individualResult
.put( "status", String.format( "Failed to delete permission for %s and path %s.", id, path ) );
}
permissionDeleteResultArray.put( individualResult );
}
result.put( "status", "Multiple permission deletion. Check Status array" );
result.put( "statusArray", permissionDeleteResultArray );
}
} else {
result.put( "status", "Required arguments user/role and path not found" );
}
writeMessage( result.toString( 2 ), response.getOutputStream() );
}
@GET
@Path( "/getPermissions" )
public void getPermissions( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws IOException, JSONException {
String path = checkRelativePathSanity( getParameter( pathParameterPath, null, request ) );
String id = getParameter( pathParameterGroupOrUserId, null, request );
if ( path != null || id != null ) {
JSONArray permissions = mr.getPermissions( path, id, FilePermissionMetadata.DEFAULT_PERMISSIONS );
writeMessage( permissions.toString( 0 ), response.getOutputStream() );
}
}
@GET
@Path( "/resetRepository" )
public String resetRepository() {
if ( !this.service.isCurrentUserAdmin() ) {
logger.warn( "Reset repository called by a non admin user. Aborting" );
return "User has no access to this endpoint";
}
PersistenceEngine.getInstance().dropClass( FileStorer.FILE_METADATA_STORE_CLASS );
PersistenceEngine.getInstance().initializeClass( FileStorer.FILE_METADATA_STORE_CLASS );
PersistenceEngine.getInstance().dropClass( FileStorer.FILE_PERMISSIONS_METADATA_STORE_CLASS );
PersistenceEngine.getInstance().initializeClass( FileStorer.FILE_PERMISSIONS_METADATA_STORE_CLASS );
IFileRepository repo = new CfrService().getRepository();
for ( IFile file : repo.listFiles( "" ) ) {
repo.deleteFile( file.getFullPath() );
}
return "Repository Reset complete";
}
private static final String pathParameterGroupOrUserId = "id";
private static final String pathParameterPath = "path";
private static final String pathParameterPermission = "permission";
@GET
@Path( "/checkVersion" )
public void checkVersion( @Context HttpServletResponse response ) throws IOException, JSONException {
writeMessage( getVersionChecker().checkVersion().toJSON().toString(), response.getOutputStream() );
}
@GET
@Path( "/getVersion" )
public void getVersion( @Context HttpServletResponse response ) throws IOException, JSONException {
writeMessage( getVersionChecker().getVersion(), response.getOutputStream() );
}
@GET
@Path( "/about" )
public void about( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws Exception {
renderInCde( response, getRenderRequestParameters( "cfrAbout.wcdf", request ) );
}
@GET
@Path( "/browser" )
public void browser( @Context HttpServletRequest request, @Context HttpServletResponse response )
throws Exception {
renderInCde( response, getRenderRequestParameters( "cfrBrowser.wcdf", request ) );
}
public VersionChecker getVersionChecker() {
return new VersionChecker( new CfrPluginSettings() ) {
@Override
protected String getVersionCheckUrl( VersionChecker.Branch branch ) {
switch( branch ) {
case TRUNK:
return "http://ci.pentaho.com/job/pentaho-cfr/lastSuccessfulBuild/artifact/cfr-pentaho5/dist/marketplace.xml";
// case STABLE:
// return "http://ci.analytical-labs.com/job/Webdetails-CFR-Release/"
// + "lastSuccessfulBuild/artifact/dist/marketplace.xml";
default:
return null;
}
}
};
}
private void renderInCde( HttpServletResponse response, Map<String, Object> params ) throws Exception {
InterPluginBroker.run( params, response.getOutputStream() );
}
private Map<String, Object> getRenderRequestParameters( String dashboardName, HttpServletRequest request ) {
Map<String, Object> params = new HashMap<String, Object>();
params.put( "solution", "system" );
params.put( "path", UI_PATH );
params.put( "file", dashboardName );
params.put( "bypassCache", "true" );
params.put( "absolute", "false" );
params.put( "inferScheme", "false" );
// add request parameters
Enumeration<String> originalParams = request.getParameterNames();
// Iterate and put the values there
while ( originalParams.hasMoreElements() ) {
String originalParam = originalParams.nextElement();
params.put( originalParam, request.getParameter( originalParam ) );
}
return params;
}
private String getParameter( String param, HttpServletRequest request ) {
return getParameter( param, "", request );
}
private String getParameter( String param, String dflt, HttpServletRequest request ) {
return request.getParameter( param ) != null ? request.getParameter( param ) : dflt;
}
private String[] getStringArrayParameter( String param, HttpServletRequest request ) {
String[] result = (String[]) request.getParameterMap().get( param );
return result;
}
private void setResponseHeaders( String mimeType, int cacheDuration, String attachmentName,
HttpServletResponse response ) {
if ( response == null ) {
logger.warn( "Parameter 'httpresponse' not found!" );
return;
}
response.setHeader( "Content-Type", mimeType );
if ( attachmentName != null ) {
response.setHeader( "content-disposition", "attachment; filename=" + attachmentName );
} // Cache?
if ( cacheDuration > 0 ) {
response.setHeader( "Cache-Control", "max-age=" + cacheDuration );
} else {
response.setHeader( "Cache-Control", "max-age=0, no-store" );
}
}
private String getMimeType( String fileName ) {
String[] fileNameSplit = StringUtils.split( fileName, '.' );
return MimeTypes.getMimeType( fileNameSplit[ fileNameSplit.length - 1 ].toUpperCase() );
}
private void writeMessage( String message, OutputStream out ) throws IOException {
IOUtils.write( message, out );
out.flush();
}
}
| Adding the possibility to recursively set permissions
| cfr-pentaho5/src/pt/webdetails/cfr/CfrApi.java | Adding the possibility to recursively set permissions | <ide><path>fr-pentaho5/src/pt/webdetails/cfr/CfrApi.java
<ide> result = result.replaceFirst( ".", "" );
<ide> }
<ide> if ( result.startsWith( "/" ) ) {
<del> result = result.replaceFirst( ".", "" );
<add> result = result.replaceFirst( "/", "" );
<ide> }
<ide>
<ide> if ( result.endsWith( "/" ) ) {
<ide> String path = checkRelativePathSanity( getParameter( pathParameterPath, null, request ) );
<ide> String[] userOrGroupId = getStringArrayParameter( pathParameterGroupOrUserId, request );
<ide> String[] _permissions = getStringArrayParameter( pathParameterPermission, request );
<del>
<add> boolean recursive = Boolean.parseBoolean( getParameter( pathParameterRecursive, "false", request ) );
<ide> JSONObject result = new JSONObject();
<ide> if ( path != null && userOrGroupId.length > 0 && _permissions.length > 0 ) {
<add> List<String> files = new ArrayList<String>();
<add> if ( recursive ) {
<add> files = getFileNameTree( path );
<add> } else {
<add> files.add( path );
<add> }
<ide> // build valid permissions set
<ide> Set<FilePermissionEnum> validPermissions = new TreeSet<FilePermissionEnum>();
<ide> for ( String permission : _permissions ) {
<ide> }
<ide> }
<ide> JSONArray permissionAddResultArray = new JSONArray();
<del> for ( String id : userOrGroupId ) {
<del> JSONObject individualResult = new JSONObject();
<del> boolean storeResult =
<del> FileStorer.storeFilePermissions( new FilePermissionMetadata( path, id, validPermissions ) );
<del> if ( storeResult ) {
<del> individualResult.put( "status", String.format( "Added permission for path %s and user/role %s", path, id ) );
<del> } else {
<del> individualResult.put( "status", String.format( "Failed to add permission for path %s and user/role %s", path,
<del> id ) );
<del> }
<del> permissionAddResultArray.put( individualResult );
<add> for ( String file : files ) {
<add> for ( String id : userOrGroupId ) {
<add> JSONObject individualResult = new JSONObject();
<add> boolean storeResult =
<add> FileStorer.storeFilePermissions( new FilePermissionMetadata( file, id, validPermissions ) );
<add> if ( storeResult ) {
<add> individualResult
<add> .put( "status", String.format( "Added permission for path %s and user/role %s", file, id ) );
<add> } else {
<add> individualResult
<add> .put( "status", String.format( "Failed to add permission for path %s and user/role %s", file,
<add> id ) );
<add> }
<add> permissionAddResultArray.put( individualResult );
<add> }
<ide> }
<ide> result.put( "status", "Operation finished. Check statusArray for details." );
<ide> result.put( "statusArray", permissionAddResultArray );
<ide>
<ide> private static final String pathParameterPermission = "permission";
<ide>
<add> private static final String pathParameterRecursive = "recursive";
<add>
<ide> @GET
<ide> @Path( "/checkVersion" )
<ide> public void checkVersion( @Context HttpServletResponse response ) throws IOException, JSONException {
<ide> out.flush();
<ide> }
<ide>
<add> private List<String> getFileNameTree( String path ) {
<add> List<String> files = new ArrayList<String>();
<add> if ( !StringUtils.isEmpty( path ) ) {
<add> files.add( path );
<add> }
<add>
<add> files.addAll( buildFileNameTree( path, getFileNames( service.getRepository().listFiles( path ) ) ) );
<add> List<String> treatedFileNames = new ArrayList<String>();
<add> for (String file : files ) {
<add> if (file.startsWith( "/" )) {
<add> treatedFileNames.add( file.replaceFirst( "/", "" ) );
<add> } else {
<add> treatedFileNames.add( file );
<add> }
<add> }
<add> return treatedFileNames;
<add> }
<add>
<add> private List<String> buildFileNameTree( String basePath, List<String> children ) {
<add> List<String> result = new ArrayList<String>();
<add> for ( String child : children ) {
<add> String newEntry = basePath + "/" + child;
<add> result.add( newEntry );
<add> result.addAll( buildFileNameTree( newEntry, getFileNames( service.getRepository().listFiles( newEntry ) ) ) );
<add> }
<add> return result;
<add> }
<add>
<add> private List<String> getFileNames( IFile[] files ) {
<add> List<String> names = new ArrayList<String>();
<add> for ( IFile file : files ) {
<add> names.add( file.getName() );
<add> }
<add> return names;
<add> }
<add>
<ide> } |
|
Java | mit | 2be4c7873a23294d0cb4130bc0941823462f76eb | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.competitionsetup.completionstage.populator;
import org.innovateuk.ifs.competition.resource.CompetitionCompletionStage;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionSetupSection;
import org.innovateuk.ifs.competitionsetup.completionstage.viewmodel.CompletionStageViewModel;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
public class CompletionStageViewModelPopulatorTest {
@Test
public void populateModel() {
CompetitionResource competition = newCompetitionResource().
withCompletionStage(CompetitionCompletionStage.RELEASE_FEEDBACK).
build();
CompletionStageViewModel viewModel =
new CompletionStageViewModelPopulator().populateModel(null, competition);
assertThat(viewModel.getReleaseFeedbackCompletionStage()).isEqualTo(CompetitionCompletionStage.RELEASE_FEEDBACK);
assertThat(viewModel.getProjectSetupCompletionStage()).isEqualTo(CompetitionCompletionStage.PROJECT_SETUP);
}
@Test
public void sectionToPopulateModel() {
assertThat(new CompletionStageViewModelPopulator().sectionToPopulateModel()).
isEqualTo(CompetitionSetupSection.COMPLETION_STAGE);
}
}
| ifs-web-service/ifs-competition-mgt-service/src/test/java/org/innovateuk/ifs/competitionsetup/completionstage/populator/CompletionStageViewModelPopulatorTest.java | package org.innovateuk.ifs.competitionsetup.completionstage.populator;
import org.innovateuk.ifs.competition.resource.CompetitionCompletionStage;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionSetupSection;
import org.innovateuk.ifs.competition.resource.MilestoneType;
import org.innovateuk.ifs.competitionsetup.completionstage.viewmodel.CompletionStageViewModel;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
public class CompletionStageViewModelPopulatorTest {
@Test
public void populateModel() {
CompetitionResource competition = newCompetitionResource().
withCompletionStage(CompetitionCompletionStage.RELEASE_FEEDBACK).
build();
CompletionStageViewModel viewModel =
new CompletionStageViewModelPopulator().populateModel(null, competition);
assertThat(viewModel.getNonSelectableMilestones()).containsExactly(
MilestoneType.OPEN_DATE,
MilestoneType.BRIEFING_EVENT,
MilestoneType.SUBMISSION_DATE,
MilestoneType.ALLOCATE_ASSESSORS,
MilestoneType.ASSESSOR_BRIEFING,
MilestoneType.ASSESSOR_ACCEPTS,
MilestoneType.ASSESSOR_DEADLINE,
MilestoneType.LINE_DRAW,
MilestoneType.ASSESSMENT_PANEL,
MilestoneType.PANEL_DATE,
MilestoneType.FUNDERS_PANEL,
MilestoneType.NOTIFICATIONS);
assertThat(viewModel.getReleaseFeedbackCompletionStage()).isEqualTo(CompetitionCompletionStage.RELEASE_FEEDBACK);
assertThat(viewModel.getProjectSetupCompletionStage()).isEqualTo(CompetitionCompletionStage.PROJECT_SETUP);
}
@Test
public void sectionToPopulateModel() {
assertThat(new CompletionStageViewModelPopulator().sectionToPopulateModel()).
isEqualTo(CompetitionSetupSection.COMPLETION_STAGE);
}
}
| IFS-5972 fixing unit test.
| ifs-web-service/ifs-competition-mgt-service/src/test/java/org/innovateuk/ifs/competitionsetup/completionstage/populator/CompletionStageViewModelPopulatorTest.java | IFS-5972 fixing unit test. | <ide><path>fs-web-service/ifs-competition-mgt-service/src/test/java/org/innovateuk/ifs/competitionsetup/completionstage/populator/CompletionStageViewModelPopulatorTest.java
<ide> import org.innovateuk.ifs.competition.resource.CompetitionCompletionStage;
<ide> import org.innovateuk.ifs.competition.resource.CompetitionResource;
<ide> import org.innovateuk.ifs.competition.resource.CompetitionSetupSection;
<del>import org.innovateuk.ifs.competition.resource.MilestoneType;
<ide> import org.innovateuk.ifs.competitionsetup.completionstage.viewmodel.CompletionStageViewModel;
<ide> import org.junit.Test;
<ide>
<ide> CompletionStageViewModel viewModel =
<ide> new CompletionStageViewModelPopulator().populateModel(null, competition);
<ide>
<del> assertThat(viewModel.getNonSelectableMilestones()).containsExactly(
<del> MilestoneType.OPEN_DATE,
<del> MilestoneType.BRIEFING_EVENT,
<del> MilestoneType.SUBMISSION_DATE,
<del> MilestoneType.ALLOCATE_ASSESSORS,
<del> MilestoneType.ASSESSOR_BRIEFING,
<del> MilestoneType.ASSESSOR_ACCEPTS,
<del> MilestoneType.ASSESSOR_DEADLINE,
<del> MilestoneType.LINE_DRAW,
<del> MilestoneType.ASSESSMENT_PANEL,
<del> MilestoneType.PANEL_DATE,
<del> MilestoneType.FUNDERS_PANEL,
<del> MilestoneType.NOTIFICATIONS);
<del>
<ide> assertThat(viewModel.getReleaseFeedbackCompletionStage()).isEqualTo(CompetitionCompletionStage.RELEASE_FEEDBACK);
<ide> assertThat(viewModel.getProjectSetupCompletionStage()).isEqualTo(CompetitionCompletionStage.PROJECT_SETUP);
<ide> } |
|
Java | apache-2.0 | 5077e6feb0125f0ead193c532b240c37d2abc98d | 0 | devicehive/devicehive-java | package com.devicehive.controller;
import com.devicehive.auth.AllowedKeyAction;
import com.devicehive.auth.HivePrincipal;
import com.devicehive.auth.HiveRoles;
import com.devicehive.configuration.Constants;
import com.devicehive.controller.converters.SortOrder;
import com.devicehive.controller.util.ResponseFactory;
import com.devicehive.controller.util.SimpleWaiter;
import com.devicehive.exceptions.HiveException;
import com.devicehive.json.strategies.JsonPolicyDef;
import com.devicehive.json.strategies.JsonPolicyDef.Policy;
import com.devicehive.messages.handler.RestHandlerCreator;
import com.devicehive.messages.subscriptions.NotificationSubscription;
import com.devicehive.messages.subscriptions.NotificationSubscriptionStorage;
import com.devicehive.messages.subscriptions.SubscriptionManager;
import com.devicehive.model.*;
import com.devicehive.model.response.NotificationPollManyResponse;
import com.devicehive.service.AccessKeyService;
import com.devicehive.service.DeviceNotificationService;
import com.devicehive.service.DeviceService;
import com.devicehive.service.TimestampService;
import com.devicehive.util.LogExecutionTime;
import com.devicehive.util.ParseUtil;
import com.devicehive.util.ThreadLocalVariablesKeeper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.inject.Singleton;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.ws.rs.*;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.CompletionCallback;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.devicehive.auth.AllowedKeyAction.Action.CREATE_DEVICE_NOTIFICATION;
import static com.devicehive.auth.AllowedKeyAction.Action.GET_DEVICE_NOTIFICATION;
import static com.devicehive.json.strategies.JsonPolicyDef.Policy.*;
import static javax.ws.rs.core.Response.Status.*;
/**
* REST controller for device notifications: <i>/device/{deviceGuid}/notification</i> and <i>/device/notification</i>.
* See <a href="http://www.devicehive.com/restful#Reference/DeviceNotification">DeviceHive RESTful API: DeviceNotification</a> for details.
*
* @author rroschin
*/
@Path("/device")
@LogExecutionTime
@Singleton
public class DeviceNotificationController {
private static final Logger logger = LoggerFactory.getLogger(DeviceNotificationController.class);
private DeviceNotificationService notificationService;
private SubscriptionManager subscriptionManager;
private DeviceNotificationService deviceNotificationService;
private DeviceService deviceService;
private TimestampService timestampService;
private AccessKeyService accessKeyService;
private ExecutorService asyncPool;
@EJB
public void setNotificationService(DeviceNotificationService notificationService) {
this.notificationService = notificationService;
}
@EJB
public void setSubscriptionManager(SubscriptionManager subscriptionManager) {
this.subscriptionManager = subscriptionManager;
}
@EJB
public void setDeviceNotificationService(DeviceNotificationService deviceNotificationService) {
this.deviceNotificationService = deviceNotificationService;
}
@EJB
public void setDeviceService(DeviceService deviceService) {
this.deviceService = deviceService;
}
@EJB
public void setTimestampService(TimestampService timestampService) {
this.timestampService = timestampService;
}
@EJB
public void setAccessKeyService(AccessKeyService accessKeyService) {
this.accessKeyService = accessKeyService;
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/query">DeviceHive
* RESTful API: DeviceNotification: query</a>
* Queries device notifications.
*
* @param guid Device unique identifier.
* @param start Filter by notification start timestamp (UTC).
* @param end Filter by notification end timestamp (UTC).
* @param notification Filter by notification name.
* @param sortField Result list sort field. Available values are Timestamp (default) and Notification.
* @param sortOrder Result list sort order. Available values are ASC and DESC.
* @param take Number of records to take from the result list (default is 1000).
* @param skip Number of records to skip from the result list.
* @return If successful, this method returns array of <a href="http://www.devicehive
* .com/restful#Reference/DeviceNotification">DeviceNotification</a> resources in the response body.
* <table>
* <tr>
* <td>Property Name</td>
* <td>Type</td>
* <td>Description</td>
* </tr>
* <tr>
* <td>id</td>
* <td>integer</td>
* <td>Notification identifier</td>
* </tr>
* <tr>
* <td>timestamp</td>
* <td>datetime</td>
* <td>Notification timestamp (UTC)</td>
* </tr>
* <tr>
* <td>notification</td>
* <td>string</td>
* <td>Notification name</td>
* </tr>
* <tr>
* <td>parameters</td>
* <td>object</td>
* <td>Notification parameters, a JSON object with an arbitrary structure</td>
* </tr>
* </table>
*/
@GET
@Path("/{deviceGuid}/notification")
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
@AllowedKeyAction(action = {GET_DEVICE_NOTIFICATION})
public Response query(@PathParam("deviceGuid") String guid,
@QueryParam("start") Timestamp start,
@QueryParam("end") Timestamp end,
@QueryParam("notification") String notification,
@QueryParam("sortField") String sortField,
@QueryParam("sortOrder") @SortOrder Boolean sortOrder,
@QueryParam("take") Integer take,
@QueryParam("skip") Integer skip,
@QueryParam("gridInterval") Integer gridInterval) {
logger.debug("Device notification query requested. Guid {}, start {}, end {}, notification {}, sort field {}," +
"sort order {}, take {}, skip {}", guid, start, end, notification, sortField, sortOrder, take, skip);
if (sortOrder == null) {
sortOrder = true;
}
if (!"Timestamp".equals(sortField) && !"Notification".equals(sortField) && sortField != null) {
logger.debug("Device notification query request failed Bad request sort field. Guid {}, start {}, end {}," +
" notification {}, sort field {}, sort order {}, take {}, skip {}", guid, start, end,
notification, sortField, sortOrder, take, skip);
return ResponseFactory.response(Response.Status.BAD_REQUEST,
new ErrorResponse(BAD_REQUEST.getStatusCode(), ErrorResponse.INVALID_REQUEST_PARAMETERS_MESSAGE));
} else if (sortField != null) {
sortField = StringUtils.uncapitalize(sortField);
}
if (sortField == null) {
sortField = "timestamp";
}
sortField = sortField.toLowerCase();
HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
Device device = deviceService.getDeviceWithNetworkAndDeviceClass(guid, principal);
List<DeviceNotification> result = notificationService.queryDeviceNotification(device, start, end,
notification, sortField, sortOrder, take, skip, gridInterval);
logger.debug("Device notification query succeed. Guid {}, start {}, end {}, notification {}, sort field {}," +
"sort order {}, take {}, skip {}", guid, start, end, notification, sortField, sortOrder, take, skip);
return ResponseFactory.response(Response.Status.OK, result, Policy.NOTIFICATION_TO_CLIENT);
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/get">DeviceHive
* RESTful API: DeviceNotification: get</a>
* Gets information about device notification.
*
* @param guid Device unique identifier.
* @param notificationId Notification identifier.
* @return If successful, this method returns a <a href="http://www.devicehive
* .com/restful#Reference/DeviceNotification">DeviceNotification</a> resource in the response body.
* <table>
* <tr>
* <td>Property Name</td>
* <td>Type</td>
* <td>Description</td>
* </tr>
* <tr>
* <td>id</td>
* <td>integer</td>
* <td>Notification identifier</td>
* </tr>
* <tr>
* <td>timestamp</td>
* <td>datetime</td>
* <td>Notification timestamp (UTC)</td>
* </tr>
* <tr>
* <td>notification</td>
* <td>string</td>
* <td>Notification name</td>
* </tr>
* <tr>
* <td>parameters</td>
* <td>object</td>
* <td>Notification parameters, a JSON object with an arbitrary structure</td>
* </tr>
* </table>
*/
@GET
@Path("/{deviceGuid}/notification/{id}")
@AllowedKeyAction(action = {GET_DEVICE_NOTIFICATION})
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
public Response get(@PathParam("deviceGuid") String guid, @PathParam("id") Long notificationId) {
logger.debug("Device notification requested. Guid {}, notification id {}", guid, notificationId);
HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
DeviceNotification deviceNotification = notificationService.findById(notificationId);
if (deviceNotification == null) {
throw new HiveException("Device notification with id : " + notificationId + " not found",
NOT_FOUND.getStatusCode());
}
String deviceGuidFromNotification = deviceNotification.getDevice().getGuid();
if (!deviceGuidFromNotification.equals(guid)) {
logger.debug("No device notifications found for device with guid : {}", guid);
return ResponseFactory.response(NOT_FOUND, new ErrorResponse("No device notifications " +
"found for device with guid : " + guid));
}
Device device = deviceService.findByGuidWithPermissionsCheck(guid, principal);
if (device == null) {
logger.debug("No permissions to get notifications for device with guid : {}", guid);
return ResponseFactory.response(Response.Status.NOT_FOUND, new ErrorResponse("No device notifications " +
"found for device with guid : " + guid));
}
logger.debug("Device notification proceed successfully");
return ResponseFactory.response(Response.Status.OK, deviceNotification, NOTIFICATION_TO_CLIENT);
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/poll">DeviceHive RESTful API: DeviceNotification: poll</a>
*
* @param deviceGuid Device unique identifier.
* @param timestamp Timestamp of the last received command (UTC). If not specified, the server's timestamp is taken instead.
* @param timeout Waiting timeout in seconds (default: 30 seconds, maximum: 60 seconds). Specify 0 to disable waiting.
*/
@GET
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
@AllowedKeyAction(action = {GET_DEVICE_NOTIFICATION})
@Path("/{deviceGuid}/notification/poll")
public void poll(
@PathParam("deviceGuid") final String deviceGuid,
@QueryParam("names") final String namesString,
@QueryParam("timestamp") final Timestamp timestamp,
@DefaultValue(Constants.DEFAULT_WAIT_TIMEOUT) @Min(0) @Max(Constants.MAX_WAIT_TIMEOUT) @QueryParam
("waitTimeout") final long timeout,
@Suspended final AsyncResponse asyncResponse) {
final HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
asyncResponse.register(new CompletionCallback() {
@Override
public void onComplete(Throwable throwable) {
logger.debug("DeviceCNotification poll proceed successfully. device guid = {}", deviceGuid);
}
});
asyncPool.submit(new Runnable() {
@Override
public void run() {
try {
SubscriptionFilter subscriptionFilter = SubscriptionFilter.createForSingleDevice(deviceGuid, ParseUtil.getList(namesString), timestamp);
List<DeviceNotification> list = getOrWaitForNotifications(principal,subscriptionFilter, timeout);
Response response = ResponseFactory.response(OK, list, Policy.NOTIFICATION_TO_CLIENT);
asyncResponse.resume(response);
} catch (Exception e) {
logger.error("Error: " + e.getMessage(), e);
asyncResponse.resume(e);
}
}
});
}
@GET
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
@Path("/notification/poll")
public void pollMany(
@DefaultValue(Constants.DEFAULT_WAIT_TIMEOUT) @Min(0) @Max(Constants.MAX_WAIT_TIMEOUT)
@QueryParam
("waitTimeout") final long timeout,
@QueryParam("timestamp") final Timestamp timestamp,
@QueryParam("deviceGuids") final String deviceGuids,
@Suspended final AsyncResponse asyncResponse) {
final HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
asyncResponse.register(new CompletionCallback() {
@Override
public void onComplete(Throwable throwable) {
logger.debug("Device notification poll many proceed successfully for devices: {}", deviceGuids);
}
});
asyncPool.submit(new Runnable() {
@Override
public void run() {
try {
SubscriptionFilter subscriptionFilter = SubscriptionFilter.createForManyDevices(ParseUtil.getList(deviceGuids), timestamp);
List<DeviceNotification> list =
getOrWaitForNotifications(principal, subscriptionFilter, timeout);
List<NotificationPollManyResponse> resultList = new ArrayList<>(list.size());
for (DeviceNotification notification : list) {
resultList.add(new NotificationPollManyResponse(notification, notification.getDevice().getGuid()));
}
asyncResponse.resume(ResponseFactory.response(Response.Status.OK, resultList, Policy.NOTIFICATION_TO_CLIENT));
} catch (Exception e) {
logger.error("Error: " + e.getMessage(), e);
asyncResponse.resume(e);
}
}
});
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/pollMany">DeviceHive RESTful API: DeviceNotification: pollMany</a>
*
* @param subscriptionFilter Device unique identifiers with names and
* timestamp of the last received command (UTC). If not specified, the server's timestamp is taken instead.
* @param timeout Waiting timeout in seconds (default: 30 seconds, maximum: 60 seconds). Specify 0 to disable waiting.
*/
@POST
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
@Path("/notification/poll")
public void pollMany(
@DefaultValue(Constants.DEFAULT_WAIT_TIMEOUT) @Min(0) @Max(Constants.MAX_WAIT_TIMEOUT)
@FormParam("waitTimeout") final long timeout,
final SubscriptionFilter subscriptionFilter,
@Suspended final AsyncResponse asyncResponse) {
final HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
asyncResponse.register(new CompletionCallback() {
@Override
public void onComplete(Throwable throwable) {
logger.debug("Device notification poll many proceed successfully for devices: {}", subscriptionFilter);
}
});
asyncPool.submit(new Runnable() {
@Override
public void run() {
try {
List<DeviceNotification> list =
getOrWaitForNotifications(principal, subscriptionFilter, timeout);
List<NotificationPollManyResponse> resultList = new ArrayList<>(list.size());
for (DeviceNotification notification : list) {
resultList.add(new NotificationPollManyResponse(notification, notification.getDevice().getGuid()));
}
asyncResponse.resume(ResponseFactory.response(Response.Status.OK, resultList, Policy.NOTIFICATION_TO_CLIENT));
} catch (Exception e) {
logger.error("Error: " + e.getMessage(), e);
asyncResponse.resume(e);
}
}
});
}
private List<DeviceNotification> getOrWaitForNotifications(HivePrincipal principal,
SubscriptionFilter subscriptionFilter,
long timeout) {
logger.debug("Device notification pollMany requested for : {}. Timeout = {}",subscriptionFilter, timeout);
if (subscriptionFilter.getTimestamp() == null) {
subscriptionFilter.setTimestamp(timestampService.getTimestamp());
}
List<DeviceNotification> list = deviceNotificationService.getDeviceNotificationList(subscriptionFilter, principal);
if (list.isEmpty()) {
NotificationSubscriptionStorage storage = subscriptionManager.getNotificationSubscriptionStorage();
String reqId = UUID.randomUUID().toString();
RestHandlerCreator restHandlerCreator = new RestHandlerCreator();
Set<NotificationSubscription> subscriptionSet = new HashSet<>();
if (subscriptionFilter.getDeviceFilters() != null ) {
Map<Device, List<String>> filters = deviceService.createFilterMap(subscriptionFilter.getDeviceFilters(), principal);
for (Map.Entry<Device, List<String>> entry : filters.entrySet()) {
subscriptionSet
.add(new NotificationSubscription(principal, entry.getKey().getId(), reqId, entry.getValue(),
restHandlerCreator));
}
} else {
subscriptionSet
.add(new NotificationSubscription(principal, Constants.DEVICE_NOTIFICATION_NULL_ID_SUBSTITUTE,
reqId,
subscriptionFilter.getNames(),
restHandlerCreator));
}
if (SimpleWaiter
.subscribeAndWait(storage, subscriptionSet, restHandlerCreator.getFutureTask(), timeout)) {
list = deviceNotificationService.getDeviceNotificationList(subscriptionFilter, principal);
}
return list;
}
return list;
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/insert">DeviceHive
* RESTful API: DeviceNotification: insert</a>
* Creates new device notification.
*
* @param guid Device unique identifier.
* @param notification In the request body, supply a DeviceNotification resource.
* <table>
* <tr>
* <td>Property Name</td>
* <td>Required</td>
* <td>Type</td>
* <td>Description</td>
* </tr>
* <tr>
* <td>notification</td>
* <td>Yes</td>
* <td>string</td>
* <td>Notification name.</td>
* </tr>
* <tr>
* <td>parameters</td>
* <td>No</td>
* <td>object</td>
* <td>Notification parameters, a JSON object with an arbitrary structure.</td>
* </tr>
* </table>
* @return If successful, this method returns a <a href="http://www.devicehive.com/restful#Reference/DeviceNotification">DeviceNotification</a> resource in the response body.
* <table>
* <tr>
* <tr>Property Name</tr>
* <tr>Type</tr>
* <tr>Description</tr>
* </tr>
* <tr>
* <td>id</td>
* <td>integer</td>
* <td>Notification identifier.</td>
* </tr>
* <tr>
* <td>timestamp</td>
* <td>datetime</td>
* <td>Notification timestamp (UTC).</td>
* </tr>
* </table>
*/
@POST
@RolesAllowed({HiveRoles.DEVICE, HiveRoles.ADMIN, HiveRoles.CLIENT, HiveRoles.KEY})
@AllowedKeyAction(action = {CREATE_DEVICE_NOTIFICATION})
@Path("/{deviceGuid}/notification")
@Consumes(MediaType.APPLICATION_JSON)
public Response insert(@PathParam("deviceGuid") String guid,
@JsonPolicyDef(NOTIFICATION_FROM_DEVICE) DeviceNotification notification) {
logger.debug("DeviceNotification insertAll requested");
HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
if (notification == null || notification.getNotification() == null) {
logger.debug(
"DeviceNotification insertAll proceed with error. Bad notification: notification is required.");
return ResponseFactory.response(BAD_REQUEST,
new ErrorResponse(BAD_REQUEST.getStatusCode(),
ErrorResponse.INVALID_REQUEST_PARAMETERS_MESSAGE));
}
Device device = deviceService.findByGuidWithPermissionsCheck(guid, principal);
if (device == null) {
return ResponseFactory.response(NOT_FOUND,
new ErrorResponse(NOT_FOUND.getStatusCode(), "No device with such guid : " + guid + " exists"));
}
if (device.getNetwork() == null) {
return ResponseFactory.response(FORBIDDEN,
new ErrorResponse(FORBIDDEN.getStatusCode(), "No access to device"));
}
notificationService.submitDeviceNotification(notification, device);
logger.debug("DeviceNotification insertAll proceed successfully");
return ResponseFactory.response(CREATED, notification, NOTIFICATION_TO_DEVICE);
}
@PreDestroy
public void shutdownThreads() {
logger.debug("Try to shutdown device notifications' pool");
asyncPool.shutdown();
logger.debug("Device notifications' pool has been shut down");
}
@PostConstruct
public void initPool() {
asyncPool = Executors.newCachedThreadPool();
}
} | server/src/main/java/com/devicehive/controller/DeviceNotificationController.java | package com.devicehive.controller;
import com.devicehive.auth.AllowedKeyAction;
import com.devicehive.auth.HivePrincipal;
import com.devicehive.auth.HiveRoles;
import com.devicehive.configuration.Constants;
import com.devicehive.controller.converters.SortOrder;
import com.devicehive.controller.util.ResponseFactory;
import com.devicehive.controller.util.SimpleWaiter;
import com.devicehive.exceptions.HiveException;
import com.devicehive.json.strategies.JsonPolicyDef;
import com.devicehive.json.strategies.JsonPolicyDef.Policy;
import com.devicehive.messages.handler.RestHandlerCreator;
import com.devicehive.messages.subscriptions.NotificationSubscription;
import com.devicehive.messages.subscriptions.NotificationSubscriptionStorage;
import com.devicehive.messages.subscriptions.SubscriptionManager;
import com.devicehive.model.*;
import com.devicehive.model.response.NotificationPollManyResponse;
import com.devicehive.service.AccessKeyService;
import com.devicehive.service.DeviceNotificationService;
import com.devicehive.service.DeviceService;
import com.devicehive.service.TimestampService;
import com.devicehive.util.LogExecutionTime;
import com.devicehive.util.ParseUtil;
import com.devicehive.util.ThreadLocalVariablesKeeper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.inject.Singleton;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.ws.rs.*;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.CompletionCallback;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.devicehive.auth.AllowedKeyAction.Action.CREATE_DEVICE_NOTIFICATION;
import static com.devicehive.auth.AllowedKeyAction.Action.GET_DEVICE_NOTIFICATION;
import static com.devicehive.json.strategies.JsonPolicyDef.Policy.*;
import static javax.ws.rs.core.Response.Status.*;
/**
* REST controller for device notifications: <i>/device/{deviceGuid}/notification</i> and <i>/device/notification</i>.
* See <a href="http://www.devicehive.com/restful#Reference/DeviceNotification">DeviceHive RESTful API: DeviceNotification</a> for details.
*
* @author rroschin
*/
@Path("/device")
@LogExecutionTime
@Singleton
public class DeviceNotificationController {
private static final Logger logger = LoggerFactory.getLogger(DeviceNotificationController.class);
private DeviceNotificationService notificationService;
private SubscriptionManager subscriptionManager;
private DeviceNotificationService deviceNotificationService;
private DeviceService deviceService;
private TimestampService timestampService;
private AccessKeyService accessKeyService;
private ExecutorService asyncPool;
@EJB
public void setNotificationService(DeviceNotificationService notificationService) {
this.notificationService = notificationService;
}
@EJB
public void setSubscriptionManager(SubscriptionManager subscriptionManager) {
this.subscriptionManager = subscriptionManager;
}
@EJB
public void setDeviceNotificationService(DeviceNotificationService deviceNotificationService) {
this.deviceNotificationService = deviceNotificationService;
}
@EJB
public void setDeviceService(DeviceService deviceService) {
this.deviceService = deviceService;
}
@EJB
public void setTimestampService(TimestampService timestampService) {
this.timestampService = timestampService;
}
@EJB
public void setAccessKeyService(AccessKeyService accessKeyService) {
this.accessKeyService = accessKeyService;
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/query">DeviceHive
* RESTful API: DeviceNotification: query</a>
* Queries device notifications.
*
* @param guid Device unique identifier.
* @param start Filter by notification start timestamp (UTC).
* @param end Filter by notification end timestamp (UTC).
* @param notification Filter by notification name.
* @param sortField Result list sort field. Available values are Timestamp (default) and Notification.
* @param sortOrder Result list sort order. Available values are ASC and DESC.
* @param take Number of records to take from the result list (default is 1000).
* @param skip Number of records to skip from the result list.
* @return If successful, this method returns array of <a href="http://www.devicehive
* .com/restful#Reference/DeviceNotification">DeviceNotification</a> resources in the response body.
* <table>
* <tr>
* <td>Property Name</td>
* <td>Type</td>
* <td>Description</td>
* </tr>
* <tr>
* <td>id</td>
* <td>integer</td>
* <td>Notification identifier</td>
* </tr>
* <tr>
* <td>timestamp</td>
* <td>datetime</td>
* <td>Notification timestamp (UTC)</td>
* </tr>
* <tr>
* <td>notification</td>
* <td>string</td>
* <td>Notification name</td>
* </tr>
* <tr>
* <td>parameters</td>
* <td>object</td>
* <td>Notification parameters, a JSON object with an arbitrary structure</td>
* </tr>
* </table>
*/
@GET
@Path("/{deviceGuid}/notification")
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
@AllowedKeyAction(action = {GET_DEVICE_NOTIFICATION})
public Response query(@PathParam("deviceGuid") String guid,
@QueryParam("start") Timestamp start,
@QueryParam("end") Timestamp end,
@QueryParam("notification") String notification,
@QueryParam("sortField") String sortField,
@QueryParam("sortOrder") @SortOrder Boolean sortOrder,
@QueryParam("take") Integer take,
@QueryParam("skip") Integer skip,
@QueryParam("gridInterval") Integer gridInterval) {
logger.debug("Device notification query requested. Guid {}, start {}, end {}, notification {}, sort field {}," +
"sort order {}, take {}, skip {}", guid, start, end, notification, sortField, sortOrder, take, skip);
if (sortOrder == null) {
sortOrder = true;
}
if (!"Timestamp".equals(sortField) && !"Notification".equals(sortField) && sortField != null) {
logger.debug("Device notification query request failed Bad request sort field. Guid {}, start {}, end {}," +
" notification {}, sort field {}, sort order {}, take {}, skip {}", guid, start, end,
notification, sortField, sortOrder, take, skip);
return ResponseFactory.response(Response.Status.BAD_REQUEST,
new ErrorResponse(BAD_REQUEST.getStatusCode(), ErrorResponse.INVALID_REQUEST_PARAMETERS_MESSAGE));
} else if (sortField != null) {
sortField = StringUtils.uncapitalize(sortField);
}
if (sortField == null) {
sortField = "timestamp";
}
sortField = sortField.toLowerCase();
HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
Device device = deviceService.getDeviceWithNetworkAndDeviceClass(guid, principal);
List<DeviceNotification> result = notificationService.queryDeviceNotification(device, start, end,
notification, sortField, sortOrder, take, skip, gridInterval);
logger.debug("Device notification query succeed. Guid {}, start {}, end {}, notification {}, sort field {}," +
"sort order {}, take {}, skip {}", guid, start, end, notification, sortField, sortOrder, take, skip);
return ResponseFactory.response(Response.Status.OK, result, Policy.NOTIFICATION_TO_CLIENT);
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/get">DeviceHive
* RESTful API: DeviceNotification: get</a>
* Gets information about device notification.
*
* @param guid Device unique identifier.
* @param notificationId Notification identifier.
* @return If successful, this method returns a <a href="http://www.devicehive
* .com/restful#Reference/DeviceNotification">DeviceNotification</a> resource in the response body.
* <table>
* <tr>
* <td>Property Name</td>
* <td>Type</td>
* <td>Description</td>
* </tr>
* <tr>
* <td>id</td>
* <td>integer</td>
* <td>Notification identifier</td>
* </tr>
* <tr>
* <td>timestamp</td>
* <td>datetime</td>
* <td>Notification timestamp (UTC)</td>
* </tr>
* <tr>
* <td>notification</td>
* <td>string</td>
* <td>Notification name</td>
* </tr>
* <tr>
* <td>parameters</td>
* <td>object</td>
* <td>Notification parameters, a JSON object with an arbitrary structure</td>
* </tr>
* </table>
*/
@GET
@Path("/{deviceGuid}/notification/{id}")
@AllowedKeyAction(action = {GET_DEVICE_NOTIFICATION})
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
public Response get(@PathParam("deviceGuid") String guid, @PathParam("id") Long notificationId) {
logger.debug("Device notification requested. Guid {}, notification id {}", guid, notificationId);
HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
DeviceNotification deviceNotification = notificationService.findById(notificationId);
if (deviceNotification == null) {
throw new HiveException("Device notification with id : " + notificationId + " not found",
NOT_FOUND.getStatusCode());
}
String deviceGuidFromNotification = deviceNotification.getDevice().getGuid();
if (!deviceGuidFromNotification.equals(guid)) {
logger.debug("No device notifications found for device with guid : {}", guid);
return ResponseFactory.response(NOT_FOUND, new ErrorResponse("No device notifications " +
"found for device with guid : " + guid));
}
Device device = deviceService.findByGuidWithPermissionsCheck(guid, principal);
if (device == null) {
logger.debug("No permissions to get notifications for device with guid : {}", guid);
return ResponseFactory.response(Response.Status.NOT_FOUND, new ErrorResponse("No device notifications " +
"found for device with guid : " + guid));
}
logger.debug("Device notification proceed successfully");
return ResponseFactory.response(Response.Status.OK, deviceNotification, NOTIFICATION_TO_CLIENT);
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/poll">DeviceHive RESTful API: DeviceNotification: poll</a>
*
* @param deviceGuid Device unique identifier.
* @param timestamp Timestamp of the last received command (UTC). If not specified, the server's timestamp is taken instead.
* @param timeout Waiting timeout in seconds (default: 30 seconds, maximum: 60 seconds). Specify 0 to disable waiting.
*/
@GET
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
@AllowedKeyAction(action = {GET_DEVICE_NOTIFICATION})
@Path("/{deviceGuid}/notification/poll")
public void poll(
@PathParam("deviceGuid") final String deviceGuid,
@QueryParam("names") final String namesString,
@QueryParam("timestamp") final Timestamp timestamp,
@DefaultValue(Constants.DEFAULT_WAIT_TIMEOUT) @Min(0) @Max(Constants.MAX_WAIT_TIMEOUT) @QueryParam
("waitTimeout") final long timeout,
@Suspended final AsyncResponse asyncResponse) {
final HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
asyncResponse.register(new CompletionCallback() {
@Override
public void onComplete(Throwable throwable) {
logger.debug("DeviceCNotification poll proceed successfully. device guid = {}", deviceGuid);
}
});
asyncPool.submit(new Runnable() {
@Override
public void run() {
try {
SubscriptionFilter subscriptionFilter = SubscriptionFilter.createForSingleDevice(deviceGuid, ParseUtil.getList(namesString), timestamp);
List<DeviceNotification> list = getOrWaitForNotifications(principal,subscriptionFilter, timeout);
Response response = ResponseFactory.response(OK, list, Policy.NOTIFICATION_TO_CLIENT);
asyncResponse.resume(response);
} catch (Exception e) {
logger.error("Error: " + e.getMessage(), e);
asyncResponse.resume(e);
}
}
});
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/pollMany">DeviceHive RESTful API: DeviceNotification: pollMany</a>
*
* @param subscriptionFilter Device unique identifiers with names and
* timestamp of the last received command (UTC). If not specified, the server's timestamp is taken instead.
* @param timeout Waiting timeout in seconds (default: 30 seconds, maximum: 60 seconds). Specify 0 to disable waiting.
*/
@GET
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
@Path("/notification/poll")
@Deprecated
public void pollMany(
@DefaultValue(Constants.DEFAULT_WAIT_TIMEOUT) @Min(0) @Max(Constants.MAX_WAIT_TIMEOUT)
@FormParam("waitTimeout") final long timeout,
final SubscriptionFilter subscriptionFilter,
@Suspended final AsyncResponse asyncResponse) {
final HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
asyncResponse.register(new CompletionCallback() {
@Override
public void onComplete(Throwable throwable) {
logger.debug("Device notification poll many proceed successfully for devices: {}", subscriptionFilter);
}
});
asyncPool.submit(new Runnable() {
@Override
public void run() {
try {
List<DeviceNotification> list =
getOrWaitForNotifications(principal, subscriptionFilter, timeout);
List<NotificationPollManyResponse> resultList = new ArrayList<>(list.size());
for (DeviceNotification notification : list) {
resultList.add(new NotificationPollManyResponse(notification, notification.getDevice().getGuid()));
}
asyncResponse.resume(ResponseFactory.response(Response.Status.OK, resultList, Policy.NOTIFICATION_TO_CLIENT));
} catch (Exception e) {
logger.error("Error: " + e.getMessage(), e);
asyncResponse.resume(e);
}
}
});
}
private List<DeviceNotification> getOrWaitForNotifications(HivePrincipal principal,
SubscriptionFilter subscriptionFilter,
long timeout) {
logger.debug("Device notification pollMany requested for : {}. Timeout = {}",subscriptionFilter, timeout);
if (subscriptionFilter.getTimestamp() == null) {
subscriptionFilter.setTimestamp(timestampService.getTimestamp());
}
List<DeviceNotification> list = deviceNotificationService.getDeviceNotificationList(subscriptionFilter, principal);
if (list.isEmpty()) {
NotificationSubscriptionStorage storage = subscriptionManager.getNotificationSubscriptionStorage();
String reqId = UUID.randomUUID().toString();
RestHandlerCreator restHandlerCreator = new RestHandlerCreator();
Set<NotificationSubscription> subscriptionSet = new HashSet<>();
if (subscriptionFilter.getDeviceFilters() != null ) {
Map<Device, List<String>> filters = deviceService.createFilterMap(subscriptionFilter.getDeviceFilters(), principal);
for (Map.Entry<Device, List<String>> entry : filters.entrySet()) {
subscriptionSet
.add(new NotificationSubscription(principal, entry.getKey().getId(), reqId, entry.getValue(),
restHandlerCreator));
}
} else {
subscriptionSet
.add(new NotificationSubscription(principal, Constants.DEVICE_NOTIFICATION_NULL_ID_SUBSTITUTE,
reqId,
subscriptionFilter.getNames(),
restHandlerCreator));
}
if (SimpleWaiter
.subscribeAndWait(storage, subscriptionSet, restHandlerCreator.getFutureTask(), timeout)) {
list = deviceNotificationService.getDeviceNotificationList(subscriptionFilter, principal);
}
return list;
}
return list;
}
/**
* Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/insert">DeviceHive
* RESTful API: DeviceNotification: insert</a>
* Creates new device notification.
*
* @param guid Device unique identifier.
* @param notification In the request body, supply a DeviceNotification resource.
* <table>
* <tr>
* <td>Property Name</td>
* <td>Required</td>
* <td>Type</td>
* <td>Description</td>
* </tr>
* <tr>
* <td>notification</td>
* <td>Yes</td>
* <td>string</td>
* <td>Notification name.</td>
* </tr>
* <tr>
* <td>parameters</td>
* <td>No</td>
* <td>object</td>
* <td>Notification parameters, a JSON object with an arbitrary structure.</td>
* </tr>
* </table>
* @return If successful, this method returns a <a href="http://www.devicehive.com/restful#Reference/DeviceNotification">DeviceNotification</a> resource in the response body.
* <table>
* <tr>
* <tr>Property Name</tr>
* <tr>Type</tr>
* <tr>Description</tr>
* </tr>
* <tr>
* <td>id</td>
* <td>integer</td>
* <td>Notification identifier.</td>
* </tr>
* <tr>
* <td>timestamp</td>
* <td>datetime</td>
* <td>Notification timestamp (UTC).</td>
* </tr>
* </table>
*/
@POST
@RolesAllowed({HiveRoles.DEVICE, HiveRoles.ADMIN, HiveRoles.CLIENT, HiveRoles.KEY})
@AllowedKeyAction(action = {CREATE_DEVICE_NOTIFICATION})
@Path("/{deviceGuid}/notification")
@Consumes(MediaType.APPLICATION_JSON)
public Response insert(@PathParam("deviceGuid") String guid,
@JsonPolicyDef(NOTIFICATION_FROM_DEVICE) DeviceNotification notification) {
logger.debug("DeviceNotification insertAll requested");
HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
if (notification == null || notification.getNotification() == null) {
logger.debug(
"DeviceNotification insertAll proceed with error. Bad notification: notification is required.");
return ResponseFactory.response(BAD_REQUEST,
new ErrorResponse(BAD_REQUEST.getStatusCode(),
ErrorResponse.INVALID_REQUEST_PARAMETERS_MESSAGE));
}
Device device = deviceService.findByGuidWithPermissionsCheck(guid, principal);
if (device == null) {
return ResponseFactory.response(NOT_FOUND,
new ErrorResponse(NOT_FOUND.getStatusCode(), "No device with such guid : " + guid + " exists"));
}
if (device.getNetwork() == null) {
return ResponseFactory.response(FORBIDDEN,
new ErrorResponse(FORBIDDEN.getStatusCode(), "No access to device"));
}
notificationService.submitDeviceNotification(notification, device);
logger.debug("DeviceNotification insertAll proceed successfully");
return ResponseFactory.response(CREATED, notification, NOTIFICATION_TO_DEVICE);
}
@PreDestroy
public void shutdownThreads() {
logger.debug("Try to shutdown device notifications' pool");
asyncPool.shutdown();
logger.debug("Device notifications' pool has been shut down");
}
@PostConstruct
public void initPool() {
asyncPool = Executors.newCachedThreadPool();
}
} | Fixes to DNC methods
| server/src/main/java/com/devicehive/controller/DeviceNotificationController.java | Fixes to DNC methods | <ide><path>erver/src/main/java/com/devicehive/controller/DeviceNotificationController.java
<ide> }
<ide>
<ide>
<add> @GET
<add> @RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
<add> @Path("/notification/poll")
<add> public void pollMany(
<add> @DefaultValue(Constants.DEFAULT_WAIT_TIMEOUT) @Min(0) @Max(Constants.MAX_WAIT_TIMEOUT)
<add> @QueryParam
<add> ("waitTimeout") final long timeout,
<add> @QueryParam("timestamp") final Timestamp timestamp,
<add> @QueryParam("deviceGuids") final String deviceGuids,
<add> @Suspended final AsyncResponse asyncResponse) {
<add> final HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
<add> asyncResponse.register(new CompletionCallback() {
<add> @Override
<add> public void onComplete(Throwable throwable) {
<add> logger.debug("Device notification poll many proceed successfully for devices: {}", deviceGuids);
<add> }
<add> });
<add> asyncPool.submit(new Runnable() {
<add> @Override
<add> public void run() {
<add> try {
<add> SubscriptionFilter subscriptionFilter = SubscriptionFilter.createForManyDevices(ParseUtil.getList(deviceGuids), timestamp);
<add> List<DeviceNotification> list =
<add> getOrWaitForNotifications(principal, subscriptionFilter, timeout);
<add> List<NotificationPollManyResponse> resultList = new ArrayList<>(list.size());
<add> for (DeviceNotification notification : list) {
<add> resultList.add(new NotificationPollManyResponse(notification, notification.getDevice().getGuid()));
<add> }
<add> asyncResponse.resume(ResponseFactory.response(Response.Status.OK, resultList, Policy.NOTIFICATION_TO_CLIENT));
<add> } catch (Exception e) {
<add> logger.error("Error: " + e.getMessage(), e);
<add> asyncResponse.resume(e);
<add> }
<add> }
<add> });
<add> }
<ide> /**
<ide> * Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceNotification/pollMany">DeviceHive RESTful API: DeviceNotification: pollMany</a>
<ide> *
<ide> * @param timeout Waiting timeout in seconds (default: 30 seconds, maximum: 60 seconds). Specify 0 to disable waiting.
<ide> */
<ide>
<del> @GET
<add> @POST
<ide> @RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.KEY})
<ide> @Path("/notification/poll")
<del> @Deprecated
<ide> public void pollMany(
<ide> @DefaultValue(Constants.DEFAULT_WAIT_TIMEOUT) @Min(0) @Max(Constants.MAX_WAIT_TIMEOUT)
<ide> @FormParam("waitTimeout") final long timeout, |
|
Java | apache-2.0 | 85848c25a940f1e42de9fabf8f2b78b6417179e8 | 0 | PascalSchumacher/commons-lang,vanta/commons-lang,xiwc/commons-lang,weston100721/commons-lang,hollycroxton/commons-lang,apache/commons-lang,vanta/commons-lang,xiwc/commons-lang,MuShiiii/commons-lang,hollycroxton/commons-lang,byMan/naya279,longestname1/commonslang,jacktan1991/commons-lang,suntengteng/commons-lang,britter/commons-lang,MarkDacek/commons-lang,xuerenlv/commons-lang,vanta/commons-lang,MarkDacek/commons-lang,Ajeet-Ganga/commons-lang,jankill/commons-lang,xuerenlv/commons-lang,chaoyi66/commons-lang,MarkDacek/commons-lang,longestname1/commonslang,longestname1/commonslang,Ajeet-Ganga/commons-lang,byMan/naya279,weston100721/commons-lang,britter/commons-lang,jacktan1991/commons-lang,MuShiiii/commons-lang,suntengteng/commons-lang,arbasha/commons-lang,hollycroxton/commons-lang,lovecindy/commons-lang,jankill/commons-lang,apache/commons-lang,PascalSchumacher/commons-lang,xiwc/commons-lang,apache/commons-lang,jankill/commons-lang,chaoyi66/commons-lang,lovecindy/commons-lang,britter/commons-lang,mohanaraosv/commons-lang,mohanaraosv/commons-lang,arbasha/commons-lang,Ajeet-Ganga/commons-lang,arbasha/commons-lang,chaoyi66/commons-lang,lovecindy/commons-lang,MuShiiii/commons-lang,mohanaraosv/commons-lang,byMan/naya279,PascalSchumacher/commons-lang,xuerenlv/commons-lang,jacktan1991/commons-lang,weston100721/commons-lang,suntengteng/commons-lang | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.builder;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
import java.util.WeakHashMap;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.SystemUtils;
/**
* <p>Controls <code>String</code> formatting for {@link ToStringBuilder}.
* The main public interface is always via <code>ToStringBuilder</code>.</p>
*
* <p>These classes are intended to be used as <code>Singletons</code>.
* There is no need to instantiate a new style each time. A program
* will generally use one of the predefined constants on this class.
* Alternatively, the {@link StandardToStringStyle} class can be used
* to set the individual settings. Thus most styles can be achieved
* without subclassing.</p>
*
* <p>If required, a subclass can override as many or as few of the
* methods as it requires. Each object type (from <code>boolean</code>
* to <code>long</code> to <code>Object</code> to <code>int[]</code>) has
* its own methods to output it. Most have two versions, detail and summary.
*
* <p>For example, the detail version of the array based methods will
* output the whole array, whereas the summary method will just output
* the array length.</p>
*
* <p>If you want to format the output of certain objects, such as dates, you
* must create a subclass and override a method.
* <pre>
* public class MyStyle extends ToStringStyle {
* protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
* if (value instanceof Date) {
* value = new SimpleDateFormat("yyyy-MM-dd").format(value);
* }
* buffer.append(value);
* }
* }
* </pre>
* </p>
*
* @since 1.0
* @version $Id$
*/
public abstract class ToStringStyle implements Serializable {
/**
* Serialization version ID.
*/
private static final long serialVersionUID = -2587890625525655916L;
/**
* The default toString style. Using the Using the <code>Person</code>
* example from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* Person@182f0db[name=John Doe,age=33,smoker=false]
* </pre>
*/
public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle();
/**
* The multi line toString style. Using the Using the <code>Person</code>
* example from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* Person@182f0db[
* name=John Doe
* age=33
* smoker=false
* ]
* </pre>
*/
public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle();
/**
* The no field names toString style. Using the Using the
* <code>Person</code> example from {@link ToStringBuilder}, the output
* would look like this:
*
* <pre>
* Person@182f0db[John Doe,33,false]
* </pre>
*/
public static final ToStringStyle NO_FIELD_NAMES_STYLE = new NoFieldNameToStringStyle();
/**
* The short prefix toString style. Using the <code>Person</code> example
* from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* Person[name=John Doe,age=33,smoker=false]
* </pre>
*
* @since 2.1
*/
public static final ToStringStyle SHORT_PREFIX_STYLE = new ShortPrefixToStringStyle();
/**
* The simple toString style. Using the Using the <code>Person</code>
* example from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* John Doe,33,false
* </pre>
*/
public static final ToStringStyle SIMPLE_STYLE = new SimpleToStringStyle();
/**
* <p>
* A registry of objects used by <code>reflectionToString</code> methods
* to detect cyclical object references and avoid infinite loops.
* </p>
*/
private static final ThreadLocal<WeakHashMap<Object, Object>> REGISTRY =
new ThreadLocal<WeakHashMap<Object,Object>>();
/*
* Note that objects of this class are generally shared between threads, so
* an instance variable would not be suitable here.
*
* In normal use the registry should always be left empty, because the caller
* should call toString() which will clean up.
*
* See LANG-792
*/
/**
* <p>
* Returns the registry of objects being traversed by the <code>reflectionToString</code>
* methods in the current thread.
* </p>
*
* @return Set the registry of objects being traversed
*/
static Map<Object, Object> getRegistry() {
return REGISTRY.get();
}
/**
* <p>
* Returns <code>true</code> if the registry contains the given object.
* Used by the reflection methods to avoid infinite loops.
* </p>
*
* @param value
* The object to lookup in the registry.
* @return boolean <code>true</code> if the registry contains the given
* object.
*/
static boolean isRegistered(Object value) {
Map<Object, Object> m = getRegistry();
return m != null && m.containsKey(value);
}
/**
* <p>
* Registers the given object. Used by the reflection methods to avoid
* infinite loops.
* </p>
*
* @param value
* The object to register.
*/
static void register(Object value) {
if (value != null) {
Map<Object, Object> m = getRegistry();
if (m == null) {
REGISTRY.set(new WeakHashMap<Object, Object>());
}
getRegistry().put(value, null);
}
}
/**
* <p>
* Unregisters the given object.
* </p>
*
* <p>
* Used by the reflection methods to avoid infinite loops.
* </p>
*
* @param value
* The object to unregister.
*/
static void unregister(Object value) {
if (value != null) {
Map<Object, Object> m = getRegistry();
if (m != null) {
m.remove(value);
if (m.isEmpty()) {
REGISTRY.remove();
}
}
}
}
/**
* Whether to use the field names, the default is <code>true</code>.
*/
private boolean useFieldNames = true;
/**
* Whether to use the class name, the default is <code>true</code>.
*/
private boolean useClassName = true;
/**
* Whether to use short class names, the default is <code>false</code>.
*/
private boolean useShortClassName = false;
/**
* Whether to use the identity hash code, the default is <code>true</code>.
*/
private boolean useIdentityHashCode = true;
/**
* The content start <code>'['</code>.
*/
private String contentStart = "[";
/**
* The content end <code>']'</code>.
*/
private String contentEnd = "]";
/**
* The field name value separator <code>'='</code>.
*/
private String fieldNameValueSeparator = "=";
/**
* Whether the field separator should be added before any other fields.
*/
private boolean fieldSeparatorAtStart = false;
/**
* Whether the field separator should be added after any other fields.
*/
private boolean fieldSeparatorAtEnd = false;
/**
* The field separator <code>','</code>.
*/
private String fieldSeparator = ",";
/**
* The array start <code>'{'</code>.
*/
private String arrayStart = "{";
/**
* The array separator <code>','</code>.
*/
private String arraySeparator = ",";
/**
* The detail for array content.
*/
private boolean arrayContentDetail = true;
/**
* The array end <code>'}'</code>.
*/
private String arrayEnd = "}";
/**
* The value to use when fullDetail is <code>null</code>,
* the default value is <code>true</code>.
*/
private boolean defaultFullDetail = true;
/**
* The <code>null</code> text <code>'<null>'</code>.
*/
private String nullText = "<null>";
/**
* The summary size text start <code>'<size'</code>.
*/
private String sizeStartText = "<size=";
/**
* The summary size text start <code>'>'</code>.
*/
private String sizeEndText = ">";
/**
* The summary object text start <code>'<'</code>.
*/
private String summaryObjectStartText = "<";
/**
* The summary object text start <code>'>'</code>.
*/
private String summaryObjectEndText = ">";
//----------------------------------------------------------------------------
/**
* <p>Constructor.</p>
*/
protected ToStringStyle() {
super();
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> the superclass toString.</p>
* <p>NOTE: It assumes that the toString has been created from the same ToStringStyle. </p>
*
* <p>A <code>null</code> <code>superToString</code> is ignored.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param superToString the <code>super.toString()</code>
* @since 2.0
*/
public void appendSuper(StringBuffer buffer, String superToString) {
appendToString(buffer, superToString);
}
/**
* <p>Append to the <code>toString</code> another toString.</p>
* <p>NOTE: It assumes that the toString has been created from the same ToStringStyle. </p>
*
* <p>A <code>null</code> <code>toString</code> is ignored.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param toString the additional <code>toString</code>
* @since 2.0
*/
public void appendToString(StringBuffer buffer, String toString) {
if (toString != null) {
int pos1 = toString.indexOf(contentStart) + contentStart.length();
int pos2 = toString.lastIndexOf(contentEnd);
if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) {
String data = toString.substring(pos1, pos2);
if (fieldSeparatorAtStart) {
removeLastFieldSeparator(buffer);
}
buffer.append(data);
appendFieldSeparator(buffer);
}
}
}
/**
* <p>Append to the <code>toString</code> the start of data indicator.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> to build a <code>toString</code> for
*/
public void appendStart(StringBuffer buffer, Object object) {
if (object != null) {
appendClassName(buffer, object);
appendIdentityHashCode(buffer, object);
appendContentStart(buffer);
if (fieldSeparatorAtStart) {
appendFieldSeparator(buffer);
}
}
}
/**
* <p>Append to the <code>toString</code> the end of data indicator.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> to build a
* <code>toString</code> for.
*/
public void appendEnd(StringBuffer buffer, Object object) {
if (this.fieldSeparatorAtEnd == false) {
removeLastFieldSeparator(buffer);
}
appendContentEnd(buffer);
unregister(object);
}
/**
* <p>Remove the last field separator from the buffer.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @since 2.0
*/
protected void removeLastFieldSeparator(StringBuffer buffer) {
int len = buffer.length();
int sepLen = fieldSeparator.length();
if (len > 0 && sepLen > 0 && len >= sepLen) {
boolean match = true;
for (int i = 0; i < sepLen; i++) {
if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) {
match = false;
break;
}
}
if (match) {
buffer.setLength(len - sepLen);
}
}
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value, printing the full <code>toString</code> of the
* <code>Object</code> passed in.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (value == null) {
appendNullText(buffer, fieldName);
} else {
appendInternal(buffer, fieldName, value, isFullDetail(fullDetail));
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>,
* correctly interpreting its type.</p>
*
* <p>This method performs the main lookup by Class type to correctly
* route arrays, <code>Collections</code>, <code>Maps</code> and
* <code>Objects</code> to the appropriate method.</p>
*
* <p>Either detail or summary views can be specified.</p>
*
* <p>If a cycle is detected, an object will be appended with the
* <code>Object.toString()</code> format.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
* @param detail output detail or not
*/
protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) {
if (isRegistered(value)
&& !(value instanceof Number || value instanceof Boolean || value instanceof Character)) {
appendCyclicObject(buffer, fieldName, value);
return;
}
register(value);
try {
if (value instanceof Collection<?>) {
if (detail) {
appendDetail(buffer, fieldName, (Collection<?>) value);
} else {
appendSummarySize(buffer, fieldName, ((Collection<?>) value).size());
}
} else if (value instanceof Map<?, ?>) {
if (detail) {
appendDetail(buffer, fieldName, (Map<?, ?>) value);
} else {
appendSummarySize(buffer, fieldName, ((Map<?, ?>) value).size());
}
} else if (value instanceof long[]) {
if (detail) {
appendDetail(buffer, fieldName, (long[]) value);
} else {
appendSummary(buffer, fieldName, (long[]) value);
}
} else if (value instanceof int[]) {
if (detail) {
appendDetail(buffer, fieldName, (int[]) value);
} else {
appendSummary(buffer, fieldName, (int[]) value);
}
} else if (value instanceof short[]) {
if (detail) {
appendDetail(buffer, fieldName, (short[]) value);
} else {
appendSummary(buffer, fieldName, (short[]) value);
}
} else if (value instanceof byte[]) {
if (detail) {
appendDetail(buffer, fieldName, (byte[]) value);
} else {
appendSummary(buffer, fieldName, (byte[]) value);
}
} else if (value instanceof char[]) {
if (detail) {
appendDetail(buffer, fieldName, (char[]) value);
} else {
appendSummary(buffer, fieldName, (char[]) value);
}
} else if (value instanceof double[]) {
if (detail) {
appendDetail(buffer, fieldName, (double[]) value);
} else {
appendSummary(buffer, fieldName, (double[]) value);
}
} else if (value instanceof float[]) {
if (detail) {
appendDetail(buffer, fieldName, (float[]) value);
} else {
appendSummary(buffer, fieldName, (float[]) value);
}
} else if (value instanceof boolean[]) {
if (detail) {
appendDetail(buffer, fieldName, (boolean[]) value);
} else {
appendSummary(buffer, fieldName, (boolean[]) value);
}
} else if (value.getClass().isArray()) {
if (detail) {
appendDetail(buffer, fieldName, (Object[]) value);
} else {
appendSummary(buffer, fieldName, (Object[]) value);
}
} else {
if (detail) {
appendDetail(buffer, fieldName, value);
} else {
appendSummary(buffer, fieldName, value);
}
}
} finally {
unregister(value);
}
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value that has been detected to participate in a cycle. This
* implementation will print the standard string value of the value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
*
* @since 2.2
*/
protected void appendCyclicObject(StringBuffer buffer, String fieldName, Object value) {
ObjectUtils.identityToString(buffer, value);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value, printing the full detail of the <code>Object</code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
buffer.append(value);
}
/**
* <p>Append to the <code>toString</code> a <code>Collection</code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param coll the <code>Collection</code> to add to the
* <code>toString</code>, not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Collection<?> coll) {
buffer.append(coll);
}
/**
* <p>Append to the <code>toString</code> a <code>Map<code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param map the <code>Map</code> to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Map<?, ?> map) {
buffer.append(map);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value, printing a summary of the <code>Object</code>.</P>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, Object value) {
buffer.append(summaryObjectStartText);
buffer.append(getShortClassName(value.getClass()));
buffer.append(summaryObjectEndText);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, long value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, long value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, int value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, int value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, short value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, short value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, byte value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, byte value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, char value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, char value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, double value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, double value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, float value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, float value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, boolean value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) {
buffer.append(value);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> the detail of an
* <code>Object</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
Object item = array[i];
if (i > 0) {
buffer.append(arraySeparator);
}
if (item == null) {
appendNullText(buffer, fieldName);
} else {
appendInternal(buffer, fieldName, item, arrayContentDetail);
}
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> the detail of an array type.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
* @since 2.0
*/
protected void reflectionAppendArrayDetail(StringBuffer buffer, String fieldName, Object array) {
buffer.append(arrayStart);
int length = Array.getLength(array);
for (int i = 0; i < length; i++) {
Object item = Array.get(array, i);
if (i > 0) {
buffer.append(arraySeparator);
}
if (item == null) {
appendNullText(buffer, fieldName);
} else {
appendInternal(buffer, fieldName, item, arrayContentDetail);
}
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of an
* <code>Object</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>long</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>long</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of an
* <code>int</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of an
* <code>int</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>short</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>short</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>byte</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>byte</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>char</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>char</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>double</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>double</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>float</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>float</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>boolean</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>boolean</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> the class name.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> whose name to output
*/
protected void appendClassName(StringBuffer buffer, Object object) {
if (useClassName && object != null) {
register(object);
if (useShortClassName) {
buffer.append(getShortClassName(object.getClass()));
} else {
buffer.append(object.getClass().getName());
}
}
}
/**
* <p>Append the {@link System#identityHashCode(java.lang.Object)}.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> whose id to output
*/
protected void appendIdentityHashCode(StringBuffer buffer, Object object) {
if (this.isUseIdentityHashCode() && object!=null) {
register(object);
buffer.append('@');
buffer.append(Integer.toHexString(System.identityHashCode(object)));
}
}
/**
* <p>Append to the <code>toString</code> the content start.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
*/
protected void appendContentStart(StringBuffer buffer) {
buffer.append(contentStart);
}
/**
* <p>Append to the <code>toString</code> the content end.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
*/
protected void appendContentEnd(StringBuffer buffer) {
buffer.append(contentEnd);
}
/**
* <p>Append to the <code>toString</code> an indicator for <code>null</code>.</p>
*
* <p>The default indicator is <code>'<null>'</code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
*/
protected void appendNullText(StringBuffer buffer, String fieldName) {
buffer.append(nullText);
}
/**
* <p>Append to the <code>toString</code> the field separator.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
*/
protected void appendFieldSeparator(StringBuffer buffer) {
buffer.append(fieldSeparator);
}
/**
* <p>Append to the <code>toString</code> the field start.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
*/
protected void appendFieldStart(StringBuffer buffer, String fieldName) {
if (useFieldNames && fieldName != null) {
buffer.append(fieldName);
buffer.append(fieldNameValueSeparator);
}
}
/**
* <p>Append to the <code>toString<code> the field end.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
*/
protected void appendFieldEnd(StringBuffer buffer, String fieldName) {
appendFieldSeparator(buffer);
}
/**
* <p>Append to the <code>toString</code> a size summary.</p>
*
* <p>The size summary is used to summarize the contents of
* <code>Collections</code>, <code>Maps</code> and arrays.</p>
*
* <p>The output consists of a prefix, the passed in size
* and a suffix.</p>
*
* <p>The default format is <code>'<size=n>'<code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param size the size to append
*/
protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) {
buffer.append(sizeStartText);
buffer.append(size);
buffer.append(sizeEndText);
}
/**
* <p>Is this field to be output in full detail.</p>
*
* <p>This method converts a detail request into a detail level.
* The calling code may request full detail (<code>true</code>),
* but a subclass might ignore that and always return
* <code>false</code>. The calling code may pass in
* <code>null</code> indicating that it doesn't care about
* the detail level. In this case the default detail level is
* used.</p>
*
* @param fullDetailRequest the detail level requested
* @return whether full detail is to be shown
*/
protected boolean isFullDetail(Boolean fullDetailRequest) {
if (fullDetailRequest == null) {
return defaultFullDetail;
}
return fullDetailRequest.booleanValue();
}
/**
* <p>Gets the short class name for a class.</p>
*
* <p>The short class name is the classname excluding
* the package name.</p>
*
* @param cls the <code>Class</code> to get the short name of
* @return the short name
*/
protected String getShortClassName(Class<?> cls) {
return ClassUtils.getShortClassName(cls);
}
// Setters and getters for the customizable parts of the style
// These methods are not expected to be overridden, except to make public
// (They are not public so that immutable subclasses can be written)
//---------------------------------------------------------------------
/**
* <p>Gets whether to use the class name.</p>
*
* @return the current useClassName flag
*/
protected boolean isUseClassName() {
return useClassName;
}
/**
* <p>Sets whether to use the class name.</p>
*
* @param useClassName the new useClassName flag
*/
protected void setUseClassName(boolean useClassName) {
this.useClassName = useClassName;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to output short or long class names.</p>
*
* @return the current useShortClassName flag
* @since 2.0
*/
protected boolean isUseShortClassName() {
return useShortClassName;
}
/**
* <p>Sets whether to output short or long class names.</p>
*
* @param useShortClassName the new useShortClassName flag
* @since 2.0
*/
protected void setUseShortClassName(boolean useShortClassName) {
this.useShortClassName = useShortClassName;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to use the identity hash code.</p>
*
* @return the current useIdentityHashCode flag
*/
protected boolean isUseIdentityHashCode() {
return useIdentityHashCode;
}
/**
* <p>Sets whether to use the identity hash code.</p>
*
* @param useIdentityHashCode the new useIdentityHashCode flag
*/
protected void setUseIdentityHashCode(boolean useIdentityHashCode) {
this.useIdentityHashCode = useIdentityHashCode;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to use the field names passed in.</p>
*
* @return the current useFieldNames flag
*/
protected boolean isUseFieldNames() {
return useFieldNames;
}
/**
* <p>Sets whether to use the field names passed in.</p>
*
* @param useFieldNames the new useFieldNames flag
*/
protected void setUseFieldNames(boolean useFieldNames) {
this.useFieldNames = useFieldNames;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to use full detail when the caller doesn't
* specify.</p>
*
* @return the current defaultFullDetail flag
*/
protected boolean isDefaultFullDetail() {
return defaultFullDetail;
}
/**
* <p>Sets whether to use full detail when the caller doesn't
* specify.</p>
*
* @param defaultFullDetail the new defaultFullDetail flag
*/
protected void setDefaultFullDetail(boolean defaultFullDetail) {
this.defaultFullDetail = defaultFullDetail;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to output array content detail.</p>
*
* @return the current array content detail setting
*/
protected boolean isArrayContentDetail() {
return arrayContentDetail;
}
/**
* <p>Sets whether to output array content detail.</p>
*
* @param arrayContentDetail the new arrayContentDetail flag
*/
protected void setArrayContentDetail(boolean arrayContentDetail) {
this.arrayContentDetail = arrayContentDetail;
}
//---------------------------------------------------------------------
/**
* <p>Gets the array start text.</p>
*
* @return the current array start text
*/
protected String getArrayStart() {
return arrayStart;
}
/**
* <p>Sets the array start text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param arrayStart the new array start text
*/
protected void setArrayStart(String arrayStart) {
if (arrayStart == null) {
arrayStart = "";
}
this.arrayStart = arrayStart;
}
//---------------------------------------------------------------------
/**
* <p>Gets the array end text.</p>
*
* @return the current array end text
*/
protected String getArrayEnd() {
return arrayEnd;
}
/**
* <p>Sets the array end text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param arrayEnd the new array end text
*/
protected void setArrayEnd(String arrayEnd) {
if (arrayEnd == null) {
arrayEnd = "";
}
this.arrayEnd = arrayEnd;
}
//---------------------------------------------------------------------
/**
* <p>Gets the array separator text.</p>
*
* @return the current array separator text
*/
protected String getArraySeparator() {
return arraySeparator;
}
/**
* <p>Sets the array separator text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param arraySeparator the new array separator text
*/
protected void setArraySeparator(String arraySeparator) {
if (arraySeparator == null) {
arraySeparator = "";
}
this.arraySeparator = arraySeparator;
}
//---------------------------------------------------------------------
/**
* <p>Gets the content start text.</p>
*
* @return the current content start text
*/
protected String getContentStart() {
return contentStart;
}
/**
* <p>Sets the content start text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param contentStart the new content start text
*/
protected void setContentStart(String contentStart) {
if (contentStart == null) {
contentStart = "";
}
this.contentStart = contentStart;
}
//---------------------------------------------------------------------
/**
* <p>Gets the content end text.</p>
*
* @return the current content end text
*/
protected String getContentEnd() {
return contentEnd;
}
/**
* <p>Sets the content end text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param contentEnd the new content end text
*/
protected void setContentEnd(String contentEnd) {
if (contentEnd == null) {
contentEnd = "";
}
this.contentEnd = contentEnd;
}
//---------------------------------------------------------------------
/**
* <p>Gets the field name value separator text.</p>
*
* @return the current field name value separator text
*/
protected String getFieldNameValueSeparator() {
return fieldNameValueSeparator;
}
/**
* <p>Sets the field name value separator text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param fieldNameValueSeparator the new field name value separator text
*/
protected void setFieldNameValueSeparator(String fieldNameValueSeparator) {
if (fieldNameValueSeparator == null) {
fieldNameValueSeparator = "";
}
this.fieldNameValueSeparator = fieldNameValueSeparator;
}
//---------------------------------------------------------------------
/**
* <p>Gets the field separator text.</p>
*
* @return the current field separator text
*/
protected String getFieldSeparator() {
return fieldSeparator;
}
/**
* <p>Sets the field separator text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param fieldSeparator the new field separator text
*/
protected void setFieldSeparator(String fieldSeparator) {
if (fieldSeparator == null) {
fieldSeparator = "";
}
this.fieldSeparator = fieldSeparator;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether the field separator should be added at the start
* of each buffer.</p>
*
* @return the fieldSeparatorAtStart flag
* @since 2.0
*/
protected boolean isFieldSeparatorAtStart() {
return fieldSeparatorAtStart;
}
/**
* <p>Sets whether the field separator should be added at the start
* of each buffer.</p>
*
* @param fieldSeparatorAtStart the fieldSeparatorAtStart flag
* @since 2.0
*/
protected void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) {
this.fieldSeparatorAtStart = fieldSeparatorAtStart;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether the field separator should be added at the end
* of each buffer.</p>
*
* @return fieldSeparatorAtEnd flag
* @since 2.0
*/
protected boolean isFieldSeparatorAtEnd() {
return fieldSeparatorAtEnd;
}
/**
* <p>Sets whether the field separator should be added at the end
* of each buffer.</p>
*
* @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag
* @since 2.0
*/
protected void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) {
this.fieldSeparatorAtEnd = fieldSeparatorAtEnd;
}
//---------------------------------------------------------------------
/**
* <p>Gets the text to output when <code>null</code> found.</p>
*
* @return the current text to output when null found
*/
protected String getNullText() {
return nullText;
}
/**
* <p>Sets the text to output when <code>null</code> found.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param nullText the new text to output when null found
*/
protected void setNullText(String nullText) {
if (nullText == null) {
nullText = "";
}
this.nullText = nullText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the start text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output before the size value.</p>
*
* @return the current start of size text
*/
protected String getSizeStartText() {
return sizeStartText;
}
/**
* <p>Sets the start text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output before the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param sizeStartText the new start of size text
*/
protected void setSizeStartText(String sizeStartText) {
if (sizeStartText == null) {
sizeStartText = "";
}
this.sizeStartText = sizeStartText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the end text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output after the size value.</p>
*
* @return the current end of size text
*/
protected String getSizeEndText() {
return sizeEndText;
}
/**
* <p>Sets the end text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output after the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param sizeEndText the new end of size text
*/
protected void setSizeEndText(String sizeEndText) {
if (sizeEndText == null) {
sizeEndText = "";
}
this.sizeEndText = sizeEndText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the start text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output before the size value.</p>
*
* @return the current start of summary text
*/
protected String getSummaryObjectStartText() {
return summaryObjectStartText;
}
/**
* <p>Sets the start text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output before the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param summaryObjectStartText the new start of summary text
*/
protected void setSummaryObjectStartText(String summaryObjectStartText) {
if (summaryObjectStartText == null) {
summaryObjectStartText = "";
}
this.summaryObjectStartText = summaryObjectStartText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the end text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output after the size value.</p>
*
* @return the current end of summary text
*/
protected String getSummaryObjectEndText() {
return summaryObjectEndText;
}
/**
* <p>Sets the end text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output after the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param summaryObjectEndText the new end of summary text
*/
protected void setSummaryObjectEndText(String summaryObjectEndText) {
if (summaryObjectEndText == null) {
summaryObjectEndText = "";
}
this.summaryObjectEndText = summaryObjectEndText;
}
//----------------------------------------------------------------------------
/**
* <p>Default <code>ToStringStyle</code>.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class DefaultToStringStyle extends ToStringStyle {
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
DefaultToStringStyle() {
super();
}
/**
* <p>Ensure <code>Singleton</code> after serialization.</p>
*
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.DEFAULT_STYLE;
}
}
//----------------------------------------------------------------------------
/**
* <p><code>ToStringStyle</code> that does not print out
* the field names.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.
*/
private static final class NoFieldNameToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
NoFieldNameToStringStyle() {
super();
this.setUseFieldNames(false);
}
/**
* <p>Ensure <code>Singleton</code> after serialization.</p>
*
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.NO_FIELD_NAMES_STYLE;
}
}
//----------------------------------------------------------------------------
/**
* <p><code>ToStringStyle</code> that prints out the short
* class name and no identity hashcode.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class ShortPrefixToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
ShortPrefixToStringStyle() {
super();
this.setUseShortClassName(true);
this.setUseIdentityHashCode(false);
}
/**
* <p>Ensure <code>Singleton</ode> after serialization.</p>
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.SHORT_PREFIX_STYLE;
}
}
/**
* <p><code>ToStringStyle</code> that does not print out the
* classname, identity hashcode, content start or field name.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class SimpleToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
SimpleToStringStyle() {
super();
this.setUseClassName(false);
this.setUseIdentityHashCode(false);
this.setUseFieldNames(false);
this.setContentStart("");
this.setContentEnd("");
}
/**
* <p>Ensure <code>Singleton</ode> after serialization.</p>
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.SIMPLE_STYLE;
}
}
//----------------------------------------------------------------------------
/**
* <p><code>ToStringStyle</code> that outputs on multiple lines.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class MultiLineToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
MultiLineToStringStyle() {
super();
this.setContentStart("[");
this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + " ");
this.setFieldSeparatorAtStart(true);
this.setContentEnd(SystemUtils.LINE_SEPARATOR + "]");
}
/**
* <p>Ensure <code>Singleton</code> after serialization.</p>
*
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.MULTI_LINE_STYLE;
}
}
}
| src/main/java/org/apache/commons/lang3/builder/ToStringStyle.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.commons.lang3.builder;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
import java.util.WeakHashMap;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.SystemUtils;
/**
* <p>Controls <code>String</code> formatting for {@link ToStringBuilder}.
* The main public interface is always via <code>ToStringBuilder</code>.</p>
*
* <p>These classes are intended to be used as <code>Singletons</code>.
* There is no need to instantiate a new style each time. A program
* will generally use one of the predefined constants on this class.
* Alternatively, the {@link StandardToStringStyle} class can be used
* to set the individual settings. Thus most styles can be achieved
* without subclassing.</p>
*
* <p>If required, a subclass can override as many or as few of the
* methods as it requires. Each object type (from <code>boolean</code>
* to <code>long</code> to <code>Object</code> to <code>int[]</code>) has
* its own methods to output it. Most have two versions, detail and summary.
*
* <p>For example, the detail version of the array based methods will
* output the whole array, whereas the summary method will just output
* the array length.</p>
*
* <p>If you want to format the output of certain objects, such as dates, you
* must create a subclass and override a method.
* <pre>
* public class MyStyle extends ToStringStyle {
* protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
* if (value instanceof Date) {
* value = new SimpleDateFormat("yyyy-MM-dd").format(value);
* }
* buffer.append(value);
* }
* }
* </pre>
* </p>
*
* @since 1.0
* @version $Id$
*/
public abstract class ToStringStyle implements Serializable {
/**
* Serialization version ID.
*/
private static final long serialVersionUID = -2587890625525655916L;
/**
* The default toString style. Using the Using the <code>Person</code>
* example from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* Person@182f0db[name=John Doe,age=33,smoker=false]
* </pre>
*/
public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle();
/**
* The multi line toString style. Using the Using the <code>Person</code>
* example from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* Person@182f0db[
* name=John Doe
* age=33
* smoker=false
* ]
* </pre>
*/
public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle();
/**
* The no field names toString style. Using the Using the
* <code>Person</code> example from {@link ToStringBuilder}, the output
* would look like this:
*
* <pre>
* Person@182f0db[John Doe,33,false]
* </pre>
*/
public static final ToStringStyle NO_FIELD_NAMES_STYLE = new NoFieldNameToStringStyle();
/**
* The short prefix toString style. Using the <code>Person</code> example
* from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* Person[name=John Doe,age=33,smoker=false]
* </pre>
*
* @since 2.1
*/
public static final ToStringStyle SHORT_PREFIX_STYLE = new ShortPrefixToStringStyle();
/**
* The simple toString style. Using the Using the <code>Person</code>
* example from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* John Doe,33,false
* </pre>
*/
public static final ToStringStyle SIMPLE_STYLE = new SimpleToStringStyle();
/**
* <p>
* A registry of objects used by <code>reflectionToString</code> methods
* to detect cyclical object references and avoid infinite loops.
* </p>
*/
private static final ThreadLocal<WeakHashMap<Object, Object>> REGISTRY =
new ThreadLocal<WeakHashMap<Object,Object>>();
/**
* <p>
* Returns the registry of objects being traversed by the <code>reflectionToString</code>
* methods in the current thread.
* </p>
*
* @return Set the registry of objects being traversed
*/
static Map<Object, Object> getRegistry() {
return REGISTRY.get();
}
/**
* <p>
* Returns <code>true</code> if the registry contains the given object.
* Used by the reflection methods to avoid infinite loops.
* </p>
*
* @param value
* The object to lookup in the registry.
* @return boolean <code>true</code> if the registry contains the given
* object.
*/
static boolean isRegistered(Object value) {
Map<Object, Object> m = getRegistry();
return m != null && m.containsKey(value);
}
/**
* <p>
* Registers the given object. Used by the reflection methods to avoid
* infinite loops.
* </p>
*
* @param value
* The object to register.
*/
static void register(Object value) {
if (value != null) {
Map<Object, Object> m = getRegistry();
if (m == null) {
REGISTRY.set(new WeakHashMap<Object, Object>());
}
getRegistry().put(value, null);
}
}
/**
* <p>
* Unregisters the given object.
* </p>
*
* <p>
* Used by the reflection methods to avoid infinite loops.
* </p>
*
* @param value
* The object to unregister.
*/
static void unregister(Object value) {
if (value != null) {
Map<Object, Object> m = getRegistry();
if (m != null) {
m.remove(value);
if (m.isEmpty()) {
REGISTRY.remove();
}
}
}
}
/**
* Whether to use the field names, the default is <code>true</code>.
*/
private boolean useFieldNames = true;
/**
* Whether to use the class name, the default is <code>true</code>.
*/
private boolean useClassName = true;
/**
* Whether to use short class names, the default is <code>false</code>.
*/
private boolean useShortClassName = false;
/**
* Whether to use the identity hash code, the default is <code>true</code>.
*/
private boolean useIdentityHashCode = true;
/**
* The content start <code>'['</code>.
*/
private String contentStart = "[";
/**
* The content end <code>']'</code>.
*/
private String contentEnd = "]";
/**
* The field name value separator <code>'='</code>.
*/
private String fieldNameValueSeparator = "=";
/**
* Whether the field separator should be added before any other fields.
*/
private boolean fieldSeparatorAtStart = false;
/**
* Whether the field separator should be added after any other fields.
*/
private boolean fieldSeparatorAtEnd = false;
/**
* The field separator <code>','</code>.
*/
private String fieldSeparator = ",";
/**
* The array start <code>'{'</code>.
*/
private String arrayStart = "{";
/**
* The array separator <code>','</code>.
*/
private String arraySeparator = ",";
/**
* The detail for array content.
*/
private boolean arrayContentDetail = true;
/**
* The array end <code>'}'</code>.
*/
private String arrayEnd = "}";
/**
* The value to use when fullDetail is <code>null</code>,
* the default value is <code>true</code>.
*/
private boolean defaultFullDetail = true;
/**
* The <code>null</code> text <code>'<null>'</code>.
*/
private String nullText = "<null>";
/**
* The summary size text start <code>'<size'</code>.
*/
private String sizeStartText = "<size=";
/**
* The summary size text start <code>'>'</code>.
*/
private String sizeEndText = ">";
/**
* The summary object text start <code>'<'</code>.
*/
private String summaryObjectStartText = "<";
/**
* The summary object text start <code>'>'</code>.
*/
private String summaryObjectEndText = ">";
//----------------------------------------------------------------------------
/**
* <p>Constructor.</p>
*/
protected ToStringStyle() {
super();
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> the superclass toString.</p>
* <p>NOTE: It assumes that the toString has been created from the same ToStringStyle. </p>
*
* <p>A <code>null</code> <code>superToString</code> is ignored.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param superToString the <code>super.toString()</code>
* @since 2.0
*/
public void appendSuper(StringBuffer buffer, String superToString) {
appendToString(buffer, superToString);
}
/**
* <p>Append to the <code>toString</code> another toString.</p>
* <p>NOTE: It assumes that the toString has been created from the same ToStringStyle. </p>
*
* <p>A <code>null</code> <code>toString</code> is ignored.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param toString the additional <code>toString</code>
* @since 2.0
*/
public void appendToString(StringBuffer buffer, String toString) {
if (toString != null) {
int pos1 = toString.indexOf(contentStart) + contentStart.length();
int pos2 = toString.lastIndexOf(contentEnd);
if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) {
String data = toString.substring(pos1, pos2);
if (fieldSeparatorAtStart) {
removeLastFieldSeparator(buffer);
}
buffer.append(data);
appendFieldSeparator(buffer);
}
}
}
/**
* <p>Append to the <code>toString</code> the start of data indicator.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> to build a <code>toString</code> for
*/
public void appendStart(StringBuffer buffer, Object object) {
if (object != null) {
appendClassName(buffer, object);
appendIdentityHashCode(buffer, object);
appendContentStart(buffer);
if (fieldSeparatorAtStart) {
appendFieldSeparator(buffer);
}
}
}
/**
* <p>Append to the <code>toString</code> the end of data indicator.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> to build a
* <code>toString</code> for.
*/
public void appendEnd(StringBuffer buffer, Object object) {
if (this.fieldSeparatorAtEnd == false) {
removeLastFieldSeparator(buffer);
}
appendContentEnd(buffer);
unregister(object);
}
/**
* <p>Remove the last field separator from the buffer.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @since 2.0
*/
protected void removeLastFieldSeparator(StringBuffer buffer) {
int len = buffer.length();
int sepLen = fieldSeparator.length();
if (len > 0 && sepLen > 0 && len >= sepLen) {
boolean match = true;
for (int i = 0; i < sepLen; i++) {
if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) {
match = false;
break;
}
}
if (match) {
buffer.setLength(len - sepLen);
}
}
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value, printing the full <code>toString</code> of the
* <code>Object</code> passed in.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (value == null) {
appendNullText(buffer, fieldName);
} else {
appendInternal(buffer, fieldName, value, isFullDetail(fullDetail));
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>,
* correctly interpreting its type.</p>
*
* <p>This method performs the main lookup by Class type to correctly
* route arrays, <code>Collections</code>, <code>Maps</code> and
* <code>Objects</code> to the appropriate method.</p>
*
* <p>Either detail or summary views can be specified.</p>
*
* <p>If a cycle is detected, an object will be appended with the
* <code>Object.toString()</code> format.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
* @param detail output detail or not
*/
protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) {
if (isRegistered(value)
&& !(value instanceof Number || value instanceof Boolean || value instanceof Character)) {
appendCyclicObject(buffer, fieldName, value);
return;
}
register(value);
try {
if (value instanceof Collection<?>) {
if (detail) {
appendDetail(buffer, fieldName, (Collection<?>) value);
} else {
appendSummarySize(buffer, fieldName, ((Collection<?>) value).size());
}
} else if (value instanceof Map<?, ?>) {
if (detail) {
appendDetail(buffer, fieldName, (Map<?, ?>) value);
} else {
appendSummarySize(buffer, fieldName, ((Map<?, ?>) value).size());
}
} else if (value instanceof long[]) {
if (detail) {
appendDetail(buffer, fieldName, (long[]) value);
} else {
appendSummary(buffer, fieldName, (long[]) value);
}
} else if (value instanceof int[]) {
if (detail) {
appendDetail(buffer, fieldName, (int[]) value);
} else {
appendSummary(buffer, fieldName, (int[]) value);
}
} else if (value instanceof short[]) {
if (detail) {
appendDetail(buffer, fieldName, (short[]) value);
} else {
appendSummary(buffer, fieldName, (short[]) value);
}
} else if (value instanceof byte[]) {
if (detail) {
appendDetail(buffer, fieldName, (byte[]) value);
} else {
appendSummary(buffer, fieldName, (byte[]) value);
}
} else if (value instanceof char[]) {
if (detail) {
appendDetail(buffer, fieldName, (char[]) value);
} else {
appendSummary(buffer, fieldName, (char[]) value);
}
} else if (value instanceof double[]) {
if (detail) {
appendDetail(buffer, fieldName, (double[]) value);
} else {
appendSummary(buffer, fieldName, (double[]) value);
}
} else if (value instanceof float[]) {
if (detail) {
appendDetail(buffer, fieldName, (float[]) value);
} else {
appendSummary(buffer, fieldName, (float[]) value);
}
} else if (value instanceof boolean[]) {
if (detail) {
appendDetail(buffer, fieldName, (boolean[]) value);
} else {
appendSummary(buffer, fieldName, (boolean[]) value);
}
} else if (value.getClass().isArray()) {
if (detail) {
appendDetail(buffer, fieldName, (Object[]) value);
} else {
appendSummary(buffer, fieldName, (Object[]) value);
}
} else {
if (detail) {
appendDetail(buffer, fieldName, value);
} else {
appendSummary(buffer, fieldName, value);
}
}
} finally {
unregister(value);
}
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value that has been detected to participate in a cycle. This
* implementation will print the standard string value of the value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
*
* @since 2.2
*/
protected void appendCyclicObject(StringBuffer buffer, String fieldName, Object value) {
ObjectUtils.identityToString(buffer, value);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value, printing the full detail of the <code>Object</code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
buffer.append(value);
}
/**
* <p>Append to the <code>toString</code> a <code>Collection</code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param coll the <code>Collection</code> to add to the
* <code>toString</code>, not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Collection<?> coll) {
buffer.append(coll);
}
/**
* <p>Append to the <code>toString</code> a <code>Map<code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param map the <code>Map</code> to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Map<?, ?> map) {
buffer.append(map);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value, printing a summary of the <code>Object</code>.</P>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, Object value) {
buffer.append(summaryObjectStartText);
buffer.append(getShortClassName(value.getClass()));
buffer.append(summaryObjectEndText);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, long value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, long value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, int value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, int value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, short value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, short value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, byte value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, byte value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, char value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, char value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, double value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, double value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, float value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, float value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, boolean value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) {
buffer.append(value);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> the detail of an
* <code>Object</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
Object item = array[i];
if (i > 0) {
buffer.append(arraySeparator);
}
if (item == null) {
appendNullText(buffer, fieldName);
} else {
appendInternal(buffer, fieldName, item, arrayContentDetail);
}
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> the detail of an array type.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
* @since 2.0
*/
protected void reflectionAppendArrayDetail(StringBuffer buffer, String fieldName, Object array) {
buffer.append(arrayStart);
int length = Array.getLength(array);
for (int i = 0; i < length; i++) {
Object item = Array.get(array, i);
if (i > 0) {
buffer.append(arraySeparator);
}
if (item == null) {
appendNullText(buffer, fieldName);
} else {
appendInternal(buffer, fieldName, item, arrayContentDetail);
}
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of an
* <code>Object</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>long</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>long</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of an
* <code>int</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of an
* <code>int</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>short</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>short</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>byte</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>byte</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>char</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>char</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>double</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>double</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>float</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>float</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>boolean</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>boolean</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> the class name.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> whose name to output
*/
protected void appendClassName(StringBuffer buffer, Object object) {
if (useClassName && object != null) {
register(object);
if (useShortClassName) {
buffer.append(getShortClassName(object.getClass()));
} else {
buffer.append(object.getClass().getName());
}
}
}
/**
* <p>Append the {@link System#identityHashCode(java.lang.Object)}.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> whose id to output
*/
protected void appendIdentityHashCode(StringBuffer buffer, Object object) {
if (this.isUseIdentityHashCode() && object!=null) {
register(object);
buffer.append('@');
buffer.append(Integer.toHexString(System.identityHashCode(object)));
}
}
/**
* <p>Append to the <code>toString</code> the content start.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
*/
protected void appendContentStart(StringBuffer buffer) {
buffer.append(contentStart);
}
/**
* <p>Append to the <code>toString</code> the content end.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
*/
protected void appendContentEnd(StringBuffer buffer) {
buffer.append(contentEnd);
}
/**
* <p>Append to the <code>toString</code> an indicator for <code>null</code>.</p>
*
* <p>The default indicator is <code>'<null>'</code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
*/
protected void appendNullText(StringBuffer buffer, String fieldName) {
buffer.append(nullText);
}
/**
* <p>Append to the <code>toString</code> the field separator.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
*/
protected void appendFieldSeparator(StringBuffer buffer) {
buffer.append(fieldSeparator);
}
/**
* <p>Append to the <code>toString</code> the field start.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
*/
protected void appendFieldStart(StringBuffer buffer, String fieldName) {
if (useFieldNames && fieldName != null) {
buffer.append(fieldName);
buffer.append(fieldNameValueSeparator);
}
}
/**
* <p>Append to the <code>toString<code> the field end.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
*/
protected void appendFieldEnd(StringBuffer buffer, String fieldName) {
appendFieldSeparator(buffer);
}
/**
* <p>Append to the <code>toString</code> a size summary.</p>
*
* <p>The size summary is used to summarize the contents of
* <code>Collections</code>, <code>Maps</code> and arrays.</p>
*
* <p>The output consists of a prefix, the passed in size
* and a suffix.</p>
*
* <p>The default format is <code>'<size=n>'<code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param size the size to append
*/
protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) {
buffer.append(sizeStartText);
buffer.append(size);
buffer.append(sizeEndText);
}
/**
* <p>Is this field to be output in full detail.</p>
*
* <p>This method converts a detail request into a detail level.
* The calling code may request full detail (<code>true</code>),
* but a subclass might ignore that and always return
* <code>false</code>. The calling code may pass in
* <code>null</code> indicating that it doesn't care about
* the detail level. In this case the default detail level is
* used.</p>
*
* @param fullDetailRequest the detail level requested
* @return whether full detail is to be shown
*/
protected boolean isFullDetail(Boolean fullDetailRequest) {
if (fullDetailRequest == null) {
return defaultFullDetail;
}
return fullDetailRequest.booleanValue();
}
/**
* <p>Gets the short class name for a class.</p>
*
* <p>The short class name is the classname excluding
* the package name.</p>
*
* @param cls the <code>Class</code> to get the short name of
* @return the short name
*/
protected String getShortClassName(Class<?> cls) {
return ClassUtils.getShortClassName(cls);
}
// Setters and getters for the customizable parts of the style
// These methods are not expected to be overridden, except to make public
// (They are not public so that immutable subclasses can be written)
//---------------------------------------------------------------------
/**
* <p>Gets whether to use the class name.</p>
*
* @return the current useClassName flag
*/
protected boolean isUseClassName() {
return useClassName;
}
/**
* <p>Sets whether to use the class name.</p>
*
* @param useClassName the new useClassName flag
*/
protected void setUseClassName(boolean useClassName) {
this.useClassName = useClassName;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to output short or long class names.</p>
*
* @return the current useShortClassName flag
* @since 2.0
*/
protected boolean isUseShortClassName() {
return useShortClassName;
}
/**
* <p>Sets whether to output short or long class names.</p>
*
* @param useShortClassName the new useShortClassName flag
* @since 2.0
*/
protected void setUseShortClassName(boolean useShortClassName) {
this.useShortClassName = useShortClassName;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to use the identity hash code.</p>
*
* @return the current useIdentityHashCode flag
*/
protected boolean isUseIdentityHashCode() {
return useIdentityHashCode;
}
/**
* <p>Sets whether to use the identity hash code.</p>
*
* @param useIdentityHashCode the new useIdentityHashCode flag
*/
protected void setUseIdentityHashCode(boolean useIdentityHashCode) {
this.useIdentityHashCode = useIdentityHashCode;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to use the field names passed in.</p>
*
* @return the current useFieldNames flag
*/
protected boolean isUseFieldNames() {
return useFieldNames;
}
/**
* <p>Sets whether to use the field names passed in.</p>
*
* @param useFieldNames the new useFieldNames flag
*/
protected void setUseFieldNames(boolean useFieldNames) {
this.useFieldNames = useFieldNames;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to use full detail when the caller doesn't
* specify.</p>
*
* @return the current defaultFullDetail flag
*/
protected boolean isDefaultFullDetail() {
return defaultFullDetail;
}
/**
* <p>Sets whether to use full detail when the caller doesn't
* specify.</p>
*
* @param defaultFullDetail the new defaultFullDetail flag
*/
protected void setDefaultFullDetail(boolean defaultFullDetail) {
this.defaultFullDetail = defaultFullDetail;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to output array content detail.</p>
*
* @return the current array content detail setting
*/
protected boolean isArrayContentDetail() {
return arrayContentDetail;
}
/**
* <p>Sets whether to output array content detail.</p>
*
* @param arrayContentDetail the new arrayContentDetail flag
*/
protected void setArrayContentDetail(boolean arrayContentDetail) {
this.arrayContentDetail = arrayContentDetail;
}
//---------------------------------------------------------------------
/**
* <p>Gets the array start text.</p>
*
* @return the current array start text
*/
protected String getArrayStart() {
return arrayStart;
}
/**
* <p>Sets the array start text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param arrayStart the new array start text
*/
protected void setArrayStart(String arrayStart) {
if (arrayStart == null) {
arrayStart = "";
}
this.arrayStart = arrayStart;
}
//---------------------------------------------------------------------
/**
* <p>Gets the array end text.</p>
*
* @return the current array end text
*/
protected String getArrayEnd() {
return arrayEnd;
}
/**
* <p>Sets the array end text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param arrayEnd the new array end text
*/
protected void setArrayEnd(String arrayEnd) {
if (arrayEnd == null) {
arrayEnd = "";
}
this.arrayEnd = arrayEnd;
}
//---------------------------------------------------------------------
/**
* <p>Gets the array separator text.</p>
*
* @return the current array separator text
*/
protected String getArraySeparator() {
return arraySeparator;
}
/**
* <p>Sets the array separator text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param arraySeparator the new array separator text
*/
protected void setArraySeparator(String arraySeparator) {
if (arraySeparator == null) {
arraySeparator = "";
}
this.arraySeparator = arraySeparator;
}
//---------------------------------------------------------------------
/**
* <p>Gets the content start text.</p>
*
* @return the current content start text
*/
protected String getContentStart() {
return contentStart;
}
/**
* <p>Sets the content start text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param contentStart the new content start text
*/
protected void setContentStart(String contentStart) {
if (contentStart == null) {
contentStart = "";
}
this.contentStart = contentStart;
}
//---------------------------------------------------------------------
/**
* <p>Gets the content end text.</p>
*
* @return the current content end text
*/
protected String getContentEnd() {
return contentEnd;
}
/**
* <p>Sets the content end text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param contentEnd the new content end text
*/
protected void setContentEnd(String contentEnd) {
if (contentEnd == null) {
contentEnd = "";
}
this.contentEnd = contentEnd;
}
//---------------------------------------------------------------------
/**
* <p>Gets the field name value separator text.</p>
*
* @return the current field name value separator text
*/
protected String getFieldNameValueSeparator() {
return fieldNameValueSeparator;
}
/**
* <p>Sets the field name value separator text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param fieldNameValueSeparator the new field name value separator text
*/
protected void setFieldNameValueSeparator(String fieldNameValueSeparator) {
if (fieldNameValueSeparator == null) {
fieldNameValueSeparator = "";
}
this.fieldNameValueSeparator = fieldNameValueSeparator;
}
//---------------------------------------------------------------------
/**
* <p>Gets the field separator text.</p>
*
* @return the current field separator text
*/
protected String getFieldSeparator() {
return fieldSeparator;
}
/**
* <p>Sets the field separator text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param fieldSeparator the new field separator text
*/
protected void setFieldSeparator(String fieldSeparator) {
if (fieldSeparator == null) {
fieldSeparator = "";
}
this.fieldSeparator = fieldSeparator;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether the field separator should be added at the start
* of each buffer.</p>
*
* @return the fieldSeparatorAtStart flag
* @since 2.0
*/
protected boolean isFieldSeparatorAtStart() {
return fieldSeparatorAtStart;
}
/**
* <p>Sets whether the field separator should be added at the start
* of each buffer.</p>
*
* @param fieldSeparatorAtStart the fieldSeparatorAtStart flag
* @since 2.0
*/
protected void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) {
this.fieldSeparatorAtStart = fieldSeparatorAtStart;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether the field separator should be added at the end
* of each buffer.</p>
*
* @return fieldSeparatorAtEnd flag
* @since 2.0
*/
protected boolean isFieldSeparatorAtEnd() {
return fieldSeparatorAtEnd;
}
/**
* <p>Sets whether the field separator should be added at the end
* of each buffer.</p>
*
* @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag
* @since 2.0
*/
protected void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) {
this.fieldSeparatorAtEnd = fieldSeparatorAtEnd;
}
//---------------------------------------------------------------------
/**
* <p>Gets the text to output when <code>null</code> found.</p>
*
* @return the current text to output when null found
*/
protected String getNullText() {
return nullText;
}
/**
* <p>Sets the text to output when <code>null</code> found.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param nullText the new text to output when null found
*/
protected void setNullText(String nullText) {
if (nullText == null) {
nullText = "";
}
this.nullText = nullText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the start text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output before the size value.</p>
*
* @return the current start of size text
*/
protected String getSizeStartText() {
return sizeStartText;
}
/**
* <p>Sets the start text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output before the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param sizeStartText the new start of size text
*/
protected void setSizeStartText(String sizeStartText) {
if (sizeStartText == null) {
sizeStartText = "";
}
this.sizeStartText = sizeStartText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the end text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output after the size value.</p>
*
* @return the current end of size text
*/
protected String getSizeEndText() {
return sizeEndText;
}
/**
* <p>Sets the end text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output after the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param sizeEndText the new end of size text
*/
protected void setSizeEndText(String sizeEndText) {
if (sizeEndText == null) {
sizeEndText = "";
}
this.sizeEndText = sizeEndText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the start text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output before the size value.</p>
*
* @return the current start of summary text
*/
protected String getSummaryObjectStartText() {
return summaryObjectStartText;
}
/**
* <p>Sets the start text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output before the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param summaryObjectStartText the new start of summary text
*/
protected void setSummaryObjectStartText(String summaryObjectStartText) {
if (summaryObjectStartText == null) {
summaryObjectStartText = "";
}
this.summaryObjectStartText = summaryObjectStartText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the end text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output after the size value.</p>
*
* @return the current end of summary text
*/
protected String getSummaryObjectEndText() {
return summaryObjectEndText;
}
/**
* <p>Sets the end text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output after the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param summaryObjectEndText the new end of summary text
*/
protected void setSummaryObjectEndText(String summaryObjectEndText) {
if (summaryObjectEndText == null) {
summaryObjectEndText = "";
}
this.summaryObjectEndText = summaryObjectEndText;
}
//----------------------------------------------------------------------------
/**
* <p>Default <code>ToStringStyle</code>.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class DefaultToStringStyle extends ToStringStyle {
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
DefaultToStringStyle() {
super();
}
/**
* <p>Ensure <code>Singleton</code> after serialization.</p>
*
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.DEFAULT_STYLE;
}
}
//----------------------------------------------------------------------------
/**
* <p><code>ToStringStyle</code> that does not print out
* the field names.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.
*/
private static final class NoFieldNameToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
NoFieldNameToStringStyle() {
super();
this.setUseFieldNames(false);
}
/**
* <p>Ensure <code>Singleton</code> after serialization.</p>
*
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.NO_FIELD_NAMES_STYLE;
}
}
//----------------------------------------------------------------------------
/**
* <p><code>ToStringStyle</code> that prints out the short
* class name and no identity hashcode.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class ShortPrefixToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
ShortPrefixToStringStyle() {
super();
this.setUseShortClassName(true);
this.setUseIdentityHashCode(false);
}
/**
* <p>Ensure <code>Singleton</ode> after serialization.</p>
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.SHORT_PREFIX_STYLE;
}
}
/**
* <p><code>ToStringStyle</code> that does not print out the
* classname, identity hashcode, content start or field name.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class SimpleToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
SimpleToStringStyle() {
super();
this.setUseClassName(false);
this.setUseIdentityHashCode(false);
this.setUseFieldNames(false);
this.setContentStart("");
this.setContentEnd("");
}
/**
* <p>Ensure <code>Singleton</ode> after serialization.</p>
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.SIMPLE_STYLE;
}
}
//----------------------------------------------------------------------------
/**
* <p><code>ToStringStyle</code> that outputs on multiple lines.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class MultiLineToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
MultiLineToStringStyle() {
super();
this.setContentStart("[");
this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + " ");
this.setFieldSeparatorAtStart(true);
this.setContentEnd(SystemUtils.LINE_SEPARATOR + "]");
}
/**
* <p>Ensure <code>Singleton</code> after serialization.</p>
*
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.MULTI_LINE_STYLE;
}
}
}
| Documentation
git-svn-id: bab3daebc4e66440cbcc4aded890e63215874748@1298506 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java | Documentation | <ide><path>rc/main/java/org/apache/commons/lang3/builder/ToStringStyle.java
<ide> */
<ide> private static final ThreadLocal<WeakHashMap<Object, Object>> REGISTRY =
<ide> new ThreadLocal<WeakHashMap<Object,Object>>();
<add> /*
<add> * Note that objects of this class are generally shared between threads, so
<add> * an instance variable would not be suitable here.
<add> *
<add> * In normal use the registry should always be left empty, because the caller
<add> * should call toString() which will clean up.
<add> *
<add> * See LANG-792
<add> */
<ide>
<ide> /**
<ide> * <p> |
|
Java | apache-2.0 | 515b57fcc61e93512652326378b5fc0edb22ce94 | 0 | ingenieux/beanstalker,ingenieux/beanstalker | package br.com.ingenieux.mojo.beanstalk.env;
/*
* 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.
*/
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.isBlank;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.plugin.AbstractMojoExecutionException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesCommand;
import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesContext;
import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesContextBuilder;
import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentCommand;
import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentContext;
import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentContextBuilder;
import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentCommand;
import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentContext;
import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentContextBuilder;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting;
import com.amazonaws.services.elasticbeanstalk.model.CreateEnvironmentResult;
import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationSettingsRequest;
import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationSettingsResult;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription;
/**
* Launches a new environment and, when done, replace with the existing,
* terminating when needed. It combines both create-environment,
* wait-for-environment, swap-environment-cnames, and terminate-environment
*
* @since 0.2.0
*/
@Mojo(name="replace-environment")
// Best Guess Evar
public class ReplaceEnvironmentMojo extends CreateEnvironmentMojo {
/**
*
*/
private static final Pattern PATTERN_NUMBERED = Pattern
.compile("^(.*)-(\\d+)$");
/**
* Max Environment Name
*/
private static final int MAX_ENVNAME_LEN = 23;
/**
* Minutes until timeout
*/
@Parameter(property="beanstalk.timeoutMins", defaultValue = "20")
Integer timeoutMins;
@Override
protected EnvironmentDescription handleResults(List<EnvironmentDescription> environments)
throws MojoExecutionException {
// Don't care - We're an exception to the rule, you know.
return null;
}
@Override
protected Object executeInternal() throws AbstractMojoExecutionException {
/*
* Is the desired cname not being used by other environments? If so,
* just launch the environment
*/
if (!hasEnvironmentFor(applicationName, cnamePrefix)) {
if (getLog().isInfoEnabled())
getLog().info("Just launching a new environment.");
return super.executeInternal();
}
/*
* Gets the current environment using this cname
*/
EnvironmentDescription curEnv = getEnvironmentFor(applicationName,
cnamePrefix);
/*
* Decides on a cnamePrefix, and launches a new environment
*/
String cnamePrefixToCreate = getCNamePrefixToCreate();
if (getLog().isInfoEnabled())
getLog().info(
"Creating a new environment on " + cnamePrefixToCreate
+ ".elasticbeanstalk.com");
copyOptionSettings(curEnv);
if (! solutionStack.equals(curEnv.getSolutionStackName())) {
if (getLog().isInfoEnabled())
getLog().info(
format("(btw, we're launching with solutionStack/ set to '%s' instead of the default ('%s'). " +
"If this is not the case, then we kindly ask you to file a bug report on the mailing list :)",
curEnv.getSolutionStackName(), solutionStack));
solutionStack = curEnv.getSolutionStackName();
}
String newEnvironmentName = getNewEnvironmentName(this.environmentName);
if (getLog().isInfoEnabled())
getLog().info("And it'll be named " + newEnvironmentName);
CreateEnvironmentResult createEnvResult = createEnvironment(
cnamePrefixToCreate, newEnvironmentName);
/*
* Waits for completion
*/
EnvironmentDescription newEnvDesc = null;
try {
newEnvDesc = waitForEnvironment(createEnvResult.getEnvironmentId());
} catch (Exception exc) {
/*
* Terminates the failed launched environment
*/
terminateAndWaitForEnvironment(createEnvResult.getEnvironmentId());
handleException(exc);
return null;
}
/*
* Swaps
*/
swapEnvironmentCNames(newEnvDesc.getEnvironmentId(),
curEnv.getEnvironmentId(), cnamePrefix);
/*
* Terminates the previous environment - and waits for it
*/
terminateAndWaitForEnvironment(curEnv.getEnvironmentId());
return createEnvResult;
}
/**
* Prior to Launching a New Environment, lets look and copy the most we can
*
* @param curEnv
* current environment
*/
private void copyOptionSettings(EnvironmentDescription curEnv) {
/**
* Skip if we don't have anything
*/
if (null != this.optionSettings && this.optionSettings.length > 0)
return;
DescribeConfigurationSettingsResult configSettings = getService()
.describeConfigurationSettings(
new DescribeConfigurationSettingsRequest()
.withApplicationName(applicationName)
.withEnvironmentName(
curEnv.getEnvironmentName()));
List<ConfigurationOptionSetting> newOptionSettings = new ArrayList<ConfigurationOptionSetting>(
configSettings.getConfigurationSettings().get(0)
.getOptionSettings());
ListIterator<ConfigurationOptionSetting> listIterator = newOptionSettings
.listIterator();
while (listIterator.hasNext()) {
ConfigurationOptionSetting curOptionSetting = listIterator.next();
/*
* Filters out harmful options
*
* I really mean harmful - If you mention a terminated environment
* settings, Elastic Beanstalk will accept, but this might lead to
* inconsistent states, specially when creating / listing environments.
*
* Trust me on this one.
*/
boolean bInvalid = isBlank(curOptionSetting.getValue());
if (!bInvalid)
bInvalid |= (curOptionSetting.getNamespace().equals(
"aws:cloudformation:template:parameter") && curOptionSetting
.getOptionName().equals("AppSource"));
if (!bInvalid)
bInvalid |= (curOptionSetting.getNamespace().equals(
"aws:elasticbeanstalk:sns:topics") && curOptionSetting
.getOptionName().equals("Notification Topic ARN"));
if (!bInvalid)
bInvalid |= (curOptionSetting.getValue().contains(curEnv
.getEnvironmentId()));
if (bInvalid) {
getLog().debug(format("Excluding Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(), curOptionSetting.getOptionName(), curOptionSetting.getValue()));
listIterator.remove();
} else {
getLog().debug(format("Using Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(), curOptionSetting.getOptionName(), curOptionSetting.getValue()));
}
}
/*
* Then copy it back
*/
this.optionSettings = newOptionSettings
.toArray(new ConfigurationOptionSetting[newOptionSettings
.size()]);
}
/**
* Swaps environment cnames
*
* @param newEnvironmentId
* environment id
* @param curEnvironmentId
* environment id
* @param cnamePrefix
* @throws AbstractMojoExecutionException
*/
protected void swapEnvironmentCNames(String newEnvironmentId,
String curEnvironmentId, String cnamePrefix)
throws AbstractMojoExecutionException {
getLog().info(
"Swapping environment cnames " + newEnvironmentId + " and "
+ curEnvironmentId);
{
SwapCNamesContext context = SwapCNamesContextBuilder
.swapCNamesContext()//
.withSourceEnvironmentId(newEnvironmentId)//
.withDestinationEnvironmentId(curEnvironmentId)//
.build();
SwapCNamesCommand command = new SwapCNamesCommand(this);
command.execute(context);
}
{
WaitForEnvironmentContext context = new WaitForEnvironmentContextBuilder()
.withApplicationName(applicationName)//
.withStatusToWaitFor("Ready")//
.withEnvironmentId(newEnvironmentId)//
.withTimeoutMins(timeoutMins)//
.withDomainToWaitFor(cnamePrefix).build();
WaitForEnvironmentCommand command = new WaitForEnvironmentCommand(
this);
command.execute(context);
}
}
/**
* Terminates and waits for an environment
*
* @param environmentId
* environment id to terminate
* @throws AbstractMojoExecutionException
*/
protected void terminateAndWaitForEnvironment(String environmentId)
throws AbstractMojoExecutionException {
{
getLog().info("Terminating environmentId=" + environmentId);
TerminateEnvironmentContext terminatecontext = new TerminateEnvironmentContextBuilder()
.withEnvironmentId(environmentId)
.withTerminateResources(true).build();
TerminateEnvironmentCommand command = new TerminateEnvironmentCommand(
this);
command.execute(terminatecontext);
}
{
WaitForEnvironmentContext context = new WaitForEnvironmentContextBuilder()
.withApplicationName(applicationName)
.withEnvironmentId(environmentId)
.withStatusToWaitFor("Terminated")
.withTimeoutMins(timeoutMins).build();
WaitForEnvironmentCommand command = new WaitForEnvironmentCommand(
this);
command.execute(context);
}
}
/**
* Waits for an environment to get ready. Throws an exception either if this
* environment couldn't get into Ready state or there was a timeout
*
* @param environmentId
* environmentId to wait for
* @return EnvironmentDescription in Ready state
* @throws AbstractMojoExecutionException
*/
protected EnvironmentDescription waitForEnvironment(String environmentId)
throws AbstractMojoExecutionException {
getLog().info(
"Waiting for environmentId " + environmentId
+ " to get into Ready state");
WaitForEnvironmentContext context = new WaitForEnvironmentContextBuilder()
.withApplicationName(applicationName)
.withStatusToWaitFor("Ready").withEnvironmentId(environmentId)
.withTimeoutMins(timeoutMins).build();
WaitForEnvironmentCommand command = new WaitForEnvironmentCommand(this);
return command.execute(context);
}
/**
* Creates a cname prefix if needed, or returns the desired one
*
* @return cname prefix to launch environment into
*/
protected String getCNamePrefixToCreate() {
String cnamePrefixToReturn = cnamePrefix;
int i = 0;
while (hasEnvironmentFor(applicationName, cnamePrefixToReturn))
cnamePrefixToReturn = String.format("%s-%d", cnamePrefix, i++);
return cnamePrefixToReturn;
}
/**
* Boolean predicate for environment existence
*
* @param applicationName
* application name
* @param cnamePrefix
* cname prefix
* @return true if the application name has this cname prefix
*/
protected boolean hasEnvironmentFor(String applicationName,
String cnamePrefix) {
return null != getEnvironmentFor(applicationName, cnamePrefix);
}
/**
* Returns the environment description matching applicationName and
* cnamePrefix
*
* @param applicationName
* application name
* @param cnamePrefix
* cname prefix
* @return environment description
*/
protected EnvironmentDescription getEnvironmentFor(String applicationName,
String cnamePrefix) {
Collection<EnvironmentDescription> environments = getEnvironmentsFor(applicationName);
String cnameToMatch = String.format("%s.elasticbeanstalk.com",
cnamePrefix);
/*
* Finds a matching environment
*/
for (EnvironmentDescription envDesc : environments)
if (envDesc.getCNAME().equals(cnameToMatch))
return envDesc;
return null;
}
private String getNewEnvironmentName(String newEnvironmentName) {
String result = newEnvironmentName;
String environmentRadical = result;
int i = 0;
{
Matcher matcher = PATTERN_NUMBERED.matcher(newEnvironmentName);
if (matcher.matches()) {
environmentRadical = matcher.group(1);
i = 1 + Integer.valueOf(matcher.group(2));
}
}
while (containsNamedEnvironment(result))
result = formatAndTruncate("%s-%d", MAX_ENVNAME_LEN,
environmentRadical, i++);
return result;
}
/**
* Elastic Beanstalk Contains a Max EnvironmentName Limit. Lets truncate it,
* shall we?
*
* @param mask
* String.format Mask
* @param maxLen
* Maximum Length
* @param args
* String.format args
* @return formatted String, or maxLen rightmost characters
*/
protected String formatAndTruncate(String mask, int maxLen, Object... args) {
String result = String.format(mask, args);
if (result.length() > maxLen)
result = result
.substring(result.length() - maxLen, result.length());
return result;
}
/**
* Boolean predicate for named environment
*
* @param environmentName
* environment name
* @return true if environment name exists
*/
protected boolean containsNamedEnvironment(String environmentName) {
for (EnvironmentDescription envDesc : getEnvironmentsFor(applicationName))
if (envDesc.getEnvironmentName().equals(environmentName))
return true;
return false;
}
}
| beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/env/ReplaceEnvironmentMojo.java | package br.com.ingenieux.mojo.beanstalk.env;
/*
* 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.
*/
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.isBlank;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.ListIterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.plugin.AbstractMojoExecutionException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesCommand;
import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesContext;
import br.com.ingenieux.mojo.beanstalk.cmd.env.swap.SwapCNamesContextBuilder;
import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentCommand;
import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentContext;
import br.com.ingenieux.mojo.beanstalk.cmd.env.terminate.TerminateEnvironmentContextBuilder;
import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentCommand;
import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentContext;
import br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor.WaitForEnvironmentContextBuilder;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting;
import com.amazonaws.services.elasticbeanstalk.model.CreateEnvironmentResult;
import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationSettingsRequest;
import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationSettingsResult;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription;
/**
* Launches a new environment and, when done, replace with the existing,
* terminating when needed. It combines both create-environment,
* wait-for-environment, swap-environment-cnames, and terminate-environment
*
* @since 0.2.0
*/
@Mojo(name="replace-environment")
// Best Guess Evar
public class ReplaceEnvironmentMojo extends CreateEnvironmentMojo {
/**
*
*/
private static final Pattern PATTERN_NUMBERED = Pattern
.compile("^(.*)-(\\d+)$");
/**
* Max Environment Name
*/
private static final int MAX_ENVNAME_LEN = 23;
/**
* Minutes until timeout
*/
@Parameter(property="beanstalk.timeoutMins", defaultValue = "20")
Integer timeoutMins;
@Override
protected EnvironmentDescription handleResults(List<EnvironmentDescription> environments)
throws MojoExecutionException {
// Don't care - We're an exception to the rule, you know.
return null;
}
@Override
protected Object executeInternal() throws AbstractMojoExecutionException {
/*
* Is the desired cname not being used by other environments? If so,
* just launch the environment
*/
if (!hasEnvironmentFor(applicationName, cnamePrefix)) {
if (getLog().isInfoEnabled())
getLog().info("Just launching a new environment.");
return super.executeInternal();
}
/*
* Gets the current environment using this cname
*/
EnvironmentDescription curEnv = getEnvironmentFor(applicationName,
cnamePrefix);
/*
* Decides on a cnamePrefix, and launches a new environment
*/
String cnamePrefixToCreate = getCNamePrefixToCreate();
if (getLog().isInfoEnabled())
getLog().info(
"Creating a new environment on " + cnamePrefixToCreate
+ ".elasticbeanstalk.com");
copyOptionSettings(curEnv);
if (! solutionStack.equals(curEnv.getSolutionStackName())) {
if (getLog().isInfoEnabled())
getLog().info(
format("(btw, we're launching with solutionStack/ set to '%s' instead of the default ('%s'). " +
"If this is not the case, then we kindly ask you to file a bug report on the mailing list :)",
curEnv.getSolutionStackName(), solutionStack));
solutionStack = curEnv.getSolutionStackName();
}
String newEnvironmentName = getNewEnvironmentName(this.environmentName);
if (getLog().isInfoEnabled())
getLog().info("And it'll be named " + newEnvironmentName);
CreateEnvironmentResult createEnvResult = createEnvironment(
cnamePrefixToCreate, newEnvironmentName);
/*
* Waits for completion
*/
EnvironmentDescription newEnvDesc = null;
try {
newEnvDesc = waitForEnvironment(createEnvResult.getEnvironmentId());
} catch (Exception exc) {
/*
* Terminates the failed launched environment
*/
terminateAndWaitForEnvironment(createEnvResult.getEnvironmentId());
handleException(exc);
return null;
}
/*
* Swaps
*/
swapEnvironmentCNames(newEnvDesc.getEnvironmentId(),
curEnv.getEnvironmentId(), cnamePrefix);
/*
* Terminates the previous environment - and waits for it
*/
terminateAndWaitForEnvironment(curEnv.getEnvironmentId());
return createEnvResult;
}
/**
* Prior to Launching a New Environment, lets look and copy the most we can
*
* @param curEnv
* current environment
*/
private void copyOptionSettings(EnvironmentDescription curEnv) {
/**
* Skip if we don't have anything
*/
if (null != this.optionSettings && this.optionSettings.length > 0)
return;
DescribeConfigurationSettingsResult configSettings = getService()
.describeConfigurationSettings(
new DescribeConfigurationSettingsRequest()
.withApplicationName(applicationName)
.withEnvironmentName(
curEnv.getEnvironmentName()));
List<ConfigurationOptionSetting> newOptionSettings = new ArrayList<ConfigurationOptionSetting>(
configSettings.getConfigurationSettings().get(0)
.getOptionSettings());
ListIterator<ConfigurationOptionSetting> listIterator = newOptionSettings
.listIterator();
while (listIterator.hasNext()) {
ConfigurationOptionSetting curOptionSetting = listIterator.next();
/*
* Filters out harmful options
*
* I really mean harmful - If you mention a terminated environment
* settings, Elastic Beanstalk will accept, but this might lead to
* inconsistent states, specially when creating / listing environments.
*
* Trust me on this one.
*/
boolean bInvalid = isBlank(curOptionSetting.getValue());
if (!bInvalid)
bInvalid |= (curOptionSetting.getNamespace().equals(
"aws:cloudformation:template:parameter") && curOptionSetting
.getOptionName().equals("AppSource"));
if (!bInvalid)
bInvalid |= (curOptionSetting.getValue().contains(curEnv
.getEnvironmentId()));
if (bInvalid) {
getLog().debug(format("Excluding Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(), curOptionSetting.getOptionName(), curOptionSetting.getValue()));
listIterator.remove();
} else {
getLog().debug(format("Using Option Setting: %s:%s['%s']", curOptionSetting.getNamespace(), curOptionSetting.getOptionName(), curOptionSetting.getValue()));
}
}
/*
* Then copy it back
*/
this.optionSettings = newOptionSettings
.toArray(new ConfigurationOptionSetting[newOptionSettings
.size()]);
}
/**
* Swaps environment cnames
*
* @param newEnvironmentId
* environment id
* @param curEnvironmentId
* environment id
* @param cnamePrefix
* @throws AbstractMojoExecutionException
*/
protected void swapEnvironmentCNames(String newEnvironmentId,
String curEnvironmentId, String cnamePrefix)
throws AbstractMojoExecutionException {
getLog().info(
"Swapping environment cnames " + newEnvironmentId + " and "
+ curEnvironmentId);
{
SwapCNamesContext context = SwapCNamesContextBuilder
.swapCNamesContext()//
.withSourceEnvironmentId(newEnvironmentId)//
.withDestinationEnvironmentId(curEnvironmentId)//
.build();
SwapCNamesCommand command = new SwapCNamesCommand(this);
command.execute(context);
}
{
WaitForEnvironmentContext context = new WaitForEnvironmentContextBuilder()
.withApplicationName(applicationName)//
.withStatusToWaitFor("Ready")//
.withEnvironmentId(newEnvironmentId)//
.withTimeoutMins(timeoutMins)//
.withDomainToWaitFor(cnamePrefix).build();
WaitForEnvironmentCommand command = new WaitForEnvironmentCommand(
this);
command.execute(context);
}
}
/**
* Terminates and waits for an environment
*
* @param environmentId
* environment id to terminate
* @throws AbstractMojoExecutionException
*/
protected void terminateAndWaitForEnvironment(String environmentId)
throws AbstractMojoExecutionException {
{
getLog().info("Terminating environmentId=" + environmentId);
TerminateEnvironmentContext terminatecontext = new TerminateEnvironmentContextBuilder()
.withEnvironmentId(environmentId)
.withTerminateResources(true).build();
TerminateEnvironmentCommand command = new TerminateEnvironmentCommand(
this);
command.execute(terminatecontext);
}
{
WaitForEnvironmentContext context = new WaitForEnvironmentContextBuilder()
.withApplicationName(applicationName)
.withEnvironmentId(environmentId)
.withStatusToWaitFor("Terminated")
.withTimeoutMins(timeoutMins).build();
WaitForEnvironmentCommand command = new WaitForEnvironmentCommand(
this);
command.execute(context);
}
}
/**
* Waits for an environment to get ready. Throws an exception either if this
* environment couldn't get into Ready state or there was a timeout
*
* @param environmentId
* environmentId to wait for
* @return EnvironmentDescription in Ready state
* @throws AbstractMojoExecutionException
*/
protected EnvironmentDescription waitForEnvironment(String environmentId)
throws AbstractMojoExecutionException {
getLog().info(
"Waiting for environmentId " + environmentId
+ " to get into Ready state");
WaitForEnvironmentContext context = new WaitForEnvironmentContextBuilder()
.withApplicationName(applicationName)
.withStatusToWaitFor("Ready").withEnvironmentId(environmentId)
.withTimeoutMins(timeoutMins).build();
WaitForEnvironmentCommand command = new WaitForEnvironmentCommand(this);
return command.execute(context);
}
/**
* Creates a cname prefix if needed, or returns the desired one
*
* @return cname prefix to launch environment into
*/
protected String getCNamePrefixToCreate() {
String cnamePrefixToReturn = cnamePrefix;
int i = 0;
while (hasEnvironmentFor(applicationName, cnamePrefixToReturn))
cnamePrefixToReturn = String.format("%s-%d", cnamePrefix, i++);
return cnamePrefixToReturn;
}
/**
* Boolean predicate for environment existence
*
* @param applicationName
* application name
* @param cnamePrefix
* cname prefix
* @return true if the application name has this cname prefix
*/
protected boolean hasEnvironmentFor(String applicationName,
String cnamePrefix) {
return null != getEnvironmentFor(applicationName, cnamePrefix);
}
/**
* Returns the environment description matching applicationName and
* cnamePrefix
*
* @param applicationName
* application name
* @param cnamePrefix
* cname prefix
* @return environment description
*/
protected EnvironmentDescription getEnvironmentFor(String applicationName,
String cnamePrefix) {
Collection<EnvironmentDescription> environments = getEnvironmentsFor(applicationName);
String cnameToMatch = String.format("%s.elasticbeanstalk.com",
cnamePrefix);
/*
* Finds a matching environment
*/
for (EnvironmentDescription envDesc : environments)
if (envDesc.getCNAME().equals(cnameToMatch))
return envDesc;
return null;
}
private String getNewEnvironmentName(String newEnvironmentName) {
String result = newEnvironmentName;
String environmentRadical = result;
int i = 0;
{
Matcher matcher = PATTERN_NUMBERED.matcher(newEnvironmentName);
if (matcher.matches()) {
environmentRadical = matcher.group(1);
i = 1 + Integer.valueOf(matcher.group(2));
}
}
while (containsNamedEnvironment(result))
result = formatAndTruncate("%s-%d", MAX_ENVNAME_LEN,
environmentRadical, i++);
return result;
}
/**
* Elastic Beanstalk Contains a Max EnvironmentName Limit. Lets truncate it,
* shall we?
*
* @param mask
* String.format Mask
* @param maxLen
* Maximum Length
* @param args
* String.format args
* @return formatted String, or maxLen rightmost characters
*/
protected String formatAndTruncate(String mask, int maxLen, Object... args) {
String result = String.format(mask, args);
if (result.length() > maxLen)
result = result
.substring(result.length() - maxLen, result.length());
return result;
}
/**
* Boolean predicate for named environment
*
* @param environmentName
* environment name
* @return true if environment name exists
*/
protected boolean containsNamedEnvironment(String environmentName) {
for (EnvironmentDescription envDesc : getEnvironmentsFor(applicationName))
if (envDesc.getEnvironmentName().equals(environmentName))
return true;
return false;
}
}
| Adding exclusion for NTARN Option Setting
| beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/env/ReplaceEnvironmentMojo.java | Adding exclusion for NTARN Option Setting | <ide><path>eanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/env/ReplaceEnvironmentMojo.java
<ide> "aws:cloudformation:template:parameter") && curOptionSetting
<ide> .getOptionName().equals("AppSource"));
<ide>
<add> if (!bInvalid)
<add> bInvalid |= (curOptionSetting.getNamespace().equals(
<add> "aws:elasticbeanstalk:sns:topics") && curOptionSetting
<add> .getOptionName().equals("Notification Topic ARN"));
<add>
<ide> if (!bInvalid)
<ide> bInvalid |= (curOptionSetting.getValue().contains(curEnv
<ide> .getEnvironmentId())); |
|
Java | apache-2.0 | d53605d9df1436307c020868f4450e6fc733aa24 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
/*
* Author: max
*/
package com.intellij.codeInspection.ex;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.util.InspectionMessage;
import com.intellij.icons.AllIcons;
import com.intellij.ide.impl.ContentManagerWatcher;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiElement;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.content.TabbedPaneContentUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.HashSet;
import java.util.Set;
public class InspectionManagerEx extends InspectionManagerBase {
private final NotNullLazyValue<ContentManager> myContentManager;
private final Set<GlobalInspectionContextImpl> myRunningContexts = new HashSet<>();
public InspectionManagerEx(final Project project) {
super(project);
if (ApplicationManager.getApplication().isHeadlessEnvironment()) {
myContentManager = new NotNullLazyValue<ContentManager>() {
@NotNull
@Override
protected ContentManager compute() {
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
toolWindowManager.registerToolWindow(ToolWindowId.INSPECTION, true, ToolWindowAnchor.BOTTOM, project);
return ContentFactory.SERVICE.getInstance().createContentManager(new TabbedPaneContentUI(), true, project);
}
};
}
else {
myContentManager = new NotNullLazyValue<ContentManager>() {
@NotNull
@Override
protected ContentManager compute() {
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
ToolWindow toolWindow = toolWindowManager.registerToolWindow(ToolWindowId.INSPECTION, true, ToolWindowAnchor.BOTTOM, project);
ContentManager contentManager = toolWindow.getContentManager();
toolWindow.setIcon(AllIcons.Toolwindows.ToolWindowInspection);
ContentManagerWatcher.watchContentManager(toolWindow, contentManager);
return contentManager;
}
};
}
}
@NotNull
public ProblemDescriptor createProblemDescriptor(@NotNull final PsiElement psiElement,
@NotNull final @InspectionMessage String descriptionTemplate,
@NotNull final ProblemHighlightType highlightType,
@Nullable final HintAction hintAction,
boolean onTheFly,
LocalQuickFix @Nullable ... fixes) {
return new ProblemDescriptorImpl(psiElement, psiElement, descriptionTemplate, fixes, highlightType, false, null, hintAction, onTheFly);
}
@Override
@NotNull
public GlobalInspectionContextImpl createNewGlobalContext(boolean reuse) {
return createNewGlobalContext();
}
@NotNull
@Override
public GlobalInspectionContextImpl createNewGlobalContext() {
final GlobalInspectionContextImpl inspectionContext = new GlobalInspectionContextImpl(getProject(), myContentManager);
myRunningContexts.add(inspectionContext);
return inspectionContext;
}
void closeRunningContext(@NotNull GlobalInspectionContextImpl globalInspectionContext){
myRunningContexts.remove(globalInspectionContext);
}
@NotNull
public Set<GlobalInspectionContextImpl> getRunningContexts() {
return myRunningContexts;
}
@TestOnly
@NotNull
public NotNullLazyValue<ContentManager> getContentManager() {
return myContentManager;
}
}
| platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionManagerEx.java | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
/*
* Author: max
*/
package com.intellij.codeInspection.ex;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.util.InspectionMessage;
import com.intellij.icons.AllIcons;
import com.intellij.ide.impl.ContentManagerWatcher;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiElement;
import com.intellij.ui.content.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.HashSet;
import java.util.Set;
public class InspectionManagerEx extends InspectionManagerBase {
private final NotNullLazyValue<ContentManager> myContentManager;
private final Set<GlobalInspectionContextImpl> myRunningContexts = new HashSet<>();
public InspectionManagerEx(final Project project) {
super(project);
if (ApplicationManager.getApplication().isHeadlessEnvironment()) {
myContentManager = new NotNullLazyValue<ContentManager>() {
@NotNull
@Override
protected ContentManager compute() {
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
toolWindowManager.registerToolWindow(ToolWindowId.INSPECTION, true, ToolWindowAnchor.BOTTOM, project);
return ContentFactory.SERVICE.getInstance().createContentManager(new TabbedPaneContentUI(), true, project);
}
};
}
else {
myContentManager = new NotNullLazyValue<ContentManager>() {
@NotNull
@Override
protected ContentManager compute() {
ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
ToolWindow toolWindow = toolWindowManager.registerToolWindow(ToolWindowId.INSPECTION, true, ToolWindowAnchor.BOTTOM, project);
ContentManager contentManager = toolWindow.getContentManager();
toolWindow.setIcon(AllIcons.Toolwindows.ToolWindowInspection);
ContentManagerWatcher.watchContentManager(toolWindow, contentManager);
contentManager.addContentManagerListener(new ContentManagerListener() {
private static final String PREFIX = "of ";
@Override
public void contentAdded(@NotNull ContentManagerEvent event) {
handleContentSizeChanged();
}
@Override
public void contentRemoved(@NotNull ContentManagerEvent event) {
handleContentSizeChanged();
}
private void handleContentSizeChanged() {
final int count = contentManager.getContentCount();
if (count == 1) {
final Content content = contentManager.getContent(0);
final String displayName = content.getDisplayName();
if (!content.getDisplayName().startsWith(PREFIX)) {
content.setDisplayName(PREFIX + displayName);
}
}
else if (count > 1) {
for (Content content : contentManager.getContents()) {
if (content.getDisplayName().startsWith(PREFIX)) {
content.setDisplayName(content.getDisplayName().substring(PREFIX.length()));
}
}
}
}
});
return contentManager;
}
};
}
}
@NotNull
public ProblemDescriptor createProblemDescriptor(@NotNull final PsiElement psiElement,
@NotNull final @InspectionMessage String descriptionTemplate,
@NotNull final ProblemHighlightType highlightType,
@Nullable final HintAction hintAction,
boolean onTheFly,
LocalQuickFix @Nullable ... fixes) {
return new ProblemDescriptorImpl(psiElement, psiElement, descriptionTemplate, fixes, highlightType, false, null, hintAction, onTheFly);
}
@Override
@NotNull
public GlobalInspectionContextImpl createNewGlobalContext(boolean reuse) {
return createNewGlobalContext();
}
@NotNull
@Override
public GlobalInspectionContextImpl createNewGlobalContext() {
final GlobalInspectionContextImpl inspectionContext = new GlobalInspectionContextImpl(getProject(), myContentManager);
myRunningContexts.add(inspectionContext);
return inspectionContext;
}
void closeRunningContext(@NotNull GlobalInspectionContextImpl globalInspectionContext){
myRunningContexts.remove(globalInspectionContext);
}
@NotNull
public Set<GlobalInspectionContextImpl> getRunningContexts() {
return myRunningContexts;
}
@TestOnly
@NotNull
public NotNullLazyValue<ContentManager> getContentManager() {
return myContentManager;
}
}
| inspections view: simplify inspections results tab header
may not work for localizations
GitOrigin-RevId: 07dc5e358b4d32699defb210cc5e54b0e90707aa | platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionManagerEx.java | inspections view: simplify inspections results tab header | <ide><path>latform/lang-impl/src/com/intellij/codeInspection/ex/InspectionManagerEx.java
<ide> import com.intellij.openapi.wm.ToolWindowId;
<ide> import com.intellij.openapi.wm.ToolWindowManager;
<ide> import com.intellij.psi.PsiElement;
<del>import com.intellij.ui.content.*;
<add>import com.intellij.ui.content.ContentFactory;
<add>import com.intellij.ui.content.ContentManager;
<add>import com.intellij.ui.content.TabbedPaneContentUI;
<ide> import org.jetbrains.annotations.NotNull;
<ide> import org.jetbrains.annotations.Nullable;
<ide> import org.jetbrains.annotations.TestOnly;
<ide> ContentManager contentManager = toolWindow.getContentManager();
<ide> toolWindow.setIcon(AllIcons.Toolwindows.ToolWindowInspection);
<ide> ContentManagerWatcher.watchContentManager(toolWindow, contentManager);
<del> contentManager.addContentManagerListener(new ContentManagerListener() {
<del> private static final String PREFIX = "of ";
<del>
<del> @Override
<del> public void contentAdded(@NotNull ContentManagerEvent event) {
<del> handleContentSizeChanged();
<del> }
<del>
<del> @Override
<del> public void contentRemoved(@NotNull ContentManagerEvent event) {
<del> handleContentSizeChanged();
<del> }
<del>
<del> private void handleContentSizeChanged() {
<del> final int count = contentManager.getContentCount();
<del> if (count == 1) {
<del> final Content content = contentManager.getContent(0);
<del> final String displayName = content.getDisplayName();
<del> if (!content.getDisplayName().startsWith(PREFIX)) {
<del> content.setDisplayName(PREFIX + displayName);
<del> }
<del> }
<del> else if (count > 1) {
<del> for (Content content : contentManager.getContents()) {
<del> if (content.getDisplayName().startsWith(PREFIX)) {
<del> content.setDisplayName(content.getDisplayName().substring(PREFIX.length()));
<del> }
<del> }
<del> }
<del> }
<del> });
<ide> return contentManager;
<ide> }
<ide> }; |
|
Java | agpl-3.0 | 45cdb97204ccbd247806906f19bdf37702430456 | 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 | 29ccd72a-2e61-11e5-9284-b827eb9e62be | hello.java | 29c74706-2e61-11e5-9284-b827eb9e62be | 29ccd72a-2e61-11e5-9284-b827eb9e62be | hello.java | 29ccd72a-2e61-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>29c74706-2e61-11e5-9284-b827eb9e62be
<add>29ccd72a-2e61-11e5-9284-b827eb9e62be |
|
Java | mit | 1d3ce4bb9c0be84055a8cf45098e28e2ebbe0f60 | 0 | we4sz/DAT076,we4sz/DAT076 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chalmers.dat076.moviefinder.controller;
import edu.chalmers.dat076.moviefinder.model.User;
import edu.chalmers.dat076.moviefinder.model.UserLoginModel;
import edu.chalmers.dat076.moviefinder.model.UserRole;
import javax.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author John
*/
@Controller
@RequestMapping("api/login")
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.POST)
public @ResponseBody
User login(HttpSession s, @RequestBody UserLoginModel login) {
User u;
if (login.getUsername().equals("admin")) {
u = new User(login.getUsername(), UserRole.ADMIN);
} else {
u = new User(login.getUsername(), UserRole.VIEWER);
}
s.setAttribute("user", u);
return u;
}
@RequestMapping(value = "/me", method = RequestMethod.GET)
public @ResponseBody
User getMe(HttpSession s) {
User u = (User) s.getAttribute("user");
return u;
}
@RequestMapping(value = "/logout", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void logout(HttpSession s) {
s.removeAttribute("user");
}
}
| MovieFinder/src/main/java/edu/chalmers/dat076/moviefinder/controller/LoginController.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.chalmers.dat076.moviefinder.controller;
import edu.chalmers.dat076.moviefinder.model.User;
import edu.chalmers.dat076.moviefinder.model.UserLoginModel;
import edu.chalmers.dat076.moviefinder.model.UserRole;
import javax.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author John
*/
@Controller
@RequestMapping("api/login")
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.POST)
public @ResponseBody
User login(HttpSession s, @RequestBody UserLoginModel login) {
User u;
if (login.getUsername().equals("admin")) {
u = new User(login.getUsername(), UserRole.ADMIN);
} else {
u = new User(login.getUsername(), UserRole.VIEWER);
}
s.setAttribute("user", u);
return u;
}
@RequestMapping(value = "/me", method = RequestMethod.GET)
public @ResponseBody
User getMe(HttpSession s) {
User u = (User) s.getAttribute("user");
return u;
}
@RequestMapping(value = "/logout", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void logout(HttpSession s) {
s.invalidate();
}
}
| Changed logout to not destroy session.
Destroying the session on logout breaks the csrf-token, as the value is stored by spring-security in the session. Changed it instead to just unset the "user" property.
| MovieFinder/src/main/java/edu/chalmers/dat076/moviefinder/controller/LoginController.java | Changed logout to not destroy session. | <ide><path>ovieFinder/src/main/java/edu/chalmers/dat076/moviefinder/controller/LoginController.java
<ide> @RequestMapping(value = "/logout", method = RequestMethod.POST)
<ide> @ResponseStatus(value = HttpStatus.OK)
<ide> public void logout(HttpSession s) {
<del> s.invalidate();
<add> s.removeAttribute("user");
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 81d79cd1a938b654ccff38197a1a59c3a0ee3f2a | 0 | dataArtisans/cascading-flink | /*
* Copyright 2015 data Artisans GmbH
*
* 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.dataartisans.flink.cascading.planner;
import akka.actor.ActorSystem;
import cascading.flow.planner.FlowStepJob;
import cascading.management.state.ClientState;
import cascading.stats.FlowNodeStats;
import cascading.stats.FlowStepStats;
import com.dataartisans.flink.cascading.runtime.stats.AccumulatorCache;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.JobSubmissionResult;
import org.apache.flink.api.common.Plan;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.LocalEnvironment;
import org.apache.flink.client.program.Client;
import org.apache.flink.client.program.ContextEnvironment;
import org.apache.flink.client.program.JobWithJars;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.core.fs.Path;
import org.apache.flink.optimizer.DataStatistics;
import org.apache.flink.optimizer.Optimizer;
import org.apache.flink.optimizer.plan.OptimizedPlan;
import org.apache.flink.optimizer.plantranslate.JobGraphGenerator;
import org.apache.flink.runtime.client.JobClient;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.instance.ActorGateway;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.messages.JobManagerMessages;
import org.apache.flink.runtime.minicluster.FlinkMiniCluster;
import org.apache.flink.runtime.minicluster.LocalFlinkMiniCluster;
import org.apache.hadoop.conf.Configuration;
import scala.concurrent.Await;
import scala.concurrent.duration.FiniteDuration;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FlinkFlowStepJob extends FlowStepJob<Configuration>
{
private final Configuration currentConf;
private JobID jobID;
private Throwable jobException;
private List<String> classPath;
private final ExecutionEnvironment env;
private AccumulatorCache accumulatorCache;
private Future<JobSubmissionResult> jobSubmission;
private ExecutorService executorService = Executors.newFixedThreadPool(1);
private static final int accumulatorUpdateIntervalSecs = 10;
private volatile static FlinkMiniCluster localCluster;
private volatile static int localClusterUsers;
private static final Object lock = new Object();
private static final FiniteDuration DEFAULT_TIMEOUT = new FiniteDuration(60, TimeUnit.SECONDS);
public FlinkFlowStepJob( ClientState clientState, FlinkFlowStep flowStep, Configuration currentConf, List<String> classPath ) {
super(clientState, currentConf, flowStep, 1000, 60000, 60000);
this.currentConf = currentConf;
this.env = ((FlinkFlowStep)this.flowStep).getExecutionEnvironment();
this.classPath = classPath;
if( flowStep.isDebugEnabled() ) {
flowStep.logDebug("using polling interval: " + pollingInterval);
}
}
@Override
public Configuration getConfig() {
return currentConf;
}
@Override
protected FlowStepStats createStepStats(ClientState clientState) {
this.accumulatorCache = new AccumulatorCache(accumulatorUpdateIntervalSecs, DEFAULT_TIMEOUT);
return new FlinkFlowStepStats(this.flowStep, clientState, accumulatorCache);
}
protected void internalBlockOnStop() throws IOException {
if (jobSubmission != null && !jobSubmission.isDone()) {
if (isLocalExecution()) {
final ActorGateway jobManager = localCluster.getLeaderGateway(DEFAULT_TIMEOUT);
scala.concurrent.Future<Object> response = jobManager.ask(new JobManagerMessages.CancelJob(jobID), DEFAULT_TIMEOUT);
try {
Await.result(response, DEFAULT_TIMEOUT);
} catch (Exception e) {
throw new IOException("Canceling the job with ID " + jobID + " failed.", e);
}
} else {
try {
((ContextEnvironment) env).getClient().cancel(jobID);
} catch (Exception e) {
throw new IOException("An exception occurred while stopping the Flink job:\n" + e.getMessage());
}
}
}
}
protected void internalNonBlockingStart() throws IOException {
Plan plan = env.createProgramPlan();
Optimizer optimizer = new Optimizer(new DataStatistics(), new org.apache.flink.configuration.Configuration());
OptimizedPlan optimizedPlan = optimizer.compile(plan);
final JobGraph jobGraph = new JobGraphGenerator().compileJobGraph(optimizedPlan);
for (String jarPath : classPath) {
jobGraph.addJar(new Path(jarPath));
}
jobID = jobGraph.getJobID();
accumulatorCache.setJobID(jobID);
Callable<JobSubmissionResult> callable;
if (isLocalExecution()) {
flowStep.logInfo("Executing in local mode.");
final ActorSystem actorSystem = JobClient.startJobClientActorSystem(new org.apache.flink.configuration.Configuration());
startLocalCluster();
final ActorGateway jobManager = localCluster.getLeaderGateway(DEFAULT_TIMEOUT);
accumulatorCache.setLocalJobManager(jobManager);
JobClient.uploadJarFiles(jobGraph, jobManager, DEFAULT_TIMEOUT);
callable = new Callable<JobSubmissionResult>() {
@Override
public JobSubmissionResult call() throws JobExecutionException {
return JobClient.submitJobAndWait(actorSystem, jobManager, jobGraph,
DEFAULT_TIMEOUT, true, ClassLoader.getSystemClassLoader());
}
};
} else {
flowStep.logInfo("Executing in cluster mode.");
try {
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
jobGraph.addJar(new Path(path));
classPath.add(path);
} catch (URISyntaxException e) {
throw new IOException("Could not add the submission JAR as a dependency.");
}
final Client client = ((ContextEnvironment) env).getClient();
accumulatorCache.setClient(client);
final ClassLoader loader;
List<URL> classPathUrls = new ArrayList<URL>(classPath.size());
for (String path : classPath) {
classPathUrls.add(new URL(path));
}
loader = JobWithJars.buildUserCodeClassLoader(classPathUrls, Collections.<URL>emptyList(),getClass().getClassLoader());
callable = new Callable<JobSubmissionResult>() {
@Override
public JobSubmissionResult call() throws Exception {
return client.runBlocking(jobGraph, loader);
}
};
}
jobSubmission = executorService.submit(callable);
flowStep.logInfo("submitted Flink job: " + jobID);
}
@Override
protected void updateNodeStatus( FlowNodeStats flowNodeStats ) {
try {
if (internalNonBlockingIsComplete() && internalNonBlockingIsSuccessful()) {
flowNodeStats.markSuccessful();
} else if(internalIsStartedRunning()) {
flowNodeStats.isRunning();
} else {
flowNodeStats.markFailed(jobException);
}
} catch (IOException e) {
flowStep.logError("Failed to update node status.");
}
}
protected boolean internalNonBlockingIsSuccessful() throws IOException {
try {
jobSubmission.get(0, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
return false;
} catch (ExecutionException e) {
jobException = e.getCause();
return false;
} catch (TimeoutException e) {
return false;
}
boolean isDone = jobSubmission.isDone();
if (isDone) {
accumulatorCache.update(true);
stopCluster();
}
return isDone;
}
@Override
protected boolean isRemoteExecution() {
return isLocalExecution();
}
@Override
protected Throwable getThrowable() {
return jobException;
}
protected String internalJobId() {
return jobID.toString();
}
protected boolean internalNonBlockingIsComplete() throws IOException {
return jobSubmission.isDone();
}
protected void dumpDebugInfo() {
}
protected boolean internalIsStartedRunning() {
return jobSubmission != null;
}
private boolean isLocalExecution() {
return env instanceof LocalEnvironment;
}
private void startLocalCluster() {
synchronized (lock) {
if (localCluster == null) {
org.apache.flink.configuration.Configuration configuration = new org.apache.flink.configuration.Configuration();
configuration.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, env.getParallelism() * 2);
localCluster = new LocalFlinkMiniCluster(configuration);
localCluster.start();
}
localClusterUsers++;
}
}
private void stopCluster() {
synchronized (lock) {
if (localCluster != null) {
if (--localClusterUsers <= 0) {
localCluster.shutdown();
localCluster.awaitTermination();
localCluster = null;
localClusterUsers = 0;
accumulatorCache.setLocalJobManager(null);
}
}
if (executorService != null) {
executorService.shutdown();
}
}
}
}
| src/main/java/com/dataartisans/flink/cascading/planner/FlinkFlowStepJob.java | /*
* Copyright 2015 data Artisans GmbH
*
* 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.dataartisans.flink.cascading.planner;
import akka.actor.ActorSystem;
import cascading.flow.planner.FlowStepJob;
import cascading.management.state.ClientState;
import cascading.stats.FlowNodeStats;
import cascading.stats.FlowStepStats;
import com.dataartisans.flink.cascading.runtime.stats.AccumulatorCache;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.JobSubmissionResult;
import org.apache.flink.api.common.Plan;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.LocalEnvironment;
import org.apache.flink.client.program.Client;
import org.apache.flink.client.program.ContextEnvironment;
import org.apache.flink.client.program.JobWithJars;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.core.fs.Path;
import org.apache.flink.optimizer.DataStatistics;
import org.apache.flink.optimizer.Optimizer;
import org.apache.flink.optimizer.plan.OptimizedPlan;
import org.apache.flink.optimizer.plantranslate.JobGraphGenerator;
import org.apache.flink.runtime.client.JobClient;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.instance.ActorGateway;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.messages.JobManagerMessages;
import org.apache.flink.runtime.minicluster.FlinkMiniCluster;
import org.apache.flink.runtime.minicluster.LocalFlinkMiniCluster;
import org.apache.hadoop.conf.Configuration;
import scala.concurrent.Await;
import scala.concurrent.duration.FiniteDuration;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FlinkFlowStepJob extends FlowStepJob<Configuration>
{
private final Configuration currentConf;
private JobID jobID;
private Throwable jobException;
private List<String> classPath;
private final ExecutionEnvironment env;
private AccumulatorCache accumulatorCache;
private Future<JobSubmissionResult> jobSubmission;
private ExecutorService executorService = Executors.newFixedThreadPool(1);
private static final int accumulatorUpdateIntervalSecs = 10;
private volatile static FlinkMiniCluster localCluster;
private volatile static int localClusterUsers;
private static final Object lock = new Object();
private static final FiniteDuration DEFAULT_TIMEOUT = new FiniteDuration(60, TimeUnit.SECONDS);
public FlinkFlowStepJob( ClientState clientState, FlinkFlowStep flowStep, Configuration currentConf, List<String> classPath ) {
super(clientState, currentConf, flowStep, 1000, 60000, 60000);
this.currentConf = currentConf;
this.env = ((FlinkFlowStep)this.flowStep).getExecutionEnvironment();
this.classPath = classPath;
if( flowStep.isDebugEnabled() ) {
flowStep.logDebug("using polling interval: " + pollingInterval);
}
}
@Override
public Configuration getConfig() {
return currentConf;
}
@Override
protected FlowStepStats createStepStats(ClientState clientState) {
this.accumulatorCache = new AccumulatorCache(accumulatorUpdateIntervalSecs, DEFAULT_TIMEOUT);
return new FlinkFlowStepStats(this.flowStep, clientState, accumulatorCache);
}
protected void internalBlockOnStop() throws IOException {
if (jobSubmission != null && !jobSubmission.isDone()) {
if (isLocalExecution()) {
final ActorGateway jobManager = localCluster.getLeaderGateway(DEFAULT_TIMEOUT);
scala.concurrent.Future<Object> response = jobManager.ask(new JobManagerMessages.CancelJob(jobID), DEFAULT_TIMEOUT);
try {
Await.result(response, DEFAULT_TIMEOUT);
} catch (Exception e) {
throw new IOException("Canceling the job with ID " + jobID + " failed.", e);
}
} else {
try {
((ContextEnvironment) env).getClient().cancel(jobID);
} catch (Exception e) {
throw new IOException("An exception occurred while stopping the Flink job:\n" + e.getMessage());
}
}
}
}
protected void internalNonBlockingStart() throws IOException {
Plan plan = env.createProgramPlan();
Optimizer optimizer = new Optimizer(new DataStatistics(), new org.apache.flink.configuration.Configuration());
OptimizedPlan optimizedPlan = optimizer.compile(plan);
final JobGraph jobGraph = new JobGraphGenerator().compileJobGraph(optimizedPlan);
for (String jarPath : classPath) {
jobGraph.addJar(new Path(jarPath));
}
jobID = jobGraph.getJobID();
accumulatorCache.setJobID(jobID);
Callable<JobSubmissionResult> callable;
if (isLocalExecution()) {
flowStep.logInfo("Executing in local mode.");
final ActorSystem actorSystem = JobClient.startJobClientActorSystem(new org.apache.flink.configuration.Configuration());
startLocalCluster();
final ActorGateway jobManager = localCluster.getLeaderGateway(DEFAULT_TIMEOUT);
accumulatorCache.setLocalJobManager(jobManager);
JobClient.uploadJarFiles(jobGraph, jobManager, DEFAULT_TIMEOUT);
callable = new Callable<JobSubmissionResult>() {
@Override
public JobSubmissionResult call() throws JobExecutionException {
return JobClient.submitJobAndWait(actorSystem, jobManager, jobGraph,
DEFAULT_TIMEOUT, true, ClassLoader.getSystemClassLoader());
}
};
} else {
flowStep.logInfo("Executing in cluster mode.");
try {
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
jobGraph.addJar(new Path(path));
classPath.add(path);
} catch (URISyntaxException e) {
throw new IOException("Could not add the submission JAR as a dependency.");
}
final Client client = ((ContextEnvironment) env).getClient();
accumulatorCache.setClient(client);
final ClassLoader loader;
List<File> fileList = new ArrayList<File>(classPath.size());
for (String path : classPath) {
fileList.add(new File(path));
}
loader = JobWithJars.buildUserCodeClassLoader(fileList, getClass().getClassLoader());
callable = new Callable<JobSubmissionResult>() {
@Override
public JobSubmissionResult call() throws Exception {
return client.runBlocking(jobGraph, loader);
}
};
}
jobSubmission = executorService.submit(callable);
flowStep.logInfo("submitted Flink job: " + jobID);
}
@Override
protected void updateNodeStatus( FlowNodeStats flowNodeStats ) {
try {
if (internalNonBlockingIsComplete() && internalNonBlockingIsSuccessful()) {
flowNodeStats.markSuccessful();
} else if(internalIsStartedRunning()) {
flowNodeStats.isRunning();
} else {
flowNodeStats.markFailed(jobException);
}
} catch (IOException e) {
flowStep.logError("Failed to update node status.");
}
}
protected boolean internalNonBlockingIsSuccessful() throws IOException {
try {
jobSubmission.get(0, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
return false;
} catch (ExecutionException e) {
jobException = e.getCause();
return false;
} catch (TimeoutException e) {
return false;
}
boolean isDone = jobSubmission.isDone();
if (isDone) {
accumulatorCache.update(true);
stopCluster();
}
return isDone;
}
@Override
protected boolean isRemoteExecution() {
return isLocalExecution();
}
@Override
protected Throwable getThrowable() {
return jobException;
}
protected String internalJobId() {
return jobID.toString();
}
protected boolean internalNonBlockingIsComplete() throws IOException {
return jobSubmission.isDone();
}
protected void dumpDebugInfo() {
}
protected boolean internalIsStartedRunning() {
return jobSubmission != null;
}
private boolean isLocalExecution() {
return env instanceof LocalEnvironment;
}
private void startLocalCluster() {
synchronized (lock) {
if (localCluster == null) {
org.apache.flink.configuration.Configuration configuration = new org.apache.flink.configuration.Configuration();
configuration.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, env.getParallelism() * 2);
localCluster = new LocalFlinkMiniCluster(configuration);
localCluster.start();
}
localClusterUsers++;
}
}
private void stopCluster() {
synchronized (lock) {
if (localCluster != null) {
if (--localClusterUsers <= 0) {
localCluster.shutdown();
localCluster.awaitTermination();
localCluster = null;
localClusterUsers = 0;
accumulatorCache.setLocalJobManager(null);
}
}
if (executorService != null) {
executorService.shutdown();
}
}
}
}
| Fix project after commit 0ee0c1f on apache/flink
| src/main/java/com/dataartisans/flink/cascading/planner/FlinkFlowStepJob.java | Fix project after commit 0ee0c1f on apache/flink | <ide><path>rc/main/java/com/dataartisans/flink/cascading/planner/FlinkFlowStepJob.java
<ide> import scala.concurrent.Await;
<ide> import scala.concurrent.duration.FiniteDuration;
<ide>
<del>import java.io.File;
<ide> import java.io.IOException;
<ide> import java.net.URISyntaxException;
<add>import java.net.URL;
<ide> import java.util.ArrayList;
<add>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.concurrent.Callable;
<ide> import java.util.concurrent.ExecutionException;
<ide> accumulatorCache.setClient(client);
<ide>
<ide> final ClassLoader loader;
<del> List<File> fileList = new ArrayList<File>(classPath.size());
<add> List<URL> classPathUrls = new ArrayList<URL>(classPath.size());
<ide> for (String path : classPath) {
<del> fileList.add(new File(path));
<del> }
<del> loader = JobWithJars.buildUserCodeClassLoader(fileList, getClass().getClassLoader());
<add> classPathUrls.add(new URL(path));
<add> }
<add> loader = JobWithJars.buildUserCodeClassLoader(classPathUrls, Collections.<URL>emptyList(),getClass().getClassLoader());
<ide>
<ide> callable = new Callable<JobSubmissionResult>() {
<ide> @Override |
|
Java | unlicense | f271a707e67ab0fbf5e5c874877f70464da25d48 | 0 | PatandFioneTakeAI/Bags-and-Weights | package heaney.lebold.bagsandweights;
import heaney.lebold.bagsandweights.constraints.BagFilledConstraint;
import heaney.lebold.bagsandweights.constraints.IConstraint;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class BagsAndWeights {
//private int stepsTaken;
private List<Weight> weights;
private List<Bag> bags;
private List<IConstraint> constraints;
private List<List<Bag>> memoizationList;
private boolean topLevelValid;
private boolean subLevelValid;
public BagsAndWeights(List<Weight> weights, List<Bag> bags, List<IConstraint> constraints){
this.weights = weights;
this.bags = bags;
this.constraints = constraints;
this.topLevelValid = true;
this.subLevelValid = true;
//this.stepsTaken = 0;
this.memoizationList = new ArrayList<List<Bag>>();
}
public void init(){
//Call backtracking method
if(this.solve()){ //true if solved
//Print solution
for(Bag bag: this.bags){
System.out.print(bag.getID());
bag.forEach((w) -> System.out.print(" " + w.getID()));
System.out.println();
System.out.println("number of items: " + bag.size());
System.out.println("total weight: " + bag.getTotalWeight() + "/" + bag.getMaxWeight());
System.out.println("wasted capacity: " + (bag.getMaxWeight() - bag.getTotalWeight()));
System.out.println();
}
//System.out.println("\n\nTotal Steps Taken: " + this.stepsTaken);
}
else{
System.out.println("There are no solutions with the given constraints.");
}
}
private boolean solve(){
//this.stepsTaken++;
//Memoization
for(List<Bag> localBagList: this.memoizationList){
boolean isCopy = true;
for(int n=0; n< localBagList.size(); n++){
Bag localBag = localBagList.get(n);
Bag globalBag = this.bags.get(n);
if(!localBag.getContents().containsAll(globalBag.getContents()))
isCopy = false;
if(!globalBag.getContents().containsAll(localBag.getContents()))
isCopy = false;
}
if(isCopy)
return false;
else
this.memoizationList.add(new ArrayList<Bag>(this.bags));
}
//allFinal remains true if all constraints are satisfied
boolean allFinal = true;
for(IConstraint constraint: this.constraints){
//Check if current state violates constraint directly
if(!constraint.isValid(this.bags))
return false;
//Check if current state violates constraint at all
if(!constraint.isFinal(this.bags))
allFinal = false;
}
//All constraints satisfied and all weights placed. This is a solution!
if(allFinal && this.weights.isEmpty())
return true;
//Copy weights available at this stage
List<Weight> weightsToTestBase = new ArrayList<Weight>(this.weights);
for(Bag bag: this.bags){
// Get local list of weights for this bag
List<Weight> weightsToTest = new ArrayList<Weight>(weightsToTestBase);
// Apply heuristic to remove weights that are too heavy
applyMRVHeuristic(bag,weightsToTest);
// Apply heuristic to order weights based on forward checking
applyLCVHeuristic(bag,weightsToTest);
// For each weight in best -> worst order
for(Weight weight: weightsToTest){
if(bag.canFit(weight)){
/* Take action (add weight to bag) */
this.weights.remove(weight);
weightsToTestBase.remove(weight);
bag.addWeight(weight);
//If the problem can be solved by this partial solution, escape
if(solve())
return true;
/* Revoke action (pull weight from bag) */
bag.removeWeight(weight);
weightsToTestBase.add(weight);
this.weights.add(weight);
}
}
}
//This partial state yields no solutions
return false;
}
/* Remove weights that put bags over capacity */
private void applyMRVHeuristic(Bag bag, List<Weight> unsortedWeights){
unsortedWeights.sort((w1,w2) -> {
return w2.getWeight() - w1.getWeight();
});
while(!unsortedWeights.isEmpty() && bag.getTotalWeight() + unsortedWeights.get(0).getWeight() > bag.getMaxWeight()){
unsortedWeights.remove(0);
}
}
/* Order weights based on heuristic/forward checking */
private void applyLCVHeuristic(Bag bag, List<Weight> unsortedWeightsBase){
//Get local copy of unplaced weights
List<Weight> unsortedWeights = new ArrayList<Weight>(unsortedWeightsBase);
//Map used to rank each weight based on number of valid sub-placements
HashMap<Weight,Integer> weightValues = new HashMap<Weight,Integer>();
for(int n = unsortedWeights.size()-1; n >= 0; n--){
Weight weight = unsortedWeights.get(n);
if(!weightValues.containsKey(weight))
weightValues.put(weight, 0);
//Place weight in bag, check to see if new state is valid. (if not, dump weight from list)
bag.addWeight(weight);
this.topLevelValid = true;
this.constraints.forEach((c) -> {
if(!c.isValid(this.bags))
this.topLevelValid = false;
});
if(!topLevelValid){
unsortedWeightsBase.remove(weight);
}
// subList -> weights placed in turn after placing last weight
List<Weight> subList = new ArrayList<Weight>(unsortedWeights);
subList.remove(weight);
// validCount -> number of valid moves after last weight place
int validCount = 0;
for(Bag b: this.bags){
for(Weight subWeight: subList){
//Test weight in bag, if valid state, increment validCount
b.addWeight(subWeight);
this.subLevelValid = true;
this.constraints.forEach((c) -> {
if(!c.isValid(this.bags))
this.subLevelValid = false;
});
b.removeWeight(subWeight);
if(this.subLevelValid)
validCount++;
}
}
//Push to map validCount with key of the placed weight
weightValues.put(weight, validCount);
//Undo weight placement
bag.removeWeight(weight);
}
//Sort list based on validCount for each weight
unsortedWeightsBase.sort((w1,w2) -> {
return weightValues.get(w2) - weightValues.get(w1);
});
}
public static void main(String[] args){
//Handle arguments
if(args.length != 1){
System.out.println("Invalid syntax: $ java BagsAndWeights.jar <inputdata.txt>");
return;
}
File inputFile = new File(args[0]);
try {
//Load the file into buffer
Scanner scanner = new Scanner(inputFile);
InputParser[] sections = {InputParser.VARIABLES,
InputParser.VALUES,InputParser.FITTING_LIMITS,
InputParser.UNARY_INCLUSIVE,InputParser.UNARY_EXCLUSIVE,
InputParser.BINARY_EQUALS,InputParser.BINARY_NOT_EQUALS,
InputParser.MUTUAL_INCLUSIVE};
scanner.nextLine(); //Bump past first "#####"
/*List of sub-lists of objects (object Type different depending on section) */
ArrayList<ArrayList<Object>> data = new ArrayList<ArrayList<Object>>();
for(InputParser section:sections){
/* List of objects to be loaded from input in this section */
ArrayList<Object> objects = new ArrayList<Object>();
data.add(objects);
// Load in each line of data for this section
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.startsWith("#####")) //If true, advance to next section
break;
//Obtain object from InputParser
objects.add(InputParser.getData(section, line));
}
}
scanner.close();
//Cast weights from Object sub-list to new List
ArrayList<Weight> weights = new ArrayList<Weight>();
data.get(0).forEach((w) -> weights.add((Weight)w));
//Cast bags from Object sub-list to new List
ArrayList<Bag> bags = new ArrayList<Bag>();
data.get(1).forEach((b) -> bags.add((Bag)b));
//Cast all constraints from all other sub-lists to new List
List<IConstraint> constraints = new ArrayList<IConstraint>();
for(int n=2; n < data.size(); n++)
data.get(n).forEach( (c) -> constraints.add((IConstraint)c));
//Add additional constraints not directly specified in input
for(Bag bag: bags){
BagFilledConstraint constraint = new BagFilledConstraint(bag);
constraints.add(constraint);
}
//Solve problem
BagsAndWeights solver = new BagsAndWeights(weights,bags,constraints);
solver.init();
} catch (FileNotFoundException e) {
System.out.println(" File \"" + args[0] + "\" not found.");
return;
}
}
}
| heaney/lebold/bagsandweights/BagsAndWeights.java | package heaney.lebold.bagsandweights;
import heaney.lebold.bagsandweights.constraints.BagFilledConstraint;
import heaney.lebold.bagsandweights.constraints.IConstraint;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class BagsAndWeights {
//private int stepsTaken;
private List<Weight> weights;
private List<Bag> bags;
private List<IConstraint> constraints;
private List<List<Bag>> memoizationList;
private boolean topLevelValid;
private boolean subLevelValid;
public BagsAndWeights(List<Weight> weights, List<Bag> bags, List<IConstraint> constraints){
this.weights = weights;
this.bags = bags;
this.constraints = constraints;
this.topLevelValid = true;
this.subLevelValid = true;
//this.stepsTaken = 0;
this.memoizationList = new ArrayList<List<Bag>>();
}
public void init(){
//Call backtracking method
if(this.solve()){ //true if solved
//Print solution
for(Bag bag: this.bags){
System.out.print(bag.getID());
bag.forEach((w) -> System.out.print(" " + w.getID()));
System.out.println();
System.out.println("number of items: " + bag.size());
System.out.println("total weight: " + bag.getTotalWeight() + "/" + bag.getMaxWeight());
System.out.println("wasted capacity: " + (bag.getMaxWeight() - bag.getTotalWeight()));
System.out.println();
}
//System.out.println("\n\nTotal Steps Taken: " + this.stepsTaken);
}
else{
System.out.println("There are no solutions with the given constraints.");
}
}
private boolean solve(){
//this.stepsTaken++;
//Memoization
for(List<Bag> localBagList: this.memoizationList){
boolean isCopy = true;
for(int n=0; n< localBagList.size(); n++){
Bag localBag = localBagList.get(n);
Bag globalBag = this.bags.get(n);
if(!localBag.getContents().containsAll(globalBag.getContents()))
isCopy = false;
if(!globalBag.getContents().containsAll(localBag.getContents()))
isCopy = false;
}
if(isCopy)
return false;
else
this.memoizationList.add(new ArrayList<Bag>(this.bags));
}
//allFinal remains true if all constraints are satisfied
boolean allFinal = true;
for(IConstraint constraint: this.constraints){
//Check if current state violates constraint directly
if(!constraint.isValid(this.bags))
return false;
//Check if current state violates constraint at all
if(!constraint.isFinal(this.bags))
allFinal = false;
}
//All constraints satisfied and all weights placed. This is a solution!
if(allFinal && this.weights.isEmpty())
return true;
//Copy weights available at this stage
List<Weight> weightsToTestBase = new ArrayList<Weight>(this.weights);
for(Bag bag: this.bags){
// Get local list of weights for this bag
List<Weight> weightsToTest = new ArrayList<Weight>(weightsToTestBase);
// Apply heuristic to remove weights that are too heavy
applyMRVHeuristic(bag,weightsToTest);
// Apply heuristic to order weights based on forward checking
applyLCVHeuristic(bag,weightsToTest);
// For each weight in best -> worst order
for(Weight weight: weightsToTest){
if(bag.canFit(weight)){
/* Take action (add weight to bag) */
this.weights.remove(weight);
weightsToTestBase.remove(weight);
bag.addWeight(weight);
//If the problem can be solved by this partial solution, escape
if(solve())
return true;
/* Revoke action (pull weight from bag) */
bag.removeWeight(weight);
weightsToTestBase.add(weight);
this.weights.add(weight);
}
}
}
//This partial state yields no solutions
return false;
}
/* Remove weights that put bags over capacity */
private void applyMRVHeuristic(Bag bag, List<Weight> unsortedWeights){
unsortedWeights.sort((w1,w2) -> {
return w2.getWeight() - w1.getWeight();
});
while(!unsortedWeights.isEmpty() && bag.getTotalWeight() + unsortedWeights.get(0).getWeight() > bag.getMaxWeight()){
unsortedWeights.remove(0);
}
}
/* Order weights based on heuristic/forward checking */
private void applyLCVHeuristic(Bag bag, List<Weight> unsortedWeightsBase){
List<Weight> unsortedWeights = new ArrayList<Weight>(unsortedWeightsBase);
HashMap<Weight,Integer> weightValues = new HashMap<Weight,Integer>();
for(int n = unsortedWeights.size()-1; n >= 0; n--){
Weight weight = unsortedWeights.get(n);
if(!weightValues.containsKey(weight))
weightValues.put(weight, 0);
bag.addWeight(weight);
this.topLevelValid = true;
this.constraints.forEach((c) -> {
if(!c.isValid(this.bags))
this.topLevelValid = false;
});
if(!topLevelValid){
unsortedWeightsBase.remove(weight);
}
List<Weight> subList = new ArrayList<Weight>(unsortedWeights);
subList.remove(weight);
int validCount = 0;
for(Bag b: this.bags){
for(Weight subWeight: subList){
b.addWeight(subWeight);
this.subLevelValid = true;
this.constraints.forEach((c) -> {
if(!c.isValid(this.bags))
this.subLevelValid = false;
});
b.removeWeight(subWeight);
if(this.subLevelValid)
validCount++;
}
}
weightValues.put(weight, validCount);
bag.removeWeight(weight);
}
unsortedWeightsBase.sort((w1,w2) -> {
return weightValues.get(w2) - weightValues.get(w1);
});
}
public static void main(String[] args){
//Handle arguments
if(args.length != 1){
System.out.println("Invalid syntax: $ java BagsAndWeights.jar <inputdata.txt>");
return;
}
File inputFile = new File(args[0]);
try {
//Load the file into buffer
Scanner scanner = new Scanner(inputFile);
InputParser[] sections = {InputParser.VARIABLES,
InputParser.VALUES,InputParser.FITTING_LIMITS,
InputParser.UNARY_INCLUSIVE,InputParser.UNARY_EXCLUSIVE,
InputParser.BINARY_EQUALS,InputParser.BINARY_NOT_EQUALS,
InputParser.MUTUAL_INCLUSIVE};
scanner.nextLine(); //Bump past first "#####"
/*List of sub-lists of objects (object Type different depending on section) */
ArrayList<ArrayList<Object>> data = new ArrayList<ArrayList<Object>>();
for(InputParser section:sections){
/* List of objects to be loaded from input in this section */
ArrayList<Object> objects = new ArrayList<Object>();
data.add(objects);
// Load in each line of data for this section
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.startsWith("#####")) //If true, advance to next section
break;
//Obtain object from InputParser
objects.add(InputParser.getData(section, line));
}
}
scanner.close();
//Cast weights from Object sub-list to new List
ArrayList<Weight> weights = new ArrayList<Weight>();
data.get(0).forEach((w) -> weights.add((Weight)w));
//Cast bags from Object sub-list to new List
ArrayList<Bag> bags = new ArrayList<Bag>();
data.get(1).forEach((b) -> bags.add((Bag)b));
//Cast all constraints from all other sub-lists to new List
List<IConstraint> constraints = new ArrayList<IConstraint>();
for(int n=2; n < data.size(); n++)
data.get(n).forEach( (c) -> constraints.add((IConstraint)c));
//Add additional constraints not directly specified in input
for(Bag bag: bags){
BagFilledConstraint constraint = new BagFilledConstraint(bag);
constraints.add(constraint);
}
//Solve problem
BagsAndWeights solver = new BagsAndWeights(weights,bags,constraints);
solver.init();
} catch (FileNotFoundException e) {
System.out.println(" File \"" + args[0] + "\" not found.");
return;
}
}
}
| Commented LCV
| heaney/lebold/bagsandweights/BagsAndWeights.java | Commented LCV | <ide><path>eaney/lebold/bagsandweights/BagsAndWeights.java
<ide>
<ide> /* Order weights based on heuristic/forward checking */
<ide> private void applyLCVHeuristic(Bag bag, List<Weight> unsortedWeightsBase){
<add> //Get local copy of unplaced weights
<ide> List<Weight> unsortedWeights = new ArrayList<Weight>(unsortedWeightsBase);
<add>
<add> //Map used to rank each weight based on number of valid sub-placements
<ide> HashMap<Weight,Integer> weightValues = new HashMap<Weight,Integer>();
<ide> for(int n = unsortedWeights.size()-1; n >= 0; n--){
<ide> Weight weight = unsortedWeights.get(n);
<ide> if(!weightValues.containsKey(weight))
<ide> weightValues.put(weight, 0);
<add>
<add> //Place weight in bag, check to see if new state is valid. (if not, dump weight from list)
<ide> bag.addWeight(weight);
<ide> this.topLevelValid = true;
<ide> this.constraints.forEach((c) -> {
<ide> if(!topLevelValid){
<ide> unsortedWeightsBase.remove(weight);
<ide> }
<add>
<add> // subList -> weights placed in turn after placing last weight
<ide> List<Weight> subList = new ArrayList<Weight>(unsortedWeights);
<ide> subList.remove(weight);
<add>
<add> // validCount -> number of valid moves after last weight place
<ide> int validCount = 0;
<ide> for(Bag b: this.bags){
<ide> for(Weight subWeight: subList){
<add> //Test weight in bag, if valid state, increment validCount
<ide> b.addWeight(subWeight);
<ide> this.subLevelValid = true;
<ide> this.constraints.forEach((c) -> {
<ide> validCount++;
<ide> }
<ide> }
<add> //Push to map validCount with key of the placed weight
<ide> weightValues.put(weight, validCount);
<ide>
<add> //Undo weight placement
<ide> bag.removeWeight(weight);
<ide> }
<add>
<add> //Sort list based on validCount for each weight
<ide> unsortedWeightsBase.sort((w1,w2) -> {
<ide> return weightValues.get(w2) - weightValues.get(w1);
<ide> }); |
|
Java | apache-2.0 | 18848da6f0af6f89ed66a08e610a1479f6e054c1 | 0 | calvinjia/tachyon,ShailShah/alluxio,PasaLab/tachyon,aaudiber/alluxio,bf8086/alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,jswudi/alluxio,Alluxio/alluxio,Reidddddd/alluxio,bf8086/alluxio,apc999/alluxio,jswudi/alluxio,riversand963/alluxio,Alluxio/alluxio,wwjiang007/alluxio,aaudiber/alluxio,madanadit/alluxio,yuluo-ding/alluxio,bf8086/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,wwjiang007/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,EvilMcJerkface/alluxio,madanadit/alluxio,bf8086/alluxio,jswudi/alluxio,ShailShah/alluxio,Alluxio/alluxio,maobaolong/alluxio,madanadit/alluxio,ShailShah/alluxio,calvinjia/tachyon,maobaolong/alluxio,maboelhassan/alluxio,jsimsa/alluxio,ChangerYoung/alluxio,bf8086/alluxio,yuluo-ding/alluxio,PasaLab/tachyon,maobaolong/alluxio,Alluxio/alluxio,riversand963/alluxio,Reidddddd/mo-alluxio,ShailShah/alluxio,jswudi/alluxio,maobaolong/alluxio,calvinjia/tachyon,WilliamZapata/alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,wwjiang007/alluxio,madanadit/alluxio,calvinjia/tachyon,PasaLab/tachyon,jswudi/alluxio,wwjiang007/alluxio,yuluo-ding/alluxio,jswudi/alluxio,maobaolong/alluxio,madanadit/alluxio,ChangerYoung/alluxio,aaudiber/alluxio,riversand963/alluxio,WilliamZapata/alluxio,maobaolong/alluxio,Alluxio/alluxio,wwjiang007/alluxio,riversand963/alluxio,uronce-cc/alluxio,Reidddddd/alluxio,maboelhassan/alluxio,uronce-cc/alluxio,PasaLab/tachyon,Reidddddd/mo-alluxio,jsimsa/alluxio,ChangerYoung/alluxio,riversand963/alluxio,yuluo-ding/alluxio,EvilMcJerkface/alluxio,jsimsa/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,riversand963/alluxio,bf8086/alluxio,apc999/alluxio,apc999/alluxio,aaudiber/alluxio,aaudiber/alluxio,aaudiber/alluxio,ChangerYoung/alluxio,jsimsa/alluxio,maobaolong/alluxio,apc999/alluxio,maboelhassan/alluxio,maboelhassan/alluxio,PasaLab/tachyon,madanadit/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,wwjiang007/alluxio,uronce-cc/alluxio,calvinjia/tachyon,aaudiber/alluxio,EvilMcJerkface/alluxio,PasaLab/tachyon,Reidddddd/alluxio,maboelhassan/alluxio,madanadit/alluxio,WilliamZapata/alluxio,jsimsa/alluxio,jsimsa/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,apc999/alluxio,ChangerYoung/alluxio,Alluxio/alluxio,maboelhassan/alluxio,Alluxio/alluxio,calvinjia/tachyon,calvinjia/tachyon,PasaLab/tachyon,yuluo-ding/alluxio,ShailShah/alluxio,wwjiang007/alluxio,madanadit/alluxio,Reidddddd/alluxio,bf8086/alluxio,ShailShah/alluxio,uronce-cc/alluxio,bf8086/alluxio,yuluo-ding/alluxio,Alluxio/alluxio,ChangerYoung/alluxio,Reidddddd/mo-alluxio,wwjiang007/alluxio,uronce-cc/alluxio,EvilMcJerkface/alluxio,uronce-cc/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,Reidddddd/mo-alluxio | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the โLicenseโ). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.master.file;
import alluxio.AlluxioURI;
import alluxio.Configuration;
import alluxio.Constants;
import alluxio.LocalAlluxioClusterResource;
import alluxio.exception.DirectoryNotEmptyException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.FileAlreadyExistsException;
import alluxio.exception.FileDoesNotExistException;
import alluxio.exception.InvalidPathException;
import alluxio.master.MasterTestUtils;
import alluxio.master.block.BlockMaster;
import alluxio.master.file.meta.TtlBucketPrivateAccess;
import alluxio.master.file.options.CompleteFileOptions;
import alluxio.master.file.options.CreateDirectoryOptions;
import alluxio.master.file.options.CreateFileOptions;
import alluxio.security.authentication.AuthType;
import alluxio.security.authentication.AuthenticatedClientUser;
import alluxio.util.CommonUtils;
import alluxio.util.IdUtils;
import alluxio.wire.FileInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.Timeout;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Test behavior of {@link FileSystemMaster}.
*
* For example, (concurrently) creating/deleting/renaming files.
*/
public class FileSystemMasterIntegrationTest {
class ConcurrentCreator implements Callable<Void> {
private int mDepth;
private int mConcurrencyDepth;
private AlluxioURI mInitPath;
ConcurrentCreator(int depth, int concurrencyDepth, AlluxioURI initPath) {
mDepth = depth;
mConcurrencyDepth = concurrencyDepth;
mInitPath = initPath;
}
@Override
public Void call() throws Exception {
AuthenticatedClientUser.set(TEST_AUTHENTICATE_USER);
exec(mDepth, mConcurrencyDepth, mInitPath);
return null;
}
public void exec(int depth, int concurrencyDepth, AlluxioURI path) throws Exception {
if (depth < 1) {
return;
} else if (depth == 1) {
long fileId = mFsMaster.create(path, CreateFileOptions.defaults());
Assert.assertEquals(fileId, mFsMaster.getFileId(path));
// verify the user permission for file
FileInfo fileInfo = mFsMaster.getFileInfo(fileId);
Assert.assertEquals(TEST_AUTHENTICATE_USER, fileInfo.getUserName());
Assert.assertEquals(0644, (short) fileInfo.getPermission());
} else {
mFsMaster.mkdir(path, CreateDirectoryOptions.defaults());
Assert.assertNotNull(mFsMaster.getFileId(path));
long dirId = mFsMaster.getFileId(path);
Assert.assertNotEquals(-1, dirId);
FileInfo dirInfo = mFsMaster.getFileInfo(dirId);
Assert.assertEquals(TEST_AUTHENTICATE_USER, dirInfo.getUserName());
Assert.assertEquals(0755, (short) dirInfo.getPermission());
}
if (concurrencyDepth > 0) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE);
for (int i = 0; i < FILES_PER_NODE; i++) {
Callable<Void> call = (new ConcurrentCreator(depth - 1, concurrencyDepth - 1,
path.join(Integer.toString(i))));
futures.add(executor.submit(call));
}
for (Future<Void> f : futures) {
f.get();
}
} finally {
executor.shutdown();
}
} else {
for (int i = 0; i < FILES_PER_NODE; i++) {
exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i)));
}
}
}
}
/*
* This class provides multiple concurrent threads to free all files in one directory.
*/
class ConcurrentFreer implements Callable<Void> {
private int mDepth;
private int mConcurrencyDepth;
private AlluxioURI mInitPath;
ConcurrentFreer(int depth, int concurrencyDepth, AlluxioURI initPath) {
mDepth = depth;
mConcurrencyDepth = concurrencyDepth;
mInitPath = initPath;
}
@Override
public Void call() throws Exception {
exec(mDepth, mConcurrencyDepth, mInitPath);
return null;
}
private void doFree(AlluxioURI path) throws Exception {
mFsMaster.free(path, true);
Assert.assertNotEquals(IdUtils.INVALID_FILE_ID, mFsMaster.getFileId(path));
}
public void exec(int depth, int concurrencyDepth, AlluxioURI path) throws Exception {
if (depth < 1) {
return;
} else if (depth == 1 || (path.hashCode() % 10 == 0)) {
// Sometimes we want to try freeing a path when we're not all the way down, which is what
// the second condition is for.
doFree(path);
} else {
if (concurrencyDepth > 0) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE);
for (int i = 0; i < FILES_PER_NODE; i++) {
Callable<Void> call = (new ConcurrentDeleter(depth - 1, concurrencyDepth - 1,
path.join(Integer.toString(i))));
futures.add(executor.submit(call));
}
for (Future<Void> f : futures) {
f.get();
}
} finally {
executor.shutdown();
}
} else {
for (int i = 0; i < FILES_PER_NODE; i++) {
exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i)));
}
}
doFree(path);
}
}
}
/*
* This class provides multiple concurrent threads to delete all files in one directory.
*/
class ConcurrentDeleter implements Callable<Void> {
private int mDepth;
private int mConcurrencyDepth;
private AlluxioURI mInitPath;
ConcurrentDeleter(int depth, int concurrencyDepth, AlluxioURI initPath) {
mDepth = depth;
mConcurrencyDepth = concurrencyDepth;
mInitPath = initPath;
}
@Override
public Void call() throws Exception {
exec(mDepth, mConcurrencyDepth, mInitPath);
return null;
}
private void doDelete(AlluxioURI path) throws Exception {
mFsMaster.deleteFile(path, true);
Assert.assertEquals(IdUtils.INVALID_FILE_ID, mFsMaster.getFileId(path));
}
public void exec(int depth, int concurrencyDepth, AlluxioURI path) throws Exception {
if (depth < 1) {
return;
} else if (depth == 1 || (path.hashCode() % 10 == 0)) {
// Sometimes we want to try deleting a path when we're not all the way down, which is what
// the second condition is for.
doDelete(path);
} else {
if (concurrencyDepth > 0) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE);
for (int i = 0; i < FILES_PER_NODE; i++) {
Callable<Void> call = (new ConcurrentDeleter(depth - 1, concurrencyDepth - 1,
path.join(Integer.toString(i))));
futures.add(executor.submit(call));
}
for (Future<Void> f : futures) {
f.get();
}
} finally {
executor.shutdown();
}
} else {
for (int i = 0; i < FILES_PER_NODE; i++) {
exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i)));
}
}
doDelete(path);
}
}
}
class ConcurrentRenamer implements Callable<Void> {
private int mDepth;
private int mConcurrencyDepth;
private AlluxioURI mRootPath;
private AlluxioURI mRootPath2;
private AlluxioURI mInitPath;
ConcurrentRenamer(int depth, int concurrencyDepth, AlluxioURI rootPath, AlluxioURI rootPath2,
AlluxioURI initPath) {
mDepth = depth;
mConcurrencyDepth = concurrencyDepth;
mRootPath = rootPath;
mRootPath2 = rootPath2;
mInitPath = initPath;
}
@Override
public Void call() throws Exception {
AuthenticatedClientUser.set(TEST_AUTHENTICATE_USER);
exec(mDepth, mConcurrencyDepth, mInitPath);
return null;
}
public void exec(int depth, int concurrencyDepth, AlluxioURI path) throws Exception {
if (depth < 1) {
return;
} else if (depth == 1 || (depth < mDepth && path.hashCode() % 10 < 3)) {
// Sometimes we want to try renaming a path when we're not all the way down, which is what
// the second condition is for. We have to create the path in the destination up till what
// we're renaming. This might already exist, so createFile could throw a
// FileAlreadyExistsException, which we silently handle.
AlluxioURI srcPath = mRootPath.join(path);
AlluxioURI dstPath = mRootPath2.join(path);
long fileId = mFsMaster.getFileId(srcPath);
try {
CreateDirectoryOptions options = CreateDirectoryOptions.defaults().setRecursive(true);
mFsMaster.mkdir(dstPath.getParent(), options);
} catch (FileAlreadyExistsException e) {
// This is an acceptable exception to get, since we don't know if the parent has been
// created yet by another thread.
} catch (InvalidPathException e) {
// This could happen if we are renaming something that's a child of the root.
}
mFsMaster.rename(srcPath, dstPath);
Assert.assertEquals(fileId, mFsMaster.getFileId(dstPath));
} else if (concurrencyDepth > 0) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE);
for (int i = 0; i < FILES_PER_NODE; i++) {
Callable<Void> call = (new ConcurrentRenamer(depth - 1, concurrencyDepth - 1, mRootPath,
mRootPath2, path.join(Integer.toString(i))));
futures.add(executor.submit(call));
}
for (Future<Void> f : futures) {
f.get();
}
} finally {
executor.shutdown();
}
} else {
for (int i = 0; i < FILES_PER_NODE; i++) {
exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i)));
}
}
}
}
private static final int DEPTH = 6;
private static final int FILES_PER_NODE = 4;
private static final int CONCURRENCY_DEPTH = 3;
private static final AlluxioURI ROOT_PATH = new AlluxioURI("/root");
private static final AlluxioURI ROOT_PATH2 = new AlluxioURI("/root2");
// Modify current time so that implementations can't accidentally pass unit tests by ignoring
// this specified time and always using System.currentTimeMillis()
private static final long TEST_CURRENT_TIME = 300;
/**
* The authenticate user is gotten from current thread local. If MasterInfo starts a concurrent
* thread to do operations, {@link AuthenticatedClientUser} will be null. So
* {@link AuthenticatedClientUser#set(String)} should be called in the {@link Callable#call()} to
* set this user for testing.
*/
private static final String TEST_AUTHENTICATE_USER = "test-user";
@Rule
public Timeout mGlobalTimeout = Timeout.seconds(60);
@Rule
public LocalAlluxioClusterResource mLocalAlluxioClusterResource =
new LocalAlluxioClusterResource(1000, Constants.GB,
Constants.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName(),
Constants.SECURITY_AUTHORIZATION_PERMISSION_ENABLED, "true");
private Configuration mMasterConfiguration;
private FileSystemMaster mFsMaster;
@Rule
public ExpectedException mThrown = ExpectedException.none();
@Before
public final void before() throws Exception {
// mock the authentication user
AuthenticatedClientUser.set(TEST_AUTHENTICATE_USER);
mFsMaster =
mLocalAlluxioClusterResource.get().getMaster().getInternalMaster().getFileSystemMaster();
mMasterConfiguration = mLocalAlluxioClusterResource.get().getMasterConf();
TtlBucketPrivateAccess
.setTtlIntervalMs(mMasterConfiguration.getLong(Constants.MASTER_TTL_CHECKER_INTERVAL_MS));
}
@Test
public void clientFileInfoDirectoryTest() throws Exception {
AlluxioURI path = new AlluxioURI("/testFolder");
mFsMaster.mkdir(path, CreateDirectoryOptions.defaults());
long fileId = mFsMaster.getFileId(path);
FileInfo fileInfo = mFsMaster.getFileInfo(fileId);
Assert.assertEquals("testFolder", fileInfo.getName());
Assert.assertEquals(1, fileInfo.getFileId());
Assert.assertEquals(0, fileInfo.getLength());
Assert.assertFalse(fileInfo.isCacheable());
Assert.assertTrue(fileInfo.isCompleted());
Assert.assertTrue(fileInfo.isFolder());
Assert.assertFalse(fileInfo.isPersisted());
Assert.assertFalse(fileInfo.isPinned());
Assert.assertEquals(TEST_AUTHENTICATE_USER, fileInfo.getUserName());
Assert.assertEquals(0755, (short) fileInfo.getPermission());
}
@Test
public void clientFileInfoEmptyFileTest() throws Exception {
long fileId = mFsMaster.create(new AlluxioURI("/testFile"), CreateFileOptions.defaults());
FileInfo fileInfo = mFsMaster.getFileInfo(fileId);
Assert.assertEquals("testFile", fileInfo.getName());
Assert.assertEquals(fileId, fileInfo.getFileId());
Assert.assertEquals(0, fileInfo.getLength());
Assert.assertTrue(fileInfo.isCacheable());
Assert.assertFalse(fileInfo.isCompleted());
Assert.assertFalse(fileInfo.isFolder());
Assert.assertFalse(fileInfo.isPersisted());
Assert.assertFalse(fileInfo.isPinned());
Assert.assertEquals(Constants.NO_TTL, fileInfo.getTtl());
Assert.assertEquals(TEST_AUTHENTICATE_USER, fileInfo.getUserName());
Assert.assertEquals(0644, (short) fileInfo.getPermission());
}
private FileSystemMaster createFileSystemMasterFromJournal() throws IOException {
return MasterTestUtils.createFileSystemMasterFromJournal(mMasterConfiguration);
}
// TODO(calvin): This test currently relies on the fact the HDFS client is a cached instance to
// avoid invalid lease exception. This should be fixed.
@Ignore
@Test
public void concurrentCreateJournalTest() throws Exception {
// Makes sure the file id's are the same between a master info and the journal it creates
for (int i = 0; i < 5; i++) {
ConcurrentCreator concurrentCreator =
new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentCreator.call();
FileSystemMaster fsMaster = createFileSystemMasterFromJournal();
for (FileInfo info : mFsMaster.getFileInfoList(new AlluxioURI("/"))) {
AlluxioURI path = new AlluxioURI(info.getPath());
Assert.assertEquals(mFsMaster.getFileId(path), fsMaster.getFileId(path));
}
before();
}
}
@Test
public void concurrentCreateTest() throws Exception {
ConcurrentCreator concurrentCreator =
new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentCreator.call();
}
@Test
public void concurrentDeleteTest() throws Exception {
ConcurrentCreator concurrentCreator =
new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentCreator.call();
ConcurrentDeleter concurrentDeleter =
new ConcurrentDeleter(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentDeleter.call();
Assert.assertEquals(0,
mFsMaster.getFileInfoList(new AlluxioURI("/")).size());
}
@Test
public void concurrentFreeTest() throws Exception {
ConcurrentCreator concurrentCreator =
new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentCreator.call();
ConcurrentFreer concurrentFreer =
new ConcurrentFreer(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentFreer.call();
}
@Test
public void concurrentRenameTest() throws Exception {
ConcurrentCreator concurrentCreator =
new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentCreator.call();
int numFiles = mFsMaster.getFileInfoList(ROOT_PATH).size();
ConcurrentRenamer concurrentRenamer = new ConcurrentRenamer(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH,
ROOT_PATH2, AlluxioURI.EMPTY_URI);
concurrentRenamer.call();
Assert.assertEquals(numFiles,
mFsMaster.getFileInfoList(ROOT_PATH2).size());
}
@Test
public void createAlreadyExistFileTest() throws Exception {
mThrown.expect(FileAlreadyExistsException.class);
mFsMaster.create(new AlluxioURI("/testFile"), CreateFileOptions.defaults());
mFsMaster.mkdir(new AlluxioURI("/testFile"), CreateDirectoryOptions.defaults());
}
@Test
public void createDirectoryTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
FileInfo fileInfo = mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertTrue(fileInfo.isFolder());
Assert.assertEquals(TEST_AUTHENTICATE_USER, fileInfo.getUserName());
Assert.assertEquals(0755, (short) fileInfo.getPermission());
}
@Test
public void createFileInvalidPathTest() throws Exception {
mThrown.expect(InvalidPathException.class);
mFsMaster.create(new AlluxioURI("testFile"), CreateFileOptions.defaults());
}
@Test
public void createFileInvalidPathTest2() throws Exception {
mThrown.expect(FileAlreadyExistsException.class);
mFsMaster.create(new AlluxioURI("/"), CreateFileOptions.defaults());
}
@Test
public void createFileInvalidPathTest3() throws Exception {
mThrown.expect(InvalidPathException.class);
mFsMaster.create(new AlluxioURI("/testFile1"), CreateFileOptions.defaults());
mFsMaster.create(new AlluxioURI("/testFile1/testFile2"), CreateFileOptions.defaults());
}
@Test
public void createFilePerfTest() throws Exception {
for (int k = 0; k < 200; k++) {
CreateDirectoryOptions options = CreateDirectoryOptions.defaults().setRecursive(true);
mFsMaster.mkdir(
new AlluxioURI("/testFile").join(Constants.MASTER_COLUMN_FILE_PREFIX + k).join("0"),
options);
}
for (int k = 0; k < 200; k++) {
mFsMaster.getFileInfo(mFsMaster.getFileId(
new AlluxioURI("/testFile").join(Constants.MASTER_COLUMN_FILE_PREFIX + k).join("0")));
}
}
@Test
public void createFileTest() throws Exception {
mFsMaster.create(new AlluxioURI("/testFile"), CreateFileOptions.defaults());
FileInfo fileInfo = mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFile")));
Assert.assertFalse(fileInfo.isFolder());
Assert.assertEquals(TEST_AUTHENTICATE_USER, fileInfo.getUserName());
Assert.assertEquals(0644, (short) fileInfo.getPermission());
}
@Test
public void deleteDirectoryWithDirectoriesTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
mFsMaster.mkdir(new AlluxioURI("/testFolder/testFolder2"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile"), CreateFileOptions.defaults());
long fileId2 = mFsMaster.create(new AlluxioURI("/testFolder/testFolder2/testFile2"),
CreateFileOptions.defaults());
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(2, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
Assert.assertEquals(fileId2,
mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2/testFile2")));
Assert.assertTrue(mFsMaster.deleteFile(new AlluxioURI("/testFolder"), true));
Assert.assertEquals(IdUtils.INVALID_FILE_ID,
mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2/testFile2")));
}
@Test
public void deleteDirectoryWithDirectoriesTest2() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
mFsMaster.mkdir(new AlluxioURI("/testFolder/testFolder2"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile"), CreateFileOptions.defaults());
long fileId2 = mFsMaster.create(new AlluxioURI("/testFolder/testFolder2/testFile2"),
CreateFileOptions.defaults());
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(2, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
Assert.assertEquals(fileId2,
mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2/testFile2")));
try {
mFsMaster.deleteFile(new AlluxioURI("/testFolder/testFolder2"), false);
Assert.fail("Deleting a nonempty directory nonrecursively should fail");
} catch (DirectoryNotEmptyException e) {
Assert.assertEquals(
ExceptionMessage.DELETE_NONEMPTY_DIRECTORY_NONRECURSIVE.getMessage("testFolder2"),
e.getMessage());
}
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(2, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
Assert.assertEquals(fileId2,
mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2/testFile2")));
}
@Test
public void deleteDirectoryWithFilesTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile"), CreateFileOptions.defaults());
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
Assert.assertTrue(mFsMaster.deleteFile(new AlluxioURI("/testFolder"), true));
Assert.assertEquals(IdUtils.INVALID_FILE_ID,
mFsMaster.getFileId(new AlluxioURI("/testFolder")));
}
@Test
public void deleteDirectoryWithFilesTest2() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile"), CreateFileOptions.defaults());
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
try {
mFsMaster.deleteFile(new AlluxioURI("/testFolder"), false);
Assert.fail("Deleting a nonempty directory nonrecursively should fail");
} catch (DirectoryNotEmptyException e) {
Assert.assertEquals(
ExceptionMessage.DELETE_NONEMPTY_DIRECTORY_NONRECURSIVE.getMessage("testFolder"),
e.getMessage());
}
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
}
@Test
public void deleteEmptyDirectoryTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertTrue(mFsMaster.deleteFile(new AlluxioURI("/testFolder"), true));
Assert.assertEquals(IdUtils.INVALID_FILE_ID,
mFsMaster.getFileId(new AlluxioURI("/testFolder")));
}
@Test
public void deleteFileTest() throws Exception {
long fileId = mFsMaster.create(new AlluxioURI("/testFile"), CreateFileOptions.defaults());
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFile")));
Assert.assertTrue(mFsMaster.deleteFile(new AlluxioURI("/testFile"), true));
Assert.assertEquals(IdUtils.INVALID_FILE_ID, mFsMaster.getFileId(new AlluxioURI("/testFile")));
}
@Test
public void deleteRootTest() throws Exception {
Assert.assertFalse(mFsMaster.deleteFile(new AlluxioURI("/"), true));
Assert.assertFalse(mFsMaster.deleteFile(new AlluxioURI("/"), false));
}
@Test
public void getCapacityBytesTest() {
BlockMaster blockMaster =
mLocalAlluxioClusterResource.get().getMaster().getInternalMaster().getBlockMaster();
Assert.assertEquals(1000, blockMaster.getCapacityBytes());
}
@Test
public void lastModificationTimeCompleteFileTest() throws Exception {
long fileId = mFsMaster.create(new AlluxioURI("/testFile"), CreateFileOptions.defaults());
long opTimeMs = TEST_CURRENT_TIME;
mFsMaster.completeFileInternal(Lists.<Long>newArrayList(), fileId, 0, opTimeMs);
FileInfo fileInfo = mFsMaster.getFileInfo(fileId);
Assert.assertEquals(opTimeMs, fileInfo.getLastModificationTimeMs());
}
@Test
public void lastModificationTimeCreateFileTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long opTimeMs = TEST_CURRENT_TIME;
CreateFileOptions options = CreateFileOptions.defaults().setOperationTimeMs(opTimeMs);
mFsMaster.createInternal(new AlluxioURI("/testFolder/testFile"), options);
FileInfo folderInfo = mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(opTimeMs, folderInfo.getLastModificationTimeMs());
}
@Test
public void lastModificationTimeDeleteTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile"), CreateFileOptions.defaults());
long folderId = mFsMaster.getFileId(new AlluxioURI("/testFolder"));
Assert.assertEquals(1, folderId);
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
long opTimeMs = TEST_CURRENT_TIME;
Assert.assertTrue(mFsMaster.deleteFileInternal(fileId, true, true, opTimeMs));
FileInfo folderInfo = mFsMaster.getFileInfo(folderId);
Assert.assertEquals(opTimeMs, folderInfo.getLastModificationTimeMs());
}
@Test
public void lastModificationTimeRenameTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile1"), CreateFileOptions.defaults());
long opTimeMs = TEST_CURRENT_TIME;
mFsMaster.renameInternal(fileId, new AlluxioURI("/testFolder/testFile2"), true, opTimeMs);
FileInfo folderInfo = mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(opTimeMs, folderInfo.getLastModificationTimeMs());
}
@Test
public void listFilesTest() throws Exception {
CreateFileOptions options = CreateFileOptions.defaults().setBlockSizeBytes(64);
HashSet<Long> ids = new HashSet<Long>();
HashSet<Long> dirIds = new HashSet<Long>();
for (int i = 0; i < 10; i++) {
AlluxioURI dir = new AlluxioURI("/i" + i);
mFsMaster.mkdir(dir, CreateDirectoryOptions.defaults());
dirIds.add(mFsMaster.getFileId(dir));
for (int j = 0; j < 10; j++) {
ids.add(mFsMaster.create(dir.join("j" + j), options));
}
}
HashSet<Long> listedIds = Sets.newHashSet();
HashSet<Long> listedDirIds = Sets.newHashSet();
List<FileInfo> infoList = mFsMaster.getFileInfoList(new AlluxioURI("/"));
for (FileInfo info : infoList) {
long id = info.getFileId();
listedDirIds.add(id);
for (FileInfo fileInfo : mFsMaster.getFileInfoList(new AlluxioURI(info.getPath()))) {
listedIds.add(fileInfo.getFileId());
}
}
Assert.assertEquals(ids, listedIds);
Assert.assertEquals(dirIds, listedDirIds);
}
@Test
public void lsTest() throws Exception {
CreateFileOptions options = CreateFileOptions.defaults().setBlockSizeBytes(64);
for (int i = 0; i < 10; i++) {
mFsMaster.mkdir(new AlluxioURI("/i" + i), CreateDirectoryOptions.defaults());
for (int j = 0; j < 10; j++) {
mFsMaster.create(new AlluxioURI("/i" + i + "/j" + j), options);
}
}
Assert.assertEquals(1,
mFsMaster.getFileInfoList(new AlluxioURI("/i0/j0")).size());
for (int i = 0; i < 10; i++) {
Assert.assertEquals(10,
mFsMaster.getFileInfoList(new AlluxioURI("/i" + i)).size());
}
Assert.assertEquals(10,
mFsMaster.getFileInfoList(new AlluxioURI("/")).size());
}
@Test
public void notFileCompletionTest() throws Exception {
mThrown.expect(FileDoesNotExistException.class);
mFsMaster.mkdir(new AlluxioURI("/testFile"), CreateDirectoryOptions.defaults());
CompleteFileOptions options = CompleteFileOptions.defaults();
mFsMaster.completeFile(new AlluxioURI("/testFile"), options);
}
@Test
public void renameExistingDstTest() throws Exception {
mFsMaster.create(new AlluxioURI("/testFile1"), CreateFileOptions.defaults());
mFsMaster.create(new AlluxioURI("/testFile2"), CreateFileOptions.defaults());
try {
mFsMaster.rename(new AlluxioURI("/testFile1"), new AlluxioURI("/testFile2"));
Assert.fail("Should not be able to rename to an existing file");
} catch (Exception e) {
// expected
}
}
@Test
public void renameNonexistentTest() throws Exception {
mFsMaster.create(new AlluxioURI("/testFile1"), CreateFileOptions.defaults());
Assert.assertEquals(IdUtils.INVALID_FILE_ID, mFsMaster.getFileId(new AlluxioURI("/testFile2")));
}
@Test
public void renameToDeeper() throws Exception {
CreateFileOptions createFileOptions = CreateFileOptions.defaults().setRecursive(true);
CreateDirectoryOptions createDirectoryOptions =
CreateDirectoryOptions.defaults().setRecursive(true);
mThrown.expect(InvalidPathException.class);
mFsMaster.mkdir(new AlluxioURI("/testDir1/testDir2"), createDirectoryOptions);
mFsMaster.create(new AlluxioURI("/testDir1/testDir2/testDir3/testFile3"), createFileOptions);
mFsMaster.rename(new AlluxioURI("/testDir1/testDir2"),
new AlluxioURI("/testDir1/testDir2/testDir3/testDir4"));
}
@Test
public void ttlCreateFileTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long ttl = 100;
CreateFileOptions options = CreateFileOptions.defaults().setTtl(ttl);
mFsMaster.createInternal(new AlluxioURI("/testFolder/testFile"), options);
FileInfo folderInfo =
mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
Assert.assertEquals(ttl, folderInfo.getTtl());
}
@Test
public void ttlExpiredCreateFileTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long ttl = 1;
CreateFileOptions options = CreateFileOptions.defaults().setTtl(ttl);
long fileId = mFsMaster.create(new AlluxioURI("/testFolder/testFile1"), options);
FileInfo folderInfo =
mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile1")));
Assert.assertEquals(fileId, folderInfo.getFileId());
Assert.assertEquals(ttl, folderInfo.getTtl());
CommonUtils.sleepMs(5000);
mThrown.expect(FileDoesNotExistException.class);
mFsMaster.getFileInfo(fileId);
}
@Test
public void ttlRenameTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long ttl = 1;
CreateFileOptions options = CreateFileOptions.defaults().setTtl(ttl);
long fileId = mFsMaster.create(new AlluxioURI("/testFolder/testFile1"), options);
mFsMaster.renameInternal(fileId, new AlluxioURI("/testFolder/testFile2"), true,
TEST_CURRENT_TIME);
FileInfo folderInfo =
mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile2")));
Assert.assertEquals(ttl, folderInfo.getTtl());
}
// TODO(gene): Journal format has changed, maybe add Version to the format and add this test back
// or remove this test when we have better tests against journal checkpoint.
// @Test
// public void writeImageTest() throws IOException {
// // initialize the MasterInfo
// Journal journal =
// new Journal(mLocalAlluxioCluster.getAlluxioHome() + "journal/", "image.data", "log.data",
// mMasterAlluxioConf);
// Journal
// MasterInfo info =
// new MasterInfo(new InetSocketAddress(9999), journal, mExecutorService, mMasterAlluxioConf);
// // create the output streams
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// DataOutputStream dos = new DataOutputStream(os);
// ObjectMapper mapper = JsonObject.createObjectMapper();
// ObjectWriter writer = mapper.writer();
// ImageElement version = null;
// ImageElement checkpoint = null;
// // write the image
// info.writeImage(writer, dos);
// // parse the written bytes and look for the Checkpoint and Version ImageElements
// String[] splits = new String(os.toByteArray()).split("\n");
// for (String split : splits) {
// byte[] bytes = split.getBytes();
// JsonParser parser = mapper.getFactory().createParser(bytes);
// ImageElement ele = parser.readValueAs(ImageElement.class);
// if (ele.mType.equals(ImageElementType.Checkpoint)) {
// checkpoint = ele;
// }
// if (ele.mType.equals(ImageElementType.Version)) {
// version = ele;
// }
// }
// // test the elements
// Assert.assertNotNull(checkpoint);
// Assert.assertEquals(checkpoint.mType, ImageElementType.Checkpoint);
// Assert.assertEquals(Constants.JOURNAL_VERSION, version.getInt("version").intValue());
// Assert.assertEquals(1, checkpoint.getInt("inodeCounter").intValue());
// Assert.assertEquals(0, checkpoint.getInt("editTransactionCounter").intValue());
// Assert.assertEquals(0, checkpoint.getInt("dependencyCounter").intValue());
// }
}
| tests/src/test/java/alluxio/master/file/FileSystemMasterIntegrationTest.java | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the โLicenseโ). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.master.file;
import alluxio.AlluxioURI;
import alluxio.Configuration;
import alluxio.Constants;
import alluxio.LocalAlluxioClusterResource;
import alluxio.exception.DirectoryNotEmptyException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.FileAlreadyExistsException;
import alluxio.exception.FileDoesNotExistException;
import alluxio.exception.InvalidPathException;
import alluxio.master.MasterTestUtils;
import alluxio.master.block.BlockMaster;
import alluxio.master.file.meta.TtlBucketPrivateAccess;
import alluxio.master.file.options.CompleteFileOptions;
import alluxio.master.file.options.CreateDirectoryOptions;
import alluxio.master.file.options.CreateFileOptions;
import alluxio.security.authentication.AuthType;
import alluxio.security.authentication.AuthenticatedClientUser;
import alluxio.util.CommonUtils;
import alluxio.util.IdUtils;
import alluxio.wire.FileInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.Timeout;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Test behavior of {@link FileSystemMaster}.
*
* For example, (concurrently) creating/deleting/renaming files.
*/
public class FileSystemMasterIntegrationTest {
class ConcurrentCreator implements Callable<Void> {
private int mDepth;
private int mConcurrencyDepth;
private AlluxioURI mInitPath;
ConcurrentCreator(int depth, int concurrencyDepth, AlluxioURI initPath) {
mDepth = depth;
mConcurrencyDepth = concurrencyDepth;
mInitPath = initPath;
}
@Override
public Void call() throws Exception {
AuthenticatedClientUser.set(TEST_AUTHENTICATE_USER);
exec(mDepth, mConcurrencyDepth, mInitPath);
return null;
}
public void exec(int depth, int concurrencyDepth, AlluxioURI path) throws Exception {
if (depth < 1) {
return;
} else if (depth == 1) {
long fileId = mFsMaster.create(path, CreateFileOptions.defaults());
Assert.assertEquals(fileId, mFsMaster.getFileId(path));
// verify the user permission for file
FileInfo fileInfo = mFsMaster.getFileInfo(fileId);
Assert.assertEquals(TEST_AUTHENTICATE_USER, fileInfo.getUserName());
Assert.assertEquals(0644, (short) fileInfo.getPermission());
} else {
mFsMaster.mkdir(path, CreateDirectoryOptions.defaults());
Assert.assertNotNull(mFsMaster.getFileId(path));
long dirId = mFsMaster.getFileId(path);
Assert.assertNotEquals(-1, dirId);
FileInfo dirInfo = mFsMaster.getFileInfo(dirId);
Assert.assertEquals(TEST_AUTHENTICATE_USER, dirInfo.getUserName());
Assert.assertEquals(0755, (short) dirInfo.getPermission());
}
if (concurrencyDepth > 0) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE);
for (int i = 0; i < FILES_PER_NODE; i++) {
Callable<Void> call = (new ConcurrentCreator(depth - 1, concurrencyDepth - 1,
path.join(Integer.toString(i))));
futures.add(executor.submit(call));
}
for (Future<Void> f : futures) {
f.get();
}
} finally {
executor.shutdown();
}
} else {
for (int i = 0; i < FILES_PER_NODE; i++) {
exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i)));
}
}
}
}
/*
* This class provides multiple concurrent threads to free all files in one directory.
*/
class ConcurrentFreer implements Callable<Void> {
private int mDepth;
private int mConcurrencyDepth;
private AlluxioURI mInitPath;
ConcurrentFreer(int depth, int concurrencyDepth, AlluxioURI initPath) {
mDepth = depth;
mConcurrencyDepth = concurrencyDepth;
mInitPath = initPath;
}
@Override
public Void call() throws Exception {
exec(mDepth, mConcurrencyDepth, mInitPath);
return null;
}
private void doFree(AlluxioURI path) throws Exception {
mFsMaster.free(path, true);
Assert.assertNotEquals(IdUtils.INVALID_FILE_ID, mFsMaster.getFileId(path));
}
public void exec(int depth, int concurrencyDepth, AlluxioURI path) throws Exception {
if (depth < 1) {
return;
} else if (depth == 1 || (path.hashCode() % 10 == 0)) {
// Sometimes we want to try freeing a path when we're not all the way down, which is what
// the second condition is for.
doFree(path);
} else {
if (concurrencyDepth > 0) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE);
for (int i = 0; i < FILES_PER_NODE; i++) {
Callable<Void> call = (new ConcurrentDeleter(depth - 1, concurrencyDepth - 1,
path.join(Integer.toString(i))));
futures.add(executor.submit(call));
}
for (Future<Void> f : futures) {
f.get();
}
} finally {
executor.shutdown();
}
} else {
for (int i = 0; i < FILES_PER_NODE; i++) {
exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i)));
}
}
doFree(path);
}
}
}
/*
* This class provides multiple concurrent threads to delete all files in one directory.
*/
class ConcurrentDeleter implements Callable<Void> {
private int mDepth;
private int mConcurrencyDepth;
private AlluxioURI mInitPath;
ConcurrentDeleter(int depth, int concurrencyDepth, AlluxioURI initPath) {
mDepth = depth;
mConcurrencyDepth = concurrencyDepth;
mInitPath = initPath;
}
@Override
public Void call() throws Exception {
exec(mDepth, mConcurrencyDepth, mInitPath);
return null;
}
private void doDelete(AlluxioURI path) throws Exception {
mFsMaster.deleteFile(path, true);
Assert.assertEquals(IdUtils.INVALID_FILE_ID, mFsMaster.getFileId(path));
}
public void exec(int depth, int concurrencyDepth, AlluxioURI path) throws Exception {
if (depth < 1) {
return;
} else if (depth == 1 || (path.hashCode() % 10 == 0)) {
// Sometimes we want to try deleting a path when we're not all the way down, which is what
// the second condition is for.
doDelete(path);
} else {
if (concurrencyDepth > 0) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE);
for (int i = 0; i < FILES_PER_NODE; i++) {
Callable<Void> call = (new ConcurrentDeleter(depth - 1, concurrencyDepth - 1,
path.join(Integer.toString(i))));
futures.add(executor.submit(call));
}
for (Future<Void> f : futures) {
f.get();
}
} finally {
executor.shutdown();
}
} else {
for (int i = 0; i < FILES_PER_NODE; i++) {
exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i)));
}
}
doDelete(path);
}
}
}
class ConcurrentRenamer implements Callable<Void> {
private int mDepth;
private int mConcurrencyDepth;
private AlluxioURI mRootPath;
private AlluxioURI mRootPath2;
private AlluxioURI mInitPath;
ConcurrentRenamer(int depth, int concurrencyDepth, AlluxioURI rootPath, AlluxioURI rootPath2,
AlluxioURI initPath) {
mDepth = depth;
mConcurrencyDepth = concurrencyDepth;
mRootPath = rootPath;
mRootPath2 = rootPath2;
mInitPath = initPath;
}
@Override
public Void call() throws Exception {
AuthenticatedClientUser.set(TEST_AUTHENTICATE_USER);
exec(mDepth, mConcurrencyDepth, mInitPath);
return null;
}
public void exec(int depth, int concurrencyDepth, AlluxioURI path) throws Exception {
if (depth < 1) {
return;
} else if (depth == 1 || (depth < mDepth && path.hashCode() % 10 < 3)) {
// Sometimes we want to try renaming a path when we're not all the way down, which is what
// the second condition is for. We have to create the path in the destination up till what
// we're renaming. This might already exist, so createFile could throw a
// FileAlreadyExistsException, which we silently handle.
AlluxioURI srcPath = mRootPath.join(path);
AlluxioURI dstPath = mRootPath2.join(path);
long fileId = mFsMaster.getFileId(srcPath);
try {
CreateDirectoryOptions options = CreateDirectoryOptions.defaults().setRecursive(true);
mFsMaster.mkdir(dstPath.getParent(), options);
} catch (FileAlreadyExistsException e) {
// This is an acceptable exception to get, since we don't know if the parent has been
// created yet by another thread.
} catch (InvalidPathException e) {
// This could happen if we are renaming something that's a child of the root.
}
mFsMaster.rename(srcPath, dstPath);
Assert.assertEquals(fileId, mFsMaster.getFileId(dstPath));
} else if (concurrencyDepth > 0) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE);
for (int i = 0; i < FILES_PER_NODE; i++) {
Callable<Void> call = (new ConcurrentRenamer(depth - 1, concurrencyDepth - 1, mRootPath,
mRootPath2, path.join(Integer.toString(i))));
futures.add(executor.submit(call));
}
for (Future<Void> f : futures) {
f.get();
}
} finally {
executor.shutdown();
}
} else {
for (int i = 0; i < FILES_PER_NODE; i++) {
exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i)));
}
}
}
}
private static final int DEPTH = 6;
private static final int FILES_PER_NODE = 4;
private static final int CONCURRENCY_DEPTH = 3;
private static final AlluxioURI ROOT_PATH = new AlluxioURI("/root");
private static final AlluxioURI ROOT_PATH2 = new AlluxioURI("/root2");
// Modify current time so that implementations can't accidentally pass unit tests by ignoring
// this specified time and always using System.currentTimeMillis()
private static final long TEST_CURRENT_TIME = 300;
/**
* The authenticate user is gotten from current thread local. If MasterInfo starts a concurrent
* thread to do operations, {@link AuthenticatedClientUser} will be null. So
* {@link AuthenticatedClientUser#set(String)} should be called in the {@link Callable#call()} to
* set this user for testing.
*/
private static final String TEST_AUTHENTICATE_USER = "test-user";
@Rule
public Timeout mGlobalTimeout = Timeout.seconds(60);
@Rule
public LocalAlluxioClusterResource mLocalAlluxioClusterResource =
new LocalAlluxioClusterResource(1000, Constants.GB,
Constants.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName());
private Configuration mMasterConfiguration;
private FileSystemMaster mFsMaster;
@Rule
public ExpectedException mThrown = ExpectedException.none();
@Before
public final void before() throws Exception {
// mock the authentication user
AuthenticatedClientUser.set(TEST_AUTHENTICATE_USER);
mFsMaster =
mLocalAlluxioClusterResource.get().getMaster().getInternalMaster().getFileSystemMaster();
mMasterConfiguration = mLocalAlluxioClusterResource.get().getMasterConf();
TtlBucketPrivateAccess
.setTtlIntervalMs(mMasterConfiguration.getLong(Constants.MASTER_TTL_CHECKER_INTERVAL_MS));
}
@Test
public void clientFileInfoDirectoryTest() throws Exception {
AlluxioURI path = new AlluxioURI("/testFolder");
mFsMaster.mkdir(path, CreateDirectoryOptions.defaults());
long fileId = mFsMaster.getFileId(path);
FileInfo fileInfo = mFsMaster.getFileInfo(fileId);
Assert.assertEquals("testFolder", fileInfo.getName());
Assert.assertEquals(1, fileInfo.getFileId());
Assert.assertEquals(0, fileInfo.getLength());
Assert.assertFalse(fileInfo.isCacheable());
Assert.assertTrue(fileInfo.isCompleted());
Assert.assertTrue(fileInfo.isFolder());
Assert.assertFalse(fileInfo.isPersisted());
Assert.assertFalse(fileInfo.isPinned());
Assert.assertEquals(TEST_AUTHENTICATE_USER, fileInfo.getUserName());
Assert.assertEquals(0755, (short) fileInfo.getPermission());
}
@Test
public void clientFileInfoEmptyFileTest() throws Exception {
long fileId = mFsMaster.create(new AlluxioURI("/testFile"), CreateFileOptions.defaults());
FileInfo fileInfo = mFsMaster.getFileInfo(fileId);
Assert.assertEquals("testFile", fileInfo.getName());
Assert.assertEquals(fileId, fileInfo.getFileId());
Assert.assertEquals(0, fileInfo.getLength());
Assert.assertTrue(fileInfo.isCacheable());
Assert.assertFalse(fileInfo.isCompleted());
Assert.assertFalse(fileInfo.isFolder());
Assert.assertFalse(fileInfo.isPersisted());
Assert.assertFalse(fileInfo.isPinned());
Assert.assertEquals(Constants.NO_TTL, fileInfo.getTtl());
Assert.assertEquals(TEST_AUTHENTICATE_USER, fileInfo.getUserName());
Assert.assertEquals(0644, (short) fileInfo.getPermission());
}
private FileSystemMaster createFileSystemMasterFromJournal() throws IOException {
return MasterTestUtils.createFileSystemMasterFromJournal(mMasterConfiguration);
}
// TODO(calvin): This test currently relies on the fact the HDFS client is a cached instance to
// avoid invalid lease exception. This should be fixed.
@Ignore
@Test
public void concurrentCreateJournalTest() throws Exception {
// Makes sure the file id's are the same between a master info and the journal it creates
for (int i = 0; i < 5; i++) {
ConcurrentCreator concurrentCreator =
new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentCreator.call();
FileSystemMaster fsMaster = createFileSystemMasterFromJournal();
for (FileInfo info : mFsMaster.getFileInfoList(new AlluxioURI("/"))) {
AlluxioURI path = new AlluxioURI(info.getPath());
Assert.assertEquals(mFsMaster.getFileId(path), fsMaster.getFileId(path));
}
before();
}
}
@Test
public void concurrentCreateTest() throws Exception {
ConcurrentCreator concurrentCreator =
new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentCreator.call();
}
@Test
public void concurrentDeleteTest() throws Exception {
ConcurrentCreator concurrentCreator =
new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentCreator.call();
ConcurrentDeleter concurrentDeleter =
new ConcurrentDeleter(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentDeleter.call();
Assert.assertEquals(0,
mFsMaster.getFileInfoList(new AlluxioURI("/")).size());
}
@Test
public void concurrentFreeTest() throws Exception {
ConcurrentCreator concurrentCreator =
new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentCreator.call();
ConcurrentFreer concurrentFreer =
new ConcurrentFreer(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentFreer.call();
}
@Test
public void concurrentRenameTest() throws Exception {
ConcurrentCreator concurrentCreator =
new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH);
concurrentCreator.call();
int numFiles = mFsMaster.getFileInfoList(ROOT_PATH).size();
ConcurrentRenamer concurrentRenamer = new ConcurrentRenamer(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH,
ROOT_PATH2, AlluxioURI.EMPTY_URI);
concurrentRenamer.call();
Assert.assertEquals(numFiles,
mFsMaster.getFileInfoList(ROOT_PATH2).size());
}
@Test
public void createAlreadyExistFileTest() throws Exception {
mThrown.expect(FileAlreadyExistsException.class);
mFsMaster.create(new AlluxioURI("/testFile"), CreateFileOptions.defaults());
mFsMaster.mkdir(new AlluxioURI("/testFile"), CreateDirectoryOptions.defaults());
}
@Test
public void createDirectoryTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
FileInfo fileInfo = mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertTrue(fileInfo.isFolder());
Assert.assertEquals(TEST_AUTHENTICATE_USER, fileInfo.getUserName());
Assert.assertEquals(0755, (short) fileInfo.getPermission());
}
@Test
public void createFileInvalidPathTest() throws Exception {
mThrown.expect(InvalidPathException.class);
mFsMaster.create(new AlluxioURI("testFile"), CreateFileOptions.defaults());
}
@Test
public void createFileInvalidPathTest2() throws Exception {
mThrown.expect(FileAlreadyExistsException.class);
mFsMaster.create(new AlluxioURI("/"), CreateFileOptions.defaults());
}
@Test
public void createFileInvalidPathTest3() throws Exception {
mThrown.expect(InvalidPathException.class);
mFsMaster.create(new AlluxioURI("/testFile1"), CreateFileOptions.defaults());
mFsMaster.create(new AlluxioURI("/testFile1/testFile2"), CreateFileOptions.defaults());
}
@Test
public void createFilePerfTest() throws Exception {
for (int k = 0; k < 200; k++) {
CreateDirectoryOptions options = CreateDirectoryOptions.defaults().setRecursive(true);
mFsMaster.mkdir(
new AlluxioURI("/testFile").join(Constants.MASTER_COLUMN_FILE_PREFIX + k).join("0"),
options);
}
for (int k = 0; k < 200; k++) {
mFsMaster.getFileInfo(mFsMaster.getFileId(
new AlluxioURI("/testFile").join(Constants.MASTER_COLUMN_FILE_PREFIX + k).join("0")));
}
}
@Test
public void createFileTest() throws Exception {
mFsMaster.create(new AlluxioURI("/testFile"), CreateFileOptions.defaults());
FileInfo fileInfo = mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFile")));
Assert.assertFalse(fileInfo.isFolder());
Assert.assertEquals(TEST_AUTHENTICATE_USER, fileInfo.getUserName());
Assert.assertEquals(0644, (short) fileInfo.getPermission());
}
@Test
public void deleteDirectoryWithDirectoriesTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
mFsMaster.mkdir(new AlluxioURI("/testFolder/testFolder2"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile"), CreateFileOptions.defaults());
long fileId2 = mFsMaster.create(new AlluxioURI("/testFolder/testFolder2/testFile2"),
CreateFileOptions.defaults());
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(2, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
Assert.assertEquals(fileId2,
mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2/testFile2")));
Assert.assertTrue(mFsMaster.deleteFile(new AlluxioURI("/testFolder"), true));
Assert.assertEquals(IdUtils.INVALID_FILE_ID,
mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2/testFile2")));
}
@Test
public void deleteDirectoryWithDirectoriesTest2() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
mFsMaster.mkdir(new AlluxioURI("/testFolder/testFolder2"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile"), CreateFileOptions.defaults());
long fileId2 = mFsMaster.create(new AlluxioURI("/testFolder/testFolder2/testFile2"),
CreateFileOptions.defaults());
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(2, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
Assert.assertEquals(fileId2,
mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2/testFile2")));
try {
mFsMaster.deleteFile(new AlluxioURI("/testFolder/testFolder2"), false);
Assert.fail("Deleting a nonempty directory nonrecursively should fail");
} catch (DirectoryNotEmptyException e) {
Assert.assertEquals(
ExceptionMessage.DELETE_NONEMPTY_DIRECTORY_NONRECURSIVE.getMessage("testFolder2"),
e.getMessage());
}
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(2, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
Assert.assertEquals(fileId2,
mFsMaster.getFileId(new AlluxioURI("/testFolder/testFolder2/testFile2")));
}
@Test
public void deleteDirectoryWithFilesTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile"), CreateFileOptions.defaults());
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
Assert.assertTrue(mFsMaster.deleteFile(new AlluxioURI("/testFolder"), true));
Assert.assertEquals(IdUtils.INVALID_FILE_ID,
mFsMaster.getFileId(new AlluxioURI("/testFolder")));
}
@Test
public void deleteDirectoryWithFilesTest2() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile"), CreateFileOptions.defaults());
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
try {
mFsMaster.deleteFile(new AlluxioURI("/testFolder"), false);
Assert.fail("Deleting a nonempty directory nonrecursively should fail");
} catch (DirectoryNotEmptyException e) {
Assert.assertEquals(
ExceptionMessage.DELETE_NONEMPTY_DIRECTORY_NONRECURSIVE.getMessage("testFolder"),
e.getMessage());
}
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
}
@Test
public void deleteEmptyDirectoryTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
Assert.assertEquals(1, mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertTrue(mFsMaster.deleteFile(new AlluxioURI("/testFolder"), true));
Assert.assertEquals(IdUtils.INVALID_FILE_ID,
mFsMaster.getFileId(new AlluxioURI("/testFolder")));
}
@Test
public void deleteFileTest() throws Exception {
long fileId = mFsMaster.create(new AlluxioURI("/testFile"), CreateFileOptions.defaults());
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFile")));
Assert.assertTrue(mFsMaster.deleteFile(new AlluxioURI("/testFile"), true));
Assert.assertEquals(IdUtils.INVALID_FILE_ID, mFsMaster.getFileId(new AlluxioURI("/testFile")));
}
@Test
public void deleteRootTest() throws Exception {
Assert.assertFalse(mFsMaster.deleteFile(new AlluxioURI("/"), true));
Assert.assertFalse(mFsMaster.deleteFile(new AlluxioURI("/"), false));
}
@Test
public void getCapacityBytesTest() {
BlockMaster blockMaster =
mLocalAlluxioClusterResource.get().getMaster().getInternalMaster().getBlockMaster();
Assert.assertEquals(1000, blockMaster.getCapacityBytes());
}
@Test
public void lastModificationTimeCompleteFileTest() throws Exception {
long fileId = mFsMaster.create(new AlluxioURI("/testFile"), CreateFileOptions.defaults());
long opTimeMs = TEST_CURRENT_TIME;
mFsMaster.completeFileInternal(Lists.<Long>newArrayList(), fileId, 0, opTimeMs);
FileInfo fileInfo = mFsMaster.getFileInfo(fileId);
Assert.assertEquals(opTimeMs, fileInfo.getLastModificationTimeMs());
}
@Test
public void lastModificationTimeCreateFileTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long opTimeMs = TEST_CURRENT_TIME;
CreateFileOptions options = CreateFileOptions.defaults().setOperationTimeMs(opTimeMs);
mFsMaster.createInternal(new AlluxioURI("/testFolder/testFile"), options);
FileInfo folderInfo = mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(opTimeMs, folderInfo.getLastModificationTimeMs());
}
@Test
public void lastModificationTimeDeleteTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile"), CreateFileOptions.defaults());
long folderId = mFsMaster.getFileId(new AlluxioURI("/testFolder"));
Assert.assertEquals(1, folderId);
Assert.assertEquals(fileId, mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
long opTimeMs = TEST_CURRENT_TIME;
Assert.assertTrue(mFsMaster.deleteFileInternal(fileId, true, true, opTimeMs));
FileInfo folderInfo = mFsMaster.getFileInfo(folderId);
Assert.assertEquals(opTimeMs, folderInfo.getLastModificationTimeMs());
}
@Test
public void lastModificationTimeRenameTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long fileId =
mFsMaster.create(new AlluxioURI("/testFolder/testFile1"), CreateFileOptions.defaults());
long opTimeMs = TEST_CURRENT_TIME;
mFsMaster.renameInternal(fileId, new AlluxioURI("/testFolder/testFile2"), true, opTimeMs);
FileInfo folderInfo = mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder")));
Assert.assertEquals(opTimeMs, folderInfo.getLastModificationTimeMs());
}
@Test
public void listFilesTest() throws Exception {
CreateFileOptions options = CreateFileOptions.defaults().setBlockSizeBytes(64);
HashSet<Long> ids = new HashSet<Long>();
HashSet<Long> dirIds = new HashSet<Long>();
for (int i = 0; i < 10; i++) {
AlluxioURI dir = new AlluxioURI("/i" + i);
mFsMaster.mkdir(dir, CreateDirectoryOptions.defaults());
dirIds.add(mFsMaster.getFileId(dir));
for (int j = 0; j < 10; j++) {
ids.add(mFsMaster.create(dir.join("j" + j), options));
}
}
HashSet<Long> listedIds = Sets.newHashSet();
HashSet<Long> listedDirIds = Sets.newHashSet();
List<FileInfo> infoList = mFsMaster.getFileInfoList(new AlluxioURI("/"));
for (FileInfo info : infoList) {
long id = info.getFileId();
listedDirIds.add(id);
for (FileInfo fileInfo : mFsMaster.getFileInfoList(new AlluxioURI(info.getPath()))) {
listedIds.add(fileInfo.getFileId());
}
}
Assert.assertEquals(ids, listedIds);
Assert.assertEquals(dirIds, listedDirIds);
}
@Test
public void lsTest() throws Exception {
CreateFileOptions options = CreateFileOptions.defaults().setBlockSizeBytes(64);
for (int i = 0; i < 10; i++) {
mFsMaster.mkdir(new AlluxioURI("/i" + i), CreateDirectoryOptions.defaults());
for (int j = 0; j < 10; j++) {
mFsMaster.create(new AlluxioURI("/i" + i + "/j" + j), options);
}
}
Assert.assertEquals(1,
mFsMaster.getFileInfoList(new AlluxioURI("/i0/j0")).size());
for (int i = 0; i < 10; i++) {
Assert.assertEquals(10,
mFsMaster.getFileInfoList(new AlluxioURI("/i" + i)).size());
}
Assert.assertEquals(10,
mFsMaster.getFileInfoList(new AlluxioURI("/")).size());
}
@Test
public void notFileCompletionTest() throws Exception {
mThrown.expect(FileDoesNotExistException.class);
mFsMaster.mkdir(new AlluxioURI("/testFile"), CreateDirectoryOptions.defaults());
CompleteFileOptions options = CompleteFileOptions.defaults();
mFsMaster.completeFile(new AlluxioURI("/testFile"), options);
}
@Test
public void renameExistingDstTest() throws Exception {
mFsMaster.create(new AlluxioURI("/testFile1"), CreateFileOptions.defaults());
mFsMaster.create(new AlluxioURI("/testFile2"), CreateFileOptions.defaults());
try {
mFsMaster.rename(new AlluxioURI("/testFile1"), new AlluxioURI("/testFile2"));
Assert.fail("Should not be able to rename to an existing file");
} catch (Exception e) {
// expected
}
}
@Test
public void renameNonexistentTest() throws Exception {
mFsMaster.create(new AlluxioURI("/testFile1"), CreateFileOptions.defaults());
Assert.assertEquals(IdUtils.INVALID_FILE_ID, mFsMaster.getFileId(new AlluxioURI("/testFile2")));
}
@Test
public void renameToDeeper() throws Exception {
CreateFileOptions createFileOptions = CreateFileOptions.defaults().setRecursive(true);
CreateDirectoryOptions createDirectoryOptions =
CreateDirectoryOptions.defaults().setRecursive(true);
mThrown.expect(InvalidPathException.class);
mFsMaster.mkdir(new AlluxioURI("/testDir1/testDir2"), createDirectoryOptions);
mFsMaster.create(new AlluxioURI("/testDir1/testDir2/testDir3/testFile3"), createFileOptions);
mFsMaster.rename(new AlluxioURI("/testDir1/testDir2"),
new AlluxioURI("/testDir1/testDir2/testDir3/testDir4"));
}
@Test
public void ttlCreateFileTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long ttl = 100;
CreateFileOptions options = CreateFileOptions.defaults().setTtl(ttl);
mFsMaster.createInternal(new AlluxioURI("/testFolder/testFile"), options);
FileInfo folderInfo =
mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile")));
Assert.assertEquals(ttl, folderInfo.getTtl());
}
@Test
public void ttlExpiredCreateFileTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long ttl = 1;
CreateFileOptions options = CreateFileOptions.defaults().setTtl(ttl);
long fileId = mFsMaster.create(new AlluxioURI("/testFolder/testFile1"), options);
FileInfo folderInfo =
mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile1")));
Assert.assertEquals(fileId, folderInfo.getFileId());
Assert.assertEquals(ttl, folderInfo.getTtl());
CommonUtils.sleepMs(5000);
mThrown.expect(FileDoesNotExistException.class);
mFsMaster.getFileInfo(fileId);
}
@Test
public void ttlRenameTest() throws Exception {
mFsMaster.mkdir(new AlluxioURI("/testFolder"), CreateDirectoryOptions.defaults());
long ttl = 1;
CreateFileOptions options = CreateFileOptions.defaults().setTtl(ttl);
long fileId = mFsMaster.create(new AlluxioURI("/testFolder/testFile1"), options);
mFsMaster.renameInternal(fileId, new AlluxioURI("/testFolder/testFile2"), true,
TEST_CURRENT_TIME);
FileInfo folderInfo =
mFsMaster.getFileInfo(mFsMaster.getFileId(new AlluxioURI("/testFolder/testFile2")));
Assert.assertEquals(ttl, folderInfo.getTtl());
}
// TODO(gene): Journal format has changed, maybe add Version to the format and add this test back
// or remove this test when we have better tests against journal checkpoint.
// @Test
// public void writeImageTest() throws IOException {
// // initialize the MasterInfo
// Journal journal =
// new Journal(mLocalAlluxioCluster.getAlluxioHome() + "journal/", "image.data", "log.data",
// mMasterAlluxioConf);
// Journal
// MasterInfo info =
// new MasterInfo(new InetSocketAddress(9999), journal, mExecutorService, mMasterAlluxioConf);
// // create the output streams
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// DataOutputStream dos = new DataOutputStream(os);
// ObjectMapper mapper = JsonObject.createObjectMapper();
// ObjectWriter writer = mapper.writer();
// ImageElement version = null;
// ImageElement checkpoint = null;
// // write the image
// info.writeImage(writer, dos);
// // parse the written bytes and look for the Checkpoint and Version ImageElements
// String[] splits = new String(os.toByteArray()).split("\n");
// for (String split : splits) {
// byte[] bytes = split.getBytes();
// JsonParser parser = mapper.getFactory().createParser(bytes);
// ImageElement ele = parser.readValueAs(ImageElement.class);
// if (ele.mType.equals(ImageElementType.Checkpoint)) {
// checkpoint = ele;
// }
// if (ele.mType.equals(ImageElementType.Version)) {
// version = ele;
// }
// }
// // test the elements
// Assert.assertNotNull(checkpoint);
// Assert.assertEquals(checkpoint.mType, ImageElementType.Checkpoint);
// Assert.assertEquals(Constants.JOURNAL_VERSION, version.getInt("version").intValue());
// Assert.assertEquals(1, checkpoint.getInt("inodeCounter").intValue());
// Assert.assertEquals(0, checkpoint.getInt("editTransactionCounter").intValue());
// Assert.assertEquals(0, checkpoint.getInt("dependencyCounter").intValue());
// }
}
| fix integration
| tests/src/test/java/alluxio/master/file/FileSystemMasterIntegrationTest.java | fix integration | <ide><path>ests/src/test/java/alluxio/master/file/FileSystemMasterIntegrationTest.java
<ide> @Rule
<ide> public LocalAlluxioClusterResource mLocalAlluxioClusterResource =
<ide> new LocalAlluxioClusterResource(1000, Constants.GB,
<del> Constants.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName());
<add> Constants.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE.getAuthName(),
<add> Constants.SECURITY_AUTHORIZATION_PERMISSION_ENABLED, "true");
<ide> private Configuration mMasterConfiguration;
<ide> private FileSystemMaster mFsMaster;
<ide> |
|
Java | apache-2.0 | 0f771cba10591c5fbf0001a5d874eca8dcfecade | 0 | nasrallahmounir/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,nasrallahmounir/Footlights,trombonehero/Footlights,trombonehero/Footlights | /*
* Copyright 2011 Jonathan Anderson
*
* 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 me.footlights.core.data;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import me.footlights.core.data.store.Stat;
/**
* A logical file.
*
* Files are immutable; to modify a file, you must create and freeze a {@link MutableFile}.
*/
public class File implements me.footlights.api.File
{
public static File from(EncryptedBlock header, Collection<EncryptedBlock> ciphertext)
{
List<Block> plaintext = new ArrayList<Block>(ciphertext.size());
for (EncryptedBlock e : ciphertext) plaintext.add(e.plaintext());
return new File(header, plaintext, ciphertext);
}
public static MutableFile newBuilder() { return new MutableFile(); }
public static final class MutableFile
{
public MutableFile setContent(ByteBuffer content)
{
this.content = Arrays.asList(content);
return this;
}
public MutableFile setContent(Collection<ByteBuffer> content)
{
this.content = content;
return this;
}
MutableFile setBlocks(Collection<Block> content)
{
List<ByteBuffer> bytes = new ArrayList<ByteBuffer>(content.size());
for (Block b : content) bytes.add(b.content());
this.content = bytes;
return this;
}
MutableFile setDesiredBlockSize(int size)
{
this.desiredBlockSize = size;
return this;
}
/**
* Produce a proper {@link File} by fixing the current contents of this
* {@link MutableFile}.
*/
public File freeze() throws FormatException, GeneralSecurityException
{
// First, break the content into chunks of the appropriate size.
Collection<ByteBuffer> chunked =
rechunk(content, desiredBlockSize - Block.OVERHEAD_BYTES);
// Next, create {@link EncryptedBlock} objects.
List<EncryptedBlock> ciphertext = new ArrayList<EncryptedBlock>(chunked.size());
for (ByteBuffer b : chunked)
ciphertext.add(
Block.newBuilder()
.setContent(b)
.setDesiredSize(desiredBlockSize)
.build()
.encrypt());
// Finally, create the header. TODO: just embed links in all the blocks.
Block.Builder header = Block.newBuilder();
for (EncryptedBlock b : ciphertext) header.addLink(b.link());
return File.from(header.build().encrypt(), ciphertext);
}
private MutableFile() {}
private Iterable<ByteBuffer> content = new ArrayList<ByteBuffer>();
private int desiredBlockSize = 4096;
}
@Override public URI name() { return stat.name().toURI(); }
public Stat stat() { return stat; }
public URI key() { return header.link().key().toUri(); }
/**
* The content of the file, as one big {@link ByteBuffer}.
*
* Note that, depending on how big the {@link File} is, it might be very silly to actually
* call this method.
*/
public ByteBuffer getContents() throws IOException
{
int len = 0;
for (Block b : plaintext) len += b.content().remaining();
ByteBuffer buffer = ByteBuffer.allocateDirect(len);
for (Block b : plaintext)
buffer.put(b.content().asReadOnlyBuffer());
buffer.flip();
return buffer;
}
/**
* The content of the file, transformed into an {@link InputStream}.
*/
@Override public InputStream getInputStream()
{
final ByteBuffer[] buffers = new ByteBuffer[plaintext.size()];
for (int i = 0; i < buffers.length; i++)
buffers[i] = plaintext.get(i).content();
return new InputStream()
{
@Override public int available()
{
int total = 0;
for (int i = blockIndex; i < buffers.length; i++)
total += buffers[i].remaining();
return total;
}
@Override public int read(byte[] buffer, int offset, int len)
{
if (len == 0) return 0;
if (blockIndex >= plaintext.size()) return -1;
int pos = offset;
while ((pos < (offset + len)) && (blockIndex < buffers.length))
{
int leftToRead = len - (pos - offset);
ByteBuffer next = buffers[blockIndex];
int bytes = Math.min(leftToRead, next.remaining());
next.get(buffer, pos, bytes);
pos += bytes;
if (next.remaining() == 0) blockIndex++;
if (pos == offset) return -1;
}
return (pos - offset);
}
/** This is a horrendously inefficient way of reading data. Don't! */
@Override public int read() throws IOException
{
byte[] data = new byte[1];
int bytes = read(data, 0, data.length);
if (bytes < 0) throw new BufferUnderflowException();
if (bytes == 0)
throw new Error(
"Implementation error in File.read(byte[1]): returned 0");
return data[0];
}
private int blockIndex;
};
}
/** Encrypted blocks to be saved in a {@link Store}. */
public List<EncryptedBlock> toSave()
{
LinkedList<EncryptedBlock> everything = new LinkedList<EncryptedBlock>(ciphertext);
everything.push(header);
return everything;
}
/** A link to the {@link File} itself. */
public Link link() { return header.link(); }
/**
* The contents of the file.
*
* @throws IOException on I/O errors such as network failures
*/
List<ByteBuffer> content() throws IOException
{
List<ByteBuffer> content = new ArrayList<ByteBuffer>(plaintext.size());
for (Block b : plaintext) content.add(b.content());
return content;
}
@Override public boolean equals(Object o)
{
if (o == null) return false;
if (!(o instanceof File)) return false;
File f = (File) o;
if (!this.header.equals(f.header)) return false;
if (!this.plaintext.equals(f.plaintext)) return false;
if (!this.ciphertext.equals(f.ciphertext)) return false;
return true;
}
@Override
public String toString()
{
return "Encrypted File [ " + plaintext.size() + " blocks, name = '" + header.name() + "' ]";
}
/** Convert buffers of data, which may have any size, into buffers of a desired chunk size. */
private static Collection<ByteBuffer> rechunk(Iterable<ByteBuffer> content, int chunkSize)
{
Iterator<ByteBuffer> i = content.iterator();
ByteBuffer next = null;
List<ByteBuffer> chunked = new LinkedList<ByteBuffer>();
ByteBuffer current = ByteBuffer.allocate(chunkSize);
while (true)
{
// Fetch the next input buffer (if necessary). If there are none, we're done.
if ((next == null) || !next.hasRemaining())
{
if (i.hasNext()) next = i.next();
else break;
// If the next batch of content is already the right size, add it directly.
if (next.remaining() == chunkSize)
{
chunked.add(next);
next = null;
continue;
}
}
// If the current output buffer is full, create a new one.
if (current.remaining() == 0)
{
current.flip();
chunked.add(current);
current = ByteBuffer.allocate(chunkSize);
}
// Copy data from input to output.
int toCopy = Math.min(next.remaining(), current.remaining());
next.get(current.array(), current.position(), toCopy);
current.position(current.position() + toCopy);
}
if (current.position() > 0)
{
current.flip();
chunked.add(current);
}
return chunked;
}
/** Default constructor; produces an anonymous file */
private File(EncryptedBlock header,
Collection<Block> plaintext, Collection<EncryptedBlock> ciphertext)
{
this.header = header;
this.plaintext = new ArrayList<Block>(plaintext);
this.ciphertext = new ArrayList<EncryptedBlock>(ciphertext);
long len = 0;
for (Block b : plaintext) len += b.content().remaining();
this.stat = Stat.apply(header.name(), len);
}
private final EncryptedBlock header;
private final List<Block> plaintext;
private final List<EncryptedBlock> ciphertext;
private final Stat stat;
}
| Client/Core/src/main/java/me/footlights/core/data/File.java | /*
* Copyright 2011 Jonathan Anderson
*
* 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 me.footlights.core.data;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import me.footlights.core.data.store.Stat;
/**
* A logical file.
*
* Files are immutable; to modify a file, you must create and freeze a {@link MutableFile}.
*/
public class File implements me.footlights.api.File
{
public static File from(EncryptedBlock header, Collection<EncryptedBlock> ciphertext)
{
List<Block> plaintext = new ArrayList<Block>(ciphertext.size());
for (EncryptedBlock e : ciphertext) plaintext.add(e.plaintext());
return new File(header, plaintext, ciphertext);
}
public static MutableFile newBuilder() { return new MutableFile(); }
public static final class MutableFile
{
public MutableFile setContent(ByteBuffer content)
{
this.content = Arrays.asList(content);
return this;
}
public MutableFile setContent(Collection<ByteBuffer> content)
{
this.content = content;
return this;
}
MutableFile setBlocks(Collection<Block> content)
{
List<ByteBuffer> bytes = new ArrayList<ByteBuffer>(content.size());
for (Block b : content) bytes.add(b.content());
this.content = bytes;
return this;
}
MutableFile setDesiredBlockSize(int size)
{
this.desiredBlockSize = size;
return this;
}
/**
* Produce a proper {@link File} by fixing the current contents of this
* {@link MutableFile}.
*/
public File freeze() throws FormatException, GeneralSecurityException
{
// First, break the content into chunks of the appropriate size.
Collection<ByteBuffer> chunked =
rechunk(content, desiredBlockSize - Block.OVERHEAD_BYTES);
// Next, create {@link EncryptedBlock} objects.
List<EncryptedBlock> ciphertext = new ArrayList<EncryptedBlock>(chunked.size());
for (ByteBuffer b : chunked)
ciphertext.add(
Block.newBuilder()
.setContent(b)
.setDesiredSize(desiredBlockSize)
.build()
.encrypt());
// Finally, create the header. TODO: just embed links in all the blocks.
Block.Builder header = Block.newBuilder();
for (EncryptedBlock b : ciphertext) header.addLink(b.link());
return File.from(header.build().encrypt(), ciphertext);
}
private MutableFile() {}
private Iterable<ByteBuffer> content = new ArrayList<ByteBuffer>();
private int desiredBlockSize = 4096;
}
@Override public URI name() { return stat.name().toURI(); }
public Stat stat() { return stat; }
public URI key() { return header.link().key().toUri(); }
/**
* The content of the file, as one big {@link ByteBuffer}.
*
* Note that, depending on how big the {@link File} is, it might be very silly to actually
* call this method.
*/
public ByteBuffer getContents() throws IOException
{
int len = 0;
for (Block b : plaintext) len += b.content().remaining();
ByteBuffer buffer = ByteBuffer.allocateDirect(len);
for (Block b : plaintext)
buffer.put(b.content().asReadOnlyBuffer());
buffer.flip();
return buffer;
}
/**
* The content of the file, transformed into an {@link InputStream}.
*/
@Override public InputStream getInputStream()
{
final ByteBuffer[] buffers = new ByteBuffer[plaintext.size()];
for (int i = 0; i < buffers.length; i++)
buffers[i] = plaintext.get(i).content();
return new InputStream()
{
@Override public int available()
{
int total = 0;
for (int i = blockIndex; i < buffers.length; i++)
total += buffers[i].remaining();
return total;
}
@Override public int read(byte[] buffer, int offset, int len)
{
if (len == 0) return 0;
if (blockIndex >= plaintext.size()) return -1;
int pos = offset;
while ((pos < (offset + len)) && (blockIndex < buffers.length))
{
int leftToRead = len - (pos - offset);
ByteBuffer next = buffers[blockIndex];
int bytes = Math.min(leftToRead, next.remaining());
next.get(buffer, pos, bytes);
pos += bytes;
if (next.remaining() == 0) blockIndex++;
if (pos == offset) return -1;
}
return (pos - offset);
}
/** This is a horrendously inefficient way of reading data. Don't! */
@Override public int read() throws IOException
{
byte[] data = new byte[1];
int bytes = read(data, 0, data.length);
if (bytes < 0) throw new BufferUnderflowException();
if (bytes == 0)
throw new Error(
"Implementation error in File.read(byte[1]): returned 0");
return data[0];
}
private int blockIndex;
};
}
/** Encrypted blocks to be saved in a {@link Store}. */
public List<EncryptedBlock> toSave()
{
LinkedList<EncryptedBlock> everything = new LinkedList<EncryptedBlock>(ciphertext);
everything.push(header);
return everything;
}
/** A link to the {@link File} itself. */
public Link link() { return header.link(); }
/**
* The contents of the file.
*
* @throws IOException on I/O errors such as network failures
*/
List<ByteBuffer> content() throws IOException
{
List<ByteBuffer> content = new ArrayList<ByteBuffer>(plaintext.size());
for (Block b : plaintext) content.add(b.content());
return content;
}
@Override public boolean equals(Object o)
{
if (o == null) return false;
if (!(o instanceof File)) return false;
File f = (File) o;
if (!this.header.equals(f.header)) return false;
if (!this.plaintext.equals(f.plaintext)) return false;
if (!this.ciphertext.equals(f.ciphertext)) return false;
return true;
}
@Override
public String toString()
{
return "Encrypted File [ " + plaintext.size() + " blocks, name = '" + header.name() + "' ]";
}
/** Convert buffers of data, which may have any size, into buffers of a desired chunk size. */
private static Collection<ByteBuffer> rechunk(Iterable<ByteBuffer> content, int chunkSize)
{
Iterator<ByteBuffer> i = content.iterator();
ByteBuffer next = null;
List<ByteBuffer> chunked = new LinkedList<ByteBuffer>();
ByteBuffer current = ByteBuffer.allocate(chunkSize);
while (true)
{
// Fetch the next input buffer (if necessary). If there are none, we're done.
if ((next == null) || !next.hasRemaining())
{
if (i.hasNext()) next = i.next();
else break;
// If the next batch of content is already the right size, add it directly.
if (next.remaining() == chunkSize)
{
chunked.add(next);
next = null;
continue;
}
}
// If the current output buffer is full, create a new one.
if (current.remaining() == 0)
{
current.flip();
chunked.add(current);
current = ByteBuffer.allocate(chunkSize);
}
// Copy data from input to output.
int toCopy = Math.min(next.remaining(), current.remaining());
next.get(current.array(), current.position(), toCopy);
current.position(current.position() + toCopy);
}
if (current.position() > 0)
{
current.flip();
chunked.add(current);
}
return chunked;
}
/** Default constructor; produces an anonymous file */
private File(EncryptedBlock header,
Collection<Block> plaintext, Collection<EncryptedBlock> ciphertext)
{
this.header = header;
this.plaintext = new ArrayList<Block>(plaintext);
this.ciphertext = new ArrayList<EncryptedBlock>(ciphertext);
long len = 0;
for (Block b : plaintext) len += b.bytes();
this.stat = Stat.apply(header.name(), len);
}
private final EncryptedBlock header;
private final List<Block> plaintext;
private final List<EncryptedBlock> ciphertext;
private final Stat stat;
}
| Only count content bytes (not total block sizes). | Client/Core/src/main/java/me/footlights/core/data/File.java | Only count content bytes (not total block sizes). | <ide><path>lient/Core/src/main/java/me/footlights/core/data/File.java
<ide> this.ciphertext = new ArrayList<EncryptedBlock>(ciphertext);
<ide>
<ide> long len = 0;
<del> for (Block b : plaintext) len += b.bytes();
<add> for (Block b : plaintext) len += b.content().remaining();
<ide> this.stat = Stat.apply(header.name(), len);
<ide> }
<ide> |
|
Java | apache-2.0 | 07dc3297e26f6534304779a87fa18cf5d37e6574 | 0 | csev/evaluation,buckett/evaluation,csev/evaluation,sakaiproject/evaluation,buckett/evaluation,sakaiproject/evaluation,sakaiproject/evaluation,buckett/evaluation,csev/evaluation | /*
* Created on 23 Jan 2007
*/
package org.sakaiproject.evaluation.tool;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.sakaiproject.evaluation.logic.EvalExternalLogic;
import org.sakaiproject.evaluation.logic.EvalItemsLogic;
import org.sakaiproject.evaluation.logic.EvalTemplatesLogic;
import org.sakaiproject.evaluation.model.EvalTemplate;
/*
* A "Local DAO" to focus dependencies and centralise fetching logic for the
* Template views.
*/
public class LocalTemplateLogic {
private EvalItemsLogic itemsLogic;
public void setItemsLogic(EvalItemsLogic itemsLogic) {
this.itemsLogic = itemsLogic;
}
private EvalTemplatesLogic templatesLogic;
public void setTemplatesLogic(EvalTemplatesLogic templatesLogic) {
this.templatesLogic = templatesLogic;
}
private EvalExternalLogic external;
public void setExternal(EvalExternalLogic external) {
this.external = external;
}
public EvalTemplate fetchTemplate(Long templateId) {
return templatesLogic.getTemplateById(templateId);
}
public List fetchTemplateItems(Long templateId) {
if (templateId == null) {
return new ArrayList();
}
else {
return itemsLogic.getTemplateItemsForTemplate(templateId, external
.getCurrentUserId());
}
}
public void saveTemplate(EvalTemplate tosave) {
templatesLogic.saveTemplate(tosave, external.getCurrentUserId());
}
public EvalTemplate newTemplate() {
EvalTemplate currTemplate = new EvalTemplate(new Date(), external.getCurrentUserId(),
null, null, Boolean.FALSE);
return currTemplate;
}
}
| tool/src/java/org/sakaiproject/evaluation/tool/LocalTemplateLogic.java | /*
* Created on 23 Jan 2007
*/
package org.sakaiproject.evaluation.tool;
import java.util.Date;
import java.util.List;
import org.sakaiproject.evaluation.logic.EvalExternalLogic;
import org.sakaiproject.evaluation.logic.EvalItemsLogic;
import org.sakaiproject.evaluation.logic.EvalTemplatesLogic;
import org.sakaiproject.evaluation.model.EvalTemplate;
/*
* A "Local DAO" to focus dependencies and centralise fetching logic for the
* Template views.
*/
public class LocalTemplateLogic {
private EvalItemsLogic itemsLogic;
public void setItemsLogic(EvalItemsLogic itemsLogic) {
this.itemsLogic = itemsLogic;
}
private EvalTemplatesLogic templatesLogic;
public void setTemplatesLogic(EvalTemplatesLogic templatesLogic) {
this.templatesLogic = templatesLogic;
}
private EvalExternalLogic external;
public void setExternal(EvalExternalLogic external) {
this.external = external;
}
public EvalTemplate fetchTemplate(Long templateId) {
return templatesLogic.getTemplateById(templateId);
}
public List fetchTemplateItems(Long templateId) {
return itemsLogic.getTemplateItemsForTemplate(templateId, external
.getCurrentUserId());
}
public void saveTemplate(EvalTemplate tosave) {
templatesLogic.saveTemplate(tosave, external.getCurrentUserId());
}
public EvalTemplate newTemplate() {
EvalTemplate currTemplate = new EvalTemplate(new Date(), external.getCurrentUserId(),
null, null, Boolean.FALSE);
return currTemplate;
}
}
| null guard for fetchTemplateItems
git-svn-id: 6eed24e287f84bf0ab23ca377a3e397011128a6f@3217 fdecad78-55fc-0310-b1b2-d7d25cf747c9
| tool/src/java/org/sakaiproject/evaluation/tool/LocalTemplateLogic.java | null guard for fetchTemplateItems | <ide><path>ool/src/java/org/sakaiproject/evaluation/tool/LocalTemplateLogic.java
<ide> */
<ide> package org.sakaiproject.evaluation.tool;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.Date;
<ide> import java.util.List;
<ide>
<ide> }
<ide>
<ide> public List fetchTemplateItems(Long templateId) {
<add> if (templateId == null) {
<add> return new ArrayList();
<add> }
<add> else {
<ide> return itemsLogic.getTemplateItemsForTemplate(templateId, external
<ide> .getCurrentUserId());
<add> }
<ide> }
<ide>
<ide> public void saveTemplate(EvalTemplate tosave) { |
|
Java | apache-2.0 | e99828165ab8a5f23c7f963e6c8c8ec01a7dc20e | 0 | lievendoclo/Valkyrie-RCP,lievendoclo/Valkyrie-RCP,lievendoclo/Valkyrie-RCP | /*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.valkyriercp.application.docking;
import com.vlsolutions.swing.docking.DockingContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.ApplicationContext;
import org.valkyriercp.application.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* <tt>ApplicationPageFactory</tt> that creates instances of <tt>VLDockingApplicationPage</tt>.
*
* @author Rogan Dawes
*/
@Configurable
public class VLDockingApplicationPageFactory implements ApplicationPageFactory {
private static final Log logger = LogFactory.getLog(VLDockingApplicationPageFactory.class);
private boolean reusePages;
private Map pageCache = new HashMap();
@Autowired
private ApplicationContext applicationContext;
/*
* (non-Javadoc)
*
* @see org.springframework.richclient.application.ApplicationPageFactory#createApplicationPage(org.springframework.richclient.application.ApplicationWindow,
* org.springframework.richclient.application.PageDescriptor)
*/
public ApplicationPage createApplicationPage(ApplicationWindow window, PageDescriptor descriptor) {
if (reusePages) {
VLDockingApplicationPage page = findPage(window, descriptor);
if (page != null) {
return page;
}
}
VLDockingApplicationPage page = new VLDockingApplicationPage(window, descriptor);
if (reusePages) {
cachePage(page);
}
window.addPageListener(new PageListener() {
public void pageOpened(ApplicationPage page) {
// nothing to do here
}
public void pageClosed(ApplicationPage page) {
VLDockingApplicationPage vlDockingApplicationPage = (VLDockingApplicationPage) page;
saveDockingContext(vlDockingApplicationPage);
}
});
return page;
}
/**
* Saves the docking layout of a docking page fo the application
*
* @param dockingPage
* The application window (needed to hook in for the docking context)
*/
private void saveDockingContext(VLDockingApplicationPage dockingPage) {
DockingContext dockingContext = dockingPage.getDockingContext();
// Page descriptor needed for config path
VLDockingPageDescriptor vlDockingPageDescriptor = applicationContext.getBean(dockingPage.getId(), VLDockingPageDescriptor.class);
// Write docking context to file
BufferedOutputStream buffOs = null;
try {
File desktopLayoutFile = vlDockingPageDescriptor.getInitialLayout().getFile();
checkForConfigPath(desktopLayoutFile);
buffOs = new BufferedOutputStream(new FileOutputStream(desktopLayoutFile));
dockingContext.writeXML(buffOs);
buffOs.close();
logger.debug("Wrote docking context to config file " + desktopLayoutFile);
}
catch (IOException e) {
logger.warn("Error writing VLDocking config", e);
}
finally {
try {
buffOs.close();
}
catch (Exception e) {
}
}
}
/**
* Creates the config directory, if it doesn't exist already
*
* @param configFile
* The file for which to create the path
*/
private void checkForConfigPath(File configFile) {
String desktopLayoutFilePath = configFile.getAbsolutePath();
String configDirPath = desktopLayoutFilePath.substring(0, desktopLayoutFilePath.lastIndexOf(System
.getProperty("file.separator")));
File configDir = new File(configDirPath);
// create config dir if it does not exist
if (!configDir.exists()) {
configDir.mkdirs();
logger.debug("Newly created config directory");
}
}
protected VLDockingApplicationPage findPage(ApplicationWindow window, PageDescriptor descriptor) {
Map pages = (Map) pageCache.get(window);
if (pages == null) {
return null;
}
return (VLDockingApplicationPage) pages.get(descriptor.getId());
}
protected void cachePage(VLDockingApplicationPage page) {
Map pages = (Map) pageCache.get(page.getWindow());
if (pages == null) {
pages = new HashMap();
pageCache.put(page.getWindow(), pages);
}
pages.put(page.getId(), page);
}
/**
* @param reusePages
* the reusePages to set
*/
public void setReusePages(boolean reusePages) {
this.reusePages = reusePages;
}
}
| valkyrie-rcp-integrations/valkyrie-rcp-vldocking/src/main/java/org/valkyriercp/application/docking/VLDockingApplicationPageFactory.java | /*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.valkyriercp.application.docking;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.vlsolutions.swing.docking.DockingContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.valkyriercp.application.*;
/**
* <tt>ApplicationPageFactory</tt> that creates instances of <tt>VLDockingApplicationPage</tt>.
*
* @author Rogan Dawes
*/
public class VLDockingApplicationPageFactory implements ApplicationPageFactory {
private static final Log logger = LogFactory.getLog(VLDockingApplicationPageFactory.class);
private boolean reusePages;
private Map pageCache = new HashMap();
@Autowired
private ApplicationContext applicationContext;
/*
* (non-Javadoc)
*
* @see org.springframework.richclient.application.ApplicationPageFactory#createApplicationPage(org.springframework.richclient.application.ApplicationWindow,
* org.springframework.richclient.application.PageDescriptor)
*/
public ApplicationPage createApplicationPage(ApplicationWindow window, PageDescriptor descriptor) {
if (reusePages) {
VLDockingApplicationPage page = findPage(window, descriptor);
if (page != null) {
return page;
}
}
VLDockingApplicationPage page = new VLDockingApplicationPage(window, descriptor);
if (reusePages) {
cachePage(page);
}
window.addPageListener(new PageListener() {
public void pageOpened(ApplicationPage page) {
// nothing to do here
}
public void pageClosed(ApplicationPage page) {
VLDockingApplicationPage vlDockingApplicationPage = (VLDockingApplicationPage) page;
saveDockingContext(vlDockingApplicationPage);
}
});
return page;
}
/**
* Saves the docking layout of a docking page fo the application
*
* @param dockingPage
* The application window (needed to hook in for the docking context)
*/
private void saveDockingContext(VLDockingApplicationPage dockingPage) {
DockingContext dockingContext = dockingPage.getDockingContext();
// Page descriptor needed for config path
VLDockingPageDescriptor vlDockingPageDescriptor = applicationContext.getBean(dockingPage.getId(), VLDockingPageDescriptor.class);
// Write docking context to file
BufferedOutputStream buffOs = null;
try {
File desktopLayoutFile = vlDockingPageDescriptor.getInitialLayout().getFile();
checkForConfigPath(desktopLayoutFile);
buffOs = new BufferedOutputStream(new FileOutputStream(desktopLayoutFile));
dockingContext.writeXML(buffOs);
buffOs.close();
logger.debug("Wrote docking context to config file " + desktopLayoutFile);
}
catch (IOException e) {
logger.warn("Error writing VLDocking config", e);
}
finally {
try {
buffOs.close();
}
catch (Exception e) {
}
}
}
/**
* Creates the config directory, if it doesn't exist already
*
* @param configFile
* The file for which to create the path
*/
private void checkForConfigPath(File configFile) {
String desktopLayoutFilePath = configFile.getAbsolutePath();
String configDirPath = desktopLayoutFilePath.substring(0, desktopLayoutFilePath.lastIndexOf(System
.getProperty("file.separator")));
File configDir = new File(configDirPath);
// create config dir if it does not exist
if (!configDir.exists()) {
configDir.mkdirs();
logger.debug("Newly created config directory");
}
}
protected VLDockingApplicationPage findPage(ApplicationWindow window, PageDescriptor descriptor) {
Map pages = (Map) pageCache.get(window);
if (pages == null) {
return null;
}
return (VLDockingApplicationPage) pages.get(descriptor.getId());
}
protected void cachePage(VLDockingApplicationPage page) {
Map pages = (Map) pageCache.get(page.getWindow());
if (pages == null) {
pages = new HashMap();
pageCache.put(page.getWindow(), pages);
}
pages.put(page.getId(), page);
}
/**
* @param reusePages
* the reusePages to set
*/
public void setReusePages(boolean reusePages) {
this.reusePages = reusePages;
}
}
| configurable aspect added to class
| valkyrie-rcp-integrations/valkyrie-rcp-vldocking/src/main/java/org/valkyriercp/application/docking/VLDockingApplicationPageFactory.java | configurable aspect added to class | <ide><path>alkyrie-rcp-integrations/valkyrie-rcp-vldocking/src/main/java/org/valkyriercp/application/docking/VLDockingApplicationPageFactory.java
<ide> */
<ide> package org.valkyriercp.application.docking;
<ide>
<add>import com.vlsolutions.swing.docking.DockingContext;
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.beans.factory.annotation.Configurable;
<add>import org.springframework.context.ApplicationContext;
<add>import org.valkyriercp.application.*;
<add>
<ide> import java.io.BufferedOutputStream;
<ide> import java.io.File;
<ide> import java.io.FileOutputStream;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide>
<del>import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<del>
<del>import com.vlsolutions.swing.docking.DockingContext;
<del>import org.springframework.beans.factory.annotation.Autowired;
<del>import org.springframework.context.ApplicationContext;
<del>import org.valkyriercp.application.*;
<del>
<ide> /**
<ide> * <tt>ApplicationPageFactory</tt> that creates instances of <tt>VLDockingApplicationPage</tt>.
<ide> *
<ide> * @author Rogan Dawes
<ide> */
<add>@Configurable
<ide> public class VLDockingApplicationPageFactory implements ApplicationPageFactory {
<ide>
<ide> private static final Log logger = LogFactory.getLog(VLDockingApplicationPageFactory.class); |
|
Java | apache-2.0 | 4f1c349b7865f5fa3d00b924c262174a69c736f5 | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | package verification.platu.stategraph;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import verification.platu.common.IndexObjMap;
import verification.platu.logicAnalysis.Constraint;
import verification.platu.lpn.DualHashMap;
import verification.platu.lpn.LpnTranList;
import verification.platu.main.Main;
import verification.platu.main.Options;
import verification.platu.project.PrjState;
import verification.timed_state_exploration.zoneProject.ContinuousUtilities;
import verification.timed_state_exploration.zoneProject.EventSet;
import verification.timed_state_exploration.zoneProject.InequalityVariable;
import verification.timed_state_exploration.zoneProject.Event;
import verification.timed_state_exploration.zoneProject.IntervalPair;
import verification.timed_state_exploration.zoneProject.LPNContAndRate;
import verification.timed_state_exploration.zoneProject.LPNContinuousPair;
import verification.timed_state_exploration.zoneProject.LPNTransitionPair;
import verification.timed_state_exploration.zoneProject.TimedPrjState;
import verification.timed_state_exploration.zoneProject.Zone;
public class StateGraph {
protected State init = null;
protected IndexObjMap<State> stateCache;
protected IndexObjMap<State> localStateCache;
protected HashMap<State, State> state2LocalMap;
protected HashMap<State, LpnTranList> enabledSetTbl;
protected HashMap<State, HashMap<Transition, State>> nextStateMap;
protected List<State> stateSet = new LinkedList<State>();
protected List<State> frontierStateSet = new LinkedList<State>();
protected List<State> entryStateSet = new LinkedList<State>();
protected List<Constraint> oldConstraintSet = new LinkedList<Constraint>();
protected List<Constraint> newConstraintSet = new LinkedList<Constraint>();
protected List<Constraint> frontierConstraintSet = new LinkedList<Constraint>();
protected Set<Constraint> constraintSet = new HashSet<Constraint>();
protected LhpnFile lpn;
public StateGraph(LhpnFile lpn) {
this.lpn = lpn;
this.stateCache = new IndexObjMap<State>();
this.localStateCache = new IndexObjMap<State>();
this.state2LocalMap = new HashMap<State, State>();
this.enabledSetTbl = new HashMap<State, LpnTranList>();
this.nextStateMap = new HashMap<State, HashMap<Transition, State>>();
}
public LhpnFile getLpn(){
return this.lpn;
}
public void printStates(){
System.out.println(String.format("%-8s %5s", this.lpn.getLabel(), "|States| = " + stateCache.size()));
}
public Set<Transition> getTranList(State currentState){
return this.nextStateMap.get(currentState).keySet();
}
/**
* Finds reachable states from the given state.
* Also generates new constraints from the state transitions.
* @param baseState - State to start from
* @return Number of new transitions.
*/
public int constrFindSG(final State baseState){
boolean newStateFlag = false;
int ptr = 1;
int newTransitions = 0;
Stack<State> stStack = new Stack<State>();
Stack<LpnTranList> tranStack = new Stack<LpnTranList>();
LpnTranList currentEnabledTransitions = getEnabled(baseState);
stStack.push(baseState);
tranStack.push((LpnTranList) currentEnabledTransitions);
while (true){
ptr--;
State currentState = stStack.pop();
currentEnabledTransitions = tranStack.pop();
for (Transition firedTran : currentEnabledTransitions) {
State newState = constrFire(firedTran,currentState);
State nextState = addState(newState);
newStateFlag = false;
if(nextState == newState){
addFrontierState(nextState);
newStateFlag = true;
}
// StateTran stTran = new StateTran(currentState, firedTran, state);
if(nextState != currentState){
// this.addStateTran(currentState, nextState, firedTran);
this.addStateTran(currentState, firedTran, nextState);
newTransitions++;
// TODO: (original) check that a variable was changed before creating a constraint
if(!firedTran.isLocal()){
for(LhpnFile lpn : firedTran.getDstLpnList()){
// TODO: (temp) Hack here.
Constraint c = null; //new Constraint(currentState, nextState, firedTran, lpn);
// TODO: (temp) Ignore constraint.
//lpn.getStateGraph().addConstraint(c);
}
}
}
if(!newStateFlag) continue;
LpnTranList nextEnabledTransitions = getEnabled(nextState);
if (nextEnabledTransitions.isEmpty()) continue;
// currentEnabledTransitions = getEnabled(nexState);
// Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions);
// if(disabledTran != null) {
// System.out.println("Verification failed: " +disabledTran.getFullLabel() + " is disabled by " +
// firedTran.getFullLabel());
//
// currentState.setFailure();
// return -1;
// }
stStack.push(nextState);
tranStack.push(nextEnabledTransitions);
ptr++;
}
if (ptr == 0) {
break;
}
}
return newTransitions;
}
/**
* Finds reachable states from the given state.
* Also generates new constraints from the state transitions.
* Synchronized version of constrFindSG(). Method is not synchronized, but uses synchronized methods
* @param baseState State to start from
* @return Number of new transitions.
*/
public int synchronizedConstrFindSG(final State baseState){
boolean newStateFlag = false;
int ptr = 1;
int newTransitions = 0;
Stack<State> stStack = new Stack<State>();
Stack<LpnTranList> tranStack = new Stack<LpnTranList>();
LpnTranList currentEnabledTransitions = getEnabled(baseState);
stStack.push(baseState);
tranStack.push((LpnTranList) currentEnabledTransitions);
while (true){
ptr--;
State currentState = stStack.pop();
currentEnabledTransitions = tranStack.pop();
for (Transition firedTran : currentEnabledTransitions) {
State st = constrFire(firedTran,currentState);
State nextState = addState(st);
newStateFlag = false;
if(nextState == st){
newStateFlag = true;
addFrontierState(nextState);
}
if(nextState != currentState){
newTransitions++;
if(!firedTran.isLocal()){
// TODO: (original) check that a variable was changed before creating a constraint
for(LhpnFile lpn : firedTran.getDstLpnList()){
// TODO: (temp) Hack here.
Constraint c = null; //new Constraint(currentState, nextState, firedTran, lpn);
// TODO: (temp) Ignore constraints.
//lpn.getStateGraph().synchronizedAddConstraint(c);
}
}
}
if(!newStateFlag)
continue;
LpnTranList nextEnabledTransitions = getEnabled(nextState);
if (nextEnabledTransitions == null || nextEnabledTransitions.isEmpty()) {
continue;
}
// currentEnabledTransitions = getEnabled(nexState);
// Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions);
// if(disabledTran != null) {
// prDbg(10, "Verification failed: " +disabledTran.getFullLabel() + " is disabled by " +
// firedTran.getFullLabel());
//
// currentState.setFailure();
// return -1;
// }
stStack.push(nextState);
tranStack.push(nextEnabledTransitions);
ptr++;
}
if (ptr == 0) {
break;
}
}
return newTransitions;
}
public List<State> getFrontierStateSet(){
return this.frontierStateSet;
}
public List<State> getStateSet(){
return this.stateSet;
}
public void addFrontierState(State st){
this.entryStateSet.add(st);
}
public List<Constraint> getOldConstraintSet(){
return this.oldConstraintSet;
}
/**
* Adds constraint to the constraintSet.
* @param c - Constraint to be added.
* @return True if added, otherwise false.
*/
public boolean addConstraint(Constraint c){
if(this.constraintSet.add(c)){
this.frontierConstraintSet.add(c);
return true;
}
return false;
}
/**
* Adds constraint to the constraintSet. Synchronized version of addConstraint().
* @param c - Constraint to be added.
* @return True if added, otherwise false.
*/
public synchronized boolean synchronizedAddConstraint(Constraint c){
if(this.constraintSet.add(c)){
this.frontierConstraintSet.add(c);
return true;
}
return false;
}
public List<Constraint> getNewConstraintSet(){
return this.newConstraintSet;
}
public void genConstraints(){
oldConstraintSet.addAll(newConstraintSet);
newConstraintSet.clear();
newConstraintSet.addAll(frontierConstraintSet);
frontierConstraintSet.clear();
}
public void genFrontier(){
this.stateSet.addAll(this.frontierStateSet);
this.frontierStateSet.clear();
this.frontierStateSet.addAll(this.entryStateSet);
this.entryStateSet.clear();
}
public void setInitialState(State init){
this.init = init;
}
public State getInitialState(){
return this.init;
}
public void draw(){
String dotFile = Options.getDotPath();
if(!dotFile.endsWith("/") && !dotFile.endsWith("\\")){
String dirSlash = "/";
if(Main.isWindows) dirSlash = "\\";
dotFile = dotFile += dirSlash;
}
dotFile += this.lpn.getLabel() + ".dot";
PrintStream graph = null;
try {
graph = new PrintStream(new FileOutputStream(dotFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
graph.println("digraph SG{");
//graph.println(" fixedsize=true");
int size = this.lpn.getAllOutputs().size() + this.lpn.getAllInputs().size() + this.lpn.getAllInternals().size();
String[] variables = new String[size];
DualHashMap<String, Integer> varIndexMap = this.lpn.getVarIndexMap();
int i;
for(i = 0; i < size; i++){
variables[i] = varIndexMap.getKey(i);
}
//for(State state : this.reachableSet.keySet()){
for(int stateIdx = 0; stateIdx < this.reachSize(); stateIdx++) {
State state = this.getState(stateIdx);
String dotLabel = state.getIndex() + ": ";
int[] vector = state.getVector();
for(i = 0; i < size; i++){
dotLabel += variables[i];
if(vector[i] == 0) dotLabel += "'";
if(i < size-1) dotLabel += " ";
}
int[] mark = state.getMarking();
dotLabel += "\\n";
for(i = 0; i < mark.length; i++){
if(i == 0) dotLabel += "[";
dotLabel += mark[i];
if(i < mark.length - 1)
dotLabel += ", ";
else
dotLabel += "]";
}
String attributes = "";
if(state == this.init) attributes += " peripheries=2";
if(state.failure()) attributes += " style=filled fillcolor=\"red\"";
graph.println(" " + state.getIndex() + "[shape=ellipse width=.3 height=.3 " +
"label=\"" + dotLabel + "\"" + attributes + "]");
for(Entry<Transition, State> stateTran : this.nextStateMap.get(state).entrySet()){
State tailState = state;
State headState = stateTran.getValue();
Transition lpnTran = stateTran.getKey();
String edgeLabel = lpnTran.getName() + ": ";
int[] headVector = headState.getVector();
int[] tailVector = tailState.getVector();
for(i = 0; i < size; i++){
if(headVector[i] != tailVector[i]){
if(headVector[i] == 0){
edgeLabel += variables[i];
edgeLabel += "-";
}
else{
edgeLabel += variables[i];
edgeLabel += "+";
}
}
}
graph.println(" " + tailState.getIndex() + " -> " + headState.getIndex() + "[label=\"" + edgeLabel + "\"]");
}
}
graph.println("}");
graph.close();
}
/**
* Return the enabled transitions in the state with index 'stateIdx'.
* @param stateIdx
* @return
*/
public LpnTranList getEnabled(int stateIdx) {
State curState = this.getState(stateIdx);
return this.getEnabled(curState);
}
/**
* Return the set of all LPN transitions that are enabled in 'state'.
* @param curState
* @return
*/
public LpnTranList getEnabled(State curState) {
if (curState == null) {
throw new NullPointerException();
}
if(enabledSetTbl.containsKey(curState) == true){
return (LpnTranList)enabledSetTbl.get(curState).clone();
}
LpnTranList curEnabled = new LpnTranList();
for (Transition tran : this.lpn.getAllTransitions()) {
if (isEnabled(tran,curState)) {
if(tran.isLocal()==true)
curEnabled.addLast(tran);
else
curEnabled.addFirst(tran);
}
}
this.enabledSetTbl.put(curState, curEnabled);
return curEnabled;
}
/**
* Return the set of all LPN transitions that are enabled in 'state'.
* @param curState
* @return
*/
public LpnTranList getEnabled(State curState, boolean init) {
if (curState == null) {
throw new NullPointerException();
}
if(enabledSetTbl.containsKey(curState) == true){
if (Options.getDebugMode()) {
// System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN" + curState.getLpn().getLabel() + ": S" + curState.getIndex() + "~~~~~~~~");
// printTransitionSet((LpnTranList)enabledSetTbl.get(curState), "enabled trans at this state ");
}
return (LpnTranList)enabledSetTbl.get(curState).clone();
}
LpnTranList curEnabled = new LpnTranList();
//System.out.println("----Enabled transitions----");
if (init) {
for (Transition tran : this.lpn.getAllTransitions()) {
if (isEnabled(tran,curState)) {
if (Options.getDebugMode()) {
// System.out.println("Transition " + tran.getLpn().getLabel() + "(" + tran.getName() + ") is enabled");
}
if(tran.isLocal()==true)
curEnabled.addLast(tran);
else
curEnabled.addFirst(tran);
}
}
}
else {
for (int i=0; i < this.lpn.getAllTransitions().length; i++) {
Transition tran = this.lpn.getAllTransitions()[i];
if (curState.getTranVector()[i])
if(tran.isLocal()==true)
curEnabled.addLast(tran);
else
curEnabled.addFirst(tran);
}
}
this.enabledSetTbl.put(curState, curEnabled);
if (Options.getDebugMode()) {
// System.out.println("~~~~~~~~ State S" + curState.getIndex() + " does not exist in enabledSetTbl for LPN " + curState.getLpn().getLabel() + ". Add to enabledSetTbl.");
// printEnabledSetTbl();
}
return curEnabled;
}
private void printEnabledSetTbl() {
System.out.println("******* enabledSetTbl**********");
for (State s : enabledSetTbl.keySet()) {
System.out.print("S" + s.getIndex() + " -> ");
printTransitionSet(enabledSetTbl.get(s), "");
}
}
public boolean isEnabled(Transition tran, State curState) {
int[] varValuesVector = curState.getVector();
String tranName = tran.getName();
int tranIndex = tran.getIndex();
if (Options.getDebugMode()) {
// System.out.println("Checking " + tran);
}
if (this.lpn.getEnablingTree(tranName) != null
&& this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0
&& !(tran.isPersistent() && curState.getTranVector()[tranIndex])) {
if (Options.getDebugMode()) {
// System.out.println(tran.getName() + " " + "Enabling condition is false");
}
return false;
}
if (this.lpn.getTransitionRateTree(tranName) != null
&& this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0) {
if (Options.getDebugMode()) {
// System.out.println("Rate is zero");
}
return false;
}
if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) {
int[] curMarking = curState.getMarking();
for (int place : this.lpn.getPresetIndex(tranName)) {
if (curMarking[place]==0) {
if (Options.getDebugMode()) {
// System.out.println(tran.getName() + " " + "Missing a preset token");
}
return false;
}
}
// if a transition is enabled and it is not recorded in the enabled transition vector
curState.getTranVector()[tranIndex] = true;
}
return true;
}
public int reachSize() {
if(this.stateCache == null){
return this.stateSet.size();
}
return this.stateCache.size();
}
public boolean stateOnStack(State curState, HashSet<PrjState> stateStack) {
boolean isStateOnStack = false;
for (PrjState prjState : stateStack) {
State[] stateArray = prjState.toStateArray();
for (State s : stateArray) {
if (s == curState) {
isStateOnStack = true;
break;
}
}
if (isStateOnStack)
break;
}
return isStateOnStack;
}
/*
* Add the module state mState into the local cache, and also add its local portion into
* the local portion cache, and build the mapping between the mState and lState for fast lookup
* in the future.
*/
public State addState(State mState) {
State cachedState = this.stateCache.add(mState);
State lState = this.state2LocalMap.get(cachedState);
if(lState == null) {
lState = cachedState.getLocalState();
lState = this.localStateCache.add(lState);
this.state2LocalMap.put(cachedState, lState);
}
return cachedState;
}
/*
* Get the local portion of mState from the cache..
*/
public State getLocalState(State mState) {
return this.state2LocalMap.get(mState);
}
public State getState(int stateIdx) {
return this.stateCache.get(stateIdx);
}
public void addStateTran(State curSt, Transition firedTran, State nextSt) {
HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt);
if(nextMap == null) {
nextMap = new HashMap<Transition,State>();
nextMap.put(firedTran, nextSt);
this.nextStateMap.put(curSt, nextMap);
}
else
nextMap.put(firedTran, nextSt);
}
public State getNextState(State curSt, Transition firedTran) {
HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt);
if(nextMap == null)
return null;
return nextMap.get(firedTran);
}
private static Set<Entry<Transition, State>> emptySet = new HashSet<Entry<Transition, State>>(0);
public Set<Entry<Transition, State>> getOutgoingTrans(State currentState){
HashMap<Transition, State> tranMap = this.nextStateMap.get(currentState);
if(tranMap == null){
return emptySet;
}
return tranMap.entrySet();
}
public int numConstraints(){
if(this.constraintSet == null){
return this.oldConstraintSet.size();
}
return this.constraintSet.size();
}
public void clear(){
this.constraintSet.clear();
this.frontierConstraintSet.clear();
this.newConstraintSet.clear();
this.frontierStateSet.clear();
this.entryStateSet.clear();
this.constraintSet = null;
this.frontierConstraintSet = null;
this.newConstraintSet = null;
this.frontierStateSet = null;
this.entryStateSet = null;
this.stateCache = null;
}
public State getInitState() {
// create initial vector
int size = this.lpn.getVarIndexMap().size();
int[] initialVector = new int[size];
for(int i = 0; i < size; i++) {
String var = this.lpn.getVarIndexMap().getKey(i);
int val = this.lpn.getInitVector(var);// this.initVector.get(var);
initialVector[i] = val;
}
return new State(this.lpn, this.lpn.getInitialMarkingsArray(), initialVector, this.lpn.getInitEnabledTranArray(initialVector));
}
/**
* Fire a transition on a state array, find new local states, and return the new state array formed by the new local states.
* @param firedTran
* @param curLpnArray
* @param curStateArray
* @param curLpnIndex
* @return
*/
public State[] fire(final StateGraph[] curSgArray, final int[] curStateIdxArray, Transition firedTran) {
State[] stateArray = new State[curSgArray.length];
for(int i = 0; i < curSgArray.length; i++)
stateArray[i] = curSgArray[i].getState(curStateIdxArray[i]);
return this.fire(curSgArray, stateArray, firedTran);
}
// This method is called by search_dfs(StateGraph[], State[]).
public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran){
// HashMap<LPNContinuousPair, IntervalPair> continuousValues, Zone z) {
// public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran,
// ArrayList<HashMap<LPNContinuousPair, IntervalPair>> newAssignValues, Zone z) {
// public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran,
// ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues, Zone z) {
int thisLpnIndex = this.getLpn().getLpnIndex();
State[] nextStateArray = curStateArray.clone();
State curState = curStateArray[thisLpnIndex];
// State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran, continuousValues, z);
// State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran, newAssignValues, z);
State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran);
//int[] nextVector = nextState.getVector();
//int[] curVector = curState.getVector();
// TODO: (future) assertions in our LPN?
/*
for(Expression e : assertions){
if(e.evaluate(nextVector) == 0){
System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label);
System.exit(1);
}
}
*/
nextStateArray[thisLpnIndex] = nextState;
if(firedTran.isLocal()==true) {
// nextStateArray[thisLpnIndex] = curSgArray[thisLpnIndex].addState(nextState);
return nextStateArray;
}
HashMap<String, Integer> vvSet = new HashMap<String, Integer>();
vvSet = this.lpn.getAllVarsWithValuesAsInt(nextState.getVector());
//
// for (String key : this.lpn.getAllVarsWithValuesAsString(curState.getVector()).keySet()) {
// if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector()));
// vvSet.put(key, newValue);
// }
// // TODO: (temp) type cast continuous variable to int.
// if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector()));
// vvSet.put(key, newValue);
// }
// if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector()));
// vvSet.put(key, newValue);
// }
// }
/*
for (VarExpr s : this.getAssignments()) {
int newValue = nextVector[s.getVar().getIndex(curVector)];
vvSet.put(s.getVar().getName(), newValue);
}
*/
// Update other local states with the new values generated for the shared variables.
//nextStateArray[this.lpn.getIndex()] = nextState;
// if (!firedTran.getDstLpnList().contains(this.lpn))
// firedTran.getDstLpnList().add(this.lpn);
for(LhpnFile curLPN : firedTran.getDstLpnList()) {
int curIdx = curLPN.getLpnIndex();
// System.out.println("Checking " + curLPN.getLabel() + " " + curIdx);
State newState = curSgArray[curIdx].getNextState(curStateArray[curIdx], firedTran);
if(newState != null) {
nextStateArray[curIdx] = newState;
}
else {
State newOther = curStateArray[curIdx].update(curSgArray[curIdx], vvSet, curSgArray[curIdx].getLpn().getVarIndexMap());
if (newOther == null)
nextStateArray[curIdx] = curStateArray[curIdx];
else {
State cachedOther = curSgArray[curIdx].addState(newOther);
//nextStateArray[curIdx] = newOther;
nextStateArray[curIdx] = cachedOther;
// System.out.println("ADDING TO " + curIdx + ":\n" + curStateArray[curIdx].getIndex() + ":\n" +
// curStateArray[curIdx].print() + firedTran.getName() + "\n" +
// cachedOther.getIndex() + ":\n" + cachedOther.print());
curSgArray[curIdx].addStateTran(curStateArray[curIdx], firedTran, cachedOther);
}
}
}
return nextStateArray;
}
// TODO: (original) add transition that fires to parameters
public State fire(final StateGraph thisSg, final State curState, Transition firedTran){
// HashMap<LPNContinuousPair, IntervalPair> continuousValues, Zone z) {
// public State fire(final StateGraph thisSg, final State curState, Transition firedTran,
// ArrayList<HashMap<LPNContinuousPair, IntervalPair>> newAssignValues, Zone z) {
// public State fire(final StateGraph thisSg, final State curState, Transition firedTran,
// ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues, Zone z) {
// Search for and return cached next state first.
// if(this.nextStateMap.containsKey(curState) == true)
// return (State)this.nextStateMap.get(curState);
State nextState = thisSg.getNextState(curState, firedTran);
if(nextState != null)
return nextState;
// If no cached next state exists, do regular firing.
// Marking update
int[] curOldMarking = curState.getMarking();
int[] curNewMarking = null;
if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0)
curNewMarking = curOldMarking;
else {
curNewMarking = new int[curOldMarking.length];
curNewMarking = curOldMarking.clone();
for (int prep : this.lpn.getPresetIndex(firedTran.getName())) {
curNewMarking[prep]=0;
}
for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) {
curNewMarking[postp]=1;
}
}
// State vector update
int[] newVectorArray = curState.getVector().clone();
int[] curVector = curState.getVector();
HashMap<String, String> currentValuesAsString = this.lpn.getAllVarsWithValuesAsString(curVector);
for (String key : currentValuesAsString.keySet()) {
if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(currentValuesAsString);
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(currentValuesAsString);
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
}
// // Update rates
// final int OLD_ZERO = 0; // Case 0 in description.
//// final int NEW_NON_ZERO = 1; // Case 1 in description.
//// final int NEW_ZERO = 2; // Case 2 in description.
//// final int OLD_NON_ZERO = 3; // Case 3 in description.
//// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
//// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
//// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
//// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
//
// final int NEW_NON_ZERO = 1; // Case 1 in description.
// final int NEW_ZERO = 2; // Case 2 in description.
// final int OLD_NON_ZERO = 3; // Cade 3 in description.
// if(Options.getTimingAnalysisFlag()){
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// }
//
// for(String key : this.lpn.getContVars()){
//
// // Get the pairing.
// int lpnIndex = this.lpn.getLpnIndex();
// int contVarIndex = this.lpn.getContVarIndex(key);
//
// // Package up the indecies.
// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
//
// //Integer newRate = null;
// IntervalPair newRate = null;
// IntervalPair newValue= null;
//
// // Check if there is a new rate assignment.
// if(this.lpn.getRateAssignTree(firedTran.getName(), key) != null){
// // Get the new value.
// //IntervalPair newIntervalRate = this.lpn.getRateAssignTree(firedTran.getName(), key)
// //.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null);
// newRate = this.lpn.getRateAssignTree(firedTran.getName(), key)
// .evaluateExprBound(currentValuesAsString, z, null);
//
//// // Get the pairing.
//// int lpnIndex = this.lpn.getLpnIndex();
//// int contVarIndex = this.lpn.getContVarIndex(key);
////
//// // Package up the indecies.
//// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
//
// // Keep the current rate.
// //newRate = newIntervalRate.get_LowerBound();
//
// //contVar.setCurrentRate(newIntervalRate.get_LowerBound());
// contVar.setCurrentRate(newRate.get_LowerBound());
//
//// continuousValues.put(contVar, new IntervalPair(z.getDbmEntryByPair(contVar, LPNTransitionPair.ZERO_TIMER_PAIR),
//// z.getDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, contVar)));
//
//// // Check if the new assignment gives rate zero.
//// boolean newRateZero = newRate == 0;
//// // Check if the variable was already rate zero.
//// boolean oldRateZero = z.getCurrentRate(contVar) == 0;
////
//// // Put the new value in the appropriate set.
//// if(oldRateZero){
//// if(newRateZero){
//// // Old rate is zero and the new rate is zero.
//// newAssignValues.get(OLD_ZERO).put(contVar, newValue);
//// }
//// else{
//// // Old rate is zero and the new rate is non-zero.
//// newAssignValues.get(NEW_NON_ZERO).put(contVar, newValue);
//// }
//// }
//// else{
//// if(newRateZero){
//// // Old rate is non-zero and the new rate is zero.
//// newAssignValues.get(NEW_ZERO).put(contVar, newValue);
//// }
//// else{
//// // Old rate is non-zero and the new rate is non-zero.
//// newAssignValues.get(OLD_NON_ZERO).put(contVar, newValue);
//// }
//// }
// }
// //}
//
// // Update continuous variables.
// //for(String key : this.lpn.getContVars()){
// // Get the new assignments on the continuous variables and update inequalities.
// if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
//// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
//// newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
//
// // Get the new value.
// newValue = this.lpn.getContAssignTree(firedTran.getName(), key)
// //.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null);
// .evaluateExprBound(currentValuesAsString, z, null);
//
//// // Get the pairing.
//// int lpnIndex = this.lpn.getLpnIndex();
//// int contVarIndex = this.lpn.getContVarIndex(key);
////
//// // Package up the indecies.
//// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
//
// if(newRate == null){
// // Keep the current rate.
// contVar.setCurrentRate(z.getCurrentRate(contVar));
// }
//
//
//// continuousValues.put(contVar, newValue);
//
// // Get each inequality that involves the continuous variable.
// ArrayList<InequalityVariable> inequalities = this.lpn.getContVar(contVarIndex).getInequalities();
//
// // Update the inequalities.
// for(InequalityVariable ineq : inequalities){
// int ineqIndex = this.lpn.getVarIndexMap().get(ineq.getName());
//
//
// HashMap<LPNContAndRate, IntervalPair> continuousValues = new HashMap<LPNContAndRate, IntervalPair>();
// continuousValues.putAll(newAssignValues.get(OLD_ZERO));
// continuousValues.putAll(newAssignValues.get(NEW_NON_ZERO));
// continuousValues.putAll(newAssignValues.get(NEW_ZERO));
// continuousValues.putAll(newAssignValues.get(OLD_NON_ZERO));
//
//
// newVectorArray[ineqIndex] = ineq.evaluate(newVectorArray, z, continuousValues);
// }
// }
//
//
// // If the value did not get assigned, put in the old value.
// if(newValue == null){
// newValue = z.getContinuousBounds(contVar);
// }
//
// // Check if the new assignment gives rate zero.
// //boolean newRateZero = newRate == 0;
// boolean newRateZero = newRate.singleValue() ? newRate.get_LowerBound() == 0 : false;
// // Check if the variable was already rate zero.
// boolean oldRateZero = z.getCurrentRate(contVar) == 0;
//
// // Put the new value in the appropriate set.
// if(oldRateZero){
// if(newRateZero){
// // Old rate is zero and the new rate is zero.
// newAssignValues.get(OLD_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
// }
// else{
// // Old rate is zero and the new rate is non-zero.
// newAssignValues.get(NEW_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
// }
// }
// else{
// if(newRateZero){
// // Old rate is non-zero and the new rate is zero.
// newAssignValues.get(NEW_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
// }
// else{
// // Old rate is non-zero and the new rate is non-zero.
// newAssignValues.get(OLD_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
// }
// }
//
// }
/*
for (VarExpr s : firedTran.getAssignments()) {
int newValue = (int) s.getExpr().evaluate(curVector);
newVectorArray[s.getVar().getIndex(curVector)] = newValue;
}
*/
// Enabled transition vector update
boolean[] newEnabledTranVector = updateEnabledTranVector(curState.getTranVector(), curNewMarking, newVectorArray, firedTran);
State newState = thisSg.addState(new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranVector));
// TODO: (future) assertions in our LPN?
/*
int[] newVector = newState.getVector();
for(Expression e : assertions){
if(e.evaluate(newVector) == 0){
System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label);
System.exit(1);
}
}
*/
thisSg.addStateTran(curState, firedTran, newState);
return newState;
}
public boolean[] updateEnabledTranVector(boolean[] enabledTranBeforeFiring,
int[] newMarking, int[] newVectorArray, Transition firedTran) {
boolean[] enabledTranAfterFiring = enabledTranBeforeFiring.clone();
// Disable fired transition
if (firedTran != null) {
enabledTranAfterFiring[firedTran.getIndex()] = false;
for (Integer curConflictingTranIndex : firedTran.getConflictSetTransIndices()) {
enabledTranAfterFiring[curConflictingTranIndex] = false;
}
}
// find newly enabled transition(s) based on the updated markings and variables
if (Options.getDebugMode()) {
// System.out.println("Find newly enabled transitions at updateEnabledTranVector.");
}
for (Transition tran : this.lpn.getAllTransitions()) {
boolean needToUpdate = true;
String tranName = tran.getName();
int tranIndex = tran.getIndex();
if (Options.getDebugMode()) {
// System.out.println("Checking " + tranName);
}
if (this.lpn.getEnablingTree(tranName) != null
&& this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode()) {
// System.out.println(tran.getName() + " " + "Enabling condition is false");
}
if (enabledTranAfterFiring[tranIndex] && !tran.isPersistent())
enabledTranAfterFiring[tranIndex] = false;
continue;
}
if (this.lpn.getTransitionRateTree(tranName) != null
&& this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode()) {
// System.out.println("Rate is zero");
}
continue;
}
if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) {
for (int place : this.lpn.getPresetIndex(tranName)) {
if (newMarking[place]==0) {
if (Options.getDebugMode()) {
// System.out.println(tran.getName() + " " + "Missing a preset token");
}
needToUpdate = false;
break;
}
}
}
if (needToUpdate) {
// if a transition is enabled and it is not recorded in the enabled transition vector
enabledTranAfterFiring[tranIndex] = true;
if (Options.getDebugMode()) {
// System.out.println(tran.getName() + " is Enabled.");
}
}
}
return enabledTranAfterFiring;
}
/**
* Updates the transition vector.
* @param enabledTranBeforeFiring
* The enabling before the transition firing.
* @param newMarking
* The new marking to check for transitions with.
* @param newVectorArray
* The new values of the boolean variables.
* @param firedTran
* The transition that fire.
* @param newlyEnabled
* A list to capture the newly enabled transitions.
* @return
* The newly enabled transitions.
*/
public boolean[] updateEnabledTranVector(boolean[] enabledTranBeforeFiring,
int[] newMarking, int[] newVectorArray, Transition firedTran, HashSet<LPNTransitionPair> newlyEnabled) {
boolean[] enabledTranAfterFiring = enabledTranBeforeFiring.clone();
// Disable fired transition
if (firedTran != null) {
enabledTranAfterFiring[firedTran.getIndex()] = false;
for (Integer curConflictingTranIndex : firedTran.getConflictSetTransIndices()) {
enabledTranAfterFiring[curConflictingTranIndex] = false;
}
}
// find newly enabled transition(s) based on the updated markings and variables
if (Options.getDebugMode())
System.out.println("Finding newly enabled transitions at updateEnabledTranVector.");
for (Transition tran : this.lpn.getAllTransitions()) {
boolean needToUpdate = true;
String tranName = tran.getName();
int tranIndex = tran.getIndex();
if (Options.getDebugMode())
System.out.println("Checking " + tranName);
if (this.lpn.getEnablingTree(tranName) != null
&& this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode())
System.out.println(tran.getName() + " " + "Enabling condition is false");
if (enabledTranAfterFiring[tranIndex] && !tran.isPersistent())
enabledTranAfterFiring[tranIndex] = false;
continue;
}
if (this.lpn.getTransitionRateTree(tranName) != null
&& this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode())
System.out.println("Rate is zero");
continue;
}
if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) {
for (int place : this.lpn.getPresetIndex(tranName)) {
if (newMarking[place]==0) {
if (Options.getDebugMode())
System.out.println(tran.getName() + " " + "Missing a preset token");
needToUpdate = false;
break;
}
}
}
if (needToUpdate) {
// if a transition is enabled and it is not recorded in the enabled transition vector
enabledTranAfterFiring[tranIndex] = true;
if (Options.getDebugMode())
System.out.println(tran.getName() + " is Enabled.");
}
if(newlyEnabled != null && enabledTranAfterFiring[tranIndex] && !enabledTranBeforeFiring[tranIndex]){
newlyEnabled.add(new LPNTransitionPair(tran.getLpn().getLpnIndex(), tranIndex));
}
}
return enabledTranAfterFiring;
}
public State constrFire(Transition firedTran, final State curState) {
// Marking update
int[] curOldMarking = curState.getMarking();
int[] curNewMarking = null;
if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0){
curNewMarking = curOldMarking;
}
else {
curNewMarking = new int[curOldMarking.length - firedTran.getPreset().length + firedTran.getPostset().length];
int index = 0;
for (int i : curOldMarking) {
boolean existed = false;
for (int prep : this.lpn.getPresetIndex(firedTran.getName())) {
if (i == prep) {
existed = true;
break;
}
// TODO: (??) prep > i
else if(prep > i){
break;
}
}
if (existed == false) {
curNewMarking[index] = i;
index++;
}
}
for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) {
curNewMarking[index] = postp;
index++;
}
}
// State vector update
int[] oldVector = curState.getVector();
int size = oldVector.length;
int[] newVectorArray = new int[size];
System.arraycopy(oldVector, 0, newVectorArray, 0, size);
int[] curVector = curState.getVector();
for (String key : this.lpn.getAllVarsWithValuesAsString(curVector).keySet()) {
if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
// TODO: (temp) type cast continuous variable to int.
if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
}
// TODO: (check) Is the update is equivalent to the one below?
/*
for (VarExpr s : getAssignments()) {
int newValue = s.getExpr().evaluate(curVector);
newVectorArray[s.getVar().getIndex(curVector)] = newValue;
}
*/
// Enabled transition vector update
boolean[] newEnabledTranArray = curState.getTranVector();
newEnabledTranArray[firedTran.getIndex()] = false;
State newState = new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranArray);
// TODO: (future) assertions in our LPN?
/*
int[] newVector = newState.getVector();
for(Expression e : assertions){
if(e.evaluate(newVector) == 0){
System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label);
System.exit(1);
}
}
*/
return newState;
}
public void outputLocalStateGraph(String file) {
try {
int size = this.lpn.getVarIndexMap().size();
String varNames = "";
for(int i = 0; i < size; i++) {
varNames = varNames + ", " + this.lpn.getVarIndexMap().getKey(i);
}
varNames = varNames.replaceFirst(", ", "");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("digraph G {\n");
out.write("Inits [shape=plaintext, label=\"<" + varNames + ">\"]\n");
for (State curState : nextStateMap.keySet()) {
String markings = intArrayToString("markings", curState);
String vars = intArrayToString("vars", curState);
String enabledTrans = boolArrayToString("enabledTrans", curState);
String curStateName = "S" + curState.getIndex();
out.write(curStateName + "[shape=\"ellipse\",label=\"" + curStateName + "\\n<"+vars+">" + "\\n<"+enabledTrans+">" + "\\n<"+markings+">" + "\"]\n");
}
for (State curState : nextStateMap.keySet()) {
HashMap<Transition, State> stateTransitionPair = nextStateMap.get(curState);
for (Transition curTran : stateTransitionPair.keySet()) {
String curStateName = "S" + curState.getIndex();
String nextStateName = "S" + stateTransitionPair.get(curTran).getIndex();
String curTranName = curTran.getName();
if (curTran.isFail() && !curTran.isPersistent())
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=red]\n");
else if (!curTran.isFail() && curTran.isPersistent())
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=blue]\n");
else if (curTran.isFail() && curTran.isPersistent())
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=purple]\n");
else
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\"]\n");
}
}
out.write("}");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing local state graph as dot file.");
}
}
private String intArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("markings")) {
for (int i=0; i< curState.getMarking().length; i++) {
if (curState.getMarking()[i] == 1) {
arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ",";
}
// String tranName = curState.getLpn().getAllTransitions()[i].getName();
// if (curState.getTranVector()[i])
// System.out.println(tranName + " " + "Enabled");
// else
// System.out.println(tranName + " " + "Not Enabled");
}
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
else if (type.equals("vars")) {
for (int i=0; i< curState.getVector().length; i++) {
arrayStr = arrayStr + curState.getVector()[i] + ",";
}
if (arrayStr.contains(","))
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private String boolArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("enabledTrans")) {
for (int i=0; i< curState.getTranVector().length; i++) {
if (curState.getTranVector()[i]) {
arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getName() + ",";
}
}
if (arrayStr != "")
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private void printTransitionSet(LpnTranList transitionSet, String setName) {
if (!setName.isEmpty())
System.out.print(setName + " ");
if (transitionSet.isEmpty()) {
System.out.println("empty");
}
else {
for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) {
Transition tranInDisable = curTranIter.next();
System.out.print(tranInDisable.getName() + " ");
}
System.out.print("\n");
}
}
private static void printAmpleSet(LpnTranList transitionSet, String setName) {
if (!setName.isEmpty())
System.out.print(setName + " ");
if (transitionSet.isEmpty()) {
System.out.println("empty");
}
else {
for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) {
Transition tranInDisable = curTranIter.next();
System.out.print(tranInDisable.getName() + " ");
}
System.out.print("\n");
}
}
public HashMap<State,LpnTranList> copyEnabledSetTbl() {
HashMap<State,LpnTranList> copyEnabledSetTbl = new HashMap<State,LpnTranList>();
for (State s : enabledSetTbl.keySet()) {
LpnTranList tranList = enabledSetTbl.get(s).clone();
copyEnabledSetTbl.put(s.clone(), tranList);
}
return copyEnabledSetTbl;
}
public void setEnabledSetTbl(HashMap<State, LpnTranList> enabledSetTbl) {
this.enabledSetTbl = enabledSetTbl;
}
public HashMap<State, LpnTranList> getEnabledSetTbl() {
return this.enabledSetTbl;
}
public HashMap<State, HashMap<Transition, State>> getNextStateMap() {
return this.nextStateMap;
}
/**
* Fires a transition for the timed code.
* @param curSgArray
* The current information on the all local states.
* @param currentPrjState
* The current state.
* @param firedTran
* The transition to fire.
* @return
* The new states.
*/
public TimedPrjState fire(final StateGraph[] curSgArray,
final PrjState currentPrjState, Transition firedTran){
TimedPrjState currentTimedPrjState;
// Check that this is a timed state.
if(currentPrjState instanceof TimedPrjState){
currentTimedPrjState = (TimedPrjState) currentPrjState;
}
else{
throw new IllegalArgumentException("Attempted to use the " +
"fire(StateGraph[],PrjState,Transition)" +
"without a TimedPrjState stored in the PrjState " +
"variable. This method is meant for TimedPrjStates.");
}
// Extract relevant information from the current project state.
State[] curStateArray = currentTimedPrjState.toStateArray();
Zone[] currentZones = currentTimedPrjState.toZoneArray();
// Zone[] newZones = new Zone[curStateArray.length];
Zone[] newZones = new Zone[1];
//HashMap<LPNContinuousPair, IntervalPair> newContValues = new HashMap<LPNContinuousPair, IntervalPair>();
// ArrayList<HashMap<LPNContinuousPair, IntervalPair>> newAssignValues =
// new ArrayList<HashMap<LPNContinuousPair, IntervalPair>>();
/*
* This ArrayList contains four separate maps that store the
* rate and continuous variables assignments.
*/
// ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues =
// new ArrayList<HashMap<LPNContAndRate, IntervalPair>>();
// Get the new un-timed local states.
State[] newStates = fire(curSgArray, curStateArray, firedTran);
// currentTimedPrjState.get_zones()[0]);
// State[] newStates = fire(curSgArray, curStateArray, firedTran, newAssignValues,
// currentTimedPrjState.get_zones()[0]);
// Get the new values from rate assignments and continuous variable
// assignments. Also fix the enabled transition markings.
// Convert the values of the current marking to strings. This is needed for the evaluator.
// HashMap<String, String> valuesAsString =
// this.lpn.getAllVarsWithValuesAsString(curStateArray[this.lpn.getLpnIndex()].getVector());
// ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues =
// updateContinuousState(currentTimedPrjState.get_zones()[0], valuesAsString, curStateArray, firedTran);
ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues =
updateContinuousState(currentTimedPrjState.get_zones()[0], curStateArray, firedTran);
LpnTranList enabledTransitions = new LpnTranList();
for(int i=0; i<newStates.length; i++)
{
// enabledTransitions = getEnabled(newStates[i]);
// The stategraph has to be used to call getEnabled
// since it is being passed implicitly.
LpnTranList localEnabledTransitions = curSgArray[i].getEnabled(newStates[i]);
for(int j=0; j<localEnabledTransitions.size(); j++){
enabledTransitions.add(localEnabledTransitions.get(j));
}
// newZones[i] = currentZones[i].fire(firedTran,
// enabledTransitions, newStates);
// Update any continuous variable assignments.
// for (this.lpn.get) {
//
// if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
//// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
//// newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
//
// }
// for(String contVar : this.lpn.getContVars()){
// // Get the new range.
// InveralRange range =
// this.lpn.getContAssignTree(firedTran.getName(), contVar)
// .evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z)
// }
}
// newZones[0] = currentZones[0].fire(firedTran,
// enabledTransitions, newContValues, newStates);
newZones[0] = currentZones[0].fire(firedTran,
enabledTransitions, newAssignValues, newStates);
// ContinuousUtilities.updateInequalities(newZones[0],
// newStates[firedTran.getLpn().getLpnIndex()]);
// Warp the zone.
//newZones[0].dbmWarp(currentTimedPrjState.get_zones()[0]);
return new TimedPrjState(newStates, newZones);
}
/**
* Fires a list of events. This list can either contain a single transition
* or a set of inequalities.
* @param curSgArray
* The current information on the all local states.
* @param currentPrjState
* The current state.
* @param eventSets
* The set of events to fire.
* @return
* The new state.
*/
public TimedPrjState fire(final StateGraph[] curSgArray,
final PrjState currentPrjState, EventSet eventSet){
TimedPrjState currentTimedPrjState;
// Check that this is a timed state.
if(currentPrjState instanceof TimedPrjState){
currentTimedPrjState = (TimedPrjState) currentPrjState;
}
else{
throw new IllegalArgumentException("Attempted to use the " +
"fire(StateGraph[],PrjState,Transition)" +
"without a TimedPrjState stored in the PrjState " +
"variable. This method is meant for TimedPrjStates.");
}
// Determine if the list of events represents a list of inequalities.
if(eventSet.isInequalities()){
// Create a copy of the current states.
State[] oldStates = currentTimedPrjState.getStateArray();
State[] states = new State[oldStates.length];
for(int i=0; i<oldStates.length; i++){
states[i] = oldStates[i].clone();
}
// Get the variable index map for getting the indecies
// of the variables.
DualHashMap<String, Integer> map = lpn.getVarIndexMap();
for(Event e : eventSet){
// Extract inequality variable.
InequalityVariable iv = e.getInequalityVariable();
// Get the index to change the value.
int variableIndex = map.getValue(iv.getName());
// Flip the value of the inequality.
int[] vector = states[this.lpn.getLpnIndex()].getVector();
vector[variableIndex] =
vector[variableIndex] == 0 ? 1 : 0;
}
HashSet<LPNTransitionPair> newlyEnabled = new HashSet<LPNTransitionPair>();
// Update the enabled transitions according to inequalities that have changed.
for(int i=0; i<states.length; i++){
boolean[] newEnabledTranVector = updateEnabledTranVector(states[i].getTranVector(),
states[i].marking, states[i].vector, null, newlyEnabled);
State newState = curSgArray[i].addState(new State(this.lpn, states[i].marking, states[i].vector, newEnabledTranVector));
states[i] = newState;
}
// Get a new zone that has been restricted according to the inequalities firing.
Zone z = currentTimedPrjState.get_zones()[0].getContinuousRestrictedZone(eventSet);
// Add any new transitions.
z = z.addTransition(newlyEnabled, states);
// return new TimedPrjState(states, currentTimedPrjState.get_zones());
return new TimedPrjState(states, new Zone[]{z});
}
return fire(curSgArray, currentPrjState, eventSet.getTransition());
}
/**
* This method handles the extracting of the new rate and continuous variable assignments.
* @param z
* The previous zone.
* @param currentValuesAsString
* The current values of the Boolean varaibles converted to strings.
* @param states
* The current states.
* @param firedTran
* The fired transition.
* @return
* The continuous variable and rate assignments.
*/
// public ArrayList<HashMap<LPNContAndRate, IntervalPair>>
// updateContinuousState(Zone z, HashMap<String, String> currentValuesAsString,
// State[] states, Transition firedTran){
private ArrayList<HashMap<LPNContAndRate, IntervalPair>>
updateContinuousState(Zone z,
State[] states, Transition firedTran){
// Convert the current values of Boolean variables to strings for use in the
// Evaluator.
HashMap<String, String> currentValuesAsString =
this.lpn.getAllVarsWithValuesAsString(states[this.lpn.getLpnIndex()].getVector());
// Accumulates a set of all transitions that need their enabling conditions
// re-evaluated.
HashSet<Transition> needUpdating = new HashSet<Transition>();
// Accumulates the new assignment information.
ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues
= new ArrayList<HashMap<LPNContAndRate, IntervalPair>>();
// Update rates
final int OLD_ZERO = 0; // Case 0 in description.
// final int NEW_NON_ZERO = 1; // Case 1 in description.
// final int NEW_ZERO = 2; // Case 2 in description.
// final int OLD_NON_ZERO = 3; // Case 3 in description.
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
final int NEW_NON_ZERO = 1; // Case 1 in description.
final int NEW_ZERO = 2; // Case 2 in description.
final int OLD_NON_ZERO = 3; // Cade 3 in description.
if(Options.getTimingAnalysisFlag()){
newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
}
for(String key : this.lpn.getContVars()){
// Get the pairing.
int lpnIndex = this.lpn.getLpnIndex();
int contVarIndex = this.lpn.getContVarIndex(key);
// Package up the indecies.
LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
//Integer newRate = null;
IntervalPair newRate = null;
IntervalPair newValue= null;
// Check if there is a new rate assignment.
if(this.lpn.getRateAssignTree(firedTran.getName(), key) != null){
// Get the new value.
//IntervalPair newIntervalRate = this.lpn.getRateAssignTree(firedTran.getName(), key)
//.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null);
newRate = this.lpn.getRateAssignTree(firedTran.getName(), key)
.evaluateExprBound(currentValuesAsString, z, null);
// // Get the pairing.
// int lpnIndex = this.lpn.getLpnIndex();
// int contVarIndex = this.lpn.getContVarIndex(key);
//
// // Package up the indecies.
// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
// Keep the current rate.
//newRate = newIntervalRate.get_LowerBound();
//contVar.setCurrentRate(newIntervalRate.get_LowerBound());
contVar.setCurrentRate(newRate.get_LowerBound());
// continuousValues.put(contVar, new IntervalPair(z.getDbmEntryByPair(contVar, LPNTransitionPair.ZERO_TIMER_PAIR),
// z.getDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, contVar)));
// // Check if the new assignment gives rate zero.
// boolean newRateZero = newRate == 0;
// // Check if the variable was already rate zero.
// boolean oldRateZero = z.getCurrentRate(contVar) == 0;
//
// // Put the new value in the appropriate set.
// if(oldRateZero){
// if(newRateZero){
// // Old rate is zero and the new rate is zero.
// newAssignValues.get(OLD_ZERO).put(contVar, newValue);
// }
// else{
// // Old rate is zero and the new rate is non-zero.
// newAssignValues.get(NEW_NON_ZERO).put(contVar, newValue);
// }
// }
// else{
// if(newRateZero){
// // Old rate is non-zero and the new rate is zero.
// newAssignValues.get(NEW_ZERO).put(contVar, newValue);
// }
// else{
// // Old rate is non-zero and the new rate is non-zero.
// newAssignValues.get(OLD_NON_ZERO).put(contVar, newValue);
// }
// }
}
//}
// Update continuous variables.
//for(String key : this.lpn.getContVars()){
// Get the new assignments on the continuous variables and update inequalities.
if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
// newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
// Get the new value.
newValue = this.lpn.getContAssignTree(firedTran.getName(), key)
//.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null);
.evaluateExprBound(currentValuesAsString, z, null);
// // Get the pairing.
// int lpnIndex = this.lpn.getLpnIndex();
// int contVarIndex = this.lpn.getContVarIndex(key);
//
// // Package up the indecies.
// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
if(newRate == null){
// Keep the current rate.
contVar.setCurrentRate(z.getCurrentRate(contVar));
}
// continuousValues.put(contVar, newValue);
// Get each inequality that involves the continuous variable.
ArrayList<InequalityVariable> inequalities = this.lpn.getContVar(contVarIndex).getInequalities();
// Update the inequalities.
for(InequalityVariable ineq : inequalities){
int ineqIndex = this.lpn.getVarIndexMap().get(ineq.getName());
// Add the transitions that this inequality affects.
needUpdating.addAll(ineq.getTransitions());
HashMap<LPNContAndRate, IntervalPair> continuousValues = new HashMap<LPNContAndRate, IntervalPair>();
continuousValues.putAll(newAssignValues.get(OLD_ZERO));
continuousValues.putAll(newAssignValues.get(NEW_NON_ZERO));
continuousValues.putAll(newAssignValues.get(NEW_ZERO));
continuousValues.putAll(newAssignValues.get(OLD_NON_ZERO));
// Adjust state vector values for the inequality variables.
int[] newVectorArray = states[this.lpn.getLpnIndex()].getVector();
newVectorArray[ineqIndex] = ineq.evaluate(newVectorArray, z, continuousValues);
}
}
// If the value did not get assigned, put in the old value.
if(newValue == null){
newValue = z.getContinuousBounds(contVar);
}
// Check if the new assignment gives rate zero.
//boolean newRateZero = newRate == 0;
boolean newRateZero = newRate.singleValue() ? newRate.get_LowerBound() == 0 : false;
// Check if the variable was already rate zero.
boolean oldRateZero = z.getCurrentRate(contVar) == 0;
// Put the new value in the appropriate set.
if(oldRateZero){
if(newRateZero){
// Old rate is zero and the new rate is zero.
newAssignValues.get(OLD_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
}
else{
// Old rate is zero and the new rate is non-zero.
newAssignValues.get(NEW_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
}
}
else{
if(newRateZero){
// Old rate is non-zero and the new rate is zero.
newAssignValues.get(NEW_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
}
else{
// Old rate is non-zero and the new rate is non-zero.
newAssignValues.get(OLD_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
}
}
}
// Do the re-evaluating of the transitions.
for(Transition t : needUpdating){
// Get the index of the LPN and the index of the transition.
int lpnIndex = t.getLpn().getLpnIndex();
int tranIndex = t.getIndex();
// Get the enabled vector from the appropriate state.
int[] vector = states[lpnIndex].getVector();
// Set the (possibly) new value.
vector[tranIndex] = t.getEnablingTree().
evaluateExprBound(currentValuesAsString, z, null).get_LowerBound();
}
return newAssignValues;
}
}
| gui/src/verification/platu/stategraph/StateGraph.java | package verification.platu.stategraph;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import verification.platu.common.IndexObjMap;
import verification.platu.logicAnalysis.Constraint;
import verification.platu.lpn.DualHashMap;
import verification.platu.lpn.LpnTranList;
import verification.platu.main.Main;
import verification.platu.main.Options;
import verification.platu.project.PrjState;
import verification.timed_state_exploration.zoneProject.ContinuousUtilities;
import verification.timed_state_exploration.zoneProject.EventSet;
import verification.timed_state_exploration.zoneProject.InequalityVariable;
import verification.timed_state_exploration.zoneProject.Event;
import verification.timed_state_exploration.zoneProject.IntervalPair;
import verification.timed_state_exploration.zoneProject.LPNContAndRate;
import verification.timed_state_exploration.zoneProject.LPNContinuousPair;
import verification.timed_state_exploration.zoneProject.LPNTransitionPair;
import verification.timed_state_exploration.zoneProject.TimedPrjState;
import verification.timed_state_exploration.zoneProject.Zone;
public class StateGraph {
protected State init = null;
protected IndexObjMap<State> stateCache;
protected IndexObjMap<State> localStateCache;
protected HashMap<State, State> state2LocalMap;
protected HashMap<State, LpnTranList> enabledSetTbl;
protected HashMap<State, HashMap<Transition, State>> nextStateMap;
protected List<State> stateSet = new LinkedList<State>();
protected List<State> frontierStateSet = new LinkedList<State>();
protected List<State> entryStateSet = new LinkedList<State>();
protected List<Constraint> oldConstraintSet = new LinkedList<Constraint>();
protected List<Constraint> newConstraintSet = new LinkedList<Constraint>();
protected List<Constraint> frontierConstraintSet = new LinkedList<Constraint>();
protected Set<Constraint> constraintSet = new HashSet<Constraint>();
protected LhpnFile lpn;
public StateGraph(LhpnFile lpn) {
this.lpn = lpn;
this.stateCache = new IndexObjMap<State>();
this.localStateCache = new IndexObjMap<State>();
this.state2LocalMap = new HashMap<State, State>();
this.enabledSetTbl = new HashMap<State, LpnTranList>();
this.nextStateMap = new HashMap<State, HashMap<Transition, State>>();
}
public LhpnFile getLpn(){
return this.lpn;
}
public void printStates(){
System.out.println(String.format("%-8s %5s", this.lpn.getLabel(), "|States| = " + stateCache.size()));
}
public Set<Transition> getTranList(State currentState){
return this.nextStateMap.get(currentState).keySet();
}
/**
* Finds reachable states from the given state.
* Also generates new constraints from the state transitions.
* @param baseState - State to start from
* @return Number of new transitions.
*/
public int constrFindSG(final State baseState){
boolean newStateFlag = false;
int ptr = 1;
int newTransitions = 0;
Stack<State> stStack = new Stack<State>();
Stack<LpnTranList> tranStack = new Stack<LpnTranList>();
LpnTranList currentEnabledTransitions = getEnabled(baseState);
stStack.push(baseState);
tranStack.push((LpnTranList) currentEnabledTransitions);
while (true){
ptr--;
State currentState = stStack.pop();
currentEnabledTransitions = tranStack.pop();
for (Transition firedTran : currentEnabledTransitions) {
State newState = constrFire(firedTran,currentState);
State nextState = addState(newState);
newStateFlag = false;
if(nextState == newState){
addFrontierState(nextState);
newStateFlag = true;
}
// StateTran stTran = new StateTran(currentState, firedTran, state);
if(nextState != currentState){
// this.addStateTran(currentState, nextState, firedTran);
this.addStateTran(currentState, firedTran, nextState);
newTransitions++;
// TODO: (original) check that a variable was changed before creating a constraint
if(!firedTran.isLocal()){
for(LhpnFile lpn : firedTran.getDstLpnList()){
// TODO: (temp) Hack here.
Constraint c = null; //new Constraint(currentState, nextState, firedTran, lpn);
// TODO: (temp) Ignore constraint.
//lpn.getStateGraph().addConstraint(c);
}
}
}
if(!newStateFlag) continue;
LpnTranList nextEnabledTransitions = getEnabled(nextState);
if (nextEnabledTransitions.isEmpty()) continue;
// currentEnabledTransitions = getEnabled(nexState);
// Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions);
// if(disabledTran != null) {
// System.out.println("Verification failed: " +disabledTran.getFullLabel() + " is disabled by " +
// firedTran.getFullLabel());
//
// currentState.setFailure();
// return -1;
// }
stStack.push(nextState);
tranStack.push(nextEnabledTransitions);
ptr++;
}
if (ptr == 0) {
break;
}
}
return newTransitions;
}
/**
* Finds reachable states from the given state.
* Also generates new constraints from the state transitions.
* Synchronized version of constrFindSG(). Method is not synchronized, but uses synchronized methods
* @param baseState State to start from
* @return Number of new transitions.
*/
public int synchronizedConstrFindSG(final State baseState){
boolean newStateFlag = false;
int ptr = 1;
int newTransitions = 0;
Stack<State> stStack = new Stack<State>();
Stack<LpnTranList> tranStack = new Stack<LpnTranList>();
LpnTranList currentEnabledTransitions = getEnabled(baseState);
stStack.push(baseState);
tranStack.push((LpnTranList) currentEnabledTransitions);
while (true){
ptr--;
State currentState = stStack.pop();
currentEnabledTransitions = tranStack.pop();
for (Transition firedTran : currentEnabledTransitions) {
State st = constrFire(firedTran,currentState);
State nextState = addState(st);
newStateFlag = false;
if(nextState == st){
newStateFlag = true;
addFrontierState(nextState);
}
if(nextState != currentState){
newTransitions++;
if(!firedTran.isLocal()){
// TODO: (original) check that a variable was changed before creating a constraint
for(LhpnFile lpn : firedTran.getDstLpnList()){
// TODO: (temp) Hack here.
Constraint c = null; //new Constraint(currentState, nextState, firedTran, lpn);
// TODO: (temp) Ignore constraints.
//lpn.getStateGraph().synchronizedAddConstraint(c);
}
}
}
if(!newStateFlag)
continue;
LpnTranList nextEnabledTransitions = getEnabled(nextState);
if (nextEnabledTransitions == null || nextEnabledTransitions.isEmpty()) {
continue;
}
// currentEnabledTransitions = getEnabled(nexState);
// Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions);
// if(disabledTran != null) {
// prDbg(10, "Verification failed: " +disabledTran.getFullLabel() + " is disabled by " +
// firedTran.getFullLabel());
//
// currentState.setFailure();
// return -1;
// }
stStack.push(nextState);
tranStack.push(nextEnabledTransitions);
ptr++;
}
if (ptr == 0) {
break;
}
}
return newTransitions;
}
public List<State> getFrontierStateSet(){
return this.frontierStateSet;
}
public List<State> getStateSet(){
return this.stateSet;
}
public void addFrontierState(State st){
this.entryStateSet.add(st);
}
public List<Constraint> getOldConstraintSet(){
return this.oldConstraintSet;
}
/**
* Adds constraint to the constraintSet.
* @param c - Constraint to be added.
* @return True if added, otherwise false.
*/
public boolean addConstraint(Constraint c){
if(this.constraintSet.add(c)){
this.frontierConstraintSet.add(c);
return true;
}
return false;
}
/**
* Adds constraint to the constraintSet. Synchronized version of addConstraint().
* @param c - Constraint to be added.
* @return True if added, otherwise false.
*/
public synchronized boolean synchronizedAddConstraint(Constraint c){
if(this.constraintSet.add(c)){
this.frontierConstraintSet.add(c);
return true;
}
return false;
}
public List<Constraint> getNewConstraintSet(){
return this.newConstraintSet;
}
public void genConstraints(){
oldConstraintSet.addAll(newConstraintSet);
newConstraintSet.clear();
newConstraintSet.addAll(frontierConstraintSet);
frontierConstraintSet.clear();
}
public void genFrontier(){
this.stateSet.addAll(this.frontierStateSet);
this.frontierStateSet.clear();
this.frontierStateSet.addAll(this.entryStateSet);
this.entryStateSet.clear();
}
public void setInitialState(State init){
this.init = init;
}
public State getInitialState(){
return this.init;
}
public void draw(){
String dotFile = Options.getDotPath();
if(!dotFile.endsWith("/") && !dotFile.endsWith("\\")){
String dirSlash = "/";
if(Main.isWindows) dirSlash = "\\";
dotFile = dotFile += dirSlash;
}
dotFile += this.lpn.getLabel() + ".dot";
PrintStream graph = null;
try {
graph = new PrintStream(new FileOutputStream(dotFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
graph.println("digraph SG{");
//graph.println(" fixedsize=true");
int size = this.lpn.getAllOutputs().size() + this.lpn.getAllInputs().size() + this.lpn.getAllInternals().size();
String[] variables = new String[size];
DualHashMap<String, Integer> varIndexMap = this.lpn.getVarIndexMap();
int i;
for(i = 0; i < size; i++){
variables[i] = varIndexMap.getKey(i);
}
//for(State state : this.reachableSet.keySet()){
for(int stateIdx = 0; stateIdx < this.reachSize(); stateIdx++) {
State state = this.getState(stateIdx);
String dotLabel = state.getIndex() + ": ";
int[] vector = state.getVector();
for(i = 0; i < size; i++){
dotLabel += variables[i];
if(vector[i] == 0) dotLabel += "'";
if(i < size-1) dotLabel += " ";
}
int[] mark = state.getMarking();
dotLabel += "\\n";
for(i = 0; i < mark.length; i++){
if(i == 0) dotLabel += "[";
dotLabel += mark[i];
if(i < mark.length - 1)
dotLabel += ", ";
else
dotLabel += "]";
}
String attributes = "";
if(state == this.init) attributes += " peripheries=2";
if(state.failure()) attributes += " style=filled fillcolor=\"red\"";
graph.println(" " + state.getIndex() + "[shape=ellipse width=.3 height=.3 " +
"label=\"" + dotLabel + "\"" + attributes + "]");
for(Entry<Transition, State> stateTran : this.nextStateMap.get(state).entrySet()){
State tailState = state;
State headState = stateTran.getValue();
Transition lpnTran = stateTran.getKey();
String edgeLabel = lpnTran.getName() + ": ";
int[] headVector = headState.getVector();
int[] tailVector = tailState.getVector();
for(i = 0; i < size; i++){
if(headVector[i] != tailVector[i]){
if(headVector[i] == 0){
edgeLabel += variables[i];
edgeLabel += "-";
}
else{
edgeLabel += variables[i];
edgeLabel += "+";
}
}
}
graph.println(" " + tailState.getIndex() + " -> " + headState.getIndex() + "[label=\"" + edgeLabel + "\"]");
}
}
graph.println("}");
graph.close();
}
/**
* Return the enabled transitions in the state with index 'stateIdx'.
* @param stateIdx
* @return
*/
public LpnTranList getEnabled(int stateIdx) {
State curState = this.getState(stateIdx);
return this.getEnabled(curState);
}
/**
* Return the set of all LPN transitions that are enabled in 'state'.
* @param curState
* @return
*/
public LpnTranList getEnabled(State curState) {
if (curState == null) {
throw new NullPointerException();
}
if(enabledSetTbl.containsKey(curState) == true){
return (LpnTranList)enabledSetTbl.get(curState).clone();
}
LpnTranList curEnabled = new LpnTranList();
for (Transition tran : this.lpn.getAllTransitions()) {
if (isEnabled(tran,curState)) {
if(tran.isLocal()==true)
curEnabled.addLast(tran);
else
curEnabled.addFirst(tran);
}
}
this.enabledSetTbl.put(curState, curEnabled);
return curEnabled;
}
/**
* Return the set of all LPN transitions that are enabled in 'state'.
* @param curState
* @return
*/
public LpnTranList getEnabled(State curState, boolean init) {
if (curState == null) {
throw new NullPointerException();
}
if(enabledSetTbl.containsKey(curState) == true){
if (Options.getDebugMode()) {
// System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN" + curState.getLpn().getLabel() + ": S" + curState.getIndex() + "~~~~~~~~");
// printTransitionSet((LpnTranList)enabledSetTbl.get(curState), "enabled trans at this state ");
}
return (LpnTranList)enabledSetTbl.get(curState).clone();
}
LpnTranList curEnabled = new LpnTranList();
//System.out.println("----Enabled transitions----");
if (init) {
for (Transition tran : this.lpn.getAllTransitions()) {
if (isEnabled(tran,curState)) {
if (Options.getDebugMode()) {
// System.out.println("Transition " + tran.getLpn().getLabel() + "(" + tran.getName() + ") is enabled");
}
if(tran.isLocal()==true)
curEnabled.addLast(tran);
else
curEnabled.addFirst(tran);
}
}
}
else {
for (int i=0; i < this.lpn.getAllTransitions().length; i++) {
Transition tran = this.lpn.getAllTransitions()[i];
if (curState.getTranVector()[i])
if(tran.isLocal()==true)
curEnabled.addLast(tran);
else
curEnabled.addFirst(tran);
}
}
this.enabledSetTbl.put(curState, curEnabled);
if (Options.getDebugMode()) {
// System.out.println("~~~~~~~~ State S" + curState.getIndex() + " does not exist in enabledSetTbl for LPN " + curState.getLpn().getLabel() + ". Add to enabledSetTbl.");
// printEnabledSetTbl();
}
return curEnabled;
}
private void printEnabledSetTbl() {
System.out.println("******* enabledSetTbl**********");
for (State s : enabledSetTbl.keySet()) {
System.out.print("S" + s.getIndex() + " -> ");
printTransitionSet(enabledSetTbl.get(s), "");
}
}
public boolean isEnabled(Transition tran, State curState) {
int[] varValuesVector = curState.getVector();
String tranName = tran.getName();
int tranIndex = tran.getIndex();
if (Options.getDebugMode()) {
// System.out.println("Checking " + tran);
}
if (this.lpn.getEnablingTree(tranName) != null
&& this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0
&& !(tran.isPersistent() && curState.getTranVector()[tranIndex])) {
if (Options.getDebugMode()) {
// System.out.println(tran.getName() + " " + "Enabling condition is false");
}
return false;
}
if (this.lpn.getTransitionRateTree(tranName) != null
&& this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0) {
if (Options.getDebugMode()) {
// System.out.println("Rate is zero");
}
return false;
}
if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) {
int[] curMarking = curState.getMarking();
for (int place : this.lpn.getPresetIndex(tranName)) {
if (curMarking[place]==0) {
if (Options.getDebugMode()) {
// System.out.println(tran.getName() + " " + "Missing a preset token");
}
return false;
}
}
// if a transition is enabled and it is not recorded in the enabled transition vector
curState.getTranVector()[tranIndex] = true;
}
return true;
}
public int reachSize() {
if(this.stateCache == null){
return this.stateSet.size();
}
return this.stateCache.size();
}
public boolean stateOnStack(State curState, HashSet<PrjState> stateStack) {
boolean isStateOnStack = false;
for (PrjState prjState : stateStack) {
State[] stateArray = prjState.toStateArray();
for (State s : stateArray) {
if (s == curState) {
isStateOnStack = true;
break;
}
}
if (isStateOnStack)
break;
}
return isStateOnStack;
}
/*
* Add the module state mState into the local cache, and also add its local portion into
* the local portion cache, and build the mapping between the mState and lState for fast lookup
* in the future.
*/
public State addState(State mState) {
State cachedState = this.stateCache.add(mState);
State lState = this.state2LocalMap.get(cachedState);
if(lState == null) {
lState = cachedState.getLocalState();
lState = this.localStateCache.add(lState);
this.state2LocalMap.put(cachedState, lState);
}
return cachedState;
}
/*
* Get the local portion of mState from the cache..
*/
public State getLocalState(State mState) {
return this.state2LocalMap.get(mState);
}
public State getState(int stateIdx) {
return this.stateCache.get(stateIdx);
}
public void addStateTran(State curSt, Transition firedTran, State nextSt) {
HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt);
if(nextMap == null) {
nextMap = new HashMap<Transition,State>();
nextMap.put(firedTran, nextSt);
this.nextStateMap.put(curSt, nextMap);
}
else
nextMap.put(firedTran, nextSt);
}
public State getNextState(State curSt, Transition firedTran) {
HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt);
if(nextMap == null)
return null;
return nextMap.get(firedTran);
}
private static Set<Entry<Transition, State>> emptySet = new HashSet<Entry<Transition, State>>(0);
public Set<Entry<Transition, State>> getOutgoingTrans(State currentState){
HashMap<Transition, State> tranMap = this.nextStateMap.get(currentState);
if(tranMap == null){
return emptySet;
}
return tranMap.entrySet();
}
public int numConstraints(){
if(this.constraintSet == null){
return this.oldConstraintSet.size();
}
return this.constraintSet.size();
}
public void clear(){
this.constraintSet.clear();
this.frontierConstraintSet.clear();
this.newConstraintSet.clear();
this.frontierStateSet.clear();
this.entryStateSet.clear();
this.constraintSet = null;
this.frontierConstraintSet = null;
this.newConstraintSet = null;
this.frontierStateSet = null;
this.entryStateSet = null;
this.stateCache = null;
}
public State getInitState() {
// create initial vector
int size = this.lpn.getVarIndexMap().size();
int[] initialVector = new int[size];
for(int i = 0; i < size; i++) {
String var = this.lpn.getVarIndexMap().getKey(i);
int val = this.lpn.getInitVector(var);// this.initVector.get(var);
initialVector[i] = val;
}
return new State(this.lpn, this.lpn.getInitialMarkingsArray(), initialVector, this.lpn.getInitEnabledTranArray(initialVector));
}
/**
* Fire a transition on a state array, find new local states, and return the new state array formed by the new local states.
* @param firedTran
* @param curLpnArray
* @param curStateArray
* @param curLpnIndex
* @return
*/
public State[] fire(final StateGraph[] curSgArray, final int[] curStateIdxArray, Transition firedTran) {
State[] stateArray = new State[curSgArray.length];
for(int i = 0; i < curSgArray.length; i++)
stateArray[i] = curSgArray[i].getState(curStateIdxArray[i]);
return this.fire(curSgArray, stateArray, firedTran);
}
// This method is called by search_dfs(StateGraph[], State[]).
public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran){
// HashMap<LPNContinuousPair, IntervalPair> continuousValues, Zone z) {
// public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran,
// ArrayList<HashMap<LPNContinuousPair, IntervalPair>> newAssignValues, Zone z) {
// public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran,
// ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues, Zone z) {
int thisLpnIndex = this.getLpn().getLpnIndex();
State[] nextStateArray = curStateArray.clone();
State curState = curStateArray[thisLpnIndex];
// State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran, continuousValues, z);
// State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran, newAssignValues, z);
State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran);
//int[] nextVector = nextState.getVector();
//int[] curVector = curState.getVector();
// TODO: (future) assertions in our LPN?
/*
for(Expression e : assertions){
if(e.evaluate(nextVector) == 0){
System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label);
System.exit(1);
}
}
*/
nextStateArray[thisLpnIndex] = nextState;
if(firedTran.isLocal()==true) {
// nextStateArray[thisLpnIndex] = curSgArray[thisLpnIndex].addState(nextState);
return nextStateArray;
}
HashMap<String, Integer> vvSet = new HashMap<String, Integer>();
vvSet = this.lpn.getAllVarsWithValuesAsInt(nextState.getVector());
//
// for (String key : this.lpn.getAllVarsWithValuesAsString(curState.getVector()).keySet()) {
// if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector()));
// vvSet.put(key, newValue);
// }
// // TODO: (temp) type cast continuous variable to int.
// if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector()));
// vvSet.put(key, newValue);
// }
// if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector()));
// vvSet.put(key, newValue);
// }
// }
/*
for (VarExpr s : this.getAssignments()) {
int newValue = nextVector[s.getVar().getIndex(curVector)];
vvSet.put(s.getVar().getName(), newValue);
}
*/
// Update other local states with the new values generated for the shared variables.
//nextStateArray[this.lpn.getIndex()] = nextState;
// if (!firedTran.getDstLpnList().contains(this.lpn))
// firedTran.getDstLpnList().add(this.lpn);
for(LhpnFile curLPN : firedTran.getDstLpnList()) {
int curIdx = curLPN.getLpnIndex();
// System.out.println("Checking " + curLPN.getLabel() + " " + curIdx);
State newState = curSgArray[curIdx].getNextState(curStateArray[curIdx], firedTran);
if(newState != null) {
nextStateArray[curIdx] = newState;
}
else {
State newOther = curStateArray[curIdx].update(curSgArray[curIdx], vvSet, curSgArray[curIdx].getLpn().getVarIndexMap());
if (newOther == null)
nextStateArray[curIdx] = curStateArray[curIdx];
else {
State cachedOther = curSgArray[curIdx].addState(newOther);
//nextStateArray[curIdx] = newOther;
nextStateArray[curIdx] = cachedOther;
// System.out.println("ADDING TO " + curIdx + ":\n" + curStateArray[curIdx].getIndex() + ":\n" +
// curStateArray[curIdx].print() + firedTran.getName() + "\n" +
// cachedOther.getIndex() + ":\n" + cachedOther.print());
curSgArray[curIdx].addStateTran(curStateArray[curIdx], firedTran, cachedOther);
}
}
}
return nextStateArray;
}
// TODO: (original) add transition that fires to parameters
public State fire(final StateGraph thisSg, final State curState, Transition firedTran){
// HashMap<LPNContinuousPair, IntervalPair> continuousValues, Zone z) {
// public State fire(final StateGraph thisSg, final State curState, Transition firedTran,
// ArrayList<HashMap<LPNContinuousPair, IntervalPair>> newAssignValues, Zone z) {
// public State fire(final StateGraph thisSg, final State curState, Transition firedTran,
// ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues, Zone z) {
// Search for and return cached next state first.
// if(this.nextStateMap.containsKey(curState) == true)
// return (State)this.nextStateMap.get(curState);
State nextState = thisSg.getNextState(curState, firedTran);
if(nextState != null)
return nextState;
// If no cached next state exists, do regular firing.
// Marking update
int[] curOldMarking = curState.getMarking();
int[] curNewMarking = null;
if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0)
curNewMarking = curOldMarking;
else {
curNewMarking = new int[curOldMarking.length];
curNewMarking = curOldMarking.clone();
for (int prep : this.lpn.getPresetIndex(firedTran.getName())) {
curNewMarking[prep]=0;
}
for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) {
curNewMarking[postp]=1;
}
}
// State vector update
int[] newVectorArray = curState.getVector().clone();
int[] curVector = curState.getVector();
HashMap<String, String> currentValuesAsString = this.lpn.getAllVarsWithValuesAsString(curVector);
for (String key : currentValuesAsString.keySet()) {
if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(currentValuesAsString);
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(currentValuesAsString);
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
}
// // Update rates
// final int OLD_ZERO = 0; // Case 0 in description.
//// final int NEW_NON_ZERO = 1; // Case 1 in description.
//// final int NEW_ZERO = 2; // Case 2 in description.
//// final int OLD_NON_ZERO = 3; // Case 3 in description.
//// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
//// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
//// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
//// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
//
// final int NEW_NON_ZERO = 1; // Case 1 in description.
// final int NEW_ZERO = 2; // Case 2 in description.
// final int OLD_NON_ZERO = 3; // Cade 3 in description.
// if(Options.getTimingAnalysisFlag()){
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// }
//
// for(String key : this.lpn.getContVars()){
//
// // Get the pairing.
// int lpnIndex = this.lpn.getLpnIndex();
// int contVarIndex = this.lpn.getContVarIndex(key);
//
// // Package up the indecies.
// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
//
// //Integer newRate = null;
// IntervalPair newRate = null;
// IntervalPair newValue= null;
//
// // Check if there is a new rate assignment.
// if(this.lpn.getRateAssignTree(firedTran.getName(), key) != null){
// // Get the new value.
// //IntervalPair newIntervalRate = this.lpn.getRateAssignTree(firedTran.getName(), key)
// //.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null);
// newRate = this.lpn.getRateAssignTree(firedTran.getName(), key)
// .evaluateExprBound(currentValuesAsString, z, null);
//
//// // Get the pairing.
//// int lpnIndex = this.lpn.getLpnIndex();
//// int contVarIndex = this.lpn.getContVarIndex(key);
////
//// // Package up the indecies.
//// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
//
// // Keep the current rate.
// //newRate = newIntervalRate.get_LowerBound();
//
// //contVar.setCurrentRate(newIntervalRate.get_LowerBound());
// contVar.setCurrentRate(newRate.get_LowerBound());
//
//// continuousValues.put(contVar, new IntervalPair(z.getDbmEntryByPair(contVar, LPNTransitionPair.ZERO_TIMER_PAIR),
//// z.getDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, contVar)));
//
//// // Check if the new assignment gives rate zero.
//// boolean newRateZero = newRate == 0;
//// // Check if the variable was already rate zero.
//// boolean oldRateZero = z.getCurrentRate(contVar) == 0;
////
//// // Put the new value in the appropriate set.
//// if(oldRateZero){
//// if(newRateZero){
//// // Old rate is zero and the new rate is zero.
//// newAssignValues.get(OLD_ZERO).put(contVar, newValue);
//// }
//// else{
//// // Old rate is zero and the new rate is non-zero.
//// newAssignValues.get(NEW_NON_ZERO).put(contVar, newValue);
//// }
//// }
//// else{
//// if(newRateZero){
//// // Old rate is non-zero and the new rate is zero.
//// newAssignValues.get(NEW_ZERO).put(contVar, newValue);
//// }
//// else{
//// // Old rate is non-zero and the new rate is non-zero.
//// newAssignValues.get(OLD_NON_ZERO).put(contVar, newValue);
//// }
//// }
// }
// //}
//
// // Update continuous variables.
// //for(String key : this.lpn.getContVars()){
// // Get the new assignments on the continuous variables and update inequalities.
// if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
//// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
//// newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
//
// // Get the new value.
// newValue = this.lpn.getContAssignTree(firedTran.getName(), key)
// //.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null);
// .evaluateExprBound(currentValuesAsString, z, null);
//
//// // Get the pairing.
//// int lpnIndex = this.lpn.getLpnIndex();
//// int contVarIndex = this.lpn.getContVarIndex(key);
////
//// // Package up the indecies.
//// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
//
// if(newRate == null){
// // Keep the current rate.
// contVar.setCurrentRate(z.getCurrentRate(contVar));
// }
//
//
//// continuousValues.put(contVar, newValue);
//
// // Get each inequality that involves the continuous variable.
// ArrayList<InequalityVariable> inequalities = this.lpn.getContVar(contVarIndex).getInequalities();
//
// // Update the inequalities.
// for(InequalityVariable ineq : inequalities){
// int ineqIndex = this.lpn.getVarIndexMap().get(ineq.getName());
//
//
// HashMap<LPNContAndRate, IntervalPair> continuousValues = new HashMap<LPNContAndRate, IntervalPair>();
// continuousValues.putAll(newAssignValues.get(OLD_ZERO));
// continuousValues.putAll(newAssignValues.get(NEW_NON_ZERO));
// continuousValues.putAll(newAssignValues.get(NEW_ZERO));
// continuousValues.putAll(newAssignValues.get(OLD_NON_ZERO));
//
//
// newVectorArray[ineqIndex] = ineq.evaluate(newVectorArray, z, continuousValues);
// }
// }
//
//
// // If the value did not get assigned, put in the old value.
// if(newValue == null){
// newValue = z.getContinuousBounds(contVar);
// }
//
// // Check if the new assignment gives rate zero.
// //boolean newRateZero = newRate == 0;
// boolean newRateZero = newRate.singleValue() ? newRate.get_LowerBound() == 0 : false;
// // Check if the variable was already rate zero.
// boolean oldRateZero = z.getCurrentRate(contVar) == 0;
//
// // Put the new value in the appropriate set.
// if(oldRateZero){
// if(newRateZero){
// // Old rate is zero and the new rate is zero.
// newAssignValues.get(OLD_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
// }
// else{
// // Old rate is zero and the new rate is non-zero.
// newAssignValues.get(NEW_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
// }
// }
// else{
// if(newRateZero){
// // Old rate is non-zero and the new rate is zero.
// newAssignValues.get(NEW_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
// }
// else{
// // Old rate is non-zero and the new rate is non-zero.
// newAssignValues.get(OLD_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
// }
// }
//
// }
/*
for (VarExpr s : firedTran.getAssignments()) {
int newValue = (int) s.getExpr().evaluate(curVector);
newVectorArray[s.getVar().getIndex(curVector)] = newValue;
}
*/
// Enabled transition vector update
boolean[] newEnabledTranVector = updateEnabledTranVector(curState.getTranVector(), curNewMarking, newVectorArray, firedTran);
State newState = thisSg.addState(new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranVector));
// TODO: (future) assertions in our LPN?
/*
int[] newVector = newState.getVector();
for(Expression e : assertions){
if(e.evaluate(newVector) == 0){
System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label);
System.exit(1);
}
}
*/
thisSg.addStateTran(curState, firedTran, newState);
return newState;
}
public boolean[] updateEnabledTranVector(boolean[] enabledTranBeforeFiring,
int[] newMarking, int[] newVectorArray, Transition firedTran) {
boolean[] enabledTranAfterFiring = enabledTranBeforeFiring.clone();
// Disable fired transition
if (firedTran != null) {
enabledTranAfterFiring[firedTran.getIndex()] = false;
for (Integer curConflictingTranIndex : firedTran.getConflictSetTransIndices()) {
enabledTranAfterFiring[curConflictingTranIndex] = false;
}
}
// find newly enabled transition(s) based on the updated markings and variables
if (Options.getDebugMode()) {
// System.out.println("Finding newly enabled transitions at updateEnabledTranVector.");
}
for (Transition tran : this.lpn.getAllTransitions()) {
boolean needToUpdate = true;
String tranName = tran.getName();
int tranIndex = tran.getIndex();
if (Options.getDebugMode()) {
// System.out.println("Checking " + tranName);
}
if (this.lpn.getEnablingTree(tranName) != null
&& this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode()) {
// System.out.println(tran.getName() + " " + "Enabling condition is false");
}
if (enabledTranAfterFiring[tranIndex] && !tran.isPersistent())
enabledTranAfterFiring[tranIndex] = false;
continue;
}
if (this.lpn.getTransitionRateTree(tranName) != null
&& this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode()) {
// System.out.println("Rate is zero");
}
continue;
}
if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) {
for (int place : this.lpn.getPresetIndex(tranName)) {
if (newMarking[place]==0) {
if (Options.getDebugMode()) {
// System.out.println(tran.getName() + " " + "Missing a preset token");
}
needToUpdate = false;
break;
}
}
}
if (needToUpdate) {
// if a transition is enabled and it is not recorded in the enabled transition vector
enabledTranAfterFiring[tranIndex] = true;
if (Options.getDebugMode()) {
// System.out.println(tran.getName() + " is Enabled.");
}
}
}
return enabledTranAfterFiring;
}
/**
* Updates the transition vector.
* @param enabledTranBeforeFiring
* The enabling before the transition firing.
* @param newMarking
* The new marking to check for transitions with.
* @param newVectorArray
* The new values of the boolean variables.
* @param firedTran
* The transition that fire.
* @param newlyEnabled
* A list to capture the newly enabled transitions.
* @return
* The newly enabled transitions.
*/
public boolean[] updateEnabledTranVector(boolean[] enabledTranBeforeFiring,
int[] newMarking, int[] newVectorArray, Transition firedTran, HashSet<LPNTransitionPair> newlyEnabled) {
boolean[] enabledTranAfterFiring = enabledTranBeforeFiring.clone();
// Disable fired transition
if (firedTran != null) {
enabledTranAfterFiring[firedTran.getIndex()] = false;
for (Integer curConflictingTranIndex : firedTran.getConflictSetTransIndices()) {
enabledTranAfterFiring[curConflictingTranIndex] = false;
}
}
// find newly enabled transition(s) based on the updated markings and variables
if (Options.getDebugMode())
System.out.println("Finding newly enabled transitions at updateEnabledTranVector.");
for (Transition tran : this.lpn.getAllTransitions()) {
boolean needToUpdate = true;
String tranName = tran.getName();
int tranIndex = tran.getIndex();
if (Options.getDebugMode())
System.out.println("Checking " + tranName);
if (this.lpn.getEnablingTree(tranName) != null
&& this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode())
System.out.println(tran.getName() + " " + "Enabling condition is false");
if (enabledTranAfterFiring[tranIndex] && !tran.isPersistent())
enabledTranAfterFiring[tranIndex] = false;
continue;
}
if (this.lpn.getTransitionRateTree(tranName) != null
&& this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode())
System.out.println("Rate is zero");
continue;
}
if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) {
for (int place : this.lpn.getPresetIndex(tranName)) {
if (newMarking[place]==0) {
if (Options.getDebugMode())
System.out.println(tran.getName() + " " + "Missing a preset token");
needToUpdate = false;
break;
}
}
}
if (needToUpdate) {
// if a transition is enabled and it is not recorded in the enabled transition vector
enabledTranAfterFiring[tranIndex] = true;
if (Options.getDebugMode())
System.out.println(tran.getName() + " is Enabled.");
}
if(newlyEnabled != null && enabledTranAfterFiring[tranIndex] && !enabledTranBeforeFiring[tranIndex]){
newlyEnabled.add(new LPNTransitionPair(tran.getLpn().getLpnIndex(), tranIndex));
}
}
return enabledTranAfterFiring;
}
public State constrFire(Transition firedTran, final State curState) {
// Marking update
int[] curOldMarking = curState.getMarking();
int[] curNewMarking = null;
if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0){
curNewMarking = curOldMarking;
}
else {
curNewMarking = new int[curOldMarking.length - firedTran.getPreset().length + firedTran.getPostset().length];
int index = 0;
for (int i : curOldMarking) {
boolean existed = false;
for (int prep : this.lpn.getPresetIndex(firedTran.getName())) {
if (i == prep) {
existed = true;
break;
}
// TODO: (??) prep > i
else if(prep > i){
break;
}
}
if (existed == false) {
curNewMarking[index] = i;
index++;
}
}
for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) {
curNewMarking[index] = postp;
index++;
}
}
// State vector update
int[] oldVector = curState.getVector();
int size = oldVector.length;
int[] newVectorArray = new int[size];
System.arraycopy(oldVector, 0, newVectorArray, 0, size);
int[] curVector = curState.getVector();
for (String key : this.lpn.getAllVarsWithValuesAsString(curVector).keySet()) {
if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
// TODO: (temp) type cast continuous variable to int.
if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
}
// TODO: (check) Is the update is equivalent to the one below?
/*
for (VarExpr s : getAssignments()) {
int newValue = s.getExpr().evaluate(curVector);
newVectorArray[s.getVar().getIndex(curVector)] = newValue;
}
*/
// Enabled transition vector update
boolean[] newEnabledTranArray = curState.getTranVector();
newEnabledTranArray[firedTran.getIndex()] = false;
State newState = new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranArray);
// TODO: (future) assertions in our LPN?
/*
int[] newVector = newState.getVector();
for(Expression e : assertions){
if(e.evaluate(newVector) == 0){
System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label);
System.exit(1);
}
}
*/
return newState;
}
public void outputLocalStateGraph(String file) {
try {
int size = this.lpn.getVarIndexMap().size();
String varNames = "";
for(int i = 0; i < size; i++) {
varNames = varNames + ", " + this.lpn.getVarIndexMap().getKey(i);
}
varNames = varNames.replaceFirst(", ", "");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("digraph G {\n");
out.write("Inits [shape=plaintext, label=\"<" + varNames + ">\"]\n");
for (State curState : nextStateMap.keySet()) {
String markings = intArrayToString("markings", curState);
String vars = intArrayToString("vars", curState);
String enabledTrans = boolArrayToString("enabledTrans", curState);
String curStateName = "S" + curState.getIndex();
out.write(curStateName + "[shape=\"ellipse\",label=\"" + curStateName + "\\n<"+vars+">" + "\\n<"+enabledTrans+">" + "\\n<"+markings+">" + "\"]\n");
}
for (State curState : nextStateMap.keySet()) {
HashMap<Transition, State> stateTransitionPair = nextStateMap.get(curState);
for (Transition curTran : stateTransitionPair.keySet()) {
String curStateName = "S" + curState.getIndex();
String nextStateName = "S" + stateTransitionPair.get(curTran).getIndex();
String curTranName = curTran.getName();
if (curTran.isFail() && !curTran.isPersistent())
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=red]\n");
else if (!curTran.isFail() && curTran.isPersistent())
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=blue]\n");
else if (curTran.isFail() && curTran.isPersistent())
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=purple]\n");
else
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\"]\n");
}
}
out.write("}");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing local state graph as dot file.");
}
}
private String intArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("markings")) {
for (int i=0; i< curState.getMarking().length; i++) {
if (curState.getMarking()[i] == 1) {
arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ",";
}
// String tranName = curState.getLpn().getAllTransitions()[i].getName();
// if (curState.getTranVector()[i])
// System.out.println(tranName + " " + "Enabled");
// else
// System.out.println(tranName + " " + "Not Enabled");
}
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
else if (type.equals("vars")) {
for (int i=0; i< curState.getVector().length; i++) {
arrayStr = arrayStr + curState.getVector()[i] + ",";
}
if (arrayStr.contains(","))
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private String boolArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("enabledTrans")) {
for (int i=0; i< curState.getTranVector().length; i++) {
if (curState.getTranVector()[i]) {
arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getName() + ",";
}
}
if (arrayStr != "")
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private void printTransitionSet(LpnTranList transitionSet, String setName) {
if (!setName.isEmpty())
System.out.print(setName + " ");
if (transitionSet.isEmpty()) {
System.out.println("empty");
}
else {
for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) {
Transition tranInDisable = curTranIter.next();
System.out.print(tranInDisable.getName() + " ");
}
System.out.print("\n");
}
}
private static void printAmpleSet(LpnTranList transitionSet, String setName) {
if (!setName.isEmpty())
System.out.print(setName + " ");
if (transitionSet.isEmpty()) {
System.out.println("empty");
}
else {
for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) {
Transition tranInDisable = curTranIter.next();
System.out.print(tranInDisable.getName() + " ");
}
System.out.print("\n");
}
}
public HashMap<State,LpnTranList> copyEnabledSetTbl() {
HashMap<State,LpnTranList> copyEnabledSetTbl = new HashMap<State,LpnTranList>();
for (State s : enabledSetTbl.keySet()) {
LpnTranList tranList = enabledSetTbl.get(s).clone();
copyEnabledSetTbl.put(s.clone(), tranList);
}
return copyEnabledSetTbl;
}
public void setEnabledSetTbl(HashMap<State, LpnTranList> enabledSetTbl) {
this.enabledSetTbl = enabledSetTbl;
}
public HashMap<State, LpnTranList> getEnabledSetTbl() {
return this.enabledSetTbl;
}
public HashMap<State, HashMap<Transition, State>> getNextStateMap() {
return this.nextStateMap;
}
/**
* Fires a transition for the timed code.
* @param curSgArray
* The current information on the all local states.
* @param currentPrjState
* The current state.
* @param firedTran
* The transition to fire.
* @return
* The new states.
*/
public TimedPrjState fire(final StateGraph[] curSgArray,
final PrjState currentPrjState, Transition firedTran){
TimedPrjState currentTimedPrjState;
// Check that this is a timed state.
if(currentPrjState instanceof TimedPrjState){
currentTimedPrjState = (TimedPrjState) currentPrjState;
}
else{
throw new IllegalArgumentException("Attempted to use the " +
"fire(StateGraph[],PrjState,Transition)" +
"without a TimedPrjState stored in the PrjState " +
"variable. This method is meant for TimedPrjStates.");
}
// Extract relevant information from the current project state.
State[] curStateArray = currentTimedPrjState.toStateArray();
Zone[] currentZones = currentTimedPrjState.toZoneArray();
// Zone[] newZones = new Zone[curStateArray.length];
Zone[] newZones = new Zone[1];
//HashMap<LPNContinuousPair, IntervalPair> newContValues = new HashMap<LPNContinuousPair, IntervalPair>();
// ArrayList<HashMap<LPNContinuousPair, IntervalPair>> newAssignValues =
// new ArrayList<HashMap<LPNContinuousPair, IntervalPair>>();
/*
* This ArrayList contains four separate maps that store the
* rate and continuous variables assignments.
*/
// ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues =
// new ArrayList<HashMap<LPNContAndRate, IntervalPair>>();
// Get the new un-timed local states.
State[] newStates = fire(curSgArray, curStateArray, firedTran);
// currentTimedPrjState.get_zones()[0]);
// State[] newStates = fire(curSgArray, curStateArray, firedTran, newAssignValues,
// currentTimedPrjState.get_zones()[0]);
// Get the new values from rate assignments and continuous variable
// assignments. Also fix the enabled transition markings.
// Convert the values of the current marking to strings. This is needed for the evaluator.
// HashMap<String, String> valuesAsString =
// this.lpn.getAllVarsWithValuesAsString(curStateArray[this.lpn.getLpnIndex()].getVector());
// ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues =
// updateContinuousState(currentTimedPrjState.get_zones()[0], valuesAsString, curStateArray, firedTran);
ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues =
updateContinuousState(currentTimedPrjState.get_zones()[0], curStateArray, firedTran);
LpnTranList enabledTransitions = new LpnTranList();
for(int i=0; i<newStates.length; i++)
{
// enabledTransitions = getEnabled(newStates[i]);
// The stategraph has to be used to call getEnabled
// since it is being passed implicitly.
LpnTranList localEnabledTransitions = curSgArray[i].getEnabled(newStates[i]);
for(int j=0; j<localEnabledTransitions.size(); j++){
enabledTransitions.add(localEnabledTransitions.get(j));
}
// newZones[i] = currentZones[i].fire(firedTran,
// enabledTransitions, newStates);
// Update any continuous variable assignments.
// for (this.lpn.get) {
//
// if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
//// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
//// newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
//
// }
// for(String contVar : this.lpn.getContVars()){
// // Get the new range.
// InveralRange range =
// this.lpn.getContAssignTree(firedTran.getName(), contVar)
// .evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z)
// }
}
// newZones[0] = currentZones[0].fire(firedTran,
// enabledTransitions, newContValues, newStates);
newZones[0] = currentZones[0].fire(firedTran,
enabledTransitions, newAssignValues, newStates);
// ContinuousUtilities.updateInequalities(newZones[0],
// newStates[firedTran.getLpn().getLpnIndex()]);
// Warp the zone.
//newZones[0].dbmWarp(currentTimedPrjState.get_zones()[0]);
return new TimedPrjState(newStates, newZones);
}
/**
* Fires a list of events. This list can either contain a single transition
* or a set of inequalities.
* @param curSgArray
* The current information on the all local states.
* @param currentPrjState
* The current state.
* @param eventSets
* The set of events to fire.
* @return
* The new state.
*/
public TimedPrjState fire(final StateGraph[] curSgArray,
final PrjState currentPrjState, EventSet eventSet){
TimedPrjState currentTimedPrjState;
// Check that this is a timed state.
if(currentPrjState instanceof TimedPrjState){
currentTimedPrjState = (TimedPrjState) currentPrjState;
}
else{
throw new IllegalArgumentException("Attempted to use the " +
"fire(StateGraph[],PrjState,Transition)" +
"without a TimedPrjState stored in the PrjState " +
"variable. This method is meant for TimedPrjStates.");
}
// Determine if the list of events represents a list of inequalities.
if(eventSet.isInequalities()){
// Create a copy of the current states.
State[] oldStates = currentTimedPrjState.getStateArray();
State[] states = new State[oldStates.length];
for(int i=0; i<oldStates.length; i++){
states[i] = oldStates[i].clone();
}
// Get the variable index map for getting the indecies
// of the variables.
DualHashMap<String, Integer> map = lpn.getVarIndexMap();
for(Event e : eventSet){
// Extract inequality variable.
InequalityVariable iv = e.getInequalityVariable();
// Get the index to change the value.
int variableIndex = map.getValue(iv.getName());
// Flip the value of the inequality.
int[] vector = states[this.lpn.getLpnIndex()].getVector();
vector[variableIndex] =
vector[variableIndex] == 0 ? 1 : 0;
}
HashSet<LPNTransitionPair> newlyEnabled = new HashSet<LPNTransitionPair>();
// Update the enabled transitions according to inequalities that have changed.
for(int i=0; i<states.length; i++){
boolean[] newEnabledTranVector = updateEnabledTranVector(states[i].getTranVector(),
states[i].marking, states[i].vector, null, newlyEnabled);
State newState = curSgArray[i].addState(new State(this.lpn, states[i].marking, states[i].vector, newEnabledTranVector));
states[i] = newState;
}
// Get a new zone that has been restricted according to the inequalities firing.
Zone z = currentTimedPrjState.get_zones()[0].getContinuousRestrictedZone(eventSet);
// Add any new transitions.
z = z.addTransition(newlyEnabled, states);
// return new TimedPrjState(states, currentTimedPrjState.get_zones());
return new TimedPrjState(states, new Zone[]{z});
}
return fire(curSgArray, currentPrjState, eventSet.getTransition());
}
/**
* This method handles the extracting of the new rate and continuous variable assignments.
* @param z
* The previous zone.
* @param currentValuesAsString
* The current values of the Boolean varaibles converted to strings.
* @param states
* The current states.
* @param firedTran
* The fired transition.
* @return
* The continuous variable and rate assignments.
*/
// public ArrayList<HashMap<LPNContAndRate, IntervalPair>>
// updateContinuousState(Zone z, HashMap<String, String> currentValuesAsString,
// State[] states, Transition firedTran){
private ArrayList<HashMap<LPNContAndRate, IntervalPair>>
updateContinuousState(Zone z,
State[] states, Transition firedTran){
// Convert the current values of Boolean variables to strings for use in the
// Evaluator.
HashMap<String, String> currentValuesAsString =
this.lpn.getAllVarsWithValuesAsString(states[this.lpn.getLpnIndex()].getVector());
// Accumulates a set of all transitions that need their enabling conditions
// re-evaluated.
HashSet<Transition> needUpdating = new HashSet<Transition>();
// Accumulates the new assignment information.
ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues
= new ArrayList<HashMap<LPNContAndRate, IntervalPair>>();
// Update rates
final int OLD_ZERO = 0; // Case 0 in description.
// final int NEW_NON_ZERO = 1; // Case 1 in description.
// final int NEW_ZERO = 2; // Case 2 in description.
// final int OLD_NON_ZERO = 3; // Case 3 in description.
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
final int NEW_NON_ZERO = 1; // Case 1 in description.
final int NEW_ZERO = 2; // Case 2 in description.
final int OLD_NON_ZERO = 3; // Cade 3 in description.
if(Options.getTimingAnalysisFlag()){
newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>());
}
for(String key : this.lpn.getContVars()){
// Get the pairing.
int lpnIndex = this.lpn.getLpnIndex();
int contVarIndex = this.lpn.getContVarIndex(key);
// Package up the indecies.
LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
//Integer newRate = null;
IntervalPair newRate = null;
IntervalPair newValue= null;
// Check if there is a new rate assignment.
if(this.lpn.getRateAssignTree(firedTran.getName(), key) != null){
// Get the new value.
//IntervalPair newIntervalRate = this.lpn.getRateAssignTree(firedTran.getName(), key)
//.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null);
newRate = this.lpn.getRateAssignTree(firedTran.getName(), key)
.evaluateExprBound(currentValuesAsString, z, null);
// // Get the pairing.
// int lpnIndex = this.lpn.getLpnIndex();
// int contVarIndex = this.lpn.getContVarIndex(key);
//
// // Package up the indecies.
// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
// Keep the current rate.
//newRate = newIntervalRate.get_LowerBound();
//contVar.setCurrentRate(newIntervalRate.get_LowerBound());
contVar.setCurrentRate(newRate.get_LowerBound());
// continuousValues.put(contVar, new IntervalPair(z.getDbmEntryByPair(contVar, LPNTransitionPair.ZERO_TIMER_PAIR),
// z.getDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, contVar)));
// // Check if the new assignment gives rate zero.
// boolean newRateZero = newRate == 0;
// // Check if the variable was already rate zero.
// boolean oldRateZero = z.getCurrentRate(contVar) == 0;
//
// // Put the new value in the appropriate set.
// if(oldRateZero){
// if(newRateZero){
// // Old rate is zero and the new rate is zero.
// newAssignValues.get(OLD_ZERO).put(contVar, newValue);
// }
// else{
// // Old rate is zero and the new rate is non-zero.
// newAssignValues.get(NEW_NON_ZERO).put(contVar, newValue);
// }
// }
// else{
// if(newRateZero){
// // Old rate is non-zero and the new rate is zero.
// newAssignValues.get(NEW_ZERO).put(contVar, newValue);
// }
// else{
// // Old rate is non-zero and the new rate is non-zero.
// newAssignValues.get(OLD_NON_ZERO).put(contVar, newValue);
// }
// }
}
//}
// Update continuous variables.
//for(String key : this.lpn.getContVars()){
// Get the new assignments on the continuous variables and update inequalities.
if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
// newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
// Get the new value.
newValue = this.lpn.getContAssignTree(firedTran.getName(), key)
//.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null);
.evaluateExprBound(currentValuesAsString, z, null);
// // Get the pairing.
// int lpnIndex = this.lpn.getLpnIndex();
// int contVarIndex = this.lpn.getContVarIndex(key);
//
// // Package up the indecies.
// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex);
if(newRate == null){
// Keep the current rate.
contVar.setCurrentRate(z.getCurrentRate(contVar));
}
// continuousValues.put(contVar, newValue);
// Get each inequality that involves the continuous variable.
ArrayList<InequalityVariable> inequalities = this.lpn.getContVar(contVarIndex).getInequalities();
// Update the inequalities.
for(InequalityVariable ineq : inequalities){
int ineqIndex = this.lpn.getVarIndexMap().get(ineq.getName());
// Add the transitions that this inequality affects.
needUpdating.addAll(ineq.getTransitions());
HashMap<LPNContAndRate, IntervalPair> continuousValues = new HashMap<LPNContAndRate, IntervalPair>();
continuousValues.putAll(newAssignValues.get(OLD_ZERO));
continuousValues.putAll(newAssignValues.get(NEW_NON_ZERO));
continuousValues.putAll(newAssignValues.get(NEW_ZERO));
continuousValues.putAll(newAssignValues.get(OLD_NON_ZERO));
// Adjust state vector values for the inequality variables.
int[] newVectorArray = states[this.lpn.getLpnIndex()].getVector();
newVectorArray[ineqIndex] = ineq.evaluate(newVectorArray, z, continuousValues);
}
}
// If the value did not get assigned, put in the old value.
if(newValue == null){
newValue = z.getContinuousBounds(contVar);
}
// Check if the new assignment gives rate zero.
//boolean newRateZero = newRate == 0;
boolean newRateZero = newRate.singleValue() ? newRate.get_LowerBound() == 0 : false;
// Check if the variable was already rate zero.
boolean oldRateZero = z.getCurrentRate(contVar) == 0;
// Put the new value in the appropriate set.
if(oldRateZero){
if(newRateZero){
// Old rate is zero and the new rate is zero.
newAssignValues.get(OLD_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
}
else{
// Old rate is zero and the new rate is non-zero.
newAssignValues.get(NEW_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
}
}
else{
if(newRateZero){
// Old rate is non-zero and the new rate is zero.
newAssignValues.get(NEW_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
}
else{
// Old rate is non-zero and the new rate is non-zero.
newAssignValues.get(OLD_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue);
}
}
}
// Do the re-evaluating of the transitions.
for(Transition t : needUpdating){
// Get the index of the LPN and the index of the transition.
int lpnIndex = t.getLpn().getLpnIndex();
int tranIndex = t.getIndex();
// Get the enabled vector from the appropriate state.
int[] vector = states[lpnIndex].getVector();
// Set the (possibly) new value.
vector[tranIndex] = t.getEnablingTree().
evaluateExprBound(currentValuesAsString, z, null).get_LowerBound();
}
return newAssignValues;
}
}
| Minor fix in printing debugging messages
| gui/src/verification/platu/stategraph/StateGraph.java | Minor fix in printing debugging messages | <ide><path>ui/src/verification/platu/stategraph/StateGraph.java
<ide> }
<ide> // find newly enabled transition(s) based on the updated markings and variables
<ide> if (Options.getDebugMode()) {
<del>// System.out.println("Finding newly enabled transitions at updateEnabledTranVector.");
<add>// System.out.println("Find newly enabled transitions at updateEnabledTranVector.");
<ide> }
<ide>
<ide> for (Transition tran : this.lpn.getAllTransitions()) { |
|
Java | apache-2.0 | ae741d7a9c903011b48485422b7f2c517a40304e | 0 | alexandrnikitin/aerospike-client-java,Stratio/aerospike-client-java,pradeepsrinivasan/aerospike-client-java,pradeepsrinivasan/aerospike-client-java,alexandrnikitin/aerospike-client-java,wgpshashank/aerospike-client-java,wgpshashank/aerospike-client-java,Stratio/aerospike-client-java | /*******************************************************************************
* Copyright 2012-2014 by Aerospike.
*
* 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.aerospike.client.policy;
/**
* How to handle writes when the record already exists.
*/
public enum RecordExistsAction {
/**
* Create or update record.
* Merge write command bins with existing bins.
*/
UPDATE,
/**
* Update record only. Fail if record does not exist.
* Merge write command bins with existing bins.
*/
UPDATE_ONLY,
/**
* Create or replace record.
* Delete existing bins not referenced by write command bins.
* Supported by Aerospike 2 server versions >= 2.7.5 and
* Aerospike 3 server versions >= 3.1.6.
*/
REPLACE,
/**
* Replace record only. Fail if record does not exist.
* Delete existing bins not referenced by write command bins.
* Supported by Aerospike 2 server versions >= 2.7.5 and
* Aerospike 3 server versions >= 3.1.6.
*/
REPLACE_ONLY,
/**
* Create only. Fail if record exists.
*/
CREATE_ONLY,
/**
* @deprecated Use {@link com.aerospike.client.policy.RecordExistsAction#CREATE_ONLY}
* instead.
*/
@Deprecated
FAIL,
/**
* @deprecated Use {@link com.aerospike.client.policy.GenerationPolicy#EXPECT_GEN_EQUAL}
* in {@link com.aerospike.client.policy.WritePolicy#generationPolicy} instead.
*/
@Deprecated
EXPECT_GEN_EQUAL,
/**
* @deprecated Use {@link com.aerospike.client.policy.GenerationPolicy#EXPECT_GEN_GT}
* in {@link com.aerospike.client.policy.WritePolicy#generationPolicy} instead.
*/
@Deprecated
EXPECT_GEN_GT,
/**
* @deprecated Use {@link com.aerospike.client.policy.GenerationPolicy#DUPLICATE}
* in {@link com.aerospike.client.policy.WritePolicy#generationPolicy} instead.
*/
@Deprecated
DUPLICATE
}
| client/src/com/aerospike/client/policy/RecordExistsAction.java | /*******************************************************************************
* Copyright 2012-2014 by Aerospike.
*
* 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.aerospike.client.policy;
/**
* How to handle writes when the record already exists.
*/
public enum RecordExistsAction {
/**
* Create or update record.
* Merge write command bins with existing bins.
*/
UPDATE,
/**
* Update record only. Fail if record does not exist.
* Merge write command bins with existing bins.
*/
UPDATE_ONLY,
/**
* Create or update record.
* Delete existing bins not referenced by write command bins.
* Supported by Aerospike 2 server versions >= 2.7.5 and
* Aerospike 3 server versions >= 3.1.6.
*/
REPLACE,
/**
* Update record only. Fail if record does not exist.
* Delete existing bins not referenced by write command bins.
* Supported by Aerospike 2 server versions >= 2.7.5 and
* Aerospike 3 server versions >= 3.1.6.
*/
REPLACE_ONLY,
/**
* Create only. Fail if record exists.
*/
CREATE_ONLY,
/**
* @deprecated Use {@link com.aerospike.client.policy.RecordExistsAction#CREATE_ONLY}
* instead.
*/
@Deprecated
FAIL,
/**
* @deprecated Use {@link com.aerospike.client.policy.GenerationPolicy#EXPECT_GEN_EQUAL}
* in {@link com.aerospike.client.policy.WritePolicy#generationPolicy} instead.
*/
@Deprecated
EXPECT_GEN_EQUAL,
/**
* @deprecated Use {@link com.aerospike.client.policy.GenerationPolicy#EXPECT_GEN_GT}
* in {@link com.aerospike.client.policy.WritePolicy#generationPolicy} instead.
*/
@Deprecated
EXPECT_GEN_GT,
/**
* @deprecated Use {@link com.aerospike.client.policy.GenerationPolicy#DUPLICATE}
* in {@link com.aerospike.client.policy.WritePolicy#generationPolicy} instead.
*/
@Deprecated
DUPLICATE
}
| replace doc update
| client/src/com/aerospike/client/policy/RecordExistsAction.java | replace doc update | <ide><path>lient/src/com/aerospike/client/policy/RecordExistsAction.java
<ide> UPDATE_ONLY,
<ide>
<ide> /**
<del> * Create or update record.
<add> * Create or replace record.
<ide> * Delete existing bins not referenced by write command bins.
<ide> * Supported by Aerospike 2 server versions >= 2.7.5 and
<ide> * Aerospike 3 server versions >= 3.1.6.
<ide> REPLACE,
<ide>
<ide> /**
<del> * Update record only. Fail if record does not exist.
<add> * Replace record only. Fail if record does not exist.
<ide> * Delete existing bins not referenced by write command bins.
<ide> * Supported by Aerospike 2 server versions >= 2.7.5 and
<ide> * Aerospike 3 server versions >= 3.1.6. |
|
Java | apache-2.0 | 3bc1121b9d6f73f601776a20e6ec5b0e1ea0f4b2 | 0 | spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework | /*
* Copyright 2002-2016 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.messaging.simp.stomp;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.broker.AbstractBrokerMessageHandler;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.support.MessageHeaderInitializer;
import org.springframework.messaging.tcp.FixedIntervalReconnectStrategy;
import org.springframework.messaging.tcp.TcpConnection;
import org.springframework.messaging.tcp.TcpConnectionHandler;
import org.springframework.messaging.tcp.TcpOperations;
import org.springframework.messaging.tcp.reactor.Reactor2TcpClient;
import org.springframework.util.Assert;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.util.concurrent.ListenableFutureTask;
/**
* A {@link org.springframework.messaging.MessageHandler} that handles messages by
* forwarding them to a STOMP broker.
*
* <p>For each new {@link SimpMessageType#CONNECT CONNECT} message, an independent TCP
* connection to the broker is opened and used exclusively for all messages from the
* client that originated the CONNECT message. Messages from the same client are
* identified through the session id message header. Reversely, when the STOMP broker
* sends messages back on the TCP connection, those messages are enriched with the session
* id of the client and sent back downstream through the {@link MessageChannel} provided
* to the constructor.
*
* <p>This class also automatically opens a default "system" TCP connection to the message
* broker that is used for sending messages that originate from the server application (as
* opposed to from a client). Such messages are not associated with any client and
* therefore do not have a session id header. The "system" connection is effectively
* shared and cannot be used to receive messages. Several properties are provided to
* configure the "system" connection including:
* <ul>
* <li>{@link #setSystemLogin(String)}</li>
* <li>{@link #setSystemPasscode(String)}</li>
* <li>{@link #setSystemHeartbeatSendInterval(long)}</li>
* <li>{@link #setSystemHeartbeatReceiveInterval(long)}</li>
* </ul>
*
* @author Rossen Stoyanchev
* @author Andy Wilkinson
* @since 4.0
*/
public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler {
public static final String SYSTEM_SESSION_ID = "_system_";
private static final byte[] EMPTY_PAYLOAD = new byte[0];
private static final ListenableFutureTask<Void> EMPTY_TASK = new ListenableFutureTask<>(new VoidCallable());
// STOMP recommends error of margin for receiving heartbeats
private static final long HEARTBEAT_MULTIPLIER = 3;
private static final Message<byte[]> HEARTBEAT_MESSAGE;
/**
* A heartbeat is setup once a CONNECTED frame is received which contains
* the heartbeat settings we need. If we don't receive CONNECTED within
* a minute, the connection is closed proactively.
*/
private static final int MAX_TIME_TO_CONNECTED_FRAME = 60 * 1000;
static {
EMPTY_TASK.run();
StompHeaderAccessor accessor = StompHeaderAccessor.createForHeartbeat();
HEARTBEAT_MESSAGE = MessageBuilder.createMessage(StompDecoder.HEARTBEAT_PAYLOAD, accessor.getMessageHeaders());
}
private String relayHost = "127.0.0.1";
private int relayPort = 61613;
private String clientLogin = "guest";
private String clientPasscode = "guest";
private String systemLogin = "guest";
private String systemPasscode = "guest";
private long systemHeartbeatSendInterval = 10000;
private long systemHeartbeatReceiveInterval = 10000;
private String virtualHost;
private final Map<String, MessageHandler> systemSubscriptions = new HashMap<>(4);
private TcpOperations<byte[]> tcpClient;
private MessageHeaderInitializer headerInitializer;
private final Map<String, StompConnectionHandler> connectionHandlers =
new ConcurrentHashMap<>();
private final Stats stats = new Stats();
/**
* Create a StompBrokerRelayMessageHandler instance with the given message channels
* and destination prefixes.
* @param inboundChannel the channel for receiving messages from clients (e.g. WebSocket clients)
* @param outboundChannel the channel for sending messages to clients (e.g. WebSocket clients)
* @param brokerChannel the channel for the application to send messages to the broker
* @param destinationPrefixes the broker supported destination prefixes; destinations
* that do not match the given prefix are ignored.
*/
public StompBrokerRelayMessageHandler(SubscribableChannel inboundChannel, MessageChannel outboundChannel,
SubscribableChannel brokerChannel, Collection<String> destinationPrefixes) {
super(inboundChannel, outboundChannel, brokerChannel, destinationPrefixes);
}
/**
* Set the STOMP message broker host.
*/
public void setRelayHost(String relayHost) {
Assert.hasText(relayHost, "relayHost must not be empty");
this.relayHost = relayHost;
}
/**
* Return the STOMP message broker host.
*/
public String getRelayHost() {
return this.relayHost;
}
/**
* Set the STOMP message broker port.
*/
public void setRelayPort(int relayPort) {
this.relayPort = relayPort;
}
/**
* Return the STOMP message broker port.
*/
public int getRelayPort() {
return this.relayPort;
}
/**
* Set the interval, in milliseconds, at which the "system" connection will, in the
* absence of any other data being sent, send a heartbeat to the STOMP broker. A value
* of zero will prevent heartbeats from being sent to the broker.
* <p>The default value is 10000.
* <p>See class-level documentation for more information on the "system" connection.
*/
public void setSystemHeartbeatSendInterval(long systemHeartbeatSendInterval) {
this.systemHeartbeatSendInterval = systemHeartbeatSendInterval;
}
/**
* Return the interval, in milliseconds, at which the "system" connection will
* send heartbeats to the STOMP broker.
*/
public long getSystemHeartbeatSendInterval() {
return this.systemHeartbeatSendInterval;
}
/**
* Set the maximum interval, in milliseconds, at which the "system" connection
* expects, in the absence of any other data, to receive a heartbeat from the STOMP
* broker. A value of zero will configure the connection to expect not to receive
* heartbeats from the broker.
* <p>The default value is 10000.
* <p>See class-level documentation for more information on the "system" connection.
*/
public void setSystemHeartbeatReceiveInterval(long heartbeatReceiveInterval) {
this.systemHeartbeatReceiveInterval = heartbeatReceiveInterval;
}
/**
* Return the interval, in milliseconds, at which the "system" connection expects
* to receive heartbeats from the STOMP broker.
*/
public long getSystemHeartbeatReceiveInterval() {
return this.systemHeartbeatReceiveInterval;
}
/**
* Set the login to use when creating connections to the STOMP broker on
* behalf of connected clients.
* <p>By default this is set to "guest".
* @see #setSystemLogin(String)
*/
public void setClientLogin(String clientLogin) {
Assert.hasText(clientLogin, "clientLogin must not be empty");
this.clientLogin = clientLogin;
}
/**
* Return the configured login to use for connections to the STOMP broker
* on behalf of connected clients.
* @see #getSystemLogin()
*/
public String getClientLogin() {
return this.clientLogin;
}
/**
* Set the client passcode to use to create connections to the STOMP broker on
* behalf of connected clients.
* <p>By default this is set to "guest".
* @see #setSystemPasscode
*/
public void setClientPasscode(String clientPasscode) {
Assert.hasText(clientPasscode, "clientPasscode must not be empty");
this.clientPasscode = clientPasscode;
}
/**
* Return the configured passcode to use for connections to the STOMP broker on
* behalf of connected clients.
* @see #getSystemPasscode()
*/
public String getClientPasscode() {
return this.clientPasscode;
}
/**
* Set the login for the shared "system" connection used to send messages to
* the STOMP broker from within the application, i.e. messages not associated
* with a specific client session (e.g. REST/HTTP request handling method).
* <p>By default this is set to "guest".
*/
public void setSystemLogin(String systemLogin) {
Assert.hasText(systemLogin, "systemLogin must not be empty");
this.systemLogin = systemLogin;
}
/**
* Return the login used for the shared "system" connection to the STOMP broker.
*/
public String getSystemLogin() {
return this.systemLogin;
}
/**
* Set the passcode for the shared "system" connection used to send messages to
* the STOMP broker from within the application, i.e. messages not associated
* with a specific client session (e.g. REST/HTTP request handling method).
* <p>By default this is set to "guest".
*/
public void setSystemPasscode(String systemPasscode) {
this.systemPasscode = systemPasscode;
}
/**
* Return the passcode used for the shared "system" connection to the STOMP broker.
*/
public String getSystemPasscode() {
return this.systemPasscode;
}
/**
* Configure one more destinations to subscribe to on the shared "system"
* connection along with MessageHandler's to handle received messages.
* <p>This is for internal use in a multi-application server scenario where
* servers forward messages to each other (e.g. unresolved user destinations).
* @param subscriptions the destinations to subscribe to.
*/
public void setSystemSubscriptions(Map<String, MessageHandler> subscriptions) {
this.systemSubscriptions.clear();
if (subscriptions != null) {
this.systemSubscriptions.putAll(subscriptions);
}
}
/**
* Return the configured map with subscriptions on the "system" connection.
*/
public Map<String, MessageHandler> getSystemSubscriptions() {
return this.systemSubscriptions;
}
/**
* Set the value of the "host" header to use in STOMP CONNECT frames. When this
* property is configured, a "host" header will be added to every STOMP frame sent to
* the STOMP broker. This may be useful for example in a cloud environment where the
* actual host to which the TCP connection is established is different from the host
* providing the cloud-based STOMP service.
* <p>By default this property is not set.
*/
public void setVirtualHost(String virtualHost) {
this.virtualHost = virtualHost;
}
/**
* Return the configured virtual host value.
*/
public String getVirtualHost() {
return this.virtualHost;
}
/**
* Configure a TCP client for managing TCP connections to the STOMP broker.
* By default {@link Reactor2TcpClient} is used.
*/
public void setTcpClient(TcpOperations<byte[]> tcpClient) {
this.tcpClient = tcpClient;
}
/**
* Get the configured TCP client. Never {@code null} unless not configured
* invoked and this method is invoked before the handler is started and
* hence a default implementation initialized.
*/
public TcpOperations<byte[]> getTcpClient() {
return this.tcpClient;
}
/**
* Return the current count of TCP connection to the broker.
*/
public int getConnectionCount() {
return this.connectionHandlers.size();
}
/**
* Configure a {@link MessageHeaderInitializer} to apply to the headers of all
* messages created through the {@code StompBrokerRelayMessageHandler} that
* are sent to the client outbound message channel.
* <p>By default this property is not set.
*/
public void setHeaderInitializer(MessageHeaderInitializer headerInitializer) {
this.headerInitializer = headerInitializer;
}
/**
* Return the configured header initializer.
*/
public MessageHeaderInitializer getHeaderInitializer() {
return this.headerInitializer;
}
/**
* Return a String describing internal state and counters.
*/
public String getStatsInfo() {
return this.stats.toString();
}
@Override
protected void startInternal() {
if (this.tcpClient == null) {
StompDecoder decoder = new StompDecoder();
decoder.setHeaderInitializer(getHeaderInitializer());
Reactor2StompCodec codec = new Reactor2StompCodec(new StompEncoder(), decoder);
this.tcpClient = new StompTcpClientFactory().create(this.relayHost, this.relayPort, codec);
}
if (logger.isInfoEnabled()) {
logger.info("Connecting \"system\" session to " + this.relayHost + ":" + this.relayPort);
}
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECT);
accessor.setAcceptVersion("1.1,1.2");
accessor.setLogin(this.systemLogin);
accessor.setPasscode(this.systemPasscode);
accessor.setHeartbeat(this.systemHeartbeatSendInterval, this.systemHeartbeatReceiveInterval);
accessor.setHost(getVirtualHost());
accessor.setSessionId(SYSTEM_SESSION_ID);
if (logger.isDebugEnabled()) {
logger.debug("Forwarding " + accessor.getShortLogMessage(EMPTY_PAYLOAD));
}
SystemStompConnectionHandler handler = new SystemStompConnectionHandler(accessor);
this.connectionHandlers.put(handler.getSessionId(), handler);
this.stats.incrementConnectCount();
this.tcpClient.connect(handler, new FixedIntervalReconnectStrategy(5000));
}
@Override
protected void stopInternal() {
publishBrokerUnavailableEvent();
try {
this.tcpClient.shutdown().get(5000, TimeUnit.MILLISECONDS);
}
catch (Throwable ex) {
logger.error("Error in shutdown of TCP client", ex);
}
}
@Override
protected void handleMessageInternal(Message<?> message) {
String sessionId = SimpMessageHeaderAccessor.getSessionId(message.getHeaders());
if (!isBrokerAvailable()) {
if (sessionId == null || SYSTEM_SESSION_ID.equals(sessionId)) {
throw new MessageDeliveryException("Message broker not active. Consider subscribing to " +
"receive BrokerAvailabilityEvent's from an ApplicationListener Spring bean.");
}
StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
if (handler != null) {
handler.sendStompErrorFrameToClient("Broker not available.");
handler.clearConnection();
}
else {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
if (getHeaderInitializer() != null) {
getHeaderInitializer().initHeaders(accessor);
}
accessor.setSessionId(sessionId);
accessor.setUser(SimpMessageHeaderAccessor.getUser(message.getHeaders()));
accessor.setMessage("Broker not available.");
MessageHeaders headers = accessor.getMessageHeaders();
getClientOutboundChannel().send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers));
}
return;
}
StompHeaderAccessor stompAccessor;
StompCommand command;
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
if (accessor == null) {
throw new IllegalStateException(
"No header accessor (not using the SimpMessagingTemplate?): " + message);
}
else if (accessor instanceof StompHeaderAccessor) {
stompAccessor = (StompHeaderAccessor) accessor;
command = stompAccessor.getCommand();
}
else if (accessor instanceof SimpMessageHeaderAccessor) {
stompAccessor = StompHeaderAccessor.wrap(message);
command = stompAccessor.getCommand();
if (command == null) {
command = stompAccessor.updateStompCommandAsClientMessage();
}
}
else {
throw new IllegalStateException(
"Unexpected header accessor type " + accessor.getClass() + " in " + message);
}
if (sessionId == null) {
if (!SimpMessageType.MESSAGE.equals(stompAccessor.getMessageType())) {
if (logger.isErrorEnabled()) {
logger.error("Only STOMP SEND supported from within the server side. Ignoring " + message);
}
return;
}
sessionId = SYSTEM_SESSION_ID;
stompAccessor.setSessionId(sessionId);
}
String destination = stompAccessor.getDestination();
if (command != null && command.requiresDestination() && !checkDestinationPrefix(destination)) {
return;
}
if (StompCommand.CONNECT.equals(command)) {
if (logger.isDebugEnabled()) {
logger.debug(stompAccessor.getShortLogMessage(EMPTY_PAYLOAD));
}
stompAccessor = (stompAccessor.isMutable() ? stompAccessor : StompHeaderAccessor.wrap(message));
stompAccessor.setLogin(this.clientLogin);
stompAccessor.setPasscode(this.clientPasscode);
if (getVirtualHost() != null) {
stompAccessor.setHost(getVirtualHost());
}
StompConnectionHandler handler = new StompConnectionHandler(sessionId, stompAccessor);
this.connectionHandlers.put(sessionId, handler);
this.stats.incrementConnectCount();
this.tcpClient.connect(handler);
}
else if (StompCommand.DISCONNECT.equals(command)) {
StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
if (handler == null) {
if (logger.isDebugEnabled()) {
logger.debug("Ignoring DISCONNECT in session " + sessionId + ". Connection already cleaned up.");
}
return;
}
stats.incrementDisconnectCount();
handler.forward(message, stompAccessor);
}
else {
StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
if (handler == null) {
if (logger.isDebugEnabled()) {
logger.debug("No TCP connection for session " + sessionId + " in " + message);
}
return;
}
handler.forward(message, stompAccessor);
}
}
@Override
public String toString() {
return "StompBrokerRelay[" + this.relayHost + ":" + this.relayPort + "]";
}
private class StompConnectionHandler implements TcpConnectionHandler<byte[]> {
private final String sessionId;
private final boolean isRemoteClientSession;
private final StompHeaderAccessor connectHeaders;
private volatile TcpConnection<byte[]> tcpConnection;
private volatile boolean isStompConnected;
private StompConnectionHandler(String sessionId, StompHeaderAccessor connectHeaders) {
this(sessionId, connectHeaders, true);
}
private StompConnectionHandler(String sessionId, StompHeaderAccessor connectHeaders, boolean isClientSession) {
Assert.notNull(sessionId, "'sessionId' must not be null");
Assert.notNull(connectHeaders, "'connectHeaders' must not be null");
this.sessionId = sessionId;
this.connectHeaders = connectHeaders;
this.isRemoteClientSession = isClientSession;
}
public String getSessionId() {
return this.sessionId;
}
protected TcpConnection<byte[]> getTcpConnection() {
return this.tcpConnection;
}
@Override
public void afterConnected(TcpConnection<byte[]> connection) {
if (logger.isDebugEnabled()) {
logger.debug("TCP connection opened in session=" + getSessionId());
}
this.tcpConnection = connection;
this.tcpConnection.onReadInactivity(new Runnable() {
@Override
public void run() {
if (tcpConnection != null && !isStompConnected) {
handleTcpConnectionFailure("No CONNECTED frame received in " +
MAX_TIME_TO_CONNECTED_FRAME + " ms.", null);
}
}
}, MAX_TIME_TO_CONNECTED_FRAME);
connection.send(MessageBuilder.createMessage(EMPTY_PAYLOAD, this.connectHeaders.getMessageHeaders()));
}
@Override
public void afterConnectFailure(Throwable ex) {
handleTcpConnectionFailure("Failed to connect: " + ex.getMessage(), ex);
}
/**
* Invoked when any TCP connectivity issue is detected, i.e. failure to establish
* the TCP connection, failure to send a message, missed heartbeat, etc.
*/
protected void handleTcpConnectionFailure(String error, Throwable ex) {
if (logger.isErrorEnabled()) {
logger.error("TCP connection failure in session " + this.sessionId + ": " + error, ex);
}
try {
sendStompErrorFrameToClient(error);
}
finally {
try {
clearConnection();
}
catch (Throwable ex2) {
if (logger.isDebugEnabled()) {
logger.debug("Failure while clearing TCP connection state in session " + this.sessionId, ex2);
}
}
}
}
private void sendStompErrorFrameToClient(String errorText) {
if (this.isRemoteClientSession) {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
if (getHeaderInitializer() != null) {
getHeaderInitializer().initHeaders(headerAccessor);
}
headerAccessor.setSessionId(this.sessionId);
headerAccessor.setUser(this.connectHeaders.getUser());
headerAccessor.setMessage(errorText);
Message<?> errorMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, headerAccessor.getMessageHeaders());
handleInboundMessage(errorMessage);
}
}
protected void handleInboundMessage(Message<?> message) {
if (this.isRemoteClientSession) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
accessor.setImmutable();
StompBrokerRelayMessageHandler.this.getClientOutboundChannel().send(message);
}
}
@Override
public void handleMessage(Message<byte[]> message) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
accessor.setSessionId(this.sessionId);
accessor.setUser(this.connectHeaders.getUser());
StompCommand command = accessor.getCommand();
if (StompCommand.CONNECTED.equals(command)) {
if (logger.isDebugEnabled()) {
logger.debug("Received " + accessor.getShortLogMessage(EMPTY_PAYLOAD));
}
afterStompConnected(accessor);
}
else if (logger.isErrorEnabled() && StompCommand.ERROR.equals(command)) {
logger.error("Received " + accessor.getShortLogMessage(message.getPayload()));
}
else if (logger.isTraceEnabled()) {
logger.trace("Received " + accessor.getDetailedLogMessage(message.getPayload()));
}
handleInboundMessage(message);
}
/**
* Invoked after the STOMP CONNECTED frame is received. At this point the
* connection is ready for sending STOMP messages to the broker.
*/
protected void afterStompConnected(StompHeaderAccessor connectedHeaders) {
this.isStompConnected = true;
stats.incrementConnectedCount();
initHeartbeats(connectedHeaders);
}
private void initHeartbeats(StompHeaderAccessor connectedHeaders) {
if (this.isRemoteClientSession) {
return;
}
long clientSendInterval = this.connectHeaders.getHeartbeat()[0];
long clientReceiveInterval = this.connectHeaders.getHeartbeat()[1];
long serverSendInterval = connectedHeaders.getHeartbeat()[0];
long serverReceiveInterval = connectedHeaders.getHeartbeat()[1];
if (clientSendInterval > 0 && serverReceiveInterval > 0) {
long interval = Math.max(clientSendInterval, serverReceiveInterval);
this.tcpConnection.onWriteInactivity(new Runnable() {
@Override
public void run() {
TcpConnection<byte[]> conn = tcpConnection;
if (conn != null) {
conn.send(HEARTBEAT_MESSAGE).addCallback(
new ListenableFutureCallback<Void>() {
public void onSuccess(Void result) {
}
public void onFailure(Throwable ex) {
handleTcpConnectionFailure(
"Failed to forward heartbeat: " + ex.getMessage(), ex);
}
});
}
}
}, interval);
}
if (clientReceiveInterval > 0 && serverSendInterval > 0) {
final long interval = Math.max(clientReceiveInterval, serverSendInterval) * HEARTBEAT_MULTIPLIER;
this.tcpConnection.onReadInactivity(new Runnable() {
@Override
public void run() {
handleTcpConnectionFailure("No messages received in " + interval + " ms.", null);
}
}, interval);
}
}
@Override
public void handleFailure(Throwable ex) {
if (this.tcpConnection != null) {
handleTcpConnectionFailure("Transport failure: " + ex.getMessage(), ex);
}
else if (logger.isErrorEnabled()) {
logger.error("Transport failure: " + ex);
}
}
@Override
public void afterConnectionClosed() {
if (this.tcpConnection == null) {
return;
}
try {
if (logger.isDebugEnabled()) {
logger.debug("TCP connection to broker closed in session " + this.sessionId);
}
sendStompErrorFrameToClient("Connection to broker closed.");
}
finally {
try {
// Prevent clearConnection() from trying to close
this.tcpConnection = null;
clearConnection();
}
catch (Throwable ex) {
// Shouldn't happen with connection reset beforehand
}
}
}
/**
* Forward the given message to the STOMP broker.
* <p>The method checks whether we have an active TCP connection and have
* received the STOMP CONNECTED frame. For client messages this should be
* false only if we lose the TCP connection around the same time when a
* client message is being forwarded, so we simply log the ignored message
* at debug level. For messages from within the application being sent on
* the "system" connection an exception is raised so that components sending
* the message have a chance to handle it -- by default the broker message
* channel is synchronous.
* <p>Note that if messages arrive concurrently around the same time a TCP
* connection is lost, there is a brief period of time before the connection
* is reset when one or more messages may sneak through and an attempt made
* to forward them. Rather than synchronizing to guard against that, this
* method simply lets them try and fail. For client sessions that may
* result in an additional STOMP ERROR frame(s) being sent downstream but
* code handling that downstream should be idempotent in such cases.
* @param message the message to send (never {@code null})
* @return a future to wait for the result
*/
@SuppressWarnings("unchecked")
public ListenableFuture<Void> forward(final Message<?> message, final StompHeaderAccessor accessor) {
TcpConnection<byte[]> conn = this.tcpConnection;
if (!this.isStompConnected || conn == null) {
if (this.isRemoteClientSession) {
if (logger.isDebugEnabled()) {
logger.debug("TCP connection closed already, ignoring " +
accessor.getShortLogMessage(message.getPayload()));
}
return EMPTY_TASK;
}
else {
throw new IllegalStateException("Cannot forward messages " +
(conn != null ? "before STOMP CONNECTED. " : "while inactive. ") +
"Consider subscribing to receive BrokerAvailabilityEvent's from " +
"an ApplicationListener Spring bean. Dropped " +
accessor.getShortLogMessage(message.getPayload()));
}
}
final Message<?> messageToSend = (accessor.isMutable() && accessor.isModified()) ?
MessageBuilder.createMessage(message.getPayload(), accessor.getMessageHeaders()) : message;
StompCommand command = accessor.getCommand();
if (logger.isDebugEnabled() && (StompCommand.SEND.equals(command) || StompCommand.SUBSCRIBE.equals(command) ||
StompCommand.UNSUBSCRIBE.equals(command) || StompCommand.DISCONNECT.equals(command))) {
logger.debug("Forwarding " + accessor.getShortLogMessage(message.getPayload()));
}
else if (logger.isTraceEnabled()) {
logger.trace("Forwarding " + accessor.getDetailedLogMessage(message.getPayload()));
}
ListenableFuture<Void> future = conn.send((Message<byte[]>) messageToSend);
future.addCallback(new ListenableFutureCallback<Void>() {
@Override
public void onSuccess(Void result) {
if (accessor.getCommand() == StompCommand.DISCONNECT) {
afterDisconnectSent(accessor);
}
}
@Override
public void onFailure(Throwable ex) {
if (tcpConnection != null) {
handleTcpConnectionFailure("failed to forward " +
accessor.getShortLogMessage(message.getPayload()), ex);
}
else if (logger.isErrorEnabled()) {
logger.error("Failed to forward " + accessor.getShortLogMessage(message.getPayload()));
}
}
});
return future;
}
/**
* After a DISCONNECT there should be no more client frames so we can
* close the connection pro-actively. However, if the DISCONNECT has a
* receipt header we leave the connection open and expect the server will
* respond with a RECEIPT and then close the connection.
* @see <a href="http://stomp.github.io/stomp-specification-1.2.html#DISCONNECT">
* STOMP Specification 1.2 DISCONNECT</a>
*/
private void afterDisconnectSent(StompHeaderAccessor accessor) {
if (accessor.getReceipt() == null) {
try {
clearConnection();
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failure while clearing TCP connection state in session " + this.sessionId, ex);
}
}
}
}
/**
* Clean up state associated with the connection and close it.
* Any exception arising from closing the connection are propagated.
*/
public void clearConnection() {
if (logger.isDebugEnabled()) {
logger.debug("Cleaning up connection state for session " + this.sessionId);
}
if (this.isRemoteClientSession) {
StompBrokerRelayMessageHandler.this.connectionHandlers.remove(this.sessionId);
}
this.isStompConnected = false;
TcpConnection<byte[]> conn = this.tcpConnection;
this.tcpConnection = null;
if (conn != null) {
if (logger.isDebugEnabled()) {
logger.debug("Closing TCP connection in session " + this.sessionId);
}
conn.close();
}
}
@Override
public String toString() {
return "StompConnectionHandler[sessionId=" + this.sessionId + "]";
}
}
private class SystemStompConnectionHandler extends StompConnectionHandler {
public SystemStompConnectionHandler(StompHeaderAccessor connectHeaders) {
super(SYSTEM_SESSION_ID, connectHeaders, false);
}
@Override
protected void afterStompConnected(StompHeaderAccessor connectedHeaders) {
if (logger.isInfoEnabled()) {
logger.info("\"System\" session connected.");
}
super.afterStompConnected(connectedHeaders);
publishBrokerAvailableEvent();
sendSystemSubscriptions();
}
private void sendSystemSubscriptions() {
int i = 0;
for (String destination : getSystemSubscriptions().keySet()) {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
accessor.setSubscriptionId(String.valueOf(i++));
accessor.setDestination(destination);
if (logger.isDebugEnabled()) {
logger.debug("Subscribing to " + destination + " on \"system\" connection.");
}
TcpConnection<byte[]> conn = getTcpConnection();
if (conn != null) {
MessageHeaders headers = accessor.getMessageHeaders();
conn.send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers)).addCallback(
new ListenableFutureCallback<Void>() {
public void onSuccess(Void result) {
}
public void onFailure(Throwable ex) {
String error = "Failed to subscribe in \"system\" session.";
handleTcpConnectionFailure(error, ex);
}
});
}
}
}
@Override
protected void handleInboundMessage(Message<?> message) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (StompCommand.MESSAGE.equals(accessor.getCommand())) {
String destination = accessor.getDestination();
if (destination == null) {
if (logger.isDebugEnabled()) {
logger.debug("Got message on \"system\" connection, with no destination: " +
accessor.getDetailedLogMessage(message.getPayload()));
}
return;
}
if (!getSystemSubscriptions().containsKey(destination)) {
if (logger.isDebugEnabled()) {
logger.debug("Got message on \"system\" connection with no handler: " +
accessor.getDetailedLogMessage(message.getPayload()));
}
return;
}
try {
MessageHandler handler = getSystemSubscriptions().get(destination);
handler.handleMessage(message);
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Error while handling message on \"system\" connection.", ex);
}
}
}
}
@Override
protected void handleTcpConnectionFailure(String errorMessage, Throwable ex) {
super.handleTcpConnectionFailure(errorMessage, ex);
publishBrokerUnavailableEvent();
}
@Override
public void afterConnectionClosed() {
super.afterConnectionClosed();
publishBrokerUnavailableEvent();
}
@Override
public ListenableFuture<Void> forward(Message<?> message, StompHeaderAccessor accessor) {
try {
ListenableFuture<Void> future = super.forward(message, accessor);
if (message.getHeaders().get(SimpMessageHeaderAccessor.IGNORE_ERROR) == null) {
future.get();
}
return future;
}
catch (Throwable ex) {
throw new MessageDeliveryException(message, ex);
}
}
}
private static class StompTcpClientFactory {
public TcpOperations<byte[]> create(String relayHost, int relayPort, Reactor2StompCodec codec) {
return new Reactor2TcpClient<>(relayHost, relayPort, codec);
}
}
private static class VoidCallable implements Callable<Void> {
@Override
public Void call() throws Exception {
return null;
}
}
private class Stats {
private final AtomicInteger connect = new AtomicInteger();
private final AtomicInteger connected = new AtomicInteger();
private final AtomicInteger disconnect = new AtomicInteger();
public void incrementConnectCount() {
this.connect.incrementAndGet();
}
public void incrementConnectedCount() {
this.connected.incrementAndGet();
}
public void incrementDisconnectCount() {
this.disconnect.incrementAndGet();
}
public String toString() {
return connectionHandlers.size() + " sessions, " + relayHost + ":" + relayPort +
(isBrokerAvailable() ? " (available)" : " (not available)") +
", processed CONNECT(" + this.connect.get() + ")-CONNECTED(" +
this.connected.get() + ")-DISCONNECT(" + this.disconnect.get() + ")";
}
}
}
| spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java | /*
* Copyright 2002-2016 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.messaging.simp.stomp;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.broker.AbstractBrokerMessageHandler;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.support.MessageHeaderInitializer;
import org.springframework.messaging.tcp.FixedIntervalReconnectStrategy;
import org.springframework.messaging.tcp.TcpConnection;
import org.springframework.messaging.tcp.TcpConnectionHandler;
import org.springframework.messaging.tcp.TcpOperations;
import org.springframework.messaging.tcp.reactor.Reactor2TcpClient;
import org.springframework.util.Assert;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.util.concurrent.ListenableFutureTask;
/**
* A {@link org.springframework.messaging.MessageHandler} that handles messages by
* forwarding them to a STOMP broker.
*
* <p>For each new {@link SimpMessageType#CONNECT CONNECT} message, an independent TCP
* connection to the broker is opened and used exclusively for all messages from the
* client that originated the CONNECT message. Messages from the same client are
* identified through the session id message header. Reversely, when the STOMP broker
* sends messages back on the TCP connection, those messages are enriched with the session
* id of the client and sent back downstream through the {@link MessageChannel} provided
* to the constructor.
*
* <p>This class also automatically opens a default "system" TCP connection to the message
* broker that is used for sending messages that originate from the server application (as
* opposed to from a client). Such messages are not associated with any client and
* therefore do not have a session id header. The "system" connection is effectively
* shared and cannot be used to receive messages. Several properties are provided to
* configure the "system" connection including:
* <ul>
* <li>{@link #setSystemLogin(String)}</li>
* <li>{@link #setSystemPasscode(String)}</li>
* <li>{@link #setSystemHeartbeatSendInterval(long)}</li>
* <li>{@link #setSystemHeartbeatReceiveInterval(long)}</li>
* </ul>
*
* @author Rossen Stoyanchev
* @author Andy Wilkinson
* @since 4.0
*/
public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler {
public static final String SYSTEM_SESSION_ID = "_system_";
private static final byte[] EMPTY_PAYLOAD = new byte[0];
private static final ListenableFutureTask<Void> EMPTY_TASK = new ListenableFutureTask<>(new VoidCallable());
// STOMP recommends error of margin for receiving heartbeats
private static final long HEARTBEAT_MULTIPLIER = 3;
private static final Message<byte[]> HEARTBEAT_MESSAGE;
/**
* A heartbeat is setup once a CONNECTED frame is received which contains
* the heartbeat settings we need. If we don't receive CONNECTED within
* a minute, the connection is closed proactively.
*/
private static final int MAX_TIME_TO_CONNECTED_FRAME = 60 * 1000;
static {
EMPTY_TASK.run();
StompHeaderAccessor accessor = StompHeaderAccessor.createForHeartbeat();
HEARTBEAT_MESSAGE = MessageBuilder.createMessage(StompDecoder.HEARTBEAT_PAYLOAD, accessor.getMessageHeaders());
}
private String relayHost = "127.0.0.1";
private int relayPort = 61613;
private String clientLogin = "guest";
private String clientPasscode = "guest";
private String systemLogin = "guest";
private String systemPasscode = "guest";
private long systemHeartbeatSendInterval = 10000;
private long systemHeartbeatReceiveInterval = 10000;
private String virtualHost;
private final Map<String, MessageHandler> systemSubscriptions = new HashMap<>(4);
private TcpOperations<byte[]> tcpClient;
private MessageHeaderInitializer headerInitializer;
private final Map<String, StompConnectionHandler> connectionHandlers =
new ConcurrentHashMap<>();
private final Stats stats = new Stats();
/**
* Create a StompBrokerRelayMessageHandler instance with the given message channels
* and destination prefixes.
* @param inboundChannel the channel for receiving messages from clients (e.g. WebSocket clients)
* @param outboundChannel the channel for sending messages to clients (e.g. WebSocket clients)
* @param brokerChannel the channel for the application to send messages to the broker
* @param destinationPrefixes the broker supported destination prefixes; destinations
* that do not match the given prefix are ignored.
*/
public StompBrokerRelayMessageHandler(SubscribableChannel inboundChannel, MessageChannel outboundChannel,
SubscribableChannel brokerChannel, Collection<String> destinationPrefixes) {
super(inboundChannel, outboundChannel, brokerChannel, destinationPrefixes);
}
/**
* Set the STOMP message broker host.
*/
public void setRelayHost(String relayHost) {
Assert.hasText(relayHost, "relayHost must not be empty");
this.relayHost = relayHost;
}
/**
* Return the STOMP message broker host.
*/
public String getRelayHost() {
return this.relayHost;
}
/**
* Set the STOMP message broker port.
*/
public void setRelayPort(int relayPort) {
this.relayPort = relayPort;
}
/**
* Return the STOMP message broker port.
*/
public int getRelayPort() {
return this.relayPort;
}
/**
* Set the interval, in milliseconds, at which the "system" connection will, in the
* absence of any other data being sent, send a heartbeat to the STOMP broker. A value
* of zero will prevent heartbeats from being sent to the broker.
* <p>The default value is 10000.
* <p>See class-level documentation for more information on the "system" connection.
*/
public void setSystemHeartbeatSendInterval(long systemHeartbeatSendInterval) {
this.systemHeartbeatSendInterval = systemHeartbeatSendInterval;
}
/**
* Return the interval, in milliseconds, at which the "system" connection will
* send heartbeats to the STOMP broker.
*/
public long getSystemHeartbeatSendInterval() {
return this.systemHeartbeatSendInterval;
}
/**
* Set the maximum interval, in milliseconds, at which the "system" connection
* expects, in the absence of any other data, to receive a heartbeat from the STOMP
* broker. A value of zero will configure the connection to expect not to receive
* heartbeats from the broker.
* <p>The default value is 10000.
* <p>See class-level documentation for more information on the "system" connection.
*/
public void setSystemHeartbeatReceiveInterval(long heartbeatReceiveInterval) {
this.systemHeartbeatReceiveInterval = heartbeatReceiveInterval;
}
/**
* Return the interval, in milliseconds, at which the "system" connection expects
* to receive heartbeats from the STOMP broker.
*/
public long getSystemHeartbeatReceiveInterval() {
return this.systemHeartbeatReceiveInterval;
}
/**
* Set the login to use when creating connections to the STOMP broker on
* behalf of connected clients.
* <p>By default this is set to "guest".
* @see #setSystemLogin(String)
*/
public void setClientLogin(String clientLogin) {
Assert.hasText(clientLogin, "clientLogin must not be empty");
this.clientLogin = clientLogin;
}
/**
* Return the configured login to use for connections to the STOMP broker
* on behalf of connected clients.
* @see #getSystemLogin()
*/
public String getClientLogin() {
return this.clientLogin;
}
/**
* Set the client passcode to use to create connections to the STOMP broker on
* behalf of connected clients.
* <p>By default this is set to "guest".
* @see #setSystemPasscode
*/
public void setClientPasscode(String clientPasscode) {
Assert.hasText(clientPasscode, "clientPasscode must not be empty");
this.clientPasscode = clientPasscode;
}
/**
* Return the configured passcode to use for connections to the STOMP broker on
* behalf of connected clients.
* @see #getSystemPasscode()
*/
public String getClientPasscode() {
return this.clientPasscode;
}
/**
* Set the login for the shared "system" connection used to send messages to
* the STOMP broker from within the application, i.e. messages not associated
* with a specific client session (e.g. REST/HTTP request handling method).
* <p>By default this is set to "guest".
*/
public void setSystemLogin(String systemLogin) {
Assert.hasText(systemLogin, "systemLogin must not be empty");
this.systemLogin = systemLogin;
}
/**
* Return the login used for the shared "system" connection to the STOMP broker.
*/
public String getSystemLogin() {
return this.systemLogin;
}
/**
* Set the passcode for the shared "system" connection used to send messages to
* the STOMP broker from within the application, i.e. messages not associated
* with a specific client session (e.g. REST/HTTP request handling method).
* <p>By default this is set to "guest".
*/
public void setSystemPasscode(String systemPasscode) {
this.systemPasscode = systemPasscode;
}
/**
* Return the passcode used for the shared "system" connection to the STOMP broker.
*/
public String getSystemPasscode() {
return this.systemPasscode;
}
/**
* Configure one more destinations to subscribe to on the shared "system"
* connection along with MessageHandler's to handle received messages.
* <p>This is for internal use in a multi-application server scenario where
* servers forward messages to each other (e.g. unresolved user destinations).
* @param subscriptions the destinations to subscribe to.
*/
public void setSystemSubscriptions(Map<String, MessageHandler> subscriptions) {
this.systemSubscriptions.clear();
if (subscriptions != null) {
this.systemSubscriptions.putAll(subscriptions);
}
}
/**
* Return the configured map with subscriptions on the "system" connection.
*/
public Map<String, MessageHandler> getSystemSubscriptions() {
return this.systemSubscriptions;
}
/**
* Set the value of the "host" header to use in STOMP CONNECT frames. When this
* property is configured, a "host" header will be added to every STOMP frame sent to
* the STOMP broker. This may be useful for example in a cloud environment where the
* actual host to which the TCP connection is established is different from the host
* providing the cloud-based STOMP service.
* <p>By default this property is not set.
*/
public void setVirtualHost(String virtualHost) {
this.virtualHost = virtualHost;
}
/**
* Return the configured virtual host value.
*/
public String getVirtualHost() {
return this.virtualHost;
}
/**
* Configure a TCP client for managing TCP connections to the STOMP broker.
* By default {@link Reactor2TcpClient} is used.
*/
public void setTcpClient(TcpOperations<byte[]> tcpClient) {
this.tcpClient = tcpClient;
}
/**
* Get the configured TCP client. Never {@code null} unless not configured
* invoked and this method is invoked before the handler is started and
* hence a default implementation initialized.
*/
public TcpOperations<byte[]> getTcpClient() {
return this.tcpClient;
}
/**
* Return the current count of TCP connection to the broker.
*/
public int getConnectionCount() {
return this.connectionHandlers.size();
}
/**
* Configure a {@link MessageHeaderInitializer} to apply to the headers of all
* messages created through the {@code StompBrokerRelayMessageHandler} that
* are sent to the client outbound message channel.
* <p>By default this property is not set.
*/
public void setHeaderInitializer(MessageHeaderInitializer headerInitializer) {
this.headerInitializer = headerInitializer;
}
/**
* Return the configured header initializer.
*/
public MessageHeaderInitializer getHeaderInitializer() {
return this.headerInitializer;
}
/**
* Return a String describing internal state and counters.
*/
public String getStatsInfo() {
return this.stats.toString();
}
@Override
protected void startInternal() {
if (this.tcpClient == null) {
StompDecoder decoder = new StompDecoder();
decoder.setHeaderInitializer(getHeaderInitializer());
Reactor2StompCodec codec = new Reactor2StompCodec(new StompEncoder(), decoder);
this.tcpClient = new StompTcpClientFactory().create(this.relayHost, this.relayPort, codec);
}
if (logger.isInfoEnabled()) {
logger.info("Connecting \"system\" session to " + this.relayHost + ":" + this.relayPort);
}
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECT);
accessor.setAcceptVersion("1.1,1.2");
accessor.setLogin(this.systemLogin);
accessor.setPasscode(this.systemPasscode);
accessor.setHeartbeat(this.systemHeartbeatSendInterval, this.systemHeartbeatReceiveInterval);
accessor.setHost(getVirtualHost());
accessor.setSessionId(SYSTEM_SESSION_ID);
if (logger.isDebugEnabled()) {
logger.debug("Forwarding " + accessor.getShortLogMessage(EMPTY_PAYLOAD));
}
SystemStompConnectionHandler handler = new SystemStompConnectionHandler(accessor);
this.connectionHandlers.put(handler.getSessionId(), handler);
this.stats.incrementConnectCount();
this.tcpClient.connect(handler, new FixedIntervalReconnectStrategy(5000));
}
@Override
protected void stopInternal() {
publishBrokerUnavailableEvent();
try {
this.tcpClient.shutdown().get(5000, TimeUnit.MILLISECONDS);
}
catch (Throwable ex) {
logger.error("Error in shutdown of TCP client", ex);
}
}
@Override
protected void handleMessageInternal(Message<?> message) {
String sessionId = SimpMessageHeaderAccessor.getSessionId(message.getHeaders());
if (!isBrokerAvailable()) {
if (sessionId == null || SYSTEM_SESSION_ID.equals(sessionId)) {
throw new MessageDeliveryException("Message broker not active. Consider subscribing to " +
"receive BrokerAvailabilityEvent's from an ApplicationListener Spring bean.");
}
StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
if (handler != null) {
handler.sendStompErrorFrameToClient("Broker not available.");
handler.clearConnection();
}
else {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
if (getHeaderInitializer() != null) {
getHeaderInitializer().initHeaders(accessor);
}
accessor.setSessionId(sessionId);
accessor.setUser(SimpMessageHeaderAccessor.getUser(message.getHeaders()));
accessor.setMessage("Broker not available.");
MessageHeaders headers = accessor.getMessageHeaders();
getClientOutboundChannel().send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers));
}
return;
}
StompHeaderAccessor stompAccessor;
StompCommand command;
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
if (accessor == null) {
throw new IllegalStateException(
"No header accessor (not using the SimpMessagingTemplate?): " + message);
}
else if (accessor instanceof StompHeaderAccessor) {
stompAccessor = (StompHeaderAccessor) accessor;
command = stompAccessor.getCommand();
}
else if (accessor instanceof SimpMessageHeaderAccessor) {
stompAccessor = StompHeaderAccessor.wrap(message);
command = stompAccessor.getCommand();
if (command == null) {
command = stompAccessor.updateStompCommandAsClientMessage();
}
}
else {
throw new IllegalStateException(
"Unexpected header accessor type " + accessor.getClass() + " in " + message);
}
if (sessionId == null) {
if (!SimpMessageType.MESSAGE.equals(stompAccessor.getMessageType())) {
if (logger.isErrorEnabled()) {
logger.error("Only STOMP SEND supported from within the server side. Ignoring " + message);
}
return;
}
sessionId = SYSTEM_SESSION_ID;
stompAccessor.setSessionId(sessionId);
}
String destination = stompAccessor.getDestination();
if (command != null && command.requiresDestination() && !checkDestinationPrefix(destination)) {
return;
}
if (StompCommand.CONNECT.equals(command)) {
if (logger.isDebugEnabled()) {
logger.debug(stompAccessor.getShortLogMessage(EMPTY_PAYLOAD));
}
stompAccessor = (stompAccessor.isMutable() ? stompAccessor : StompHeaderAccessor.wrap(message));
stompAccessor.setLogin(this.clientLogin);
stompAccessor.setPasscode(this.clientPasscode);
if (getVirtualHost() != null) {
stompAccessor.setHost(getVirtualHost());
}
StompConnectionHandler handler = new StompConnectionHandler(sessionId, stompAccessor);
this.connectionHandlers.put(sessionId, handler);
this.stats.incrementConnectCount();
this.tcpClient.connect(handler);
}
else if (StompCommand.DISCONNECT.equals(command)) {
StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
if (handler == null) {
if (logger.isDebugEnabled()) {
logger.debug("Ignoring DISCONNECT in session " + sessionId + ". Connection already cleaned up.");
}
return;
}
stats.incrementDisconnectCount();
handler.forward(message, stompAccessor);
}
else {
StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
if (handler == null) {
if (logger.isDebugEnabled()) {
logger.debug("No TCP connection for session " + sessionId + " in " + message);
}
return;
}
handler.forward(message, stompAccessor);
}
}
@Override
public String toString() {
return "StompBrokerRelay[" + this.relayHost + ":" + this.relayPort + "]";
}
private class StompConnectionHandler implements TcpConnectionHandler<byte[]> {
private final String sessionId;
private final boolean isRemoteClientSession;
private final StompHeaderAccessor connectHeaders;
private volatile TcpConnection<byte[]> tcpConnection;
private volatile boolean isStompConnected;
private StompConnectionHandler(String sessionId, StompHeaderAccessor connectHeaders) {
this(sessionId, connectHeaders, true);
}
private StompConnectionHandler(String sessionId, StompHeaderAccessor connectHeaders, boolean isClientSession) {
Assert.notNull(sessionId, "'sessionId' must not be null");
Assert.notNull(connectHeaders, "'connectHeaders' must not be null");
this.sessionId = sessionId;
this.connectHeaders = connectHeaders;
this.isRemoteClientSession = isClientSession;
}
public String getSessionId() {
return this.sessionId;
}
protected TcpConnection<byte[]> getTcpConnection() {
return this.tcpConnection;
}
@Override
public void afterConnected(TcpConnection<byte[]> connection) {
if (logger.isDebugEnabled()) {
logger.debug("TCP connection opened in session=" + getSessionId());
}
this.tcpConnection = connection;
this.tcpConnection.onReadInactivity(new Runnable() {
@Override
public void run() {
if (tcpConnection != null && !isStompConnected) {
handleTcpConnectionFailure("No CONNECTED frame received in " +
MAX_TIME_TO_CONNECTED_FRAME + " ms.", null);
}
}
}, MAX_TIME_TO_CONNECTED_FRAME);
connection.send(MessageBuilder.createMessage(EMPTY_PAYLOAD, this.connectHeaders.getMessageHeaders()));
}
@Override
public void afterConnectFailure(Throwable ex) {
handleTcpConnectionFailure("Failed to connect: " + ex.getMessage(), ex);
}
/**
* Invoked when any TCP connectivity issue is detected, i.e. failure to establish
* the TCP connection, failure to send a message, missed heartbeat, etc.
*/
protected void handleTcpConnectionFailure(String error, Throwable ex) {
if (logger.isErrorEnabled()) {
logger.error("TCP connection failure in session " + this.sessionId + ": " + error, ex);
}
try {
sendStompErrorFrameToClient(error);
}
finally {
try {
clearConnection();
}
catch (Throwable ex2) {
if (logger.isDebugEnabled()) {
logger.debug("Failure while clearing TCP connection state in session " + this.sessionId, ex2);
}
}
}
}
private void sendStompErrorFrameToClient(String errorText) {
if (this.isRemoteClientSession) {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
if (getHeaderInitializer() != null) {
getHeaderInitializer().initHeaders(headerAccessor);
}
headerAccessor.setSessionId(this.sessionId);
headerAccessor.setUser(this.connectHeaders.getUser());
headerAccessor.setMessage(errorText);
Message<?> errorMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, headerAccessor.getMessageHeaders());
handleInboundMessage(errorMessage);
}
}
protected void handleInboundMessage(Message<?> message) {
if (this.isRemoteClientSession) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
accessor.setImmutable();
StompBrokerRelayMessageHandler.this.getClientOutboundChannel().send(message);
}
}
@Override
public void handleMessage(Message<byte[]> message) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
accessor.setSessionId(this.sessionId);
accessor.setUser(this.connectHeaders.getUser());
StompCommand command = accessor.getCommand();
if (StompCommand.CONNECTED.equals(command)) {
if (logger.isDebugEnabled()) {
logger.debug("Received " + accessor.getShortLogMessage(EMPTY_PAYLOAD));
}
afterStompConnected(accessor);
}
else if (logger.isErrorEnabled() && StompCommand.ERROR.equals(command)) {
logger.error("Received " + accessor.getShortLogMessage(message.getPayload()));
}
else if (logger.isTraceEnabled()) {
logger.trace("Received " + accessor.getDetailedLogMessage(message.getPayload()));
}
handleInboundMessage(message);
}
/**
* Invoked after the STOMP CONNECTED frame is received. At this point the
* connection is ready for sending STOMP messages to the broker.
*/
protected void afterStompConnected(StompHeaderAccessor connectedHeaders) {
this.isStompConnected = true;
stats.incrementConnectedCount();
initHeartbeats(connectedHeaders);
}
private void initHeartbeats(StompHeaderAccessor connectedHeaders) {
if (this.isRemoteClientSession) {
return;
}
long clientSendInterval = this.connectHeaders.getHeartbeat()[0];
long clientReceiveInterval = this.connectHeaders.getHeartbeat()[1];
long serverSendInterval = connectedHeaders.getHeartbeat()[0];
long serverReceiveInterval = connectedHeaders.getHeartbeat()[1];
if (clientSendInterval > 0 && serverReceiveInterval > 0) {
long interval = Math.max(clientSendInterval, serverReceiveInterval);
this.tcpConnection.onWriteInactivity(new Runnable() {
@Override
public void run() {
TcpConnection<byte[]> conn = tcpConnection;
if (conn != null) {
conn.send(HEARTBEAT_MESSAGE).addCallback(
new ListenableFutureCallback<Void>() {
public void onSuccess(Void result) {
}
public void onFailure(Throwable ex) {
handleTcpConnectionFailure(
"Failed to forward heartbeat: " + ex.getMessage(), ex);
}
});
}
}
}, interval);
}
if (clientReceiveInterval > 0 && serverSendInterval > 0) {
final long interval = Math.max(clientReceiveInterval, serverSendInterval) * HEARTBEAT_MULTIPLIER;
this.tcpConnection.onReadInactivity(new Runnable() {
@Override
public void run() {
handleTcpConnectionFailure("No messages received in " + interval + " ms.", null);
}
}, interval);
}
}
@Override
public void handleFailure(Throwable ex) {
if (this.tcpConnection != null) {
handleTcpConnectionFailure("Transport failure: " + ex.getMessage(), ex);
}
else if (logger.isErrorEnabled()) {
logger.error("Transport failure: " + ex);
}
}
@Override
public void afterConnectionClosed() {
if (this.tcpConnection == null) {
return;
}
try {
if (logger.isDebugEnabled()) {
logger.debug("TCP connection to broker closed in session " + this.sessionId);
}
sendStompErrorFrameToClient("Connection to broker closed.");
}
finally {
try {
// Prevent clearConnection() from trying to close
this.tcpConnection = null;
clearConnection();
}
catch (Throwable ex) {
// Shouldn't happen with connection reset beforehand
}
}
}
/**
* Forward the given message to the STOMP broker.
* <p>The method checks whether we have an active TCP connection and have
* received the STOMP CONNECTED frame. For client messages this should be
* false only if we lose the TCP connection around the same time when a
* client message is being forwarded, so we simply log the ignored message
* at debug level. For messages from within the application being sent on
* the "system" connection an exception is raised so that components sending
* the message have a chance to handle it -- by default the broker message
* channel is synchronous.
* <p>Note that if messages arrive concurrently around the same time a TCP
* connection is lost, there is a brief period of time before the connection
* is reset when one or more messages may sneak through and an attempt made
* to forward them. Rather than synchronizing to guard against that, this
* method simply lets them try and fail. For client sessions that may
* result in an additional STOMP ERROR frame(s) being sent downstream but
* code handling that downstream should be idempotent in such cases.
* @param message the message to send (never {@code null})
* @return a future to wait for the result
*/
@SuppressWarnings("unchecked")
public ListenableFuture<Void> forward(final Message<?> message, final StompHeaderAccessor accessor) {
TcpConnection<byte[]> conn = this.tcpConnection;
if (!this.isStompConnected) {
if (this.isRemoteClientSession) {
if (logger.isDebugEnabled()) {
logger.debug("TCP connection closed already, ignoring " +
accessor.getShortLogMessage(message.getPayload()));
}
return EMPTY_TASK;
}
else {
throw new IllegalStateException("Cannot forward messages " +
(conn != null ? "before STOMP CONNECTED. " : "while inactive. ") +
"Consider subscribing to receive BrokerAvailabilityEvent's from " +
"an ApplicationListener Spring bean. Dropped " +
accessor.getShortLogMessage(message.getPayload()));
}
}
final Message<?> messageToSend = (accessor.isMutable() && accessor.isModified()) ?
MessageBuilder.createMessage(message.getPayload(), accessor.getMessageHeaders()) : message;
StompCommand command = accessor.getCommand();
if (logger.isDebugEnabled() && (StompCommand.SEND.equals(command) || StompCommand.SUBSCRIBE.equals(command) ||
StompCommand.UNSUBSCRIBE.equals(command) || StompCommand.DISCONNECT.equals(command))) {
logger.debug("Forwarding " + accessor.getShortLogMessage(message.getPayload()));
}
else if (logger.isTraceEnabled()) {
logger.trace("Forwarding " + accessor.getDetailedLogMessage(message.getPayload()));
}
ListenableFuture<Void> future = conn.send((Message<byte[]>) messageToSend);
future.addCallback(new ListenableFutureCallback<Void>() {
@Override
public void onSuccess(Void result) {
if (accessor.getCommand() == StompCommand.DISCONNECT) {
afterDisconnectSent(accessor);
}
}
@Override
public void onFailure(Throwable ex) {
if (tcpConnection != null) {
handleTcpConnectionFailure("failed to forward " +
accessor.getShortLogMessage(message.getPayload()), ex);
}
else if (logger.isErrorEnabled()) {
logger.error("Failed to forward " + accessor.getShortLogMessage(message.getPayload()));
}
}
});
return future;
}
/**
* After a DISCONNECT there should be no more client frames so we can
* close the connection pro-actively. However, if the DISCONNECT has a
* receipt header we leave the connection open and expect the server will
* respond with a RECEIPT and then close the connection.
* @see <a href="http://stomp.github.io/stomp-specification-1.2.html#DISCONNECT">
* STOMP Specification 1.2 DISCONNECT</a>
*/
private void afterDisconnectSent(StompHeaderAccessor accessor) {
if (accessor.getReceipt() == null) {
try {
clearConnection();
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failure while clearing TCP connection state in session " + this.sessionId, ex);
}
}
}
}
/**
* Clean up state associated with the connection and close it.
* Any exception arising from closing the connection are propagated.
*/
public void clearConnection() {
if (logger.isDebugEnabled()) {
logger.debug("Cleaning up connection state for session " + this.sessionId);
}
if (this.isRemoteClientSession) {
StompBrokerRelayMessageHandler.this.connectionHandlers.remove(this.sessionId);
}
this.isStompConnected = false;
TcpConnection<byte[]> conn = this.tcpConnection;
this.tcpConnection = null;
if (conn != null) {
if (logger.isDebugEnabled()) {
logger.debug("Closing TCP connection in session " + this.sessionId);
}
conn.close();
}
}
@Override
public String toString() {
return "StompConnectionHandler[sessionId=" + this.sessionId + "]";
}
}
private class SystemStompConnectionHandler extends StompConnectionHandler {
public SystemStompConnectionHandler(StompHeaderAccessor connectHeaders) {
super(SYSTEM_SESSION_ID, connectHeaders, false);
}
@Override
protected void afterStompConnected(StompHeaderAccessor connectedHeaders) {
if (logger.isInfoEnabled()) {
logger.info("\"System\" session connected.");
}
super.afterStompConnected(connectedHeaders);
publishBrokerAvailableEvent();
sendSystemSubscriptions();
}
private void sendSystemSubscriptions() {
int i = 0;
for (String destination : getSystemSubscriptions().keySet()) {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
accessor.setSubscriptionId(String.valueOf(i++));
accessor.setDestination(destination);
if (logger.isDebugEnabled()) {
logger.debug("Subscribing to " + destination + " on \"system\" connection.");
}
TcpConnection<byte[]> conn = getTcpConnection();
if (conn != null) {
MessageHeaders headers = accessor.getMessageHeaders();
conn.send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers)).addCallback(
new ListenableFutureCallback<Void>() {
public void onSuccess(Void result) {
}
public void onFailure(Throwable ex) {
String error = "Failed to subscribe in \"system\" session.";
handleTcpConnectionFailure(error, ex);
}
});
}
}
}
@Override
protected void handleInboundMessage(Message<?> message) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (StompCommand.MESSAGE.equals(accessor.getCommand())) {
String destination = accessor.getDestination();
if (destination == null) {
if (logger.isDebugEnabled()) {
logger.debug("Got message on \"system\" connection, with no destination: " +
accessor.getDetailedLogMessage(message.getPayload()));
}
return;
}
if (!getSystemSubscriptions().containsKey(destination)) {
if (logger.isDebugEnabled()) {
logger.debug("Got message on \"system\" connection with no handler: " +
accessor.getDetailedLogMessage(message.getPayload()));
}
return;
}
try {
MessageHandler handler = getSystemSubscriptions().get(destination);
handler.handleMessage(message);
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Error while handling message on \"system\" connection.", ex);
}
}
}
}
@Override
protected void handleTcpConnectionFailure(String errorMessage, Throwable ex) {
super.handleTcpConnectionFailure(errorMessage, ex);
publishBrokerUnavailableEvent();
}
@Override
public void afterConnectionClosed() {
super.afterConnectionClosed();
publishBrokerUnavailableEvent();
}
@Override
public ListenableFuture<Void> forward(Message<?> message, StompHeaderAccessor accessor) {
try {
ListenableFuture<Void> future = super.forward(message, accessor);
if (message.getHeaders().get(SimpMessageHeaderAccessor.IGNORE_ERROR) == null) {
future.get();
}
return future;
}
catch (Throwable ex) {
throw new MessageDeliveryException(message, ex);
}
}
}
private static class StompTcpClientFactory {
public TcpOperations<byte[]> create(String relayHost, int relayPort, Reactor2StompCodec codec) {
return new Reactor2TcpClient<>(relayHost, relayPort, codec);
}
}
private static class VoidCallable implements Callable<Void> {
@Override
public Void call() throws Exception {
return null;
}
}
private class Stats {
private final AtomicInteger connect = new AtomicInteger();
private final AtomicInteger connected = new AtomicInteger();
private final AtomicInteger disconnect = new AtomicInteger();
public void incrementConnectCount() {
this.connect.incrementAndGet();
}
public void incrementConnectedCount() {
this.connected.incrementAndGet();
}
public void incrementDisconnectCount() {
this.disconnect.incrementAndGet();
}
public String toString() {
return connectionHandlers.size() + " sessions, " + relayHost + ":" + relayPort +
(isBrokerAvailable() ? " (available)" : " (not available)") +
", processed CONNECT(" + this.connect.get() + ")-CONNECTED(" +
this.connected.get() + ")-DISCONNECT(" + this.disconnect.get() + ")";
}
}
}
| Check both connection and connected flag
Issue: SPR-14703
| spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java | Check both connection and connected flag | <ide><path>pring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java
<ide> public ListenableFuture<Void> forward(final Message<?> message, final StompHeaderAccessor accessor) {
<ide> TcpConnection<byte[]> conn = this.tcpConnection;
<ide>
<del> if (!this.isStompConnected) {
<add> if (!this.isStompConnected || conn == null) {
<ide> if (this.isRemoteClientSession) {
<ide> if (logger.isDebugEnabled()) {
<ide> logger.debug("TCP connection closed already, ignoring " + |
|
Java | epl-1.0 | 78ccd0fe2c1629d1fe8c0724b33b82564742acda | 0 | amolenaar/fitnesse,rbevers/fitnesse,hansjoachim/fitnesse,amolenaar/fitnesse,rbevers/fitnesse,rbevers/fitnesse,hansjoachim/fitnesse,hansjoachim/fitnesse,jdufner/fitnesse,jdufner/fitnesse,amolenaar/fitnesse,jdufner/fitnesse | // Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the CPL Common Public License version 1.0.
package fitnesse.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
public abstract class Response {
public enum Format {
XML("text/xml"),
HTML("text/html; charset=utf-8"),
TEXT("text/text"),
JSON("text/json"),
JAVA("java");
private final String contentType;
private Format(String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
}
protected static final String CRLF = "\r\n";
public static SimpleDateFormat makeStandardHttpDateFormat() {
// SimpleDateFormat is not thread safe, so we need to create each
// instance independently.
SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df;
}
private int status = 200;
private HashMap<String, String> headers = new HashMap<String, String>(17);
private String contentType = Format.HTML.contentType;
private boolean withHttpHeaders = true;
public Response(String formatString) {
Format format;
if ("html".equalsIgnoreCase(formatString)) {
format = Format.HTML;
} else if ("xml".equalsIgnoreCase(formatString)) {
format = Format.XML;
} else if ("text".equalsIgnoreCase(formatString)) {
format = Format.TEXT;
} else if ("java".equalsIgnoreCase(formatString)){
format = Format.JAVA;
} else {
format = Format.HTML;
}
setContentType(format.getContentType());
}
public Response(String format, int status) {
this(format);
this.status = status;
}
public boolean isXmlFormat() {
return Format.XML.contentType.equals(contentType);
}
public boolean isHtmlFormat() {
return Format.HTML.contentType.equals(contentType);
}
public boolean isTextFormat() {
return Format.TEXT.contentType.equals(contentType);
}
public boolean isJavaFormat(){
return Format.JAVA.contentType.equals(contentType);
}
public abstract void sendTo(ResponseSender sender) throws IOException;
public abstract int getContentSize();
public int getStatus() {
return status;
}
public void setStatus(int s) {
status = s;
}
public void withoutHttpHeaders() {
this.withHttpHeaders = false;
}
public final String makeHttpHeaders() {
if (!withHttpHeaders)
return "";
if (status != 304) {
addStandardHeaders();
}
StringBuffer text = new StringBuffer();
if (!Format.TEXT.contentType.equals(contentType)) {
text.append("HTTP/1.1 ").append(status).append(" ").append(
getReasonPhrase()).append(CRLF);
makeHeaders(text);
text.append(CRLF);
}
return text.toString();
}
public String getContentType() {
return contentType;
}
public void setContentType(String type) {
contentType = type;
}
public void setContentType(Format format) {
contentType = format.getContentType();
}
public void redirect(String location) {
status = 303;
addHeader("Location", location);
}
public void setMaxAge(int age) {
addHeader("Cache-Control", "max-age=" + age);
}
public void setLastModifiedHeader(String date) {
addHeader("Last-Modified", date);
}
public void setExpiresHeader(String date) {
addHeader("Expires", date);
}
public void addHeader(String key, String value) {
headers.put(key, value);
}
public String getHeader(String key) {
return headers.get(key);
}
public byte[] getEncodedBytes(String value) {
// TODO: -AJM- Defer encoding to the latest responsible moment
try {
return value.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unable to encode data", e);
}
}
void makeHeaders(StringBuffer text) {
for (Entry<String, String> entry: headers.entrySet()) {
text.append(entry.getKey()).append(": ").append(entry.getValue()).append(CRLF);
}
}
protected void addStandardHeaders() {
addHeader("Content-Type", getContentType());
}
protected String getReasonPhrase() {
return getReasonPhrase(status);
}
private static final Map<Integer, String> reasonCodes = new HashMap<Integer, String>() {
private static final long serialVersionUID = 1L;
{
put(100, "Continue");
put(101, "Switching Protocols");
put(200, "OK");
put(201, "Created");
put(202, "Accepted");
put(203, "Non-Authoritative Information");
put(204, "No Content");
put(205, "Reset Content");
put(300, "Multiple Choices");
put(301, "Moved Permanently");
put(302, "Found");
put(303, "See Other");
put(304, "Not Modified");
put(305, "Use Proxy");
put(307, "Temporary Redirect");
put(400, "Bad Request");
put(401, "Unauthorized");
put(402, "Payment Required");
put(403, "Forbidden");
put(404, "Not Found");
put(405, "Method Not Allowed");
put(406, "Not Acceptable");
put(407, "Proxy Authentication Required");
put(408, "Request Time-out");
put(409, "Conflict");
put(410, "Gone");
put(411, "Length Required");
put(412, "Precondition Failed");
put(413, "Request Entity Too Large");
put(414, "Request-URI Too Large");
put(415, "Unsupported Media Type");
put(416, "Requested range not satisfiable");
put(417, "Expectation Failed");
put(500, "Internal Server Error");
put(501, "Not Implemented");
put(502, "Bad Gateway");
put(503, "Service Unavailable");
put(504, "Gateway Time-out");
put(505, "HTTP Version not supported");
}
};
public static String getReasonPhrase(int status) {
String reasonPhrase = reasonCodes.get(status);
return reasonPhrase == null ? "Unknown Status" : reasonPhrase;
}
}
| src/fitnesse/http/Response.java | // Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the CPL Common Public License version 1.0.
package fitnesse.http;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
public abstract class Response {
public enum Format {
XML("text/xml"),
HTML("text/html; charset=utf-8"),
TEXT("text/text"),
JSON("text/json"),
JAVA("java");
private final String contentType;
private Format(String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
}
protected static final String CRLF = "\r\n";
public static SimpleDateFormat makeStandardHttpDateFormat() {
// SimpleDateFormat is not thread safe, so we need to create each
// instance independently.
SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
return df;
}
private int status = 200;
private HashMap<String, String> headers = new HashMap<String, String>(17);
private String contentType = Format.HTML.contentType;
private boolean withHttpHeaders = true;
public Response(String formatString) {
Format format;
if ("html".equalsIgnoreCase(formatString)) {
format = Format.HTML;
} else if ("xml".equalsIgnoreCase(formatString)) {
format = Format.XML;
} else if ("text".equalsIgnoreCase(formatString)) {
format = Format.TEXT;
} else if ("java".equalsIgnoreCase(formatString)){
format = Format.JAVA;
} else {
format = Format.HTML;
}
setContentType(format.getContentType());
}
public Response(String format, int status) {
this(format);
this.status = status;
}
public boolean isXmlFormat() {
return Format.XML.contentType.equals(contentType);
}
public boolean isHtmlFormat() {
return Format.HTML.contentType.equals(contentType);
}
public boolean isTextFormat() {
return Format.TEXT.contentType.equals(contentType);
}
public boolean isJavaFormat(){
return Format.JAVA.contentType.equals(contentType);
}
public abstract void sendTo(ResponseSender sender) throws IOException;
public abstract int getContentSize();
public int getStatus() {
return status;
}
public void setStatus(int s) {
status = s;
}
public void withoutHttpHeaders() {
this.withHttpHeaders = false;
}
public final String makeHttpHeaders() {
if (!withHttpHeaders)
return "";
addStandardHeaders();
StringBuffer text = new StringBuffer();
if (!Format.TEXT.contentType.equals(contentType)) {
text.append("HTTP/1.1 ").append(status).append(" ").append(
getReasonPhrase()).append(CRLF);
makeHeaders(text);
text.append(CRLF);
}
return text.toString();
}
public String getContentType() {
return contentType;
}
public void setContentType(String type) {
contentType = type;
}
public void setContentType(Format format) {
contentType = format.getContentType();
}
public void redirect(String location) {
status = 303;
addHeader("Location", location);
}
public void setMaxAge(int age) {
addHeader("Cache-Control", "max-age=" + age);
}
public void setLastModifiedHeader(String date) {
addHeader("Last-Modified", date);
}
public void setExpiresHeader(String date) {
addHeader("Expires", date);
}
public void addHeader(String key, String value) {
headers.put(key, value);
}
public String getHeader(String key) {
return headers.get(key);
}
public byte[] getEncodedBytes(String value) {
// TODO: -AJM- Defer encoding to the latest responsible moment
try {
return value.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unable to encode data", e);
}
}
void makeHeaders(StringBuffer text) {
for (Entry<String, String> entry: headers.entrySet()) {
text.append(entry.getKey()).append(": ").append(entry.getValue()).append(CRLF);
}
}
protected void addStandardHeaders() {
addHeader("Content-Type", getContentType());
}
protected String getReasonPhrase() {
return getReasonPhrase(status);
}
private static final Map<Integer, String> reasonCodes = new HashMap<Integer, String>() {
private static final long serialVersionUID = 1L;
{
put(100, "Continue");
put(101, "Switching Protocols");
put(200, "OK");
put(201, "Created");
put(202, "Accepted");
put(203, "Non-Authoritative Information");
put(204, "No Content");
put(205, "Reset Content");
put(300, "Multiple Choices");
put(301, "Moved Permanently");
put(302, "Found");
put(303, "See Other");
put(304, "Not Modified");
put(305, "Use Proxy");
put(307, "Temporary Redirect");
put(400, "Bad Request");
put(401, "Unauthorized");
put(402, "Payment Required");
put(403, "Forbidden");
put(404, "Not Found");
put(405, "Method Not Allowed");
put(406, "Not Acceptable");
put(407, "Proxy Authentication Required");
put(408, "Request Time-out");
put(409, "Conflict");
put(410, "Gone");
put(411, "Length Required");
put(412, "Precondition Failed");
put(413, "Request Entity Too Large");
put(414, "Request-URI Too Large");
put(415, "Unsupported Media Type");
put(416, "Requested range not satisfiable");
put(417, "Expectation Failed");
put(500, "Internal Server Error");
put(501, "Not Implemented");
put(502, "Bad Gateway");
put(503, "Service Unavailable");
put(504, "Gateway Time-out");
put(505, "HTTP Version not supported");
}
};
public static String getReasonPhrase(int status) {
String reasonPhrase = reasonCodes.get(status);
return reasonPhrase == null ? "Unknown Status" : reasonPhrase;
}
}
| Quick fix to make style not break on Chrome. See #283
| src/fitnesse/http/Response.java | Quick fix to make style not break on Chrome. See #283 | <ide><path>rc/fitnesse/http/Response.java
<ide> public final String makeHttpHeaders() {
<ide> if (!withHttpHeaders)
<ide> return "";
<del> addStandardHeaders();
<add> if (status != 304) {
<add> addStandardHeaders();
<add> }
<ide> StringBuffer text = new StringBuffer();
<ide> if (!Format.TEXT.contentType.equals(contentType)) {
<ide> text.append("HTTP/1.1 ").append(status).append(" ").append( |
|
Java | apache-2.0 | d3b822645726711eb1600277907ea5fcf5d63bda | 0 | jackyglony/msgpack-java,suzukaze/msgpack-java,mikolak-net/msgpack-java,xerial/msgpack-java,dongjiaqiang/msgpack-java,DataDog/msgpack-java,xuwei-k/msgpack-java,jackyglony/msgpack-java,xuwei-k/msgpack-java,komamitsu/msgpack-java,komamitsu/msgpack-java,dongjiaqiang/msgpack-java,muga/msgpack-java-0.7,msgpack/msgpack-java,suzukaze/msgpack-java,msgpack/msgpack-java,mikolak-net/msgpack-java,DataDog/msgpack-java,xerial/msgpack-java | //
// MessagePack for Java
//
// Copyright (C) 2009-2011 FURUHASHI Sadayuki
//
// 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.msgpack.template;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import org.msgpack.MessagePackable;
import org.msgpack.MessageTypeException;
import org.msgpack.template.BigIntegerTemplate;
import org.msgpack.template.BooleanTemplate;
import org.msgpack.template.ByteArrayTemplate;
import org.msgpack.template.ByteTemplate;
import org.msgpack.template.DoubleArrayTemplate;
import org.msgpack.template.DoubleTemplate;
import org.msgpack.template.FieldList;
import org.msgpack.template.FloatArrayTemplate;
import org.msgpack.template.FloatTemplate;
import org.msgpack.template.GenericTemplate;
import org.msgpack.template.IntegerArrayTemplate;
import org.msgpack.template.IntegerTemplate;
import org.msgpack.template.LongArrayTemplate;
import org.msgpack.template.LongTemplate;
import org.msgpack.template.ShortArrayTemplate;
import org.msgpack.template.ShortTemplate;
import org.msgpack.template.StringTemplate;
import org.msgpack.template.Template;
import org.msgpack.template.ValueTemplate;
import org.msgpack.template.builder.TemplateBuilder;
import org.msgpack.template.builder.TemplateBuilderChain;
import org.msgpack.type.Value;
public class TemplateRegistry {
private TemplateRegistry parent = null;
private TemplateBuilderChain chain;
Map<Type, Template<Type>> cache;
private Map<Type, GenericTemplate> genericCache;
/**
* create <code>TemplateRegistry</code> object of root.
*/
private TemplateRegistry() {
parent = null;
chain = new TemplateBuilderChain(this);
genericCache = new HashMap<Type, GenericTemplate>();
cache = new HashMap<Type, Template<Type>>();
registerTemplates();
cache = Collections.unmodifiableMap(cache);
}
/**
*
* @param registry
*/
public TemplateRegistry(TemplateRegistry registry) {
if (registry != null) {
parent = registry;
} else {
parent = new TemplateRegistry();
}
chain = new TemplateBuilderChain(this);
cache = new HashMap<Type, Template<Type>>();
genericCache = parent.genericCache;
}
private void registerTemplates() {
register(boolean.class, BooleanTemplate.getInstance());
register(Boolean.class, BooleanTemplate.getInstance());
register(byte.class, ByteTemplate.getInstance());
register(Byte.class, ByteTemplate.getInstance());
register(short.class, ShortTemplate.getInstance());
register(Short.class, ShortTemplate.getInstance());
register(int.class, IntegerTemplate.getInstance());
register(Integer.class, IntegerTemplate.getInstance());
register(long.class, LongTemplate.getInstance());
register(Long.class, LongTemplate.getInstance());
register(float.class, FloatTemplate.getInstance());
register(Float.class, FloatTemplate.getInstance());
register(double.class, DoubleTemplate.getInstance());
register(Double.class, DoubleTemplate.getInstance());
register(BigInteger.class, BigIntegerTemplate.getInstance());
register(char.class, CharacterTemplate.getInstance());
register(Character.class, CharacterTemplate.getInstance());
register(boolean[].class, BooleanArrayTemplate.getInstance());
register(short[].class, ShortArrayTemplate.getInstance());
register(int[].class, IntegerArrayTemplate.getInstance());
register(long[].class, LongArrayTemplate.getInstance());
register(float[].class, FloatArrayTemplate.getInstance());
register(double[].class, DoubleArrayTemplate.getInstance());
register(String.class, StringTemplate.getInstance());
register(byte[].class, ByteArrayTemplate.getInstance());
register(ByteBuffer.class, ByteBufferTemplate.getInstance());
register(Value.class, ValueTemplate.getInstance());
//register(Value.class, AnyTemplate.getInstance(this));
register(List.class, new ListTemplate(AnyTemplate.getInstance(this)));
register(Collection.class, new CollectionTemplate(AnyTemplate.getInstance(this)));
register(Map.class, new MapTemplate(AnyTemplate.getInstance(this), AnyTemplate.getInstance(this)));
registerGeneric(List.class, new GenericCollectionTemplate(this, ListTemplate.class));
registerGeneric(Collection.class, new GenericCollectionTemplate(this, CollectionTemplate.class));
registerGeneric(Map.class, new GenericMapTemplate(this, MapTemplate.class));
}
public void register(final Class<?> targetClass) {
buildAndRegister(null, targetClass, false, null);
}
public void register(final Class<?> targetClass, final FieldList flist) {
if (flist == null) {
throw new NullPointerException("FieldList object is null");
}
buildAndRegister(null, targetClass, false, flist);
}
public synchronized void register(final Type targetType, final Template tmpl) {
if (tmpl == null) {
throw new NullPointerException("Template object is null");
}
if (targetType instanceof ParameterizedType) {
cache.put(((ParameterizedType) targetType).getRawType(), tmpl);
} else {
cache.put(targetType, tmpl);
}
}
public synchronized void registerGeneric(final Type targetType, final GenericTemplate tmpl) {
if (targetType instanceof ParameterizedType) {
genericCache.put(((ParameterizedType) targetType).getRawType(), tmpl);
} else {
genericCache.put(targetType, tmpl);
}
}
public synchronized boolean unregister(final Type targetType) {
Template<Type> tmpl = cache.remove(targetType);
return tmpl != null;
}
public synchronized void unregister() {
cache.clear();
}
public Template lookup(Type targetType) {
return lookupImpl(targetType);
}
private synchronized Template lookupImpl(Type targetType) {
Template tmpl;
tmpl = lookupGenericImpl(targetType);
if (tmpl != null) {
return tmpl;
}
tmpl = lookupCacheImpl(targetType);
if (tmpl != null) {
return tmpl;
}
Class<?> targetClass = (Class<?>) targetType;
if (MessagePackable.class.isAssignableFrom(targetClass)) {
tmpl = new MessagePackableTemplate(targetClass);
register(targetClass, tmpl);
return tmpl;
}
// find matched template builder and build template
tmpl = lookupWithTemplateBuilderImpl(targetClass);
if (tmpl != null) {
return tmpl;
}
// lookup template of interface type
tmpl = lookupInterfacesImpl(targetClass);
if (tmpl != null) {
return tmpl;
}
// lookup template of superclass type
tmpl = lookupSuperclassesImpl(targetClass);
if (tmpl != null) {
return tmpl;
}
throw new MessageTypeException(
"Cannot find template for " + targetClass + " class. Try to add @Message annotation to the class or call MessagePack.register(Type).");
}
@SuppressWarnings("unchecked")
private Template<Type> lookupGenericImpl(Type targetType) {
Template<Type> tmpl = null;
if (targetType instanceof ParameterizedType) {
ParameterizedType paramedType = (ParameterizedType) targetType;
// ParameterizedType is not a Class<?>?
tmpl = lookupGenericImpl0(paramedType);
if (tmpl != null) {
return tmpl;
}
try {
tmpl = parent.lookupGenericImpl0(paramedType);
if (tmpl != null) {
return tmpl;
}
} catch (NullPointerException e) { // ignore
}
targetType = paramedType.getRawType();
}
return tmpl;
}
private Template lookupGenericImpl0(final ParameterizedType targetType) {
Type rawType = targetType.getRawType();
GenericTemplate tmpl = genericCache.get(rawType);
if (tmpl == null) {
return null;
}
Type[] types = targetType.getActualTypeArguments();
Template[] tmpls = new Template[types.length];
for (int i = 0; i < types.length; ++i) {
tmpls[i] = lookup(types[i]);
}
return tmpl.build(tmpls);
}
private Template<Type> lookupCacheImpl(Type targetType) {
Template<Type> tmpl = cache.get(targetType);
if (tmpl != null) {
return tmpl;
}
try {
tmpl = parent.lookupCacheImpl(targetType);
} catch (NullPointerException e) { // ignore
}
return tmpl;
}
private <T> Template<T> lookupWithTemplateBuilderImpl(Class<T> targetClass) {
TemplateBuilder builder = chain.select(targetClass, true);
Template<T> tmpl = null;
if (builder != null) {
tmpl = builder.loadTemplate(targetClass);
if (tmpl != null) {
register(targetClass, tmpl);
return tmpl;
}
tmpl = buildAndRegister(builder, targetClass, true, null);
}
return tmpl;
}
private <T> Template<T> lookupInterfacesImpl(Class<T> targetClass) {
Class<?>[] infTypes = targetClass.getInterfaces();
Template<T> tmpl = null;
for (Class<?> infType : infTypes) {
tmpl = (Template<T>) cache.get(infType);
if (tmpl != null) {
register(targetClass, tmpl);
return tmpl;
} else {
try {
tmpl = (Template<T>) parent.lookupCacheImpl(infType);
if (tmpl != null) {
register(targetClass, tmpl);
return tmpl;
}
} catch (NullPointerException e) { // ignore
}
}
}
return tmpl;
}
private <T> Template<T> lookupSuperclassesImpl(Class<T> targetClass) {
Class<?> superClass = targetClass.getSuperclass();
Template<T> tmpl = null;
if (superClass != null) {
for (; superClass != Object.class; superClass = superClass.getSuperclass()) {
tmpl = (Template<T>) cache.get(superClass);
if (tmpl != null) {
register(targetClass, tmpl);
return tmpl;
} else {
try {
tmpl = (Template<T>) parent.lookupCacheImpl(superClass);
if (tmpl != null) {
register(targetClass, tmpl);
return tmpl;
}
} catch (NullPointerException e) { // ignore
}
}
}
}
return tmpl;
}
private synchronized Template buildAndRegister(TemplateBuilder builder, final Class targetClass,
final boolean hasAnnotation, final FieldList flist) {
Template newTmpl = null;
Template oldTmpl = null;
try {
if (cache.containsKey(targetClass)) {
oldTmpl = cache.get(targetClass);
}
newTmpl = new TemplateReference(this, targetClass);
cache.put(targetClass, newTmpl);
if (builder == null) {
builder = chain.select(targetClass, hasAnnotation);
}
newTmpl = flist != null ? builder.buildTemplate(targetClass, flist) : builder.buildTemplate(targetClass);
return newTmpl;
} catch (Exception e) {
if (oldTmpl != null) {
cache.put(targetClass, oldTmpl);
} else {
cache.remove(targetClass);
}
newTmpl = null;
if (e instanceof MessageTypeException) {
throw (MessageTypeException) e;
} else {
throw new MessageTypeException(e);
}
} finally {
if (newTmpl != null) {
cache.put(targetClass, newTmpl);
}
}
}
}
| src/main/java/org/msgpack/template/TemplateRegistry.java | //
// MessagePack for Java
//
// Copyright (C) 2009-2011 FURUHASHI Sadayuki
//
// 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.msgpack.template;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import org.msgpack.MessagePackable;
import org.msgpack.MessageTypeException;
import org.msgpack.template.BigIntegerTemplate;
import org.msgpack.template.BooleanTemplate;
import org.msgpack.template.ByteArrayTemplate;
import org.msgpack.template.ByteTemplate;
import org.msgpack.template.DoubleArrayTemplate;
import org.msgpack.template.DoubleTemplate;
import org.msgpack.template.FieldList;
import org.msgpack.template.FloatArrayTemplate;
import org.msgpack.template.FloatTemplate;
import org.msgpack.template.GenericTemplate;
import org.msgpack.template.IntegerArrayTemplate;
import org.msgpack.template.IntegerTemplate;
import org.msgpack.template.LongArrayTemplate;
import org.msgpack.template.LongTemplate;
import org.msgpack.template.ShortArrayTemplate;
import org.msgpack.template.ShortTemplate;
import org.msgpack.template.StringTemplate;
import org.msgpack.template.Template;
import org.msgpack.template.ValueTemplate;
import org.msgpack.template.builder.TemplateBuilder;
import org.msgpack.template.builder.TemplateBuilderChain;
import org.msgpack.type.Value;
public class TemplateRegistry {
private TemplateRegistry parent = null;
private TemplateBuilderChain chain;
Map<Type, Template<Type>> cache;
private Map<Type, GenericTemplate> genericCache;
/**
* create <code>TemplateRegistry</code> object of root.
*/
private TemplateRegistry() {
parent = null;
chain = new TemplateBuilderChain(this);
genericCache = new HashMap<Type, GenericTemplate>();
cache = new HashMap<Type, Template<Type>>();
registerTemplates();
cache = Collections.unmodifiableMap(cache);
}
/**
*
* @param registry
*/
public TemplateRegistry(TemplateRegistry registry) {
if (registry != null) {
parent = registry;
} else {
parent = new TemplateRegistry();
}
chain = new TemplateBuilderChain(this);
cache = new HashMap<Type, Template<Type>>();
genericCache = parent.genericCache;
}
private void registerTemplates() {
register(boolean.class, BooleanTemplate.getInstance());
register(Boolean.class, BooleanTemplate.getInstance());
register(byte.class, ByteTemplate.getInstance());
register(Byte.class, ByteTemplate.getInstance());
register(short.class, ShortTemplate.getInstance());
register(Short.class, ShortTemplate.getInstance());
register(int.class, IntegerTemplate.getInstance());
register(Integer.class, IntegerTemplate.getInstance());
register(long.class, LongTemplate.getInstance());
register(Long.class, LongTemplate.getInstance());
register(float.class, FloatTemplate.getInstance());
register(Float.class, FloatTemplate.getInstance());
register(double.class, DoubleTemplate.getInstance());
register(Double.class, DoubleTemplate.getInstance());
register(BigInteger.class, BigIntegerTemplate.getInstance());
register(char.class, CharacterTemplate.getInstance());
register(Character.class, CharacterTemplate.getInstance());
register(boolean[].class, BooleanArrayTemplate.getInstance());
register(short[].class, ShortArrayTemplate.getInstance());
register(int[].class, IntegerArrayTemplate.getInstance());
register(long[].class, LongArrayTemplate.getInstance());
register(float[].class, FloatArrayTemplate.getInstance());
register(double[].class, DoubleArrayTemplate.getInstance());
register(String.class, StringTemplate.getInstance());
register(byte[].class, ByteArrayTemplate.getInstance());
register(ByteBuffer.class, ByteBufferTemplate.getInstance());
register(Value.class, ValueTemplate.getInstance());
//register(Value.class, AnyTemplate.getInstance(this));
register(List.class, new ListTemplate(AnyTemplate.getInstance(this)));
register(Collection.class, new CollectionTemplate(AnyTemplate.getInstance(this)));
register(Map.class, new MapTemplate(AnyTemplate.getInstance(this), AnyTemplate.getInstance(this)));
registerGeneric(List.class, new GenericCollectionTemplate(this, ListTemplate.class));
registerGeneric(Collection.class, new GenericCollectionTemplate(this, CollectionTemplate.class));
registerGeneric(Map.class, new GenericMapTemplate(this, MapTemplate.class));
}
public void register(final Class<?> targetClass) {
buildAndRegister(null, targetClass, false, null);
}
public void register(final Class<?> targetClass, final FieldList flist) {
if (flist == null) {
throw new NullPointerException("FieldList object is null");
}
buildAndRegister(null, targetClass, false, flist);
}
public synchronized void register(final Type targetType, final Template tmpl) {
if (tmpl == null) {
throw new NullPointerException("Template object is null");
}
if (targetType instanceof ParameterizedType) {
cache.put(((ParameterizedType) targetType).getRawType(), tmpl);
} else {
cache.put(targetType, tmpl);
}
}
public synchronized void registerGeneric(final Type targetType, final GenericTemplate tmpl) {
if (targetType instanceof ParameterizedType) {
genericCache.put(((ParameterizedType) targetType).getRawType(), tmpl);
} else {
genericCache.put(targetType, tmpl);
}
}
public synchronized boolean unregister(final Type targetType) {
Template<Type> tmpl = cache.remove(targetType);
return tmpl != null;
}
public synchronized void unregister() {
cache.clear();
}
public Template lookup(Type targetType) {
return lookupImpl(targetType);
}
// public Template lookup(Type targetType, boolean isRecursived) {
// return lookupImpl(targetType, isRecursived);
// }
private synchronized Template lookupImpl(Type targetType) {
Template tmpl;
tmpl = lookupGenericImpl(targetType);
if (tmpl != null) {
return tmpl;
}
tmpl = lookupCacheImpl(targetType);
if (tmpl != null) {
return tmpl;
}
Class<?> targetClass = (Class<?>) targetType;
if (MessagePackable.class.isAssignableFrom(targetClass)) {
tmpl = new MessagePackableTemplate(targetClass);
register(targetClass, tmpl);
return tmpl;
}
// find matched template builder and build template
tmpl = lookupWithTemplateBuilderImpl(targetClass);
if (tmpl != null) {
return tmpl;
}
// lookup template of interface type
tmpl = lookupInterfacesImpl(targetClass);
if (tmpl != null) {
return tmpl;
}
// lookup template of superclass type
tmpl = lookupSuperclassesImpl(targetClass);
if (tmpl != null) {
return tmpl;
}
throw new MessageTypeException(
"Cannot find template for " + targetClass + " class. Try to add @Message annotation to the class or call MessagePack.register(Type).");
}
private Template lookupGenericImpl(Type targetType) {
Template tmpl;
if (targetType instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) targetType;
// ParameterizedType is not a Class<?>?
tmpl = lookupGenericImpl0(pType);
if (tmpl != null) {
return tmpl;
}
try {
tmpl = parent.lookupGenericImpl0(pType);
if (tmpl != null) {
return tmpl;
}
} catch (NullPointerException e) { // ignore
}
targetType = pType.getRawType();
}
return null;
}
private Template lookupGenericImpl0(final ParameterizedType targetType) {
Type rawType = targetType.getRawType();
GenericTemplate tmpl = genericCache.get(rawType);
if (tmpl == null) {
return null;
}
Type[] types = targetType.getActualTypeArguments();
Template[] tmpls = new Template[types.length];
for (int i = 0; i < types.length; ++i) {
tmpls[i] = lookup(types[i]);
}
return tmpl.build(tmpls);
}
private Template lookupCacheImpl(Type targetType) {
Template tmpl = cache.get(targetType);
if (tmpl != null) {
return tmpl;
}
try {
tmpl = parent.lookupCacheImpl(targetType);
if (tmpl != null) {
return tmpl;
}
} catch (NullPointerException e) { // ignore
}
return null;
}
private Template lookupWithTemplateBuilderImpl(Class<?> targetClass) {
TemplateBuilder builder = chain.select(targetClass, true);
Template tmpl;
if (builder != null) {
tmpl = builder.loadTemplate(targetClass);
if (tmpl != null) {
register(targetClass, tmpl);
return tmpl;
}
tmpl = buildAndRegister(builder, targetClass, true, null);
if (tmpl != null) {
return tmpl;
}
}
return null;
}
private Template lookupInterfacesImpl(Class<?> targetClass) {
Class<?>[] infTypes = targetClass.getInterfaces();
Template tmpl;
for (Class<?> infType : infTypes) {
tmpl = cache.get(infType);
if (tmpl != null) {
register(targetClass, tmpl);
return tmpl;
} else {
try {
tmpl = parent.lookupCacheImpl(infType);
if (tmpl != null) {
register(targetClass, tmpl);
return tmpl;
}
} catch (NullPointerException e) { // ignore
}
}
}
return null;
}
private Template lookupSuperclassesImpl(Class<?> targetClass) {
Class<?> superClass = targetClass.getSuperclass();
Template tmpl = null;
if (superClass != null) {
for (; superClass != Object.class; superClass = superClass.getSuperclass()) {
tmpl = cache.get(superClass);
if (tmpl != null) {
register(targetClass, tmpl);
return tmpl;
} else {
try {
tmpl = parent.lookupCacheImpl(superClass);
if (tmpl != null) {
register(targetClass, tmpl);
return tmpl;
}
} catch (NullPointerException e) { // ignore
}
}
}
}
return null;
}
private synchronized Template buildAndRegister(TemplateBuilder builder, final Class<?> targetClass,
final boolean hasAnnotation, final FieldList flist) {
Template newTmpl = null;
Template oldTmpl = null;
try {
if (cache.containsKey(targetClass)) {
oldTmpl = cache.get(targetClass);
}
newTmpl = new TemplateReference(this, targetClass);
cache.put(targetClass, newTmpl);
if (builder == null) {
builder = chain.select(targetClass, hasAnnotation);
}
newTmpl = flist != null ? builder.buildTemplate(targetClass, flist) : builder.buildTemplate(targetClass);
return newTmpl;
} catch (Exception e) {
if (oldTmpl != null) {
cache.put(targetClass, oldTmpl);
} else {
cache.remove(targetClass);
}
newTmpl = null;
if (e instanceof MessageTypeException) {
throw (MessageTypeException) e;
} else {
throw new MessageTypeException(e);
}
} finally {
if (newTmpl != null) {
cache.put(targetClass, newTmpl);
}
}
}
}
| refined TemplateRegistry.java
| src/main/java/org/msgpack/template/TemplateRegistry.java | refined TemplateRegistry.java | <ide><path>rc/main/java/org/msgpack/template/TemplateRegistry.java
<ide> if (flist == null) {
<ide> throw new NullPointerException("FieldList object is null");
<ide> }
<add>
<ide> buildAndRegister(null, targetClass, false, flist);
<ide> }
<ide>
<ide> if (tmpl == null) {
<ide> throw new NullPointerException("Template object is null");
<ide> }
<add>
<ide> if (targetType instanceof ParameterizedType) {
<ide> cache.put(((ParameterizedType) targetType).getRawType(), tmpl);
<ide> } else {
<ide> return lookupImpl(targetType);
<ide> }
<ide>
<del>// public Template lookup(Type targetType, boolean isRecursived) {
<del>// return lookupImpl(targetType, isRecursived);
<del>// }
<del>
<ide> private synchronized Template lookupImpl(Type targetType) {
<ide> Template tmpl;
<ide>
<ide> "Cannot find template for " + targetClass + " class. Try to add @Message annotation to the class or call MessagePack.register(Type).");
<ide> }
<ide>
<del> private Template lookupGenericImpl(Type targetType) {
<del> Template tmpl;
<add> @SuppressWarnings("unchecked")
<add> private Template<Type> lookupGenericImpl(Type targetType) {
<add> Template<Type> tmpl = null;
<ide> if (targetType instanceof ParameterizedType) {
<del> ParameterizedType pType = (ParameterizedType) targetType;
<add> ParameterizedType paramedType = (ParameterizedType) targetType;
<add>
<ide> // ParameterizedType is not a Class<?>?
<del> tmpl = lookupGenericImpl0(pType);
<add> tmpl = lookupGenericImpl0(paramedType);
<ide> if (tmpl != null) {
<ide> return tmpl;
<ide> }
<add>
<ide> try {
<del> tmpl = parent.lookupGenericImpl0(pType);
<add> tmpl = parent.lookupGenericImpl0(paramedType);
<ide> if (tmpl != null) {
<ide> return tmpl;
<ide> }
<ide> } catch (NullPointerException e) { // ignore
<ide> }
<del> targetType = pType.getRawType();
<del> }
<del> return null;
<add> targetType = paramedType.getRawType();
<add> }
<add> return tmpl;
<ide> }
<ide>
<ide> private Template lookupGenericImpl0(final ParameterizedType targetType) {
<ide> return tmpl.build(tmpls);
<ide> }
<ide>
<del> private Template lookupCacheImpl(Type targetType) {
<del> Template tmpl = cache.get(targetType);
<add> private Template<Type> lookupCacheImpl(Type targetType) {
<add> Template<Type> tmpl = cache.get(targetType);
<ide> if (tmpl != null) {
<ide> return tmpl;
<ide> }
<ide>
<ide> try {
<ide> tmpl = parent.lookupCacheImpl(targetType);
<del> if (tmpl != null) {
<del> return tmpl;
<del> }
<ide> } catch (NullPointerException e) { // ignore
<ide> }
<del> return null;
<del> }
<del>
<del> private Template lookupWithTemplateBuilderImpl(Class<?> targetClass) {
<add> return tmpl;
<add> }
<add>
<add> private <T> Template<T> lookupWithTemplateBuilderImpl(Class<T> targetClass) {
<ide> TemplateBuilder builder = chain.select(targetClass, true);
<del>
<del> Template tmpl;
<add> Template<T> tmpl = null;
<ide> if (builder != null) {
<ide> tmpl = builder.loadTemplate(targetClass);
<ide> if (tmpl != null) {
<ide> register(targetClass, tmpl);
<ide> return tmpl;
<ide> }
<del>
<ide> tmpl = buildAndRegister(builder, targetClass, true, null);
<del> if (tmpl != null) {
<del> return tmpl;
<del> }
<del> }
<del> return null;
<del> }
<del>
<del> private Template lookupInterfacesImpl(Class<?> targetClass) {
<add> }
<add> return tmpl;
<add> }
<add>
<add> private <T> Template<T> lookupInterfacesImpl(Class<T> targetClass) {
<ide> Class<?>[] infTypes = targetClass.getInterfaces();
<del> Template tmpl;
<add> Template<T> tmpl = null;
<ide> for (Class<?> infType : infTypes) {
<del> tmpl = cache.get(infType);
<add> tmpl = (Template<T>) cache.get(infType);
<ide> if (tmpl != null) {
<ide> register(targetClass, tmpl);
<ide> return tmpl;
<ide> } else {
<ide> try {
<del> tmpl = parent.lookupCacheImpl(infType);
<add> tmpl = (Template<T>) parent.lookupCacheImpl(infType);
<ide> if (tmpl != null) {
<ide> register(targetClass, tmpl);
<ide> return tmpl;
<ide> }
<ide> }
<ide> }
<del> return null;
<del> }
<del>
<del> private Template lookupSuperclassesImpl(Class<?> targetClass) {
<add> return tmpl;
<add> }
<add>
<add> private <T> Template<T> lookupSuperclassesImpl(Class<T> targetClass) {
<ide> Class<?> superClass = targetClass.getSuperclass();
<del> Template tmpl = null;
<add> Template<T> tmpl = null;
<ide> if (superClass != null) {
<ide> for (; superClass != Object.class; superClass = superClass.getSuperclass()) {
<del> tmpl = cache.get(superClass);
<add> tmpl = (Template<T>) cache.get(superClass);
<ide> if (tmpl != null) {
<ide> register(targetClass, tmpl);
<ide> return tmpl;
<ide> } else {
<ide> try {
<del> tmpl = parent.lookupCacheImpl(superClass);
<add> tmpl = (Template<T>) parent.lookupCacheImpl(superClass);
<ide> if (tmpl != null) {
<ide> register(targetClass, tmpl);
<ide> return tmpl;
<ide> }
<ide> }
<ide> }
<del> return null;
<del> }
<del>
<del> private synchronized Template buildAndRegister(TemplateBuilder builder, final Class<?> targetClass,
<add> return tmpl;
<add> }
<add>
<add> private synchronized Template buildAndRegister(TemplateBuilder builder, final Class targetClass,
<ide> final boolean hasAnnotation, final FieldList flist) {
<ide> Template newTmpl = null;
<ide> Template oldTmpl = null; |
|
Java | apache-2.0 | 71d2d31fe6d95aaa2aa05b10c2f48e56cf5ff01e | 0 | dimamo5/Terasology,AWildBeard/Terasology,mertserezli/Terasology,MarcinSc/Terasology,Nanoware/Terasology,MovingBlocks/Terasology,kartikey0303/Terasology,Nanoware/Terasology,Nanoware/Terasology,Malanius/Terasology,MarcinSc/Terasology,Josharias/Terasology,frankpunx/Terasology,frankpunx/Terasology,Halamix2/Terasology,indianajohn/Terasology,dannyzhou98/Terasology,sceptross/Terasology,Vizaxo/Terasology,AWildBeard/Terasology,DPirate/Terasology,Josharias/Terasology,Vizaxo/Terasology,indianajohn/Terasology,kartikey0303/Terasology,dannyzhou98/Terasology,Halamix2/Terasology,dimamo5/Terasology,DPirate/Terasology,flo/Terasology,MovingBlocks/Terasology,kaen/Terasology,kaen/Terasology,MovingBlocks/Terasology,Malanius/Terasology,flo/Terasology,mertserezli/Terasology,sceptross/Terasology | /*
* Copyright 2014 MovingBlocks
*
* 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.terasology.world.generation;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.world.generator.plugin.WorldGeneratorPluginLibrary;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Immortius
*/
public class WorldBuilder {
private static final Logger logger = LoggerFactory.getLogger(WorldBuilder.class);
private final List<FacetProvider> providersList = Lists.newArrayList();
private final Set<Class<? extends WorldFacet>> facetCalculationInProgress = Sets.newHashSet();
private final List<WorldRasterizer> rasterizers = Lists.newArrayList();
private final List<EntityProvider> entityProviders = new ArrayList<>();
private int seaLevel = 32;
private Long seed;
private WorldGeneratorPluginLibrary pluginLibrary;
public WorldBuilder(WorldGeneratorPluginLibrary pluginLibrary) {
this.pluginLibrary = pluginLibrary;
}
public WorldBuilder addProvider(FacetProvider provider) {
providersList.add(provider);
return this;
}
public WorldBuilder addRasterizer(WorldRasterizer rasterizer) {
rasterizers.add(rasterizer);
return this;
}
public WorldBuilder addEntities(EntityProvider entityProvider) {
entityProviders.add(entityProvider);
return this;
}
public WorldBuilder addPlugins() {
pluginLibrary.instantiateAllOfType(FacetProviderPlugin.class).forEach(this::addProvider);
pluginLibrary.instantiateAllOfType(WorldRasterizerPlugin.class).forEach(this::addRasterizer);
return this;
}
/**
* @param level the sea level, measured in blocks
* @return this
*/
public WorldBuilder setSeaLevel(int level) {
this.seaLevel = level;
return this;
}
public void setSeed(long seed) {
this.seed = seed;
}
public World build() {
// TODO: ensure the required providers are present
if (seed == null) {
throw new IllegalStateException("Seed has not been set");
}
for (FacetProvider provider : providersList) {
provider.setSeed(seed);
}
ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains = determineProviderChains();
return new WorldImpl(providerChains, rasterizers, entityProviders, determineBorders(providerChains), seaLevel);
}
private Map<Class<? extends WorldFacet>, Border3D> determineBorders(ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains) {
Map<Class<? extends WorldFacet>, Border3D> borders = Maps.newHashMap();
for (Class<? extends WorldFacet> facet : providerChains.keySet()) {
ensureBorderCalculatedForFacet(facet, providerChains, borders);
}
return borders;
}
private void ensureBorderCalculatedForFacet(Class<? extends WorldFacet> facet, ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains,
Map<Class<? extends WorldFacet>, Border3D> borders) {
if (!borders.containsKey(facet)) {
Border3D border = new Border3D(0, 0, 0);
for (FacetProvider facetProvider : providerChains.values()) {
// Find all facets that require it
Requires requires = facetProvider.getClass().getAnnotation(Requires.class);
if (requires != null) {
for (Facet requiredFacet : requires.value()) {
if (requiredFacet.value() == facet) {
Produces produces = facetProvider.getClass().getAnnotation(Produces.class);
Updates updates = facetProvider.getClass().getAnnotation(Updates.class);
FacetBorder requiredBorder = requiredFacet.border();
if (produces != null) {
for (Class<? extends WorldFacet> producedFacet : produces.value()) {
ensureBorderCalculatedForFacet(producedFacet, providerChains, borders);
Border3D borderForProducedFacet = borders.get(producedFacet);
border = border.maxWith(
borderForProducedFacet.getTop() + requiredBorder.top(),
borderForProducedFacet.getBottom() + requiredBorder.bottom(),
borderForProducedFacet.getSides() + requiredBorder.sides());
}
}
if (updates != null) {
for (Facet producedFacetAnnotation : updates.value()) {
Class<? extends WorldFacet> producedFacet = producedFacetAnnotation.value();
FacetBorder borderForFacetAnnotation = producedFacetAnnotation.border();
ensureBorderCalculatedForFacet(producedFacet, providerChains, borders);
Border3D borderForProducedFacet = borders.get(producedFacet);
border = border.maxWith(
borderForProducedFacet.getTop() + requiredBorder.top() + borderForFacetAnnotation.top(),
borderForProducedFacet.getBottom() + requiredBorder.bottom() + borderForFacetAnnotation.bottom(),
borderForProducedFacet.getSides() + requiredBorder.sides() + borderForFacetAnnotation.sides());
}
}
}
}
}
}
borders.put(facet, border);
}
}
private ListMultimap<Class<? extends WorldFacet>, FacetProvider> determineProviderChains() {
ListMultimap<Class<? extends WorldFacet>, FacetProvider> result = ArrayListMultimap.create();
Set<Class<? extends WorldFacet>> facets = Sets.newHashSet();
for (FacetProvider provider : providersList) {
Produces produces = provider.getClass().getAnnotation(Produces.class);
if (produces != null) {
facets.addAll(Arrays.asList(produces.value()));
}
Updates updates = provider.getClass().getAnnotation(Updates.class);
if (updates != null) {
for (Facet facet : updates.value()) {
facets.add(facet.value());
}
}
}
for (Class<? extends WorldFacet> facet : facets) {
determineProviderChainFor(facet, result);
}
return result;
}
private void determineProviderChainFor(Class<? extends WorldFacet> facet, ListMultimap<Class<? extends WorldFacet>, FacetProvider> result) {
if (result.containsKey(facet)) {
return;
}
if (!facetCalculationInProgress.add(facet)) {
throw new RuntimeException("Circular dependency detected when calculating facet provider ordering for " + facet);
}
Set<FacetProvider> orderedProviders = Sets.newLinkedHashSet();
// first add all @Produces facet providers
for (FacetProvider provider : providersList) {
if (producesFacet(provider, facet)) {
Requires requirements = provider.getClass().getAnnotation(Requires.class);
if (requirements != null) {
for (Facet requirement : requirements.value()) {
determineProviderChainFor(requirement.value(), result);
orderedProviders.addAll(result.get(requirement.value()));
}
}
orderedProviders.add(provider);
}
}
// then add all @Updates facet providers
for (FacetProvider provider : providersList) {
if (updatesFacet(provider, facet)) {
Requires requirements = provider.getClass().getAnnotation(Requires.class);
if (requirements != null) {
for (Facet requirement : requirements.value()) {
determineProviderChainFor(requirement.value(), result);
orderedProviders.addAll(result.get(requirement.value()));
}
}
orderedProviders.add(provider);
}
}
result.putAll(facet, orderedProviders);
facetCalculationInProgress.remove(facet);
}
private boolean producesFacet(FacetProvider provider, Class<? extends WorldFacet> facet) {
Produces produces = provider.getClass().getAnnotation(Produces.class);
if (produces != null && Arrays.asList(produces.value()).contains(facet)) {
return true;
}
return false;
}
private boolean updatesFacet(FacetProvider provider, Class<? extends WorldFacet> facet) {
Updates updates = provider.getClass().getAnnotation(Updates.class);
if (updates != null) {
for (Facet updatedFacet : updates.value()) {
if (updatedFacet.value() == facet) {
return true;
}
}
}
return false;
}
public FacetedWorldConfigurator createConfigurator() {
List<ConfigurableFacetProvider> configurables = new ArrayList<>();
for (FacetProvider facetProvider : providersList) {
if (facetProvider instanceof ConfigurableFacetProvider) {
configurables.add((ConfigurableFacetProvider) facetProvider);
}
}
FacetedWorldConfigurator worldConfigurator = new FacetedWorldConfigurator(configurables);
return worldConfigurator;
}
}
| engine/src/main/java/org/terasology/world/generation/WorldBuilder.java | /*
* Copyright 2014 MovingBlocks
*
* 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.terasology.world.generation;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.world.generator.plugin.WorldGeneratorPluginLibrary;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Immortius
*/
public class WorldBuilder {
private static final Logger logger = LoggerFactory.getLogger(WorldBuilder.class);
private final List<FacetProvider> providersList = Lists.newArrayList();
private final Set<Class<? extends WorldFacet>> facetCalculationInProgress = Sets.newHashSet();
private final List<WorldRasterizer> rasterizers = Lists.newArrayList();
private final List<EntityProvider> entityProviders = new ArrayList<>();
private int seaLevel = 32;
private Long seed;
private WorldGeneratorPluginLibrary pluginLibrary;
public WorldBuilder(WorldGeneratorPluginLibrary pluginLibrary) {
this.pluginLibrary = pluginLibrary;
}
public WorldBuilder addProvider(FacetProvider provider) {
providersList.add(provider);
return this;
}
public WorldBuilder addRasterizer(WorldRasterizer rasterizer) {
rasterizers.add(rasterizer);
return this;
}
public WorldBuilder addEntities(EntityProvider entityProvider) {
entityProviders.add(entityProvider);
return this;
}
public WorldBuilder addPlugins() {
pluginLibrary.instantiateAllOfType(FacetProviderPlugin.class).forEach(this::addProvider);
pluginLibrary.instantiateAllOfType(WorldRasterizerPlugin.class).forEach(this::addRasterizer);
return this;
}
/**
* @param level the sea level, measured in blocks
* @return this
*/
public WorldBuilder setSeaLevel(int level) {
this.seaLevel = level;
return this;
}
public void setSeed(long seed) {
this.seed = seed;
}
public World build() {
// TODO: ensure the required providers are present
if (seed == null) {
throw new IllegalStateException("Seed has not been set");
}
for (FacetProvider provider : providersList) {
provider.setSeed(seed);
}
ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains = determineProviderChains();
return new WorldImpl(providerChains, rasterizers, entityProviders, determineBorders(providerChains), seaLevel);
}
private Map<Class<? extends WorldFacet>, Border3D> determineBorders(ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains) {
Map<Class<? extends WorldFacet>, Border3D> borders = Maps.newHashMap();
for (Class<? extends WorldFacet> facet : providerChains.keySet()) {
ensureBorderCalculatedForFacet(facet, providerChains, borders);
}
return borders;
}
private void ensureBorderCalculatedForFacet(Class<? extends WorldFacet> facet, ListMultimap<Class<? extends WorldFacet>, FacetProvider> providerChains,
Map<Class<? extends WorldFacet>, Border3D> borders) {
if (!borders.containsKey(facet)) {
Border3D border = new Border3D(0, 0, 0);
for (FacetProvider facetProvider : providerChains.values()) {
// Find all facets that require it
Requires requires = facetProvider.getClass().getAnnotation(Requires.class);
if (requires != null) {
for (Facet requiredFacet : requires.value()) {
if (requiredFacet.value() == facet) {
Produces produces = facetProvider.getClass().getAnnotation(Produces.class);
Updates updates = facetProvider.getClass().getAnnotation(Updates.class);
FacetBorder requiredBorder = requiredFacet.border();
if (produces != null) {
for (Class<? extends WorldFacet> producedFacet : produces.value()) {
ensureBorderCalculatedForFacet(producedFacet, providerChains, borders);
Border3D borderForProducedFacet = borders.get(producedFacet);
border = border.maxWith(
borderForProducedFacet.getTop() + requiredBorder.top(),
borderForProducedFacet.getBottom() + requiredBorder.bottom(),
borderForProducedFacet.getSides() + requiredBorder.sides());
}
}
if (updates != null) {
for (Facet producedFacetAnnotation : updates.value()) {
Class<? extends WorldFacet> producedFacet = producedFacetAnnotation.value();
FacetBorder borderForFacetAnnotation = producedFacetAnnotation.border();
ensureBorderCalculatedForFacet(producedFacet, providerChains, borders);
Border3D borderForProducedFacet = borders.get(producedFacet);
border = border.maxWith(
borderForProducedFacet.getTop() + requiredBorder.top() + borderForFacetAnnotation.top(),
borderForProducedFacet.getBottom() + requiredBorder.bottom() + borderForFacetAnnotation.bottom(),
borderForProducedFacet.getSides() + requiredBorder.sides() + borderForFacetAnnotation.sides());
}
}
}
}
}
}
borders.put(facet, border);
}
}
private ListMultimap<Class<? extends WorldFacet>, FacetProvider> determineProviderChains() {
ListMultimap<Class<? extends WorldFacet>, FacetProvider> result = ArrayListMultimap.create();
Set<Class<? extends WorldFacet>> facets = Sets.newHashSet();
for (FacetProvider provider : providersList) {
Produces produces = provider.getClass().getAnnotation(Produces.class);
if (produces != null) {
facets.addAll(Arrays.asList(produces.value()));
}
Updates updates = provider.getClass().getAnnotation(Updates.class);
if (updates != null) {
for (Facet facet : updates.value()) {
facets.add(facet.value());
}
}
}
for (Class<? extends WorldFacet> facet : facets) {
determineProviderChainFor(facet, result);
}
return result;
}
private void determineProviderChainFor(Class<? extends WorldFacet> facet, ListMultimap<Class<? extends WorldFacet>, FacetProvider> result) {
if (result.containsKey(facet)) {
return;
}
if (!facetCalculationInProgress.add(facet)) {
throw new RuntimeException("Circular dependency detected when calculating facet provider ordering for " + facet);
}
Set<FacetProvider> orderedProviders = Sets.newLinkedHashSet();
for (FacetProvider provider : providersList) {
if (producesFacet(provider, facet)) {
Requires requirements = provider.getClass().getAnnotation(Requires.class);
if (requirements != null) {
for (Facet requirement : requirements.value()) {
determineProviderChainFor(requirement.value(), result);
orderedProviders.addAll(result.get(requirement.value()));
}
}
orderedProviders.add(provider);
}
}
result.putAll(facet, orderedProviders);
facetCalculationInProgress.remove(facet);
}
private boolean producesFacet(FacetProvider provider, Class<? extends WorldFacet> facet) {
Produces produces = provider.getClass().getAnnotation(Produces.class);
if (produces != null && Arrays.asList(produces.value()).contains(facet)) {
return true;
}
Updates updates = provider.getClass().getAnnotation(Updates.class);
if (updates != null) {
for (Facet updatedFacet : updates.value()) {
if (updatedFacet.value() == facet) {
return true;
}
}
}
return false;
}
public FacetedWorldConfigurator createConfigurator() {
List<ConfigurableFacetProvider> configurables = new ArrayList<>();
for (FacetProvider facetProvider : providersList) {
if (facetProvider instanceof ConfigurableFacetProvider) {
configurables.add((ConfigurableFacetProvider) facetProvider);
}
}
FacetedWorldConfigurator worldConfigurator = new FacetedWorldConfigurator(configurables);
return worldConfigurator;
}
}
| Add updating providers after producing providers
| engine/src/main/java/org/terasology/world/generation/WorldBuilder.java | Add updating providers after producing providers | <ide><path>ngine/src/main/java/org/terasology/world/generation/WorldBuilder.java
<ide> throw new RuntimeException("Circular dependency detected when calculating facet provider ordering for " + facet);
<ide> }
<ide> Set<FacetProvider> orderedProviders = Sets.newLinkedHashSet();
<add>
<add> // first add all @Produces facet providers
<ide> for (FacetProvider provider : providersList) {
<ide> if (producesFacet(provider, facet)) {
<ide> Requires requirements = provider.getClass().getAnnotation(Requires.class);
<ide> orderedProviders.add(provider);
<ide> }
<ide> }
<add> // then add all @Updates facet providers
<add> for (FacetProvider provider : providersList) {
<add> if (updatesFacet(provider, facet)) {
<add> Requires requirements = provider.getClass().getAnnotation(Requires.class);
<add> if (requirements != null) {
<add> for (Facet requirement : requirements.value()) {
<add> determineProviderChainFor(requirement.value(), result);
<add> orderedProviders.addAll(result.get(requirement.value()));
<add> }
<add> }
<add> orderedProviders.add(provider);
<add> }
<add> }
<ide> result.putAll(facet, orderedProviders);
<ide> facetCalculationInProgress.remove(facet);
<ide> }
<ide> if (produces != null && Arrays.asList(produces.value()).contains(facet)) {
<ide> return true;
<ide> }
<del>
<add> return false;
<add> }
<add>
<add> private boolean updatesFacet(FacetProvider provider, Class<? extends WorldFacet> facet) {
<ide> Updates updates = provider.getClass().getAnnotation(Updates.class);
<ide> if (updates != null) {
<ide> for (Facet updatedFacet : updates.value()) { |
|
Java | apache-2.0 | 07ee4a522b65c73c7d770b618b0454e95e9e9544 | 0 | mbudiu-vmw/hiero,uwieder/hiero,uwieder/hiero,lalithsuresh/hiero,lalithsuresh/hiero,mbudiu-vmw/hiero,mbudiu-vmw/hiero,lalithsuresh/hiero,lalithsuresh/hiero,uwieder/hiero,mbudiu-vmw/hiero,mbudiu-vmw/hiero,uwieder/hiero,uwieder/hiero,lalithsuresh/hiero | /*
* Copyright (c) 2017 VMware Inc. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.hiero.utils;
import org.apache.commons.math3.random.MersenneTwister;
import javax.annotation.Nullable;
public class Randomness {
final private MersenneTwister myPrg;
public Randomness() {
this.myPrg = new MersenneTwister();
}
public Randomness(long seed) {
this.myPrg = new MersenneTwister(seed);
}
public int nextInt() { return this.myPrg.nextInt(); }
public int nextInt(int range) { return this.myPrg.nextInt(range); }
public double nextDouble() { return this.myPrg.nextDouble(); }
public void setSeed(long seed) { this.myPrg.setSeed(seed); }
public boolean nextBoolean() { return this.myPrg.nextBoolean(); }
/**
* @return the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0
* and standard deviation 1.0 from this random number generator's sequence.
*/
public double nextGaussian() { return this.myPrg.nextGaussian(); }
public long nextLong() { return this.myPrg.nextLong(); }
/**
* returns a long uniformly drawn between 0 (inclusive) and n (exclusive)
*/
public long nextLong(long n) { return this.myPrg.nextLong(n); }
/**
* Generates random bytes and places them into a user-supplied byte array. The number of
* random bytes produced is equal to the length of the byte array.
*/
public void nextBytes(byte[] bytes) { this.myPrg.nextBytes(bytes); }
}
| hieroplatform/src/main/java/org/hiero/utils/Randomness.java | /*
* Copyright (c) 2017 VMware Inc. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.hiero.utils;
import org.apache.commons.math3.random.MersenneTwister;
import javax.annotation.Nullable;
public class Randomness {
//@Nullable
//private static Randomness prg;
final private MersenneTwister myPrg;
public Randomness() {
this.myPrg = new MersenneTwister();
}
public Randomness(long seed) {
this.myPrg = new MersenneTwister(seed);
}
/**
* @return If existing, the instance. Otherwise a new instance.
public Randomness getInstance() {
if (prg == null)
prg = new Randomness();
return prg;
}
*/
/**
* @return a new instance of Randomness, whether one existed before or not.
public Randomness createInstance() {
prg = new Randomness();
return prg;
}
*/
/**
* @return a new instance of Randomness, whether one existed before or not.
public Randomness createInstance(long seed) {
prg = new Randomness(seed);
return prg;
}
*/
public int nextInt() { return this.myPrg.nextInt(); }
public int nextInt(int range) { return this.myPrg.nextInt(range); }
public double nextDouble() { return this.myPrg.nextDouble(); }
public void setSeed(long seed) { this.myPrg.setSeed(seed); }
public boolean nextBoolean() { return this.myPrg.nextBoolean(); }
/**
* @return the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0
* and standard deviation 1.0 from this random number generator's sequence.
*/
public double nextGaussian() { return this.myPrg.nextGaussian(); }
public long nextLong() { return this.myPrg.nextLong(); }
/**
* returns a long uniformly drawn between 0 (inclusive) and n (exclusive)
*/
public long nextLong(long n) { return this.myPrg.nextLong(n); }
/**
* Generates random bytes and places them into a user-supplied byte array. The number of
* random bytes produced is equal to the length of the byte array.
*/
public void nextBytes(byte[] bytes) { this.myPrg.nextBytes(bytes); }
}
| Changed Randomness to be thread safe. Removed the .getInstance() method
| hieroplatform/src/main/java/org/hiero/utils/Randomness.java | Changed Randomness to be thread safe. Removed the .getInstance() method | <ide><path>ieroplatform/src/main/java/org/hiero/utils/Randomness.java
<ide> import javax.annotation.Nullable;
<ide>
<ide> public class Randomness {
<del> //@Nullable
<del> //private static Randomness prg;
<ide> final private MersenneTwister myPrg;
<ide>
<ide> public Randomness() {
<ide> this.myPrg = new MersenneTwister(seed);
<ide> }
<ide>
<del> /**
<del> * @return If existing, the instance. Otherwise a new instance.
<del>
<del> public Randomness getInstance() {
<del> if (prg == null)
<del> prg = new Randomness();
<del> return prg;
<del> }
<del>*/
<del> /**
<del> * @return a new instance of Randomness, whether one existed before or not.
<del>
<del> public Randomness createInstance() {
<del> prg = new Randomness();
<del> return prg;
<del> }
<del>*/
<del> /**
<del> * @return a new instance of Randomness, whether one existed before or not.
<del>
<del> public Randomness createInstance(long seed) {
<del> prg = new Randomness(seed);
<del> return prg;
<del> }
<del>*/
<ide> public int nextInt() { return this.myPrg.nextInt(); }
<ide>
<ide> public int nextInt(int range) { return this.myPrg.nextInt(range); } |
|
Java | mpl-2.0 | 1efcbef2b2bbb0074adb54c28df436ae2cda725b | 0 | zeromq/jeromq,fredoboulo/jeromq,trevorbernard/jeromq,c-rack/jeromq,trevorbernard/jeromq,fredoboulo/jeromq,zeromq/jeromq | /*
Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ 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 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.zeromq;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Arrays;
public class ZBeacon
{
public static final long DEFAULT_BROADCAST_INTERVAL = 1000L;
public static final String DEFAULT_BROADCAST_HOST = "255.255.255.255";
private final int port;
private InetAddress broadcastInetAddress;
private final BroadcastClient broadcastClient;
private final BroadcastServer broadcastServer;
private final byte[] beacon;
private byte[] prefix = {};
private long broadcastInterval = DEFAULT_BROADCAST_INTERVAL;
private Listener listener = null;
public ZBeacon(int port, byte[] beacon)
{
this(DEFAULT_BROADCAST_HOST, port, beacon);
}
public ZBeacon(String host, int port, byte[] beacon)
{
this(host, port, beacon, true);
}
public ZBeacon(String host, int port, byte[] beacon, boolean ignoreLocalAddress)
{
this.port = port;
this.beacon = beacon;
try {
broadcastInetAddress = InetAddress.getByName(host);
}
catch (UnknownHostException unknownHostException) {
throw new RuntimeException(unknownHostException);
}
broadcastServer = new BroadcastServer(ignoreLocalAddress);
broadcastClient = new BroadcastClient();
}
public void start()
{
if (listener != null) {
broadcastServer.start();
}
broadcastClient.start();
}
public void stop() throws InterruptedException
{
if (broadcastClient != null) {
broadcastClient.interrupt();
broadcastClient.join();
}
if (broadcastServer != null) {
broadcastServer.interrupt();
broadcastServer.join();
}
}
public void setPrefix(byte[] prefix)
{
this.prefix = prefix;
}
public byte[] getPrefix()
{
return prefix;
}
public void setListener(Listener listener)
{
this.listener = listener;
}
public Listener getListener()
{
return listener;
}
/**
* All beacons with matching prefix are passed to a listener.
*/
public interface Listener
{
void onBeacon(InetAddress sender, byte[] beacon);
}
/**
* The broadcast client periodically sends beacons via UDP to the network.
*/
private class BroadcastClient extends Thread
{
private DatagramChannel broadcastChannel;
private final InetSocketAddress broadcastInetSocketAddress;
public BroadcastClient()
{
broadcastInetSocketAddress = new InetSocketAddress(broadcastInetAddress, port);
}
@Override
public void run()
{
try {
broadcastChannel = DatagramChannel.open();
broadcastChannel.socket().setBroadcast(true);
while (!interrupted()) {
try {
broadcastChannel.send(ByteBuffer.wrap(beacon), broadcastInetSocketAddress);
Thread.sleep(broadcastInterval);
}
catch (InterruptedException interruptedException) {
break;
}
catch (Exception exception) {
throw new RuntimeException(exception);
}
}
}
catch (IOException ioException) {
throw new RuntimeException(ioException);
}
finally {
try {
broadcastChannel.close();
}
catch (IOException ioException) {
throw new RuntimeException(ioException);
}
}
}
}
/**
* The broadcast server receives beacons.
*/
private class BroadcastServer extends Thread
{
private DatagramChannel handle; // Socket for send/recv
private final boolean ignoreLocalAddress;
public BroadcastServer(boolean ignoreLocalAddress)
{
this.ignoreLocalAddress = ignoreLocalAddress;
try {
// Create UDP socket
handle = DatagramChannel.open();
handle.configureBlocking(false);
DatagramSocket sock = handle.socket();
sock.setReuseAddress(true);
sock.bind(new InetSocketAddress(InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }), port));
}
catch (IOException ioException) {
throw new RuntimeException(ioException);
}
}
@Override
public void run()
{
ByteBuffer buffer = ByteBuffer.allocate(65535);
SocketAddress sender;
int size;
while (!interrupted()) {
buffer.clear();
try {
int read = buffer.remaining();
sender = handle.receive(buffer);
if (sender == null) {
continue;
}
InetAddress senderAddress = ((InetSocketAddress) sender).getAddress();
if (ignoreLocalAddress &&
(InetAddress.getLocalHost().getHostAddress().equals(senderAddress.getHostAddress())
|| senderAddress.isAnyLocalAddress()
|| senderAddress.isLoopbackAddress())) {
continue;
}
size = read - buffer.remaining();
handleMessage(buffer, size, senderAddress);
}
catch (IOException ioException) {
throw new RuntimeException(ioException);
}
}
handle.socket().close();
}
private void handleMessage(ByteBuffer buffer, int size, InetAddress from)
{
if (size < prefix.length) {
return;
}
byte[] bytes = buffer.array();
// Compare prefix
for (int i = 0; i < prefix.length; i++) {
if (bytes[i] != prefix[i]) {
return;
}
}
listener.onBeacon(from, Arrays.copyOf(bytes, size));
}
}
public long getBroadcastInterval()
{
return broadcastInterval;
}
public void setBroadcastInterval(long broadcastInterval)
{
this.broadcastInterval = broadcastInterval;
}
}
| src/main/java/org/zeromq/ZBeacon.java | /*
Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ 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 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.zeromq;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
public class ZBeacon
{
public static final long DEFAULT_BROADCAST_INTERVAL = 1000L;
public static final String DEFAULT_BROADCAST_HOST = "255.255.255.255";
private final int port;
private InetAddress broadcastInetAddress;
private BroadcastClient broadcastClient;
private BroadcastServer broadcastServer;
private final byte[] beacon;
private byte[] prefix = {};
private long broadcastInterval = DEFAULT_BROADCAST_INTERVAL;
private Listener listener = null;
public ZBeacon(int port, byte[] beacon)
{
this(DEFAULT_BROADCAST_HOST, port, beacon);
}
public ZBeacon(String host, int port, byte[] beacon)
{
this.port = port;
this.beacon = beacon;
try {
broadcastInetAddress = InetAddress.getByName(host);
}
catch (UnknownHostException unknownHostException) {
throw new RuntimeException(unknownHostException);
}
}
public void start()
{
if (listener != null) {
broadcastServer = new BroadcastServer();
broadcastServer.start();
}
broadcastClient = new BroadcastClient();
broadcastClient.start();
}
public void stop() throws InterruptedException
{
if (broadcastClient != null) {
broadcastClient.interrupt();
broadcastClient.join();
broadcastClient = null;
}
if (broadcastServer != null) {
broadcastServer.interrupt();
broadcastServer.join();
broadcastServer = null;
}
}
public void setPrefix(byte[] prefix)
{
this.prefix = prefix;
}
public byte[] getPrefix()
{
return prefix;
}
public void setListener(Listener listener)
{
this.listener = listener;
}
public Listener getListener()
{
return listener;
}
/**
* All beacons with matching prefix are passed to a listener.
*/
public interface Listener
{
void onBeacon(InetAddress sender, byte[] beacon);
}
/**
* The broadcast client periodically sends beacons via UDP to the network.
*/
private class BroadcastClient extends Thread
{
private DatagramChannel broadcastChannel;
private final InetSocketAddress broadcastInetSocketAddress;
public BroadcastClient()
{
broadcastInetSocketAddress = new InetSocketAddress(broadcastInetAddress, port);
}
@Override
public void run()
{
try {
broadcastChannel = DatagramChannel.open();
broadcastChannel.socket().setBroadcast(true);
while (!interrupted()) {
try {
broadcastChannel.send(ByteBuffer.wrap(beacon), broadcastInetSocketAddress);
Thread.sleep(broadcastInterval);
}
catch (InterruptedException interruptedException) {
break;
}
catch (Exception exception) {
throw new RuntimeException(exception);
}
}
}
catch (IOException ioException) {
throw new RuntimeException(ioException);
}
finally {
try {
broadcastChannel.close();
}
catch (IOException ioException) {
throw new RuntimeException(ioException);
}
}
}
}
/**
* The broadcast server receives beacons.
*/
private class BroadcastServer extends Thread
{
private DatagramChannel handle; // Socket for send/recv
private InetAddress address; // Own address
public BroadcastServer()
{
try {
// Create UDP socket
handle = DatagramChannel.open();
handle.configureBlocking(false);
DatagramSocket sock = handle.socket();
sock.setReuseAddress(true);
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(interfaces)) {
if (netint.isLoopback()) {
continue;
}
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress addr : Collections.list(inetAddresses)) {
if (addr instanceof Inet4Address) {
address = addr;
}
}
}
sock.bind(new InetSocketAddress(InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }), port));
}
catch (IOException ioException) {
throw new RuntimeException(ioException);
}
}
@Override
public void run()
{
ByteBuffer buffer = ByteBuffer.allocate(65535);
SocketAddress sender;
int size;
while (!interrupted()) {
buffer.clear();
try {
int read = buffer.remaining();
sender = handle.receive(buffer);
if (sender == null) {
continue;
}
InetAddress senderAddress = ((InetSocketAddress) sender).getAddress();
if (address.equals(senderAddress)) {
continue;
}
size = read - buffer.remaining();
handleMessage(buffer, size, senderAddress);
}
catch (IOException ioException) {
throw new RuntimeException(ioException);
}
}
handle.socket().close();
}
private void handleMessage(ByteBuffer buffer, int size, InetAddress from)
{
if (size < prefix.length) {
return;
}
byte[] bytes = buffer.array();
// Compare prefix
for (int i = 0; i < prefix.length; i++) {
if (bytes[i] != prefix[i]) {
return;
}
}
listener.onBeacon(from, Arrays.copyOf(bytes, size));
}
}
public long getBroadcastInterval()
{
return broadcastInterval;
}
public void setBroadcastInterval(long broadcastInterval)
{
this.broadcastInterval = broadcastInterval;
}
}
| Problem: beacon messages are not always filtered out for local addresses
Solution: Use different technique for checking whether the sender
address is local.
| src/main/java/org/zeromq/ZBeacon.java | Problem: beacon messages are not always filtered out for local addresses | <ide><path>rc/main/java/org/zeromq/ZBeacon.java
<ide>
<ide> import java.io.IOException;
<ide> import java.net.DatagramSocket;
<del>import java.net.Inet4Address;
<ide> import java.net.InetAddress;
<ide> import java.net.InetSocketAddress;
<del>import java.net.NetworkInterface;
<ide> import java.net.SocketAddress;
<ide> import java.net.UnknownHostException;
<ide> import java.nio.ByteBuffer;
<ide> import java.nio.channels.DatagramChannel;
<ide> import java.util.Arrays;
<del>import java.util.Collections;
<del>import java.util.Enumeration;
<ide>
<ide> public class ZBeacon
<ide> {
<ide>
<ide> private final int port;
<ide> private InetAddress broadcastInetAddress;
<del> private BroadcastClient broadcastClient;
<del> private BroadcastServer broadcastServer;
<add> private final BroadcastClient broadcastClient;
<add> private final BroadcastServer broadcastServer;
<ide> private final byte[] beacon;
<ide> private byte[] prefix = {};
<ide> private long broadcastInterval = DEFAULT_BROADCAST_INTERVAL;
<ide>
<ide> public ZBeacon(String host, int port, byte[] beacon)
<ide> {
<add> this(host, port, beacon, true);
<add> }
<add>
<add> public ZBeacon(String host, int port, byte[] beacon, boolean ignoreLocalAddress)
<add> {
<ide> this.port = port;
<ide> this.beacon = beacon;
<ide> try {
<ide> catch (UnknownHostException unknownHostException) {
<ide> throw new RuntimeException(unknownHostException);
<ide> }
<add>
<add> broadcastServer = new BroadcastServer(ignoreLocalAddress);
<add> broadcastClient = new BroadcastClient();
<ide> }
<ide>
<ide> public void start()
<ide> {
<ide> if (listener != null) {
<del> broadcastServer = new BroadcastServer();
<ide> broadcastServer.start();
<ide> }
<del> broadcastClient = new BroadcastClient();
<ide> broadcastClient.start();
<ide> }
<ide>
<ide> if (broadcastClient != null) {
<ide> broadcastClient.interrupt();
<ide> broadcastClient.join();
<del> broadcastClient = null;
<ide> }
<ide> if (broadcastServer != null) {
<ide> broadcastServer.interrupt();
<ide> broadcastServer.join();
<del> broadcastServer = null;
<ide> }
<ide> }
<ide>
<ide> private class BroadcastServer extends Thread
<ide> {
<ide> private DatagramChannel handle; // Socket for send/recv
<del> private InetAddress address; // Own address
<del>
<del> public BroadcastServer()
<del> {
<add> private final boolean ignoreLocalAddress;
<add>
<add> public BroadcastServer(boolean ignoreLocalAddress)
<add> {
<add> this.ignoreLocalAddress = ignoreLocalAddress;
<ide> try {
<ide> // Create UDP socket
<ide> handle = DatagramChannel.open();
<ide> handle.configureBlocking(false);
<ide> DatagramSocket sock = handle.socket();
<ide> sock.setReuseAddress(true);
<del> Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
<del> for (NetworkInterface netint : Collections.list(interfaces)) {
<del> if (netint.isLoopback()) {
<del> continue;
<del> }
<del> Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
<del> for (InetAddress addr : Collections.list(inetAddresses)) {
<del> if (addr instanceof Inet4Address) {
<del> address = addr;
<del> }
<del> }
<del> }
<ide> sock.bind(new InetSocketAddress(InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }), port));
<ide> }
<ide> catch (IOException ioException) {
<ide>
<ide> InetAddress senderAddress = ((InetSocketAddress) sender).getAddress();
<ide>
<del> if (address.equals(senderAddress)) {
<add> if (ignoreLocalAddress &&
<add> (InetAddress.getLocalHost().getHostAddress().equals(senderAddress.getHostAddress())
<add> || senderAddress.isAnyLocalAddress()
<add> || senderAddress.isLoopbackAddress())) {
<ide> continue;
<ide> }
<add>
<ide> size = read - buffer.remaining();
<ide> handleMessage(buffer, size, senderAddress);
<ide> } |
|
Java | apache-2.0 | 5e175fc190ef313dbde52961436e4bd2556a97ce | 0 | endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS | package org.endeavourhealth.hl7;
import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.HapiContext;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v23.datatype.CX;
import ca.uhn.hl7v2.model.v23.group.ADT_A44_PATIENT;
import ca.uhn.hl7v2.model.v23.segment.MRG;
import ca.uhn.hl7v2.model.v23.segment.PID;
import ca.uhn.hl7v2.parser.Parser;
import ca.uhn.hl7v2.util.Terser;
import ca.uhn.hl7v2.validation.impl.NoValidation;
import com.google.common.base.Strings;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.endeavourhealth.common.config.ConfigManager;
import org.endeavourhealth.common.utility.SlackHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
private static final Logger LOG = LoggerFactory.getLogger(Main.class);
private static HikariDataSource connectionPool = null;
private static HapiContext context;
private static Parser parser;
/**
* utility to check the HL7 Receiver database and move any blocking messages to the Dead Letter Queue
*
* Parameters:
* <db_connection_url> <driver_class> <db_username> <db_password>
*/
public static void main(String[] args) throws Exception {
ConfigManager.Initialize("Hl7Checker");
if (args.length < 5) {
LOG.error("Expecting five parameters:");
LOG.error("<db_connection_url> <driver_class> <db_username> <db_password> <state_file>");
System.exit(0);
return;
}
String url = args[0];
String driverClass = args[1];
String user = args[2];
String pass = args[3];
String stateFile = args[4];
//optional fifth parameter puts it in read only mode
boolean readOnly = false;
if (args.length > 4) {
readOnly = Boolean.parseBoolean(args[4]);
}
LOG.info("Starting HL7 Check on " + url);
try {
openConnectionPool(url, driverClass, user, pass);
context = new DefaultHapiContext();
context.setValidationContext(new NoValidation());
parser = context.getGenericParser();
String sql = "SELECT message_id, channel_id, inbound_message_type, inbound_payload, error_message, pid2 FROM log.message WHERE error_message is not null;";
Connection connection = getConnection();
ResultSet resultSet = executeQuery(connection, sql);
Map<Integer, Integer> previousMessagesInError = readState(stateFile);
Map<Integer, Integer> currentMessagesInError = new HashMap<>();
try {
while (resultSet.next()) {
int messageId = resultSet.getInt(1);
int channelId = resultSet.getInt(2);
String messageType = resultSet.getString(3);
String inboundPayload = resultSet.getString(4);
String errorMessage = resultSet.getString(5);
String localPatientId = resultSet.getString(6);
String ignoreReason = shouldIgnore(channelId, messageType, inboundPayload, errorMessage);
if (!Strings.isNullOrEmpty(ignoreReason)) {
if (readOnly) {
LOG.info("Would have moved message " + messageId + " to the DLQ but in read only mode");
continue;
}
//if we have a non-null reason, move to the DLQ
moveToDlq(messageId, ignoreReason);
//and notify Slack that we've done so
sendSuccessSlackMessage(channelId, messageId, ignoreReason, localPatientId);
} else {
//if we can't ignore it, we need to raise an alert because the queue will now be backing up
Integer lastMessageIdInError = previousMessagesInError.get(new Integer(channelId));
if (lastMessageIdInError == null
|| lastMessageIdInError.intValue() != messageId) {
sendFailureSlackMessage(channelId, messageId, errorMessage);
}
currentMessagesInError.put(new Integer(channelId), new Integer(messageId));
}
}
} finally {
resultSet.close();
connection.close();
}
checkForErrorsBeingCleared(previousMessagesInError, currentMessagesInError);
writeState(currentMessagesInError, stateFile);
} catch (Exception ex) {
LOG.error("", ex);
//although the error may be related to Homerton, just send to one channel for simplicity
SlackHelper.sendSlackMessage(SlackHelper.Channel.Hl7Receiver, "Exception in HL7 Checker", ex);
System.exit(0);
}
LOG.info("Completed HL7 Check on " + url);
System.exit(0);
}
private static void checkForErrorsBeingCleared(Map<Integer, Integer> previousMessagesInError, Map<Integer, Integer> currentMessagesInError) throws Exception {
for (Integer channelId: previousMessagesInError.keySet()) {
Integer previousMessageIdInError = previousMessagesInError.get(channelId);
Integer currentMessageIdInError = currentMessagesInError.get(channelId);
//only send this Slack alert if the current error message ID is null, since if it's non-null, we'll
//have already send a Slack message with the details on the new message we're stuck on
/*if (currentMessageIdInError == null
|| currentMessageIdInError.intValue() != previousMessageIdInError.intValue()) {*/
if (currentMessageIdInError == null) {
String msg = getChannelName(channelId.intValue()) + " HL7 feed is no longer stuck on message " + previousMessageIdInError;
SlackHelper.sendSlackMessage(SlackHelper.Channel.Hl7Receiver, msg);
}
}
}
private static void writeState(Map<Integer, Integer> currentMessages, String stateFile) throws Exception {
//LOG.info("Writing state to " + stateFile);
List<String> lines = new ArrayList<>();
for (Integer channelId: currentMessages.keySet()) {
Integer messageId = currentMessages.get(channelId);
String line = "" + channelId + ":" + messageId;
lines.add(line);
//LOG.info("Writing line: " + line);
}
File f = new File(stateFile);
FileUtils.writeLines(f, null, lines);
//LOG.info("Written");
}
private static Map<Integer, Integer> readState(String stateFile) throws Exception {
//LOG.info("Reading state file from " + stateFile);
Map<Integer, Integer> ret = new HashMap<>();
File f = new File(stateFile);
if (f.exists()) {
//LOG.info("File exists");
List<String> lines = FileUtils.readLines(f, null);
for (String line: lines) {
//LOG.info("Line: " + line);
String[] toks = line.split(":");
String channelId = toks[0];
String messageId = toks[1];
ret.put(Integer.valueOf(channelId), Integer.valueOf(messageId));
}
}
//LOG.info("Read from file into map size " + ret.size());
return ret;
}
private static String getChannelName(int channelId) throws Exception {
String channelName = null;
if (channelId == 1) {
return "Homerton";
} else if (channelId == 2) {
return "Barts";
} else {
throw new Exception("Unknown channel " + channelId);
}
}
private static void sendFailureSlackMessage(int channelId, int messageId, String errorMessage) throws Exception {
String msg = getChannelName(channelId) + " HL7 feed is stuck on message " + messageId + "\n```" + errorMessage + "```";
SlackHelper.sendSlackMessage(SlackHelper.Channel.Hl7Receiver, msg);
}
private static void sendSuccessSlackMessage(int channelId, int messageId, String ignoreReason, String localPatientId) throws Exception {
SlackHelper.Channel channel = null;
if (channelId == 1) {
channel = SlackHelper.Channel.Hl7ReceiverAlertsHomerton;
} else if (channelId == 2) {
channel = SlackHelper.Channel.Hl7ReceiverAlertsBarts;
} else {
throw new Exception("Unknown channel " + channelId);
}
SlackHelper.sendSlackMessage(channel, "HL7 Checker moved message ID " + messageId + " (PatientId=" + localPatientId + "):\r\n" + ignoreReason);
}
/*private static String findMessageSource(int channelId) throws Exception {
String sql = "SELECT channel_name FROM configuration.channel WHERE channel_id = " + channelId + ";";
Connection connection = getConnection();
ResultSet rs = executeQuery(connection, sql);
if (!rs.next()) {
throw new Exception("Failed to find name for channel " + channelId);
}
String ret = rs.getString(1);
rs.close();
connection.close();
return ret;
}*/
private static String shouldIgnore(int channelId, String messageType, String inboundPayload, String errorMessage) throws HL7Exception {
LOG.info("Checking auto-DLQ rules");
LOG.info("channelId:" + channelId);
LOG.info("messageType:" + messageType);
LOG.info("errorMessage:" + errorMessage);
LOG.info("inboundPayload:" + inboundPayload);
// *************************************************************************************************************************************************
// Rules for Homerton
// *************************************************************************************************************************************************
if (channelId == 1
&& messageType.equals("ADT^A44")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] episodeIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String mergeEpisodeId = terser.get("/PATIENT/MRG-5");
LOG.info("mergeEpisodeId:" + mergeEpisodeId);
// If merge episodeId is missing then move to DLQ
if (Strings.isNullOrEmpty(mergeEpisodeId)) {
return "Automatically moved A44 because of missing episode ID";
}
String mergeEpisodeIdSource = terser.get("/PATIENT/MRG-5-4");
LOG.info("mergeEpisodeIdSource:" + mergeEpisodeIdSource);
// If merge episodeId is from Newham then move to DLQ
if (mergeEpisodeIdSource != null && mergeEpisodeIdSource.toUpperCase().startsWith("NEWHAM")) {
return "Automatically moved A44 because of merging Newham episode";
}
}
if (channelId == 1
&& messageType.equals("ADT^A44")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] patientIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String mergePatientId = terser.get("/PATIENT/MRG-1");
LOG.info("mergePatientId:" + mergePatientId);
// If merge patientId is missing then move to DLQ
if (Strings.isNullOrEmpty(mergePatientId)) {
return "Automatically moved A44 because of missing MRG patientId ID";
}
}
// Added 2017-10-24
if (channelId == 1
&& (messageType.startsWith("ADT^"))
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.IllegalArgumentException] episodeIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String episodeId = terser.get("/PV1-19");
LOG.info("episodeId:" + episodeId);
// If episode id / encounter id is missing then move to DLQ
if (Strings.isNullOrEmpty(episodeId)) {
return "Automatically moved ADT because of missing PV1:19";
}
String finNo = terser.get("/PID-18-1");
LOG.info("finNo:" + finNo);
// If episode id / encounter id is missing then move to DLQ
if (Strings.isNullOrEmpty(finNo)) {
return "Automatically moved ADT because of missing PID18.1 (FIN No)";
}
}
if (channelId == 1
&& messageType.startsWith("ADT^")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] episodeIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String finNoType = terser.get("/PID-18-4");
LOG.info("finNoType:" + finNoType);
// If episode id / encounter id is missing then move to DLQ
if (finNoType.compareToIgnoreCase("Newham FIN") == 0) {
return "Automatically moved ADT because PID18.4 (FIN No Type) indicates Newham";
}
}
// Added 2017-11-08
if (channelId == 1
&& messageType.equals("ADT^A34")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) {
LOG.info("Looking for MRG segment");
Message hapiMsg = parser.parse(inboundPayload);
MRG mrg = (MRG) hapiMsg.get("MRG");
// If MRG missing
if (mrg == null || mrg.isEmpty()) {
return "Automatically moved A34 because of missing MRG";
} else {
LOG.info("MRG segment found. isEmpty()=" + mrg.isEmpty());
}
}
// Added 2017-11-10
if (channelId == 1
&& messageType.equals("ADT^A35")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) {
LOG.info("Looking for MRG segment");
Message hapiMsg = parser.parse(inboundPayload);
MRG mrg = (MRG) hapiMsg.get("MRG");
// If MRG missing
if (mrg == null || mrg.isEmpty()) {
return "Automatically moved A35 because of missing MRG";
} else {
LOG.info("MRG segment found. isEmpty()=" + mrg.isEmpty());
}
}
// Added 2018-01-10
if (channelId == 1
&& messageType.startsWith("ADT^")
&& errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] Hospital servicing facility of NEWHAM GENERAL not recognised")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String servicingFacility = terser.get("/PV1-39");
LOG.info("servicingFacility(PV1:39):" + servicingFacility);
// If "NEWHAM GENERAL" then move to DLQ
if (servicingFacility.compareToIgnoreCase("NEWHAM GENERAL") == 0) {
return "Automatically moved ADT because servicing facility is NEWHAM GENERAL in Homerton channel";
}
}
// Added 2018-01-11
if (channelId == 1
&& messageType.startsWith("ADT^")
&& errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] patientIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
//Terser terser = new Terser(hapiMsg);
//String cnn = terser.get("/PID-3");
//LOG.info("PID:3(looking for CNN):" + cnn);
boolean cnnFound = false;
PID pid = (PID) hapiMsg.get("PID");
if (pid != null) {
CX[] pid3s = pid.getPid3_PatientIDInternalID();
if (pid3s != null) {
for (int i = 0; i < pid3s.length; i++) {
LOG.info("PID:3(" + i + "):" + pid3s[i].toString());
if (pid3s[i].toString().indexOf("CNN") == -1) {
LOG.info("CNN NOT FOUND");
} else {
LOG.info("CNN FOUND");
cnnFound = true;
}
}
}
}
// If "CNN" not found then move to DLQ
if (cnnFound == false) {
return "Automatically moved ADT because PID:3 does not contain CNN";
}
}
// *************************************************************************************************************************************************
// Rules for Barts
// *************************************************************************************************************************************************
// Added 2018-01-10
if (channelId == 2
&& messageType.startsWith("ADT^")
&& errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] More than one patient primary care provider")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String gpId = terser.get("/PD1-4(1)-1");
LOG.info("GP(2):" + gpId);
// If multiple GPs then move to DLQ
if (!Strings.isNullOrEmpty(gpId)) {
return "Automatically moved ADT because of multiple GPs in PD1:4";
}
}
if (channelId == 2
&& messageType.equals("ADT^A31")
&& errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] Could not create organisation ")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String gpPracticeId = terser.get("/PD1-3-3");
LOG.info("Practice:" + gpPracticeId);
// If practice id is missing or numeric then move to DLQ
if (Strings.isNullOrEmpty(gpPracticeId)
|| StringUtils.isNumeric(gpPracticeId)) {
return "Automatically moved A31 because of invalid practice code";
}
}
// Added 2017-11-07
if (channelId == 2
&& messageType.startsWith("ADT^")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] episodeIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String episodeId = terser.get("/PV1-19");
LOG.info("episodeId:" + episodeId);
// If episode id / encounter id is missing then move to DLQ
if (Strings.isNullOrEmpty(episodeId)) {
return "Automatically moved ADT because of missing PV1:19";
}
String episodeIdType = terser.get("/PV1-19-5");
LOG.info("episodeIdType:" + episodeIdType);
// If episode id / encounter id is missing then move to DLQ
if (Strings.isNullOrEmpty(episodeIdType)) {
return "Automatically moved ADT because of missing PV1:19.5 - expecting VISITID";
}
}
// Added 2017-11-08
if (channelId == 2
&& messageType.equals("ADT^A34")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) {
LOG.info("Looking for MRG segment");
Message hapiMsg = parser.parse(inboundPayload);
MRG mrg = (MRG) hapiMsg.get("MRG");
// If MRG missing
if (mrg == null || mrg.isEmpty()) {
return "Automatically moved A34 because of missing MRG";
} else {
LOG.info("MRG segment found. isEmpty()=" + mrg.isEmpty());
}
}
// Added 2017-11-08
if (channelId == 2
&& messageType.equals("ADT^A35")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) {
LOG.info("Looking for MRG segment");
Message hapiMsg = parser.parse(inboundPayload);
MRG mrg = (MRG) hapiMsg.get("MRG");
// If MRG missing
if (mrg == null || mrg.isEmpty()) {
return "Automatically moved A35 because of missing MRG";
} else {
LOG.info("MRG segment found. isEmpty()=" + mrg.isEmpty());
}
}
// Added 2018-03-30
if (channelId == 2
&& messageType.startsWith("ADT^A44")
&& errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] patientIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
//Terser terser = new Terser(hapiMsg);
//String cnn = terser.get("/PID-3");
//LOG.info("PID:3(looking for CNN):" + cnn);
try {
boolean MRNFound = false;
ADT_A44_PATIENT group = (ADT_A44_PATIENT) hapiMsg.get("PATIENT");
PID pid = (PID) group.get("PID");
//PID pid = (PID) hapiMsg.get("/PATIENT/PID");
if (pid != null) {
CX[] pid3s = pid.getPid3_PatientIDInternalID();
if (pid3s != null && pid3s.length > 0) {
MRNFound = true;
/* This check might need to be more specific than just 'PID:3 present'
for (int i = 0; i < pid3s.length; i++) {
LOG.info("PID:3(" + i + "):" + pid3s[i].toString());
if (pid3s[i].toString().indexOf("CNN") == -1) {
LOG.info("CNN NOT FOUND");
} else {
LOG.info("CNN FOUND");
MRNFound = true;
}
}*/
}
}
// If "CNN" not found then move to DLQ
if (MRNFound == false) {
return "Automatically moved ADT because PID:3 does not contain MRN";
}
}
catch (Exception ex) {
LOG.info("Error:" + ex.getMessage());
LOG.info("Error:" + hapiMsg.printStructure());
}
}
//return null to indicate we don't ignore it
return null;
}
/*
*
*/
private static void moveToDlq(int messageId, String reason) throws Exception {
//although it looks like a select, it's just invoking a function which performs an update
String sql = "SELECT helper.move_message_to_dead_letter(" + messageId + ", '" + reason + "');";
executeUpdate(sql);
sql = "UPDATE log.message"
+ " SET next_attempt_date = now() - interval '1 hour'"
+ " WHERE message_id = " + messageId + ";";
executeUpdate(sql);
}
/*
*
*/
private static void openConnectionPool(String url, String driverClass, String username, String password) throws Exception {
//force the driver to be loaded
Class.forName(driverClass);
HikariDataSource pool = new HikariDataSource();
pool.setJdbcUrl(url);
pool.setUsername(username);
pool.setPassword(password);
pool.setMaximumPoolSize(4);
pool.setMinimumIdle(1);
pool.setIdleTimeout(60000);
pool.setPoolName("Hl7CheckerPool" + url);
pool.setAutoCommit(false);
connectionPool = pool;
//test getting a connection
Connection conn = pool.getConnection();
conn.close();
}
private static Connection getConnection() throws Exception {
return connectionPool.getConnection();
}
private static void executeUpdate(String sql) throws Exception {
Connection connection = getConnection();
try {
Statement statement = connection.createStatement();
statement.execute(sql);
connection.commit();
} finally {
connection.close();
}
}
private static ResultSet executeQuery(Connection connection, String sql) throws Exception {
Statement statement = connection.createStatement();
return statement.executeQuery(sql);
}
}
| src/utility-hl7-checker/src/main/java/org/endeavourhealth/hl7/Main.java | package org.endeavourhealth.hl7;
import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.HapiContext;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v23.datatype.CX;
import ca.uhn.hl7v2.model.v23.group.ADT_A44_PATIENT;
import ca.uhn.hl7v2.model.v23.segment.MRG;
import ca.uhn.hl7v2.model.v23.segment.PID;
import ca.uhn.hl7v2.parser.Parser;
import ca.uhn.hl7v2.util.Terser;
import ca.uhn.hl7v2.validation.impl.NoValidation;
import com.google.common.base.Strings;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.endeavourhealth.common.config.ConfigManager;
import org.endeavourhealth.common.utility.SlackHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
private static final Logger LOG = LoggerFactory.getLogger(Main.class);
private static HikariDataSource connectionPool = null;
private static HapiContext context;
private static Parser parser;
/**
* utility to check the HL7 Receiver database and move any blocking messages to the Dead Letter Queue
*
* Parameters:
* <db_connection_url> <driver_class> <db_username> <db_password>
*/
public static void main(String[] args) throws Exception {
ConfigManager.Initialize("Hl7Checker");
if (args.length < 5) {
LOG.error("Expecting five parameters:");
LOG.error("<db_connection_url> <driver_class> <db_username> <db_password> <state_file>");
System.exit(0);
return;
}
String url = args[0];
String driverClass = args[1];
String user = args[2];
String pass = args[3];
String stateFile = args[4];
//optional fifth parameter puts it in read only mode
boolean readOnly = false;
if (args.length > 4) {
readOnly = Boolean.parseBoolean(args[4]);
}
LOG.info("Starting HL7 Check on " + url);
try {
openConnectionPool(url, driverClass, user, pass);
context = new DefaultHapiContext();
context.setValidationContext(new NoValidation());
parser = context.getGenericParser();
String sql = "SELECT message_id, channel_id, inbound_message_type, inbound_payload, error_message, pid2 FROM log.message WHERE error_message is not null;";
Connection connection = getConnection();
ResultSet resultSet = executeQuery(connection, sql);
Map<Integer, Integer> previousMessagesInError = readState(stateFile);
Map<Integer, Integer> currentMessagesInError = new HashMap<>();
try {
while (resultSet.next()) {
int messageId = resultSet.getInt(1);
int channelId = resultSet.getInt(2);
String messageType = resultSet.getString(3);
String inboundPayload = resultSet.getString(4);
String errorMessage = resultSet.getString(5);
String localPatientId = resultSet.getString(6);
String ignoreReason = shouldIgnore(channelId, messageType, inboundPayload, errorMessage);
if (!Strings.isNullOrEmpty(ignoreReason)) {
if (readOnly) {
LOG.info("Would have moved message " + messageId + " to the DLQ but in read only mode");
continue;
}
//if we have a non-null reason, move to the DLQ
moveToDlq(messageId, ignoreReason);
//and notify Slack that we've done so
sendSuccessSlackMessage(channelId, messageId, ignoreReason, localPatientId);
} else {
//if we can't ignore it, we need to raise an alert because the queue will now be backing up
Integer lastMessageId = previousMessagesInError.get(new Integer(channelId));
if (lastMessageId == null
|| lastMessageId.intValue() != messageId) {
sendFailureSlackMessage(channelId, messageId, errorMessage);
}
currentMessagesInError.put(new Integer(channelId), new Integer(messageId));
}
}
} finally {
resultSet.close();
connection.close();
}
writeState(currentMessagesInError, stateFile);
} catch (Exception ex) {
LOG.error("", ex);
//although the error may be related to Homerton, just send to one channel for simplicity
SlackHelper.sendSlackMessage(SlackHelper.Channel.Hl7Receiver, "Exception in HL7 Checker", ex);
System.exit(0);
}
LOG.info("Completed HL7 Check on " + url);
System.exit(0);
}
private static void writeState(Map<Integer, Integer> currentMessages, String stateFile) throws Exception {
//LOG.info("Writing state to " + stateFile);
List<String> lines = new ArrayList<>();
for (Integer channelId: currentMessages.keySet()) {
Integer messageId = currentMessages.get(channelId);
String line = "" + channelId + ":" + messageId;
lines.add(line);
//LOG.info("Writing line: " + line);
}
File f = new File(stateFile);
FileUtils.writeLines(f, null, lines);
//LOG.info("Written");
}
private static Map<Integer, Integer> readState(String stateFile) throws Exception {
//LOG.info("Reading state file from " + stateFile);
Map<Integer, Integer> ret = new HashMap<>();
File f = new File(stateFile);
if (f.exists()) {
//LOG.info("File exists");
List<String> lines = FileUtils.readLines(f, null);
for (String line: lines) {
//LOG.info("Line: " + line);
String[] toks = line.split(":");
String channelId = toks[0];
String messageId = toks[1];
ret.put(Integer.valueOf(channelId), Integer.valueOf(messageId));
}
}
//LOG.info("Read from file into map size " + ret.size());
return ret;
}
private static void sendFailureSlackMessage(int channelId, int messageId, String errorMessage) throws Exception {
String channelName = null;
if (channelId == 1) {
channelName = "Homerton";
} else if (channelId == 2) {
channelName = "Barts";
} else {
throw new Exception("Unknown channel " + channelId);
}
String msg = channelName + " HL7 feed is stuck on message " + messageId + "\n```" + errorMessage + "```";
SlackHelper.sendSlackMessage(SlackHelper.Channel.Hl7Receiver, msg);
}
private static void sendSuccessSlackMessage(int channelId, int messageId, String ignoreReason, String localPatientId) throws Exception {
SlackHelper.Channel channel = null;
if (channelId == 1) {
channel = SlackHelper.Channel.Hl7ReceiverAlertsHomerton;
} else if (channelId == 2) {
channel = SlackHelper.Channel.Hl7ReceiverAlertsBarts;
} else {
throw new Exception("Unknown channel " + channelId);
}
SlackHelper.sendSlackMessage(channel, "HL7 Checker moved message ID " + messageId + " (PatientId=" + localPatientId + "):\r\n" + ignoreReason);
}
/*private static String findMessageSource(int channelId) throws Exception {
String sql = "SELECT channel_name FROM configuration.channel WHERE channel_id = " + channelId + ";";
Connection connection = getConnection();
ResultSet rs = executeQuery(connection, sql);
if (!rs.next()) {
throw new Exception("Failed to find name for channel " + channelId);
}
String ret = rs.getString(1);
rs.close();
connection.close();
return ret;
}*/
private static String shouldIgnore(int channelId, String messageType, String inboundPayload, String errorMessage) throws HL7Exception {
LOG.info("Checking auto-DLQ rules");
LOG.info("channelId:" + channelId);
LOG.info("messageType:" + messageType);
LOG.info("errorMessage:" + errorMessage);
LOG.info("inboundPayload:" + inboundPayload);
// *************************************************************************************************************************************************
// Rules for Homerton
// *************************************************************************************************************************************************
if (channelId == 1
&& messageType.equals("ADT^A44")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] episodeIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String mergeEpisodeId = terser.get("/PATIENT/MRG-5");
LOG.info("mergeEpisodeId:" + mergeEpisodeId);
// If merge episodeId is missing then move to DLQ
if (Strings.isNullOrEmpty(mergeEpisodeId)) {
return "Automatically moved A44 because of missing episode ID";
}
String mergeEpisodeIdSource = terser.get("/PATIENT/MRG-5-4");
LOG.info("mergeEpisodeIdSource:" + mergeEpisodeIdSource);
// If merge episodeId is from Newham then move to DLQ
if (mergeEpisodeIdSource != null && mergeEpisodeIdSource.toUpperCase().startsWith("NEWHAM")) {
return "Automatically moved A44 because of merging Newham episode";
}
}
if (channelId == 1
&& messageType.equals("ADT^A44")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] patientIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String mergePatientId = terser.get("/PATIENT/MRG-1");
LOG.info("mergePatientId:" + mergePatientId);
// If merge patientId is missing then move to DLQ
if (Strings.isNullOrEmpty(mergePatientId)) {
return "Automatically moved A44 because of missing MRG patientId ID";
}
}
// Added 2017-10-24
if (channelId == 1
&& (messageType.startsWith("ADT^"))
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.IllegalArgumentException] episodeIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String episodeId = terser.get("/PV1-19");
LOG.info("episodeId:" + episodeId);
// If episode id / encounter id is missing then move to DLQ
if (Strings.isNullOrEmpty(episodeId)) {
return "Automatically moved ADT because of missing PV1:19";
}
String finNo = terser.get("/PID-18-1");
LOG.info("finNo:" + finNo);
// If episode id / encounter id is missing then move to DLQ
if (Strings.isNullOrEmpty(finNo)) {
return "Automatically moved ADT because of missing PID18.1 (FIN No)";
}
}
if (channelId == 1
&& messageType.startsWith("ADT^")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] episodeIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String finNoType = terser.get("/PID-18-4");
LOG.info("finNoType:" + finNoType);
// If episode id / encounter id is missing then move to DLQ
if (finNoType.compareToIgnoreCase("Newham FIN") == 0) {
return "Automatically moved ADT because PID18.4 (FIN No Type) indicates Newham";
}
}
// Added 2017-11-08
if (channelId == 1
&& messageType.equals("ADT^A34")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) {
LOG.info("Looking for MRG segment");
Message hapiMsg = parser.parse(inboundPayload);
MRG mrg = (MRG) hapiMsg.get("MRG");
// If MRG missing
if (mrg == null || mrg.isEmpty()) {
return "Automatically moved A34 because of missing MRG";
} else {
LOG.info("MRG segment found. isEmpty()=" + mrg.isEmpty());
}
}
// Added 2017-11-10
if (channelId == 1
&& messageType.equals("ADT^A35")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) {
LOG.info("Looking for MRG segment");
Message hapiMsg = parser.parse(inboundPayload);
MRG mrg = (MRG) hapiMsg.get("MRG");
// If MRG missing
if (mrg == null || mrg.isEmpty()) {
return "Automatically moved A35 because of missing MRG";
} else {
LOG.info("MRG segment found. isEmpty()=" + mrg.isEmpty());
}
}
// Added 2018-01-10
if (channelId == 1
&& messageType.startsWith("ADT^")
&& errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] Hospital servicing facility of NEWHAM GENERAL not recognised")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String servicingFacility = terser.get("/PV1-39");
LOG.info("servicingFacility(PV1:39):" + servicingFacility);
// If "NEWHAM GENERAL" then move to DLQ
if (servicingFacility.compareToIgnoreCase("NEWHAM GENERAL") == 0) {
return "Automatically moved ADT because servicing facility is NEWHAM GENERAL in Homerton channel";
}
}
// Added 2018-01-11
if (channelId == 1
&& messageType.startsWith("ADT^")
&& errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] patientIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
//Terser terser = new Terser(hapiMsg);
//String cnn = terser.get("/PID-3");
//LOG.info("PID:3(looking for CNN):" + cnn);
boolean cnnFound = false;
PID pid = (PID) hapiMsg.get("PID");
if (pid != null) {
CX[] pid3s = pid.getPid3_PatientIDInternalID();
if (pid3s != null) {
for (int i = 0; i < pid3s.length; i++) {
LOG.info("PID:3(" + i + "):" + pid3s[i].toString());
if (pid3s[i].toString().indexOf("CNN") == -1) {
LOG.info("CNN NOT FOUND");
} else {
LOG.info("CNN FOUND");
cnnFound = true;
}
}
}
}
// If "CNN" not found then move to DLQ
if (cnnFound == false) {
return "Automatically moved ADT because PID:3 does not contain CNN";
}
}
// *************************************************************************************************************************************************
// Rules for Barts
// *************************************************************************************************************************************************
// Added 2018-01-10
if (channelId == 2
&& messageType.startsWith("ADT^")
&& errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] More than one patient primary care provider")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String gpId = terser.get("/PD1-4(1)-1");
LOG.info("GP(2):" + gpId);
// If multiple GPs then move to DLQ
if (!Strings.isNullOrEmpty(gpId)) {
return "Automatically moved ADT because of multiple GPs in PD1:4";
}
}
if (channelId == 2
&& messageType.equals("ADT^A31")
&& errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] Could not create organisation ")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String gpPracticeId = terser.get("/PD1-3-3");
LOG.info("Practice:" + gpPracticeId);
// If practice id is missing or numeric then move to DLQ
if (Strings.isNullOrEmpty(gpPracticeId)
|| StringUtils.isNumeric(gpPracticeId)) {
return "Automatically moved A31 because of invalid practice code";
}
}
// Added 2017-11-07
if (channelId == 2
&& messageType.startsWith("ADT^")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] episodeIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
Terser terser = new Terser(hapiMsg);
String episodeId = terser.get("/PV1-19");
LOG.info("episodeId:" + episodeId);
// If episode id / encounter id is missing then move to DLQ
if (Strings.isNullOrEmpty(episodeId)) {
return "Automatically moved ADT because of missing PV1:19";
}
String episodeIdType = terser.get("/PV1-19-5");
LOG.info("episodeIdType:" + episodeIdType);
// If episode id / encounter id is missing then move to DLQ
if (Strings.isNullOrEmpty(episodeIdType)) {
return "Automatically moved ADT because of missing PV1:19.5 - expecting VISITID";
}
}
// Added 2017-11-08
if (channelId == 2
&& messageType.equals("ADT^A34")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) {
LOG.info("Looking for MRG segment");
Message hapiMsg = parser.parse(inboundPayload);
MRG mrg = (MRG) hapiMsg.get("MRG");
// If MRG missing
if (mrg == null || mrg.isEmpty()) {
return "Automatically moved A34 because of missing MRG";
} else {
LOG.info("MRG segment found. isEmpty()=" + mrg.isEmpty());
}
}
// Added 2017-11-08
if (channelId == 2
&& messageType.equals("ADT^A35")
&& errorMessage.equals("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[org.endeavourhealth.hl7transform.common.TransformException] MRG segment exists less than 1 time(s)")) {
LOG.info("Looking for MRG segment");
Message hapiMsg = parser.parse(inboundPayload);
MRG mrg = (MRG) hapiMsg.get("MRG");
// If MRG missing
if (mrg == null || mrg.isEmpty()) {
return "Automatically moved A35 because of missing MRG";
} else {
LOG.info("MRG segment found. isEmpty()=" + mrg.isEmpty());
}
}
// Added 2018-03-30
if (channelId == 2
&& messageType.startsWith("ADT^A44")
&& errorMessage.startsWith("[org.endeavourhealth.hl7receiver.model.exceptions.HL7MessageProcessorException] Transform failure\r\n[java.lang.NullPointerException] patientIdentifierValue")) {
Message hapiMsg = parser.parse(inboundPayload);
//Terser terser = new Terser(hapiMsg);
//String cnn = terser.get("/PID-3");
//LOG.info("PID:3(looking for CNN):" + cnn);
try {
boolean MRNFound = false;
ADT_A44_PATIENT group = (ADT_A44_PATIENT) hapiMsg.get("PATIENT");
PID pid = (PID) group.get("PID");
//PID pid = (PID) hapiMsg.get("/PATIENT/PID");
if (pid != null) {
CX[] pid3s = pid.getPid3_PatientIDInternalID();
if (pid3s != null && pid3s.length > 0) {
MRNFound = true;
/* This check might need to be more specific than just 'PID:3 present'
for (int i = 0; i < pid3s.length; i++) {
LOG.info("PID:3(" + i + "):" + pid3s[i].toString());
if (pid3s[i].toString().indexOf("CNN") == -1) {
LOG.info("CNN NOT FOUND");
} else {
LOG.info("CNN FOUND");
MRNFound = true;
}
}*/
}
}
// If "CNN" not found then move to DLQ
if (MRNFound == false) {
return "Automatically moved ADT because PID:3 does not contain MRN";
}
}
catch (Exception ex) {
LOG.info("Error:" + ex.getMessage());
LOG.info("Error:" + hapiMsg.printStructure());
}
}
//return null to indicate we don't ignore it
return null;
}
/*
*
*/
private static void moveToDlq(int messageId, String reason) throws Exception {
//although it looks like a select, it's just invoking a function which performs an update
String sql = "SELECT helper.move_message_to_dead_letter(" + messageId + ", '" + reason + "');";
executeUpdate(sql);
sql = "UPDATE log.message"
+ " SET next_attempt_date = now() - interval '1 hour'"
+ " WHERE message_id = " + messageId + ";";
executeUpdate(sql);
}
/*
*
*/
private static void openConnectionPool(String url, String driverClass, String username, String password) throws Exception {
//force the driver to be loaded
Class.forName(driverClass);
HikariDataSource pool = new HikariDataSource();
pool.setJdbcUrl(url);
pool.setUsername(username);
pool.setPassword(password);
pool.setMaximumPoolSize(4);
pool.setMinimumIdle(1);
pool.setIdleTimeout(60000);
pool.setPoolName("Hl7CheckerPool" + url);
pool.setAutoCommit(false);
connectionPool = pool;
//test getting a connection
Connection conn = pool.getConnection();
conn.close();
}
private static Connection getConnection() throws Exception {
return connectionPool.getConnection();
}
private static void executeUpdate(String sql) throws Exception {
Connection connection = getConnection();
try {
Statement statement = connection.createStatement();
statement.execute(sql);
connection.commit();
} finally {
connection.close();
}
}
private static ResultSet executeQuery(Connection connection, String sql) throws Exception {
Statement statement = connection.createStatement();
return statement.executeQuery(sql);
}
}
| Fix to HL7 Checker
| src/utility-hl7-checker/src/main/java/org/endeavourhealth/hl7/Main.java | Fix to HL7 Checker | <ide><path>rc/utility-hl7-checker/src/main/java/org/endeavourhealth/hl7/Main.java
<ide>
<ide> } else {
<ide> //if we can't ignore it, we need to raise an alert because the queue will now be backing up
<del> Integer lastMessageId = previousMessagesInError.get(new Integer(channelId));
<del> if (lastMessageId == null
<del> || lastMessageId.intValue() != messageId) {
<add> Integer lastMessageIdInError = previousMessagesInError.get(new Integer(channelId));
<add> if (lastMessageIdInError == null
<add> || lastMessageIdInError.intValue() != messageId) {
<ide> sendFailureSlackMessage(channelId, messageId, errorMessage);
<ide> }
<ide>
<ide> resultSet.close();
<ide> connection.close();
<ide> }
<add>
<add> checkForErrorsBeingCleared(previousMessagesInError, currentMessagesInError);
<ide>
<ide> writeState(currentMessagesInError, stateFile);
<ide>
<ide> LOG.info("Completed HL7 Check on " + url);
<ide> System.exit(0);
<ide> }
<add>
<add> private static void checkForErrorsBeingCleared(Map<Integer, Integer> previousMessagesInError, Map<Integer, Integer> currentMessagesInError) throws Exception {
<add> for (Integer channelId: previousMessagesInError.keySet()) {
<add> Integer previousMessageIdInError = previousMessagesInError.get(channelId);
<add> Integer currentMessageIdInError = currentMessagesInError.get(channelId);
<add>
<add> //only send this Slack alert if the current error message ID is null, since if it's non-null, we'll
<add> //have already send a Slack message with the details on the new message we're stuck on
<add> /*if (currentMessageIdInError == null
<add> || currentMessageIdInError.intValue() != previousMessageIdInError.intValue()) {*/
<add> if (currentMessageIdInError == null) {
<add>
<add> String msg = getChannelName(channelId.intValue()) + " HL7 feed is no longer stuck on message " + previousMessageIdInError;
<add> SlackHelper.sendSlackMessage(SlackHelper.Channel.Hl7Receiver, msg);
<add> }
<add> }
<add> }
<add>
<ide>
<ide> private static void writeState(Map<Integer, Integer> currentMessages, String stateFile) throws Exception {
<ide>
<ide> return ret;
<ide> }
<ide>
<del> private static void sendFailureSlackMessage(int channelId, int messageId, String errorMessage) throws Exception {
<del>
<add> private static String getChannelName(int channelId) throws Exception {
<ide> String channelName = null;
<ide> if (channelId == 1) {
<del> channelName = "Homerton";
<add> return "Homerton";
<ide>
<ide> } else if (channelId == 2) {
<del> channelName = "Barts";
<add> return "Barts";
<ide>
<ide> } else {
<ide> throw new Exception("Unknown channel " + channelId);
<ide> }
<del>
<del> String msg = channelName + " HL7 feed is stuck on message " + messageId + "\n```" + errorMessage + "```";
<add> }
<add>
<add> private static void sendFailureSlackMessage(int channelId, int messageId, String errorMessage) throws Exception {
<add>
<add> String msg = getChannelName(channelId) + " HL7 feed is stuck on message " + messageId + "\n```" + errorMessage + "```";
<ide> SlackHelper.sendSlackMessage(SlackHelper.Channel.Hl7Receiver, msg);
<ide> }
<ide> |
|
Java | apache-2.0 | 99a105f272ac95b932d28bd398f13ce625db559c | 0 | gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas | package uk.ac.ebi.atlas.species.services;
import com.google.auto.value.AutoValue;
import java.util.Comparator;
@AutoValue
abstract class PopularSpeciesInfo {
static PopularSpeciesInfo create(String species, String kingdom, int baselineExperiments, int differentialExperiments) {
return new AutoValue_PopularSpeciesInfo(species, kingdom, baselineExperiments + differentialExperiments, baselineExperiments, differentialExperiments);
}
abstract String species();
abstract String kingdom();
abstract int totalExperiments();
abstract int baselineExperiments();
abstract int differentialExperiments();
static Comparator<PopularSpeciesInfo> ReverseComparator = new Comparator<PopularSpeciesInfo>() {
@Override
public int compare(PopularSpeciesInfo o1, PopularSpeciesInfo o2) {
return -Integer.compare(o1.totalExperiments(), o2.totalExperiments());
}
};
}
| base/src/main/java/uk/ac/ebi/atlas/species/services/PopularSpeciesInfo.java | package uk.ac.ebi.atlas.species.services;
import com.google.auto.value.AutoValue;
@AutoValue
abstract class PopularSpeciesInfo {
static PopularSpeciesInfo create(String species, String kingdom, int baselineExperiments, int differentialExperiments) {
return new AutoValue_PopularSpeciesInfo(species, kingdom, baselineExperiments + differentialExperiments, baselineExperiments, differentialExperiments);
}
abstract String species();
abstract String kingdom();
abstract int totalExperiments();
abstract int baselineExperiments();
abstract int differentialExperiments();
}
| Add a Comparator instead of implementing Comparable
We then can use this class with FluentIterable.toSortedList.
| base/src/main/java/uk/ac/ebi/atlas/species/services/PopularSpeciesInfo.java | Add a Comparator instead of implementing Comparable We then can use this class with FluentIterable.toSortedList. | <ide><path>ase/src/main/java/uk/ac/ebi/atlas/species/services/PopularSpeciesInfo.java
<ide> package uk.ac.ebi.atlas.species.services;
<ide>
<ide> import com.google.auto.value.AutoValue;
<add>
<add>import java.util.Comparator;
<ide>
<ide> @AutoValue
<ide> abstract class PopularSpeciesInfo {
<ide> abstract int totalExperiments();
<ide> abstract int baselineExperiments();
<ide> abstract int differentialExperiments();
<add>
<add> static Comparator<PopularSpeciesInfo> ReverseComparator = new Comparator<PopularSpeciesInfo>() {
<add> @Override
<add> public int compare(PopularSpeciesInfo o1, PopularSpeciesInfo o2) {
<add> return -Integer.compare(o1.totalExperiments(), o2.totalExperiments());
<add> }
<add> };
<ide> } |
|
Java | mpl-2.0 | aae88f895c70fe4ddac7d962fc6751e1a7e2eac4 | 0 | carlwilson/veraPDF-library | package org.verapdf.model.impl.pb.cos;
import org.apache.pdfbox.cos.COSFloat;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.verapdf.model.coslayer.CosReal;
import org.verapdf.model.impl.BaseTest;
import java.util.Random;
/**
* @author Evgeniy Muravitskiy
*/
public class PBCosRealTest extends BaseTest {
private static float expected;
@BeforeClass
public static void setUp() {
expectedType = TYPES.contains(PBCosReal.COS_REAL_TYPE) ? PBCosReal.COS_REAL_TYPE : null;
expectedID = null;
Random random = new Random();
expected = random.nextFloat();
actual = new PBCosReal(new COSFloat(expected));
}
@Test
// @carlwilson temporarily ignored as it's a "boxing box" issue
public void testGetIntegerMethod() {
Assert.assertEquals(Long.valueOf((long) expected), ((CosReal) actual).getintValue());
}
@Test
public void testGetDoubleMethod() {
Assert.assertEquals(expected, ((CosReal) actual).getrealValue().doubleValue(), 0.00001);
}
@Test
public void testGetRealMethod() {
Assert.assertEquals(expected + "", ((CosReal) actual).getstringValue());
}
@AfterClass
public static void tearDown() {
expectedType = null;
actual = null;
}
}
| model-implementation/src/test/java/org/verapdf/model/impl/pb/cos/PBCosRealTest.java | package org.verapdf.model.impl.pb.cos;
import org.apache.pdfbox.cos.COSFloat;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.verapdf.model.coslayer.CosReal;
import org.verapdf.model.impl.BaseTest;
import java.util.Random;
/**
* @author Evgeniy Muravitskiy
*/
public class PBCosRealTest extends BaseTest {
private static float expected;
@BeforeClass
public static void setUp() {
expectedType = TYPES.contains(PBCosReal.COS_REAL_TYPE) ? PBCosReal.COS_REAL_TYPE : null;
expectedID = null;
Random random = new Random();
expected = random.nextFloat();
actual = new PBCosReal(new COSFloat(expected));
}
@Test
// @carlwilson temporarily ignored as it's a "boxing box" issue
@Ignore public void testGetIntegerMethod() {
Assert.assertEquals(Long.valueOf(expected + ""), ((CosReal) actual).getintValue());
}
@Test
public void testGetDoubleMethod() {
Assert.assertEquals(expected, ((CosReal) actual).getrealValue().doubleValue(), 0.00001);
}
@Test
public void testGetRealMethod() {
Assert.assertEquals(expected + "", ((CosReal) actual).getstringValue());
}
@AfterClass
public static void tearDown() {
expectedType = null;
actual = null;
}
}
| Fixes for CosReal test set
| model-implementation/src/test/java/org/verapdf/model/impl/pb/cos/PBCosRealTest.java | Fixes for CosReal test set | <ide><path>odel-implementation/src/test/java/org/verapdf/model/impl/pb/cos/PBCosRealTest.java
<ide>
<ide> @Test
<ide> // @carlwilson temporarily ignored as it's a "boxing box" issue
<del> @Ignore public void testGetIntegerMethod() {
<del> Assert.assertEquals(Long.valueOf(expected + ""), ((CosReal) actual).getintValue());
<add> public void testGetIntegerMethod() {
<add> Assert.assertEquals(Long.valueOf((long) expected), ((CosReal) actual).getintValue());
<ide> }
<ide>
<ide> @Test |
|
Java | mit | c71a071fe719fde4d7ceed3b187d06b910138c5c | 0 | elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin | package com.elmakers.mine.bukkit.magic;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.text.DecimalFormat;
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.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.bstats.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Skull;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.scheduler.BukkitTask;
import com.elmakers.mine.bukkit.action.ActionHandler;
import com.elmakers.mine.bukkit.api.attributes.AttributeProvider;
import com.elmakers.mine.bukkit.api.block.BoundingBox;
import com.elmakers.mine.bukkit.api.block.Schematic;
import com.elmakers.mine.bukkit.api.block.UndoList;
import com.elmakers.mine.bukkit.api.data.MageData;
import com.elmakers.mine.bukkit.api.data.MageDataCallback;
import com.elmakers.mine.bukkit.api.data.MageDataStore;
import com.elmakers.mine.bukkit.api.data.SpellData;
import com.elmakers.mine.bukkit.api.economy.Currency;
import com.elmakers.mine.bukkit.api.effect.EffectContext;
import com.elmakers.mine.bukkit.api.effect.EffectPlayer;
import com.elmakers.mine.bukkit.api.entity.EntityData;
import com.elmakers.mine.bukkit.api.entity.TeamProvider;
import com.elmakers.mine.bukkit.api.event.LoadEvent;
import com.elmakers.mine.bukkit.api.event.PreLoadEvent;
import com.elmakers.mine.bukkit.api.event.SaveEvent;
import com.elmakers.mine.bukkit.api.integration.ClientPlatform;
import com.elmakers.mine.bukkit.api.item.ItemData;
import com.elmakers.mine.bukkit.api.item.ItemUpdatedCallback;
import com.elmakers.mine.bukkit.api.magic.CastSourceLocation;
import com.elmakers.mine.bukkit.api.magic.DeathLocation;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageContext;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.magic.MagicAPI;
import com.elmakers.mine.bukkit.api.magic.MagicAttribute;
import com.elmakers.mine.bukkit.api.magic.MagicProvider;
import com.elmakers.mine.bukkit.api.magic.MaterialSet;
import com.elmakers.mine.bukkit.api.magic.MaterialSetManager;
import com.elmakers.mine.bukkit.api.protection.BlockBreakManager;
import com.elmakers.mine.bukkit.api.protection.BlockBuildManager;
import com.elmakers.mine.bukkit.api.protection.CastPermissionManager;
import com.elmakers.mine.bukkit.api.protection.EntityTargetingManager;
import com.elmakers.mine.bukkit.api.protection.PVPManager;
import com.elmakers.mine.bukkit.api.protection.PlayerWarp;
import com.elmakers.mine.bukkit.api.protection.PlayerWarpManager;
import com.elmakers.mine.bukkit.api.protection.PlayerWarpProvider;
import com.elmakers.mine.bukkit.api.requirements.Requirement;
import com.elmakers.mine.bukkit.api.requirements.RequirementsProcessor;
import com.elmakers.mine.bukkit.api.requirements.RequirementsProvider;
import com.elmakers.mine.bukkit.api.spell.CastingCost;
import com.elmakers.mine.bukkit.api.spell.MageSpell;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellKey;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.api.spell.SpellTemplate;
import com.elmakers.mine.bukkit.automata.Automaton;
import com.elmakers.mine.bukkit.automata.AutomatonTemplate;
import com.elmakers.mine.bukkit.block.BlockData;
import com.elmakers.mine.bukkit.block.DefaultMaterials;
import com.elmakers.mine.bukkit.block.LegacySchematic;
import com.elmakers.mine.bukkit.block.MaterialAndData;
import com.elmakers.mine.bukkit.block.MaterialBrush;
import com.elmakers.mine.bukkit.citizens.CitizensController;
import com.elmakers.mine.bukkit.configuration.MageParameters;
import com.elmakers.mine.bukkit.configuration.MagicConfiguration;
import com.elmakers.mine.bukkit.data.YamlDataFile;
import com.elmakers.mine.bukkit.dynmap.DynmapController;
import com.elmakers.mine.bukkit.economy.BaseMagicCurrency;
import com.elmakers.mine.bukkit.economy.CustomCurrency;
import com.elmakers.mine.bukkit.economy.ExperienceCurrency;
import com.elmakers.mine.bukkit.economy.HealthCurrency;
import com.elmakers.mine.bukkit.economy.HungerCurrency;
import com.elmakers.mine.bukkit.economy.ItemCurrency;
import com.elmakers.mine.bukkit.economy.LevelCurrency;
import com.elmakers.mine.bukkit.economy.ManaCurrency;
import com.elmakers.mine.bukkit.economy.SpellPointCurrency;
import com.elmakers.mine.bukkit.economy.VaultCurrency;
import com.elmakers.mine.bukkit.elementals.ElementalsController;
import com.elmakers.mine.bukkit.entity.PermissionsTeamProvider;
import com.elmakers.mine.bukkit.entity.ScoreboardTeamProvider;
import com.elmakers.mine.bukkit.essentials.EssentialsController;
import com.elmakers.mine.bukkit.essentials.MagicItemDb;
import com.elmakers.mine.bukkit.essentials.Mailer;
import com.elmakers.mine.bukkit.heroes.HeroesManager;
import com.elmakers.mine.bukkit.integration.BattleArenaManager;
import com.elmakers.mine.bukkit.integration.GenericMetadataNPCSupplier;
import com.elmakers.mine.bukkit.integration.GeyserManager;
import com.elmakers.mine.bukkit.integration.LegacyLibsDisguiseManager;
import com.elmakers.mine.bukkit.integration.LibsDisguiseManager;
import com.elmakers.mine.bukkit.integration.LightAPIManager;
import com.elmakers.mine.bukkit.integration.LogBlockManager;
import com.elmakers.mine.bukkit.integration.ModernLibsDisguiseManager;
import com.elmakers.mine.bukkit.integration.NPCSupplierSet;
import com.elmakers.mine.bukkit.integration.PlaceholderAPIManager;
import com.elmakers.mine.bukkit.integration.SkillAPIManager;
import com.elmakers.mine.bukkit.integration.SkriptManager;
import com.elmakers.mine.bukkit.integration.VaultController;
import com.elmakers.mine.bukkit.integration.mobarena.MobArenaManager;
import com.elmakers.mine.bukkit.kit.KitController;
import com.elmakers.mine.bukkit.kit.MagicKit;
import com.elmakers.mine.bukkit.magic.command.MagicTabExecutor;
import com.elmakers.mine.bukkit.magic.command.MagicTraitCommandExecutor;
import com.elmakers.mine.bukkit.magic.command.WandCommandExecutor;
import com.elmakers.mine.bukkit.magic.command.config.FetchExampleRunnable;
import com.elmakers.mine.bukkit.magic.command.config.UpdateAllExamplesCallback;
import com.elmakers.mine.bukkit.magic.listener.AnvilController;
import com.elmakers.mine.bukkit.magic.listener.BlockController;
import com.elmakers.mine.bukkit.magic.listener.CraftingController;
import com.elmakers.mine.bukkit.magic.listener.EnchantingController;
import com.elmakers.mine.bukkit.magic.listener.EntityController;
import com.elmakers.mine.bukkit.magic.listener.ErrorNotifier;
import com.elmakers.mine.bukkit.magic.listener.ExplosionController;
import com.elmakers.mine.bukkit.magic.listener.HangingController;
import com.elmakers.mine.bukkit.magic.listener.InventoryController;
import com.elmakers.mine.bukkit.magic.listener.ItemController;
import com.elmakers.mine.bukkit.magic.listener.JumpController;
import com.elmakers.mine.bukkit.magic.listener.MinigamesListener;
import com.elmakers.mine.bukkit.magic.listener.MobController;
import com.elmakers.mine.bukkit.magic.listener.MobController2;
import com.elmakers.mine.bukkit.magic.listener.PlayerController;
import com.elmakers.mine.bukkit.magic.listener.WildStackerListener;
import com.elmakers.mine.bukkit.maps.MapController;
import com.elmakers.mine.bukkit.materials.MaterialSets;
import com.elmakers.mine.bukkit.materials.SimpleMaterialSetManager;
import com.elmakers.mine.bukkit.npc.MagicNPC;
import com.elmakers.mine.bukkit.protection.AJParkourManager;
import com.elmakers.mine.bukkit.protection.CitadelManager;
import com.elmakers.mine.bukkit.protection.DeadSoulsManager;
import com.elmakers.mine.bukkit.protection.FactionsManager;
import com.elmakers.mine.bukkit.protection.GriefPreventionManager;
import com.elmakers.mine.bukkit.protection.LocketteManager;
import com.elmakers.mine.bukkit.protection.MultiverseManager;
import com.elmakers.mine.bukkit.protection.NCPManager;
import com.elmakers.mine.bukkit.protection.PreciousStonesManager;
import com.elmakers.mine.bukkit.protection.ProtectionManager;
import com.elmakers.mine.bukkit.protection.PvPManagerManager;
import com.elmakers.mine.bukkit.protection.RedProtectManager;
import com.elmakers.mine.bukkit.protection.ResidenceManager;
import com.elmakers.mine.bukkit.protection.TownyManager;
import com.elmakers.mine.bukkit.protection.WorldGuardManager;
import com.elmakers.mine.bukkit.requirements.RequirementsController;
import com.elmakers.mine.bukkit.resourcepack.ResourcePackManager;
import com.elmakers.mine.bukkit.spell.BaseSpell;
import com.elmakers.mine.bukkit.spell.SpellCategory;
import com.elmakers.mine.bukkit.tasks.ArmorUpdatedTask;
import com.elmakers.mine.bukkit.tasks.AutoSaveTask;
import com.elmakers.mine.bukkit.tasks.AutomataUpdateTask;
import com.elmakers.mine.bukkit.tasks.BatchUpdateTask;
import com.elmakers.mine.bukkit.tasks.ChangeServerTask;
import com.elmakers.mine.bukkit.tasks.ConfigCheckTask;
import com.elmakers.mine.bukkit.tasks.ConfigurationLoadTask;
import com.elmakers.mine.bukkit.tasks.DoMageLoadTask;
import com.elmakers.mine.bukkit.tasks.FinalizeIntegrationTask;
import com.elmakers.mine.bukkit.tasks.FinishGenericIntegrationTask;
import com.elmakers.mine.bukkit.tasks.LoadDataTask;
import com.elmakers.mine.bukkit.tasks.LogNotifyTask;
import com.elmakers.mine.bukkit.tasks.LogWatchdogTask;
import com.elmakers.mine.bukkit.tasks.MageQuitTask;
import com.elmakers.mine.bukkit.tasks.MageUpdateTask;
import com.elmakers.mine.bukkit.tasks.MigrateDataTask;
import com.elmakers.mine.bukkit.tasks.MigrationTask;
import com.elmakers.mine.bukkit.tasks.PostStartupLoadTask;
import com.elmakers.mine.bukkit.tasks.SaveDataTask;
import com.elmakers.mine.bukkit.tasks.SaveMageDataTask;
import com.elmakers.mine.bukkit.tasks.SaveMageTask;
import com.elmakers.mine.bukkit.tasks.UndoUpdateTask;
import com.elmakers.mine.bukkit.tasks.ValidateSpellsTask;
import com.elmakers.mine.bukkit.utility.CompatibilityUtils;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
import com.elmakers.mine.bukkit.utility.DeprecatedUtils;
import com.elmakers.mine.bukkit.utility.EntityMetadataUtils;
import com.elmakers.mine.bukkit.utility.HitboxUtils;
import com.elmakers.mine.bukkit.utility.InventoryUtils;
import com.elmakers.mine.bukkit.utility.LogMessage;
import com.elmakers.mine.bukkit.utility.MagicLogger;
import com.elmakers.mine.bukkit.utility.Messages;
import com.elmakers.mine.bukkit.utility.NMSUtils;
import com.elmakers.mine.bukkit.utility.SafetyUtils;
import com.elmakers.mine.bukkit.utility.SchematicUtils;
import com.elmakers.mine.bukkit.utility.SkinUtils;
import com.elmakers.mine.bukkit.utility.SkullLoadedCallback;
import com.elmakers.mine.bukkit.wand.LostWand;
import com.elmakers.mine.bukkit.wand.Wand;
import com.elmakers.mine.bukkit.wand.WandManaMode;
import com.elmakers.mine.bukkit.wand.WandMode;
import com.elmakers.mine.bukkit.wand.WandTemplate;
import com.elmakers.mine.bukkit.wand.WandUpgradePath;
import com.elmakers.mine.bukkit.warp.MagicWarp;
import com.elmakers.mine.bukkit.warp.WarpController;
import com.elmakers.mine.bukkit.world.MagicWorld;
import com.elmakers.mine.bukkit.world.WorldController;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import de.slikey.effectlib.math.EquationStore;
public class MagicController implements MageController {
private static final String BUILTIN_SPELL_CLASSPATH = "com.elmakers.mine.bukkit.spell.builtin";
private static final String LOST_WANDS_FILE = "lostwands";
private static final String WARPS_FILE = "warps";
private static final String SPELLS_DATA_FILE = "spells";
private static final String AUTOMATA_DATA_FILE = "automata";
private static final String NPC_DATA_FILE = "npcs";
private static final String URL_MAPS_FILE = "imagemaps";
private static final String DEFAULT_DATASTORE_PACKAGE = "com.elmakers.mine.bukkit.data";
private static final long MAGE_CACHE_EXPIRY = 10000;
private static final int MAX_WARNINGS = 10;
private static long LOG_WATCHDOG_TIMEOUT = 30000;
private static final int MAX_ERRORS = 10;
protected static Random random = new Random();
private final Set<String> builtinMageAttributes = ImmutableSet.of(
"health", "health_max", "target_health", "target_health_max",
"location_x", "location_y", "location_z",
"target_location_x", "target_location_y", "target_location_z",
"time", "moon",
"mana", "mana_max", "xp", "level", "bowpull", "bowpower", "damage", "damage_dealt",
"target_mana", "target_mana_max",
"fall_distance",
"air", "air_max", "target_air", "target_air_max",
"hunger", "target_hunger", "play_time"
);
private final Set<String> builtinAttributes = ImmutableSet.of(
"epoch",
// For interval parsing
"hours", "minutes", "seconds", "days", "weeks",
// Other constants
"pi"
);
private final Map<String, AutomatonTemplate> automatonTemplates = new HashMap<>();
private final Map<String, WandTemplate> wandTemplates = new HashMap<>();
private final Map<String, MageClassTemplate> mageClasses = new HashMap<>();
private final Map<String, ModifierTemplate> modifiers = new HashMap<>();
private final Map<String, SpellTemplate> spells = new HashMap<>();
private final Map<String, SpellTemplate> spellAliases = new HashMap<>();
private final Map<String, SpellData> templateDataMap = new HashMap<>();
private final Map<String, SpellCategory> categories = new HashMap<>();
private final Map<String, MagicAttribute> attributes = new HashMap<>();
private final Set<String> registeredAttributes = new HashSet<>();
private final Map<String, com.elmakers.mine.bukkit.magic.Mage> mages = Maps.newConcurrentMap();
private final Set<Mage> pendingConstruction = new HashSet<>();
private final PriorityQueue<UndoList> scheduledUndo = new PriorityQueue<>();
private final Map<String, WeakReference<Schematic>> schematics = new HashMap<>();
private final Map<String, Collection<EffectPlayer>> effects = new HashMap<>();
private final Map<Chunk, Integer> lockedChunks = new HashMap<>();
private final MagicLogger logger;
private final File configFolder;
private final File dataFolder;
private final File defaultsFolder;
private final Map<String, String> exampleKeyNames = new HashMap<>();
// Synchronization
private final Object saveLock = new Object();
private final SimpleMaterialSetManager materialSetManager = new SimpleMaterialSetManager();
private final Map<String, Integer> maxSpellLevels = new HashMap<>();
private final int undoTimeWindow = 6000;
private final Map<String, DamageType> damageTypes = new HashMap<>();
private final Map<Material, String> blockSkins = new HashMap<>();
private final Map<EntityType, String> mobSkins = new HashMap<>();
private final Map<EntityType, MaterialAndData> skullItems = new HashMap<>();
private final Map<EntityType, MaterialAndData> skullWallBlocks = new HashMap<>();
private final Map<EntityType, MaterialAndData> skullGroundBlocks = new HashMap<>();
private final Map<EntityType, Material> mobEggs = new HashMap<>();
private final int toggleMessageRange = 1024;
private final Material defaultMaterial = Material.DIRT;
private final Set<EntityType> undoEntityTypes = new HashSet<>();
private final Set<EntityType> friendlyEntityTypes = new HashSet<>();
private final Map<String, Currency> currencies = new HashMap<>();
private final Map<String, List<MagicNPC>> npcsByChunk = new HashMap<>();
private final Map<UUID, MagicNPC> npcsByEntity = new HashMap<>();
private final Map<UUID, MagicNPC> npcs = new HashMap<>();
private final Map<String, Map<Long, Automaton>> automata = new HashMap<>();
private final Map<Long, Automaton> activeAutomata = new HashMap<>();
private final Map<String, LostWand> lostWands = new HashMap<>();
private final Map<String, Set<String>> lostWandChunks = new HashMap<>();
private final Map<Long, Integer> lightBlocks = new HashMap<>();
private final Map<String, Integer> lightChunks = new HashMap<>();
private final boolean hasDynmap = false;
private final Messages messages = new Messages();
private final Set<String> resolvingKeys = new LinkedHashSet<>();
private final Map<String, MageData> mageDataPreCache = new ConcurrentHashMap<>();
private final FactionsManager factionsManager = new FactionsManager();
private final LocketteManager locketteManager = new LocketteManager();
private final WorldGuardManager worldGuardManager = new WorldGuardManager();
private final PvPManagerManager pvpManager = new PvPManagerManager();
private final MultiverseManager multiverseManager = new MultiverseManager();
private final PreciousStonesManager preciousStonesManager = new PreciousStonesManager();
private final TownyManager townyManager = new TownyManager();
private final GriefPreventionManager griefPreventionManager = new GriefPreventionManager();
private final NCPManager ncpManager = new NCPManager();
private final ProtectionManager protectionManager = new ProtectionManager();
private final Set<MagicProvider> externalProviders = new HashSet<>();
private final List<BlockBreakManager> blockBreakManagers = new ArrayList<>();
private final List<BlockBuildManager> blockBuildManagers = new ArrayList<>();
private final List<PVPManager> pvpManagers = new ArrayList<>();
private final List<CastPermissionManager> castManagers = new ArrayList<>();
private final List<AttributeProvider> attributeProviders = new ArrayList<>();
private final List<TeamProvider> teamProviders = new ArrayList<>();
private final List<EntityTargetingManager> targetingProviders = new ArrayList<>();
private final NPCSupplierSet npcSuppliers = new NPCSupplierSet();
private final Map<String, RequirementsProcessor> requirementProcessors = new HashMap<>();
private final Map<String, PlayerWarpManager> playerWarpManagers = new HashMap<>();
private final Map<Material, String> autoWands = new HashMap<>();
private final Map<String, String> builtinExternalExamples = new HashMap<>();
private MaterialAndData redstoneReplacement = new MaterialAndData(Material.OBSIDIAN);
private @Nonnull
MaterialSet buildingMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet indestructibleMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet restrictedMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet destructibleMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet interactibleMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet containerMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet wearableMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet meleeMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet climbableMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet undoableMaterials = MaterialSets.wildcard();
private boolean backupInventories = true;
private int undoQueueDepth = 256;
private int pendingQueueDepth = 16;
private int undoMaxPersistSize = 0;
private boolean commitOnQuit = false;
private boolean saveNonPlayerMages = false;
private String defaultWandPath = "";
private WandMode defaultWandMode = WandMode.NONE;
private WandMode defaultBrushMode = WandMode.CHEST;
private boolean showMessages = true;
private boolean showCastMessages = false;
private String messagePrefix = "";
private String castMessagePrefix = "";
private boolean soundsEnabled = true;
private String welcomeWand = "";
private int messageThrottle = 0;
private boolean spellDroppingEnabled = false;
private boolean fillingEnabled = false;
private int maxFillLevel = 0;
private boolean essentialsSignsEnabled = false;
private boolean dynmapUpdate = true;
private boolean dynmapShowWands = true;
private boolean dynmapOnlyPlayerSpells = false;
private boolean dynmapShowSpells = true;
private boolean createWorldsEnabled = true;
private float maxDamagePowerMultiplier = 2.0f;
private float maxConstructionPowerMultiplier = 5.0f;
private float maxRadiusPowerMultiplier = 2.5f;
private float maxRadiusPowerMultiplierMax = 4.0f;
private float maxRangePowerMultiplier = 3.0f;
private float maxRangePowerMultiplierMax = 5.0f;
private float maxPower = 100.0f;
private float maxCostReduction = 0.5f;
private float maxCooldownReduction = 0.5f;
private int maxMana = 1000;
private int maxManaRegeneration = 100;
private double worthBase = 1;
private boolean spEnabled = true;
private boolean spEarnEnabled = true;
private boolean castCommandCostFree = false;
private boolean castCommandCooldownFree = false;
private float castCommandPowerMultiplier = 0.0f;
private boolean castConsoleCostFree = false;
private boolean castConsoleCooldownFree = false;
private float castConsolePowerMultiplier = 0.0f;
private float costReduction = 0.0f;
private float cooldownReduction = 0.0f;
private int autoUndo = 0;
private int autoSaveTaskId = 0;
private BukkitTask configCheckTask = null;
private BukkitTask logNotifyTask = null;
private boolean savePlayerData = true;
private boolean externalPlayerData = false;
private boolean asynchronousSaving = true;
private boolean debugEffectLib = false;
private WarpController warpController = null;
private KitController kitController = null;
private Collection<ConfigurationSection> materialColors = null;
private List<Object> materialVariants = null;
private ConfigurationSection blockItems = null;
private MageDataStore mageDataStore = null;
private MageDataStore migrateDataStore = null;
private MigrateDataTask migrateDataTask = null;
private BukkitTask logWatchdogTimer = null;
private MagicPlugin plugin = null;
private int automataUpdateFrequency = 1;
private int mageUpdateFrequency = 5;
private int workFrequency = 1;
private int undoFrequency = 10;
private int workPerUpdate = 5000;
private int logVerbosity = 0;
private boolean showCastHoloText = false;
private boolean showActivateHoloText = false;
private int castHoloTextRange = 0;
private int activateHoloTextRange = 0;
private boolean urlIconsEnabled = true;
private boolean legacyIconsEnabled = false;
private boolean autoSpellUpgradesEnabled = true;
private boolean autoPathUpgradesEnabled = true;
private boolean spellProgressionEnabled = true;
private boolean bypassBuildPermissions = false;
private boolean bypassBreakPermissions = false;
private boolean bypassPvpPermissions = false;
private boolean bypassFriendlyFire = false;
private boolean useScoreboardTeams = false;
private boolean defaultFriendly = true;
private boolean protectLocked = true;
private boolean bindOnGive = false;
private List<List<String>> permissionTeams = null;
private String extraSchematicFilePath = null;
private Mailer mailer = null;
private PhysicsHandler physicsHandler = null;
private List<ConfigurationSection> invalidNPCs = new ArrayList<>();
private List<ConfigurationSection> invalidAutomata = new ArrayList<>();
private int metricsLevel = 5;
private Metrics metrics = null;
private boolean hasEssentials = false;
private boolean hasCommandBook = false;
private String exampleDefaults = null;
private Collection<String> addExamples = null;
private boolean loaded = false;
private boolean shuttingDown = false;
private boolean dataLoaded = false;
private String defaultSkillIcon = "stick";
private boolean despawnMagicMobs = false;
private int skillInventoryRows = 6;
private boolean skillsUseHeroes = true;
private boolean useHeroesMana = true;
private boolean useHeroesParties = true;
private boolean useSkillAPIAllies = true;
private boolean useBattleArenaTeams = true;
private boolean skillsUsePermissions = false;
private boolean useWildStacker = true;
private String heroesSkillPrefix = "";
private String skillsSpell = "";
private boolean isFileLockingEnabled = false;
private int fileLoadDelay = 0;
private Mage reloadingMage = null;
private ResourcePackManager resourcePacks = null;
// Sub-Controllers
private CraftingController crafting = null;
private MobController mobs = null;
private MobController2 mobs2 = null;
private ItemController items = null;
private EnchantingController enchanting = null;
private AnvilController anvil = null;
private MapController maps = null;
private DynmapController dynmap = null;
private ElementalsController elementals = null;
private CitizensController citizens = null;
private BlockController blockController = null;
private HangingController hangingController = null;
private PlayerController playerController = null;
private EntityController entityController = null;
private InventoryController inventoryController = null;
private ExplosionController explosionController = null;
private JumpController jumpController = null;
private WorldController worldController = null;
private @Nonnull
MageIdentifier mageIdentifier = new MageIdentifier();
private boolean citizensEnabled = true;
private boolean logBlockEnabled = true;
private boolean libsDisguiseEnabled = true;
private boolean skillAPIEnabled = true;
private boolean useSkillAPIMana = false;
private boolean placeholdersEnabled = true;
private boolean lightAPIEnabled = true;
private boolean skriptEnabled = true;
private boolean vaultEnabled = true;
private ConfigurationSection residenceConfiguration = null;
private ConfigurationSection redProtectConfiguration = null;
private ConfigurationSection citadelConfiguration = null;
private ConfigurationSection mobArenaConfiguration = null;
private ConfigurationSection ajParkourConfiguration = null;
private boolean castConsoleFeedback = false;
private String editorURL = null;
private boolean reloadVerboseLogging = true;
private boolean hasShopkeepers = false;
private AJParkourManager ajParkourManager = null;
private CitadelManager citadelManager = null;
private ResidenceManager residenceManager = null;
private RedProtectManager redProtectManager = null;
private RequirementsController requirementsController = null;
private HeroesManager heroesManager = null;
private LibsDisguiseManager libsDisguiseManager = null;
private SkillAPIManager skillAPIManager = null;
private BattleArenaManager battleArenaManager = null;
private PlaceholderAPIManager placeholderAPIManager = null;
private LightAPIManager lightAPIManager = null;
private MobArenaManager mobArenaManager = null;
private LogBlockManager logBlockManager = null;
private EssentialsController essentialsController = null;
private DeadSoulsManager deadSoulsController = null;
private boolean loading = false;
private boolean showExampleInstructions = false;
private int disableSpawnReplacement = 0;
private SwingType swingType = SwingType.ANIMATE_IF_ADVENTURE;
private String blockExchangeCurrency = null;
private @Nonnull
MaterialSet offhandMaterials = MaterialSets.empty();
private GeyserManager geyserManager = null;
// Special constructor used for interrogation
public MagicController() {
configFolder = null;
dataFolder = null;
defaultsFolder = null;
this.logger = new MagicLogger(Logger.getLogger("Magic"));
this.materialSetManager.setLogger(logger);
}
public MagicController(final MagicPlugin plugin) {
this.plugin = plugin;
this.logger = new MagicLogger(plugin.getLogger());
resourcePacks = new ResourcePackManager(this);
configFolder = plugin.getDataFolder();
configFolder.mkdirs();
dataFolder = new File(configFolder, "data");
dataFolder.mkdirs();
defaultsFolder = new File(configFolder, "defaults");
defaultsFolder.mkdirs();
}
@Nullable
public static Spell loadSpell(String name, ConfigurationSection node, MageController controller) {
String className = node.getString("class");
if (className == null || className.equalsIgnoreCase("action") || className.equalsIgnoreCase("actionspell")) {
className = "com.elmakers.mine.bukkit.spell.ActionSpell";
} else if (className.indexOf('.') <= 0) {
className = BUILTIN_SPELL_CLASSPATH + "." + className;
}
Class<?> spellClass = null;
try {
spellClass = Class.forName(className);
} catch (Throwable ex) {
controller.getLogger().log(Level.WARNING, "Error loading spell: " + className, ex);
return null;
}
if (spellClass.getAnnotation(Deprecated.class) != null) {
controller.getLogger().warning("Spell " + name + " is using a deprecated spell class " + className + ". This will be removed in the future, please see the default configs for alternatives.");
}
Object newObject;
try {
newObject = spellClass.getDeclaredConstructor().newInstance();
} catch (Throwable ex) {
controller.getLogger().log(Level.WARNING, "Error loading spell: " + className, ex);
return null;
}
if (newObject == null || !(newObject instanceof MageSpell)) {
controller.getLogger().warning("Error loading spell: " + className + ", does it implement MageSpell?");
return null;
}
MageSpell newSpell = (MageSpell) newObject;
newSpell.initialize(controller);
newSpell.loadTemplate(name, node);
com.elmakers.mine.bukkit.api.spell.SpellCategory category = newSpell.getCategory();
if (category instanceof SpellCategory) {
((SpellCategory) category).addSpellTemplate(newSpell);
}
return newSpell;
}
public boolean registerNMSBindings() {
if (!NMSUtils.initialize(getLogger())) {
return false;
}
SkinUtils.initialize(plugin);
EntityMetadataUtils.initialize(plugin);
return true;
}
public void onPlayerJump(Player player) {
if (climbableMaterials.testBlock(player.getLocation().getBlock())) {
return;
}
Mage mage = getRegisteredMage(player);
if (mage != null) {
mage.trigger("jump");
}
}
@Nullable
@Override
public com.elmakers.mine.bukkit.magic.Mage getRegisteredMage(String mageId) {
checkNotNull(mageId);
if (!loaded || shuttingDown) {
return null;
}
return mages.get(mageId);
}
@Nullable
public com.elmakers.mine.bukkit.magic.Mage getRegisteredMage(@Nonnull CommandSender commandSender) {
checkNotNull(commandSender);
if (commandSender instanceof Player) {
return getRegisteredMage((Player) commandSender);
}
String mageId = mageIdentifier.fromCommandSender(commandSender);
return getRegisteredMage(mageId);
}
@Nullable
@Override
public com.elmakers.mine.bukkit.magic.Mage getRegisteredMage(@Nonnull Entity entity) {
checkNotNull(entity);
String id = mageIdentifier.fromEntity(entity);
return mages.get(id);
}
@Nonnull
protected com.elmakers.mine.bukkit.magic.Mage getMageFromEntity(
@Nonnull Entity entity, @Nullable CommandSender commandSender) {
checkNotNull(entity);
String id = mageIdentifier.fromEntity(entity);
return getMage(id, commandSender, entity);
}
@Override
public com.elmakers.mine.bukkit.magic.Mage getAutomaton(String mageId, String mageName) {
checkNotNull(mageId);
checkNotNull(mageName);
com.elmakers.mine.bukkit.magic.Mage mage = getMage(mageId, mageName, null, null);
mage.setIsAutomaton(true);
return mage;
}
@Override
public com.elmakers.mine.bukkit.magic.Mage getMage(String mageId, String mageName) {
checkNotNull(mageId);
checkNotNull(mageName);
return getMage(mageId, mageName, null, null);
}
@Nonnull
public com.elmakers.mine.bukkit.magic.Mage getMage(
@Nonnull String mageId,
@Nullable CommandSender commandSender, @Nullable Entity entity) {
checkState(
commandSender != null || entity != null,
"Need to provide either an entity or a command sender for a non-automata mage.");
return getMage(mageId, null, commandSender, entity);
}
@Nonnull
@Override
public com.elmakers.mine.bukkit.magic.Mage getMage(@Nonnull Player player) {
checkNotNull(player);
return getMageFromEntity(player, player);
}
@Nonnull
@Override
public com.elmakers.mine.bukkit.magic.Mage getMage(@Nonnull Entity entity) {
checkNotNull(entity);
CommandSender commandSender = (entity instanceof Player) ? (Player) entity : null;
return getMageFromEntity(entity, commandSender);
}
@Nonnull
@Override
public com.elmakers.mine.bukkit.magic.Mage getMage(@Nonnull CommandSender commandSender) {
checkNotNull(commandSender);
if (commandSender instanceof Player) {
return getMage((Player) commandSender);
}
String mageId = mageIdentifier.fromCommandSender(commandSender);
return getMage(mageId, commandSender, null);
}
@Nonnull
protected com.elmakers.mine.bukkit.magic.Mage getMage(
@Nonnull String mageId, @Nullable String mageName,
@Nullable CommandSender commandSender, @Nullable Entity entity)
throws PluginNotLoadedException, NoSuchMageException {
checkNotNull(mageId);
if (!loaded) {
if (entity instanceof Player) {
getLogger().warning("Player data request for " + mageId + " (" + commandSender.getName() + ") failed, plugin not loaded yet");
}
throw new PluginNotLoadedException();
}
com.elmakers.mine.bukkit.magic.Mage apiMage = null;
if (!mages.containsKey(mageId)) {
if (shuttingDown) {
if (entity instanceof Player) {
getLogger().warning("Player data request for " + mageId + " (" + commandSender.getName() + ") failed, plugin is shutting down");
}
throw new PluginNotLoadedException();
}
if (entity instanceof Player && !((Player) entity).isOnline() && !isNPC(entity)) {
getLogger().warning("Player data for " + mageId + " (" + entity.getName() + ") loaded while offline!");
Thread.dumpStack();
// This will cause some really bad things to happen if using file locking, so we're going to just skip it.
if (isFileLockingEnabled) {
getLogger().warning("Returning dummy Mage to avoid locking issues");
return new com.elmakers.mine.bukkit.magic.Mage(mageId, this);
}
}
final com.elmakers.mine.bukkit.magic.Mage mage = new com.elmakers.mine.bukkit.magic.Mage(mageId, this);
mages.put(mageId, mage);
mage.setName(mageName);
mage.setCommandSender(commandSender);
mage.setEntity(entity);
if (entity instanceof Player) {
mage.setPlayer((Player) entity);
}
// Check for existing data file
// For now we only do async loads for Players
boolean isPlayer = (entity instanceof Player);
isPlayer = (isPlayer && !isNPC(entity));
if (savePlayerData && mageDataStore != null) {
if (isPlayer) {
mage.setLoading(true);
plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new DoMageLoadTask(this, mage), fileLoadDelay * 20 / 1000);
} else if (saveNonPlayerMages) {
info("Loading mage data for " + mage.getName() + " (" + mage.getId() + ") synchronously");
doLoadData(mage);
} else {
mage.load(null);
}
} else if (externalPlayerData && (isPlayer || saveNonPlayerMages)) {
mage.setLoading(true);
} else {
mage.load(null);
}
apiMage = mage;
} else {
apiMage = mages.get(mageId);
com.elmakers.mine.bukkit.magic.Mage mage = apiMage;
// In case of rapid relog, this mage may have been marked for removal already
mage.setUnloading(false);
// Re-set mage properties
mage.setName(mageName);
mage.setCommandSender(commandSender);
mage.setEntity(entity);
if (entity instanceof Player) {
mage.setPlayer((Player) entity);
}
}
if (apiMage == null) {
getLogger().warning("getMage returning null mage for " + entity + " and " + commandSender);
throw new NoSuchMageException(mageId);
}
return apiMage;
}
public void doSynchronizedLoadData(Mage mage) {
synchronized (saveLock) {
info("Loading mage data for " + mage.getName() + " (" + mage.getId() + ") at " + System.currentTimeMillis());
doLoadData(mage);
}
}
private void doLoadData(Mage mage) {
getMageData(mage.getId(), new MageDataCallback() {
@Override
public void run(MageData data) {
mage.load(data);
}
});
}
public void onPreLogin(AsyncPlayerPreLoginEvent event) {
String id = mageIdentifier.fromPreLogin(event);
Iterator<Map.Entry<String, MageData>> it = mageDataPreCache.entrySet().iterator();
while (it.hasNext()) {
MageData data = it.next().getValue();
if (data.getId().equals(id)) continue;
if (data.getCachedTimestamp() < System.currentTimeMillis() - MAGE_CACHE_EXPIRY) {
it.remove();
info("Removed expired pre-login mage data cache for id " + data.getId());
}
}
if (mageDataPreCache.containsKey(id)) return;
getMageData(id, new MageDataCallback() {
@Override
public void run(MageData data) {
if (data != null) {
info("Cached preloaded mage data cache for id " + data.getId());
mageDataPreCache.put(id, data);
}
}
});
}
private void getMageData(String id, MageDataCallback callback) {
synchronized (saveLock) {
MageData cached = mageDataPreCache.get(id);
if (cached != null) {
info("Loaded preloaded mage data from cache for id " + id);
mageDataPreCache.remove(id);
callback.run(cached);
return;
}
if (mageDataStore == null) {
callback.run(null);
return;
}
try {
mageDataStore.load(id, new MageDataCallback() {
@Override
public void run(MageData data) {
if (data == null && migrateDataStore != null) {
info(" Checking migration data store for mage data for " + id);
migrateDataStore.load(id, new MageDataCallback() {
@Override
public void run(MageData data) {
if (data != null) {
migrateDataStore.migrate(id);
info(" Auto-migrated mage data for " + id + " on load");
}
callback.run(data);
info(" Finished Loading mage data for " + id + " from migration store at " + System.currentTimeMillis());
}
});
} else {
callback.run(data);
info(" Finished Loading mage data for " + id + " at " + System.currentTimeMillis());
}
}
});
} catch (Exception ex) {
getLogger().warning("Failed to load mage data for " + id);
ex.printStackTrace();
}
}
}
public void finalizeMageLoad(com.elmakers.mine.bukkit.magic.Mage mage) {
if (mage.isPlayer()) {
kitController.onJoin(mage);
}
}
@Override
public MagicKit getKit(String key) {
return kitController.getKit(key);
}
@Override
public Set<String> getKitKeys() {
return kitController.getKitKeys();
}
@Nonnull
@Override
public Mage getConsoleMage() {
return getMage(plugin.getServer().getConsoleSender());
}
public void log(String message) {
info(message, 0);
}
@Override
public void info(String message) {
info(message, 1);
}
@Override
public void info(String message, int verbosity) {
if (loading && !reloadVerboseLogging) {
return;
}
if (logVerbosity >= verbosity) {
getLogger().info(message);
}
}
public float getMaxDamagePowerMultiplier() {
return maxDamagePowerMultiplier;
}
public float getMaxConstructionPowerMultiplier() {
return maxConstructionPowerMultiplier;
}
public float getMaxRadiusPowerMultiplier() {
return maxRadiusPowerMultiplier;
}
public float getMaxRadiusPowerMultiplierMax() {
return maxRadiusPowerMultiplierMax;
}
public float getMaxRangePowerMultiplier() {
return maxRangePowerMultiplier;
}
public float getMaxRangePowerMultiplierMax() {
return maxRangePowerMultiplierMax;
}
public int getAutoUndoInterval() {
return autoUndo;
}
public float getMaxPower() {
return maxPower;
}
public double getMaxDamageReduction(String protectionType) {
DamageType damageType = damageTypes.get(protectionType);
return damageType == null ? 0 : damageType.getMaxReduction();
}
public double getMaxAttackMultiplier(String protectionType) {
DamageType damageType = damageTypes.get(protectionType);
return damageType == null ? 1 : damageType.getMaxAttackMultiplier();
}
public double getMaxDefendMultiplier(String protectionType) {
DamageType damageType = damageTypes.get(protectionType);
return damageType == null ? 1 : damageType.getMaxDefendMultiplier();
}
@Override
public @Nonnull
Set<String> getDamageTypes() {
return damageTypes.keySet();
}
@Override
public @Nonnull
Set<String> getAttributes() {
return registeredAttributes;
}
@Override
public @Nonnull
Set<String> getInternalAttributes() {
return attributes.keySet();
}
public float getMaxCostReduction() {
return maxCostReduction;
}
public float getMaxCooldownReduction() {
return maxCooldownReduction;
}
public int getMaxMana() {
return maxMana;
}
public int getMaxManaRegeneration() {
return maxManaRegeneration;
}
@Override
public double getWorthBase() {
return worthBase;
}
@Override
public double getWorthXP() {
return getCurrency("xp").getWorth();
}
@Override
public double getWorthSkillPoints() {
return getCurrency("sp").getWorth();
}
/*
* Undo system
*/
@Nullable
@Override
public ItemStack getWorthItem() {
Currency itemCurrency = getCurrency("item");
if (itemCurrency == null || !(itemCurrency instanceof ItemCurrency)) {
return null;
}
return ((ItemCurrency) itemCurrency).getItem();
}
@Override
public double getWorthItemAmount() {
return getCurrency("item").getWorth();
}
/*
* Random utility functions
*/
@Override
@Nullable
public Currency getCurrency(String key) {
return currencies.get(key);
}
@Override
@Nonnull
public Set<String> getCurrencyKeys() {
return currencies.keySet();
}
public int getUndoQueueDepth() {
return undoQueueDepth;
}
public int getPendingQueueDepth() {
return pendingQueueDepth;
}
@Override
public String getMessagePrefix() {
return messagePrefix;
}
public String getCastMessagePrefix() {
return castMessagePrefix;
}
public boolean showCastMessages() {
return showCastMessages;
}
public boolean showMessages() {
return showMessages;
}
@Override
public boolean soundsEnabled() {
return soundsEnabled;
}
public boolean fillWands() {
return fillingEnabled;
}
@Override
public int getMaxWandFillLevel() {
return maxFillLevel;
}
/*
* Get the log, if you need to debug or log errors.
*/
@Override
public MagicLogger getLogger() {
return logger;
}
public boolean isIndestructible(Location location) {
return isIndestructible(location.getBlock());
}
public boolean isIndestructible(Block block) {
return indestructibleMaterials.testBlock(block);
}
public boolean isDestructible(Block block) {
return destructibleMaterials.testBlock(block);
}
@Override
public boolean isUndoable(Material material) {
return undoableMaterials.testMaterial(material);
}
@Deprecated // Material
protected boolean isRestricted(Material material) {
return restrictedMaterials.testMaterial(material);
}
protected boolean isRestricted(Material material, @Nullable Short data) {
if (restrictedMaterials.testMaterial(material)) {
// Fast path
return true;
}
MaterialAndData materialAndData = new MaterialAndData(material, data);
return restrictedMaterials.testMaterialAndData(materialAndData);
}
public boolean hasBuildPermission(Player player, Location location) {
return hasBuildPermission(player, location.getBlock());
}
public boolean hasBuildPermission(Player player, Block block) {
// Check all protection plugins
if (bypassBuildPermissions) return true;
if (player != null && player.hasPermission("Magic.bypass_build")) return true;
if (hasBypassPermission(player)) return true;
boolean allowed = true;
for (BlockBuildManager manager : blockBuildManagers) {
if (!manager.hasBuildPermission(player, block)) {
allowed = false;
break;
}
}
return allowed;
}
public boolean hasBreakPermission(Player player, Block block) {
// This is the same has hasBuildPermission for everything but Towny!
if (bypassBreakPermissions) return true;
if (player != null && player.hasPermission("Magic.bypass_break")) return true;
if (hasBypassPermission(player)) return true;
boolean allowed = true;
for (BlockBreakManager manager : blockBreakManagers) {
if (!manager.hasBreakPermission(player, block)) {
allowed = false;
break;
}
}
return allowed;
}
@Override
public boolean isExitAllowed(Player player, Location location) {
if (location == null) return true;
return worldGuardManager.isExitAllowed(player, location);
}
@Override
public boolean isPVPAllowed(Player player, Location location) {
if (location == null) return true;
if (bypassPvpPermissions) return true;
if (player != null && player.hasPermission("Magic.bypass_pvp")) return true;
boolean allowed = true;
for (PVPManager manager : pvpManagers) {
if (!manager.isPVPAllowed(player, location)) {
allowed = false;
break;
}
}
return allowed;
}
public void clearCache() {
schematics.clear();
for (Mage mage : mages.values()) {
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
((com.elmakers.mine.bukkit.magic.Mage) mage).clearCache();
}
}
maps.clearCache();
maps.resetAll();
}
/*
* Internal functions - don't call these, or really anything below here.
*/
@Nullable
protected InputStream findSchematic(String schematicName, String extension) {
InputStream inputSchematic;
try {
// Check extra path first
File extraSchematicFile = null;
File magicSchematicFolder = new File(plugin.getDataFolder(), "schematics");
if (magicSchematicFolder.exists()) {
extraSchematicFile = new File(magicSchematicFolder, schematicName + "." + extension);
info("Checking for schematic: " + extraSchematicFile.getAbsolutePath(), 2);
if (!extraSchematicFile.exists()) {
extraSchematicFile = null;
}
}
if (extraSchematicFile == null && extraSchematicFilePath != null && extraSchematicFilePath.length() > 0) {
File schematicFolder = new File(configFolder, "../" + extraSchematicFilePath);
if (schematicFolder.exists()) {
extraSchematicFile = new File(schematicFolder, schematicName + "." + extension);
info("Checking for external schematic: " + extraSchematicFile.getAbsolutePath(), 2);
}
}
if (extraSchematicFile != null && extraSchematicFile.exists()) {
inputSchematic = new FileInputStream(extraSchematicFile);
info("Loading file: " + extraSchematicFile.getAbsolutePath());
} else {
String fileName = schematicName + "." + extension;
inputSchematic = plugin.getResource("schematics/" + fileName);
info("Loading builtin schematic: " + fileName);
}
if (inputSchematic == null) {
throw new FileNotFoundException();
}
} catch (Exception ignored) {
inputSchematic = null;
}
return inputSchematic;
}
@Nullable
@Override
public Schematic loadSchematic(String schematicName) {
if (schematicName == null || schematicName.length() == 0) return null;
if (schematics.containsKey(schematicName)) {
WeakReference<Schematic> schematic = schematics.get(schematicName);
if (schematic != null) {
Schematic cached = schematic.get();
if (cached != null) {
return cached;
}
}
}
// Look for new schematic format first
if (CompatibilityUtils.hasBlockDataSupport()) {
final InputStream inputSchematic = findSchematic(schematicName, "schem");
if (inputSchematic != null) {
com.elmakers.mine.bukkit.block.Schematic schematic = new com.elmakers.mine.bukkit.block.Schematic(this);
schematics.put(schematicName, new WeakReference<>(schematic));
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
SchematicUtils.loadSchematic(inputSchematic, schematic, getLogger());
info("Finished loading schematic");
} catch (Exception ex) {
ex.printStackTrace();
}
});
return schematic;
}
}
// Look for legacy schematic
final InputStream legacySchematic = findSchematic(schematicName, "schematic");
if (legacySchematic == null) {
return null;
}
LegacySchematic schematic = new LegacySchematic(this);
schematics.put(schematicName, new WeakReference<>(schematic));
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
SchematicUtils.loadLegacySchematic(legacySchematic, schematic);
info("Finished loading schematic");
} catch (Exception ex) {
ex.printStackTrace();
}
});
if (schematic == null) {
getLogger().warning("Could not load schematic: " + schematicName);
}
return schematic;
}
@Override
public Collection<String> getBrushKeys() {
List<String> names = new ArrayList<>();
Material[] materials = Material.values();
for (Material material : materials) {
// Only show blocks
if (material.isBlock()) {
names.add(material.name().toLowerCase());
}
}
// Add special materials
for (String brushName : MaterialBrush.SPECIAL_MATERIAL_KEYS) {
names.add(brushName.toLowerCase());
}
// Add schematics
Collection<String> schematics = getSchematicNames();
for (String schematic : schematics) {
names.add("schematic:" + schematic);
}
return names;
}
public Collection<String> getSchematicNames() {
Collection<String> schematicNames = new ArrayList<>();
// Load internal schematics.. this may be a bit expensive.
try {
CodeSource codeSource = MagicTabExecutor.class.getProtectionDomain().getCodeSource();
if (codeSource != null) {
URL jar = codeSource.getLocation();
try (ZipInputStream zip = new ZipInputStream(jar.openStream())) {
ZipEntry entry = zip.getNextEntry();
while (entry != null) {
String name = entry.getName();
if (name.startsWith("schematics/") && (name.endsWith(".schem") || name.endsWith(".schematic"))) {
String schematicName = name
.replace(".schematic", "")
.replace(".schem", "")
.replace("schematics/", "");
schematicNames.add(schematicName);
}
entry = zip.getNextEntry();
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
// Load external schematics
try {
// Check extra path first
if (extraSchematicFilePath != null && extraSchematicFilePath.length() > 0) {
File schematicFolder = new File(configFolder, "../" + extraSchematicFilePath);
for (File schematicFile : schematicFolder.listFiles()) {
if (schematicFile.getName().endsWith(".schematic") || schematicFile.getName().endsWith(".schem")) {
String schematicName = schematicFile.getName()
.replace(".schematic", "")
.replace(".schem", "");
schematicNames.add(schematicName);
}
}
}
} catch (Exception ignored) {
}
return schematicNames;
}
/*
* Saving and loading
*/
public void initialize() {
warpController = new WarpController(this);
kitController = new KitController(this);
crafting = new CraftingController(this);
mobs = new MobController(this);
items = new ItemController(this);
enchanting = new EnchantingController(this);
anvil = new AnvilController(this);
blockController = new BlockController(this);
hangingController = new HangingController(this);
entityController = new EntityController(this);
playerController = new PlayerController(this);
inventoryController = new InventoryController(this);
explosionController = new ExplosionController(this);
requirementsController = new RequirementsController(this);
worldController = new WorldController(this);
if (NMSUtils.hasStatistics()) {
jumpController = new JumpController(this);
}
if (NMSUtils.hasEntityTransformEvent()) {
mobs2 = new MobController2(this);
}
File examplesFolder = new File(getPlugin().getDataFolder(), "examples");
examplesFolder.mkdirs();
File urlMapFile = getDataFile(URL_MAPS_FILE);
File imageCache = new File(dataFolder, "imagemapcache");
imageCache.mkdirs();
maps = new MapController(plugin, urlMapFile, imageCache);
// Initialize EffectLib.
if (com.elmakers.mine.bukkit.effect.EffectPlayer.initialize(plugin, getLogger())) {
getLogger().info("EffectLib initialized");
} else {
getLogger().warning("Failed to initialize EffectLib");
}
// Pre-create schematic folder
File magicSchematicFolder = new File(plugin.getDataFolder(), "schematics");
magicSchematicFolder.mkdirs();
// One-time migration of enchanting.yml
File legacyPathConfig = new File(configFolder, "enchanting.yml");
File pathConfig = new File(configFolder, "paths.yml");
if (!pathConfig.exists() && legacyPathConfig.exists()) {
getLogger().info("Renaming enchanting.yml to paths.yml, please update paths.yml from now on");
legacyPathConfig.renameTo(pathConfig);
}
load();
resourcePacks.startResourcePackChecks();
}
protected void postLoadIntegration() {
if (mobArenaManager != null) {
mobArenaManager.loaded();
}
}
public void processUndo() {
long now = System.currentTimeMillis();
while (scheduledUndo.size() > 0) {
UndoList undo = scheduledUndo.peek();
if (now < undo.getScheduledTime()) {
break;
}
scheduledUndo.poll();
undo.undoScheduled();
}
}
public void processPendingBatches() {
int remainingWork = workPerUpdate;
if (pendingConstruction.isEmpty()) return;
List<Mage> pending = new ArrayList<>(pendingConstruction);
while (remainingWork > 0 && !pending.isEmpty()) {
int workPerMage = Math.max(10, remainingWork / pending.size());
for (Iterator<Mage> iterator = pending.iterator(); iterator.hasNext(); ) {
Mage apiMage = iterator.next();
if (apiMage instanceof com.elmakers.mine.bukkit.magic.Mage) {
com.elmakers.mine.bukkit.magic.Mage mage = ((com.elmakers.mine.bukkit.magic.Mage) apiMage);
int workPerformed = mage.processPendingBatches(workPerMage);
if (!mage.hasPendingBatches()) {
iterator.remove();
pendingConstruction.remove(mage);
} else if (workPerformed < workPerMage) {
// Wait for next tick to process this action further since it's sleeping
iterator.remove();
}
remainingWork -= workPerformed;
}
}
}
}
protected void activateMetrics() {
// Activate Metrics
final MagicController controller = this;
metrics = null;
if (metricsLevel > 0) {
try {
metrics = new Metrics(plugin);
if (metricsLevel > 1) {
metrics.addCustomChart(new Metrics.MultiLineChart("Plugin Integration") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap) {
valueMap.put("Essentials", controller.hasEssentials ? 1 : 0);
valueMap.put("Dynmap", controller.hasDynmap ? 1 : 0);
valueMap.put("Factions", controller.factionsManager.isEnabled() ? 1 : 0);
valueMap.put("WorldGuard", controller.worldGuardManager.isEnabled() ? 1 : 0);
valueMap.put("Elementals", controller.elementalsEnabled() ? 1 : 0);
valueMap.put("Citizens", controller.citizens != null ? 1 : 0);
valueMap.put("CommandBook", controller.hasCommandBook ? 1 : 0);
valueMap.put("PvpManager", controller.pvpManager.isEnabled() ? 1 : 0);
valueMap.put("Multiverse-Core", controller.multiverseManager.isEnabled() ? 1 : 0);
valueMap.put("Towny", controller.townyManager.isEnabled() ? 1 : 0);
valueMap.put("GriefPrevention", controller.griefPreventionManager.isEnabled() ? 1 : 0);
valueMap.put("PreciousStones", controller.preciousStonesManager.isEnabled() ? 1 : 0);
valueMap.put("Lockette", controller.locketteManager.isEnabled() ? 1 : 0);
valueMap.put("NoCheatPlus", controller.ncpManager.isEnabled() ? 1 : 0);
return valueMap;
}
});
metrics.addCustomChart(new Metrics.MultiLineChart("Features Enabled") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap) {
valueMap.put("Crafting", controller.crafting.isEnabled() ? 1 : 0);
valueMap.put("Enchanting", controller.enchanting.isEnabled() ? 1 : 0);
valueMap.put("SP", controller.isSPEnabled() ? 1 : 0);
return valueMap;
}
});
}
if (metricsLevel > 2) {
metrics.addCustomChart(new Metrics.MultiLineChart("Total Casts by Category") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap) {
for (final SpellCategory category : categories.values()) {
valueMap.put(category.getName(), (int) category.getCastCount());
}
return valueMap;
}
});
}
if (metricsLevel > 3) {
metrics.addCustomChart(new Metrics.MultiLineChart("Total Casts") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap) {
for (final SpellTemplate spell : spells.values()) {
if (!(spell instanceof Spell)) continue;
valueMap.put(spell.getName(), (int) spell.getCastCount());
}
return valueMap;
}
});
}
getLogger().info("Activated BStats");
} catch (Exception ex) {
getLogger().warning("Failed to load BStats: " + ex.getMessage());
}
}
}
protected void registerListeners() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(crafting, plugin);
pm.registerEvents(mobs, plugin);
pm.registerEvents(enchanting, plugin);
pm.registerEvents(anvil, plugin);
pm.registerEvents(blockController, plugin);
pm.registerEvents(hangingController, plugin);
pm.registerEvents(entityController, plugin);
pm.registerEvents(playerController, plugin);
pm.registerEvents(inventoryController, plugin);
pm.registerEvents(explosionController, plugin);
if (jumpController != null) {
pm.registerEvents(jumpController, plugin);
}
if (mobs2 != null) {
pm.registerEvents(mobs2, plugin);
}
worldController.registerEvents();
}
public Collection<Mage> getPending() {
return pendingConstruction;
}
public Collection<UndoList> getPendingUndo() {
return scheduledUndo;
}
@Nullable
public UndoList getPendingUndo(Location location) {
return com.elmakers.mine.bukkit.block.UndoList.getUndoList(location);
}
protected void addPending(Mage mage) {
pendingConstruction.add(mage);
}
public boolean removeMarker(String id, String group) {
boolean removed = false;
if (dynmap != null) {
return dynmap.removeMarker(id, group);
}
return removed;
}
public boolean addMarker(String id, String icon, String group, String title, Location location, String description) {
if (location == null || location.getWorld() == null) return false;
return addMarker(id, icon, group, title, location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), description);
}
public boolean addMarker(String id, String icon, String group, String title, String world, int x, int y, int z, String description) {
boolean created = false;
if (dynmap != null) {
created = dynmap.addMarker(id, icon, group, title, world, x, y, z, description);
}
return created;
}
@Nullable
public Collection<String> getMarkerIcons() {
if (dynmap == null) {
return null;
}
return dynmap.getIcons();
}
@Nullable
public Collection<String> getMarkerSets() {
if (dynmap == null) {
return null;
}
return dynmap.getSets();
}
@Override
public File getConfigFolder() {
return configFolder;
}
@Override
public File getDataFolder() {
return dataFolder;
}
protected File getDataFile(String fileName) {
return new File(dataFolder, fileName + ".yml");
}
@Nullable
protected ConfigurationSection loadDataFile(String fileName) {
File dataFile = getDataFile(fileName);
if (!dataFile.exists()) {
return null;
}
Configuration configuration = YamlConfiguration.loadConfiguration(dataFile);
return configuration;
}
protected YamlDataFile createDataFile(String fileName) {
return createDataFile(fileName, true);
}
protected YamlDataFile createDataFile(String fileName, boolean checkBackupSize) {
File dataFile = new File(dataFolder, fileName + ".yml");
YamlDataFile configuration = new YamlDataFile(getLogger(), dataFile, checkBackupSize);
return configuration;
}
protected void notify(CommandSender sender, String message) {
if (sender != null) {
sender.sendMessage(message);
}
for (Player player : Bukkit.getOnlinePlayers()) {
if (player != sender && player.hasPermission("Magic.notify")) {
player.sendMessage(message);
}
}
}
public void finalizeLoad(ConfigurationLoadTask loader, CommandSender sender) {
if (!loader.isSuccessful()) {
notify(sender, ChatColor.RED + "An error occurred reloading configurations, please check server logs!");
// Check for initial load failure on startup
if (!loaded) {
getLogger().severe("*** An error occurred while loading configurations ***");
getLogger().severe("*** Magic will be disabled until the next restart ***");
getLogger().severe("*** Please check the errors above, fix configs ***");
getLogger().severe("*** And restart the server ***");
getLogger().warning("");
getLogger().warning("Note that if you start the server with working configs and");
getLogger().warning("Then use /magic load to test changes, Magic won't break");
getLogger().warning("if there are config issues.");
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(new ErrorNotifier(), plugin);
}
loading = false;
resetLoading(sender);
return;
}
// Clear some cache stuff... mainly this is for debugging/testing.
schematics.clear();
// Clear the equation store to flush out any equations that failed to parse
EquationStore.clear();
// Map aliases of loaded external examples
exampleKeyNames.clear();
exampleKeyNames.putAll(loader.getExampleKeyNames());
// Process loaded data
exampleDefaults = loader.getExampleDefaults();
addExamples = loader.getAddExamples();
// Main configuration
logger.setContext("config");
loadProperties(sender, loader.getMainConfiguration());
// Configurations that don't rely on any external integrations
logger.setContext("messages");
messages.load(loader.getMessages());
processMessages();
logger.setContext("materials");
loadMaterials(loader.getMaterials());
// Load worlds now, we're still in load=STARTUP time
logger.setContext("worlds");
loadWorlds(loader.getWorlds());
logger.setContext(null);
log("Loaded " + worldController.getCount() + " customized worlds");
// We'll need to delay everything else by one tick to let integrating plugins have a chance to load.
if (!loaded) {
// Some first-time registration that's safe to do at startup
activateMetrics();
registerListeners();
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new FinalizeIntegrationTask(this), 1);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new PostStartupLoadTask(this, loader, sender), 2);
} else {
finalizePostStartupLoad(loader, sender);
}
}
public void finalizePostStartupLoad(ConfigurationLoadTask loader, CommandSender sender) {
// Finalize integrations, we only do this one time at startup.
logger.setContext("integration");
// Register currencies and other preload integrations
registerPreLoad(loader.getMainConfiguration());
log("Registered currencies: " + StringUtils.join(currencies.keySet(), ","));
// Load custom attributes, do this prior to loadAttributes
logger.setContext("attributes");
loadAttributes(loader.getAttributes());
logger.setContext(null);
log("Loaded " + attributes.size() + " attributes");
// Do this before spell loading in case of attribute or requirement providers
logger.setContext("integration");
registerManagers();
logger.setContext("effects");
loadEffects(loader.getEffects());
logger.setContext(null);
log("Loaded " + effects.size() + " effect lists");
logger.setContext("items");
items.load(loader.getItems());
logger.setContext(null);
log("Loaded " + items.getCount() + " items");
logger.setContext("wands");
loadWandTemplates(loader.getWands());
logger.setContext(null);
log("Loaded " + getWandTemplates().size() + " wands");
logger.setContext("spells");
loadSpells(sender, loader.getSpells());
logger.setContext(null);
log("Loaded " + spells.size() + " spells");
logger.setContext("kits");
kitController.load(loader.getKits());
logger.setContext(null);
log("Loaded " + kitController.getCount() + " kits");
logger.setContext("classes");
loadMageClasses(loader.getClasses());
logger.setContext(null);
log("Loaded " + mageClasses.size() + " classes");
logger.setContext("modifiers");
loadModifiers(loader.getModifiers());
logger.setContext(null);
log("Loaded " + modifiers.size() + " classes");
logger.setContext("paths");
loadPaths(loader.getPaths());
logger.setContext(null);
log("Loaded " + getPathCount() + " progression paths");
logger.setContext("mobs");
loadMobs(loader.getMobs());
logger.setContext(null);
log("Loaded " + mobs.getCount() + " mob templates");
logger.setContext("automata");
loadAutomatonTemplates(loader.getAutomata());
logger.setContext(null);
log("Loaded " + automatonTemplates.size() + " automata templates");
logger.setContext("crafting");
crafting.load(loader.getCrafting());
// Register crafting recipes
crafting.register(this, plugin);
MagicRecipe.FIRST_REGISTER = false;
logger.setContext(null);
log("Loaded " + crafting.getCount() + " crafting recipes");
if (!loaded) {
postLoadIntegration();
}
// Notify plugins that we've finished loading.
logger.setContext(null);
LoadEvent loadEvent = new LoadEvent(this);
Bukkit.getPluginManager().callEvent(loadEvent);
loaded = true;
loading = false;
// Activate/load any active player Mages
Collection<? extends Player> allPlayers = plugin.getServer().getOnlinePlayers();
for (Player player : allPlayers) {
getMage(player);
}
if (!(sender instanceof ConsoleCommandSender)) {
getLogger().info("Finished loading configuration");
}
if (sender != null && logger.isCapturing() && isLoaded()) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new ValidateSpellsTask(this, sender));
} else {
resetLoading(sender);
notify(sender, ChatColor.AQUA + "Magic " + ChatColor.DARK_AQUA + "configuration reloaded.");
}
if (reloadingMage != null) {
Player player = reloadingMage.getPlayer();
if (!player.hasPermission("Magic.notify")) {
player.sendMessage(ChatColor.AQUA + "Spells reloaded.");
}
reloadingMage.deactivate();
reloadingMage.checkWand();
reloadingMage = null;
}
if (showExampleInstructions) {
showExampleInstructions = false;
showExampleInstructions(sender);
}
Bukkit.getScheduler().runTaskLater(plugin, new MigrationTask(this), 20 * 5);
}
private void processMessages() {
BaseMagicCurrency.formatter = new DecimalFormat(messages.get("numbers.decimal", "#,###.00"));
BaseMagicCurrency.intFormatter = new DecimalFormat(messages.get("numbers.integer", "#,###"));
}
private void registerManagers() {
// Cast Managers
if (worldGuardManager.isEnabled()) castManagers.add(worldGuardManager);
if (preciousStonesManager.isEnabled()) castManagers.add(preciousStonesManager);
if (redProtectManager != null && redProtectManager.isFlagsEnabled()) castManagers.add(redProtectManager);
// Entity Targeting Managers
if (preciousStonesManager.isEnabled()) targetingProviders.add(preciousStonesManager);
if (townyManager.isEnabled()) targetingProviders.add(townyManager);
if (residenceManager != null) targetingProviders.add(residenceManager);
if (redProtectManager != null) targetingProviders.add(redProtectManager);
// PVP Managers
if (worldGuardManager.isEnabled()) pvpManagers.add(worldGuardManager);
if (pvpManager.isEnabled()) pvpManagers.add(pvpManager);
if (multiverseManager.isEnabled()) pvpManagers.add(multiverseManager);
if (preciousStonesManager.isEnabled()) pvpManagers.add(preciousStonesManager);
if (townyManager.isEnabled()) pvpManagers.add(townyManager);
if (griefPreventionManager.isEnabled()) pvpManagers.add(griefPreventionManager);
if (factionsManager.isEnabled()) pvpManagers.add(factionsManager);
if (residenceManager != null) pvpManagers.add(residenceManager);
if (redProtectManager != null) pvpManagers.add(redProtectManager);
// Build Managers
if (worldGuardManager.isEnabled()) blockBuildManagers.add(worldGuardManager);
if (factionsManager.isEnabled()) blockBuildManagers.add(factionsManager);
if (locketteManager.isEnabled()) blockBuildManagers.add(locketteManager);
if (preciousStonesManager.isEnabled()) blockBuildManagers.add(preciousStonesManager);
if (townyManager.isEnabled()) blockBuildManagers.add(townyManager);
if (griefPreventionManager.isEnabled()) blockBuildManagers.add(griefPreventionManager);
if (mobArenaManager != null && mobArenaManager.isProtected()) blockBuildManagers.add(mobArenaManager);
if (residenceManager != null) blockBuildManagers.add(residenceManager);
if (redProtectManager != null) blockBuildManagers.add(redProtectManager);
// Break Managers
if (worldGuardManager.isEnabled()) blockBreakManagers.add(worldGuardManager);
if (factionsManager.isEnabled()) blockBreakManagers.add(factionsManager);
if (locketteManager.isEnabled()) blockBreakManagers.add(locketteManager);
if (preciousStonesManager.isEnabled()) blockBreakManagers.add(preciousStonesManager);
if (townyManager.isEnabled()) blockBreakManagers.add(townyManager);
if (griefPreventionManager.isEnabled()) blockBreakManagers.add(griefPreventionManager);
if (mobArenaManager != null && mobArenaManager.isProtected()) blockBreakManagers.add(mobArenaManager);
if (citadelManager != null) blockBreakManagers.add(citadelManager);
if (residenceManager != null) blockBreakManagers.add(residenceManager);
if (redProtectManager != null) blockBreakManagers.add(redProtectManager);
// Attribute providers
if (skillAPIManager != null) {
attributeProviders.add(skillAPIManager);
}
if (heroesManager != null) {
attributeProviders.add(heroesManager);
}
// We should be done adding attributes now
finalizeAttributes();
// Requirements providers
if (skillAPIManager != null) {
requirementProcessors.put("skillapi", skillAPIManager);
}
// Team providers
if (heroesManager != null && useHeroesParties) {
teamProviders.add(heroesManager);
}
if (skillAPIManager != null && useSkillAPIAllies) {
teamProviders.add(skillAPIManager);
}
if (useScoreboardTeams) {
teamProviders.add(new ScoreboardTeamProvider());
}
if (permissionTeams != null && !permissionTeams.isEmpty()) {
teamProviders.add(new PermissionsTeamProvider(permissionTeams));
}
if (factionsManager != null) {
teamProviders.add(factionsManager);
}
if (battleArenaManager != null && useBattleArenaTeams) {
teamProviders.add(battleArenaManager);
}
// Player warp providers
if (preciousStonesManager != null && preciousStonesManager.isEnabled()) {
playerWarpManagers.put("fields", preciousStonesManager);
}
if (redProtectManager != null) {
playerWarpManagers.put("redprotect", redProtectManager);
}
if (residenceManager != null) {
playerWarpManagers.put("residence", residenceManager);
}
Runnable genericIntegrationTask = new FinishGenericIntegrationTask(this);
// Delay loading generic integration by one tick since we can't add depends: for these plugins
if (!loaded) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, genericIntegrationTask, 1);
} else {
genericIntegrationTask.run();
}
}
public void finishGenericIntegration() {
protectionManager.check();
if (protectionManager.isEnabled()) {
blockBreakManagers.add(protectionManager);
blockBuildManagers.add(protectionManager);
}
}
public void showExampleInstructions(CommandSender sender) {
Mage mage = getMage(sender);
List<String> instructions = new ArrayList<>();
for (String example : getLoadedExamples()) {
String exampleKey = exampleKeyNames.get(example);
if (exampleKey == null || exampleKey.isEmpty()) {
exampleKey = example;
}
String exampleInstructions = messages.get("examples." + exampleKey + ".instructions", "");
if (exampleInstructions != null && !exampleInstructions.isEmpty()) {
instructions.add(exampleInstructions);
}
}
if (!instructions.isEmpty()) {
mage.sendMessage(messages.get("examples.instructions_header"));
for (String exampleInstructions : instructions) {
mage.sendMessage(exampleInstructions);
}
mage.sendMessage(messages.get("examples.instructions_footer"));
}
}
private int getPathCount() {
return WandUpgradePath.getPathKeys().size();
}
private void loadPaths(ConfigurationSection pathConfiguration) {
WandUpgradePath.loadPaths(this, pathConfiguration);
}
private void loadAttributes(ConfigurationSection attributeConfiguration) {
Set<String> keys = attributeConfiguration.getKeys(false);
attributes.clear();
for (String key : keys) {
logger.setContext("attribute." + key);
MagicAttribute attribute = new MagicAttribute(key, attributeConfiguration.getConfigurationSection(key));
attributes.put(key, attribute);
}
}
private void loadAutomatonTemplates(ConfigurationSection automataConfiguration) {
Set<String> keys = automataConfiguration.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
automatonTemplates.clear();
for (String key : keys) {
logger.setContext("automata." + key);
ConfigurationSection config = resolveConfiguration(key, automataConfiguration, templateConfigurations);
if (!ConfigurationUtils.isEnabled(config)) continue;
config = MagicConfiguration.getKeyed(this, config, "automaton", key);
AutomatonTemplate template = new AutomatonTemplate(this, key, config);
automatonTemplates.put(key, template);
}
// Update existing automata
for (Automaton active : activeAutomata.values()) {
active.pause();
}
for (Map<Long, Automaton> chunk : automata.values()) {
for (Automaton automaton : chunk.values()) {
automaton.reload();
}
}
for (Automaton active : activeAutomata.values()) {
active.resume();
}
}
public boolean isAutomataTemplate(@Nonnull String key) {
return automatonTemplates.containsKey(key);
}
@Nonnull
@Override
public Collection<String> getAutomatonTemplateKeys() {
return automatonTemplates.keySet();
}
@Nonnull
public Collection<Automaton> getActiveAutomata() {
return activeAutomata.values();
}
public Automaton getActiveAutomaton(long id) {
return activeAutomata.get(id);
}
public Collection<Automaton> getAutomata() {
List<Automaton> list = new ArrayList<>();
for (Map<Long, Automaton> chunk : automata.values()) {
list.addAll(chunk.values());
}
return list;
}
public Collection<Mage> getAutomataMages() {
Collection<Mage> all = new ArrayList<>();
for (Mage mage : mages.values()) {
if (mage.isAutomaton()) {
all.add(mage);
}
}
return all;
}
public boolean isActive(@Nonnull Automaton automaton) {
return activeAutomata.containsKey(automaton.getId());
}
@Nullable
public Automaton getAutomatonAt(@Nonnull Location location) {
String chunkId = getChunkKey(location);
if (chunkId == null) {
return null;
}
Map<Long, Automaton> restoreChunk = automata.get(chunkId);
if (restoreChunk == null) {
return null;
}
long blockId = BlockData.getBlockId(location);
return restoreChunk.get(blockId);
}
public boolean checkAutomatonBreak(Block block) {
Automaton automaton = getAutomatonAt(block.getLocation());
if (automaton != null && automaton.removeWhenBroken()) {
unregisterAutomaton(automaton);
return true;
}
return false;
}
@Nullable
public AutomatonTemplate getAutomatonTemplate(String key) {
return automatonTemplates.get(key);
}
private void loadEffects(ConfigurationSection effectsNode) {
effects.clear();
effectsNode = MagicConfiguration.getKeyed(this, effectsNode, "effects");
Collection<String> effectKeys = effectsNode.getKeys(false);
for (String effectKey : effectKeys) {
logger.setContext("effects." + effectKey);
effects.put(effectKey, loadEffects(effectsNode, effectKey));
}
}
@Override
@Nullable
public Collection<EffectPlayer> loadEffects(ConfigurationSection configuration, String effectKey) {
return loadEffects(configuration, effectKey, null);
}
@Override
@Nullable
public Collection<EffectPlayer> loadEffects(ConfigurationSection configuration, String effectKey, String logContext) {
return loadEffects(configuration, effectKey, null, null);
}
@Override
@Nullable
public Collection<EffectPlayer> loadEffects(ConfigurationSection configuration, String effectKey, String logContext, ConfigurationSection parameterMap) {
if (configuration.isString(effectKey)) {
return getEffects(configuration.getString(effectKey));
}
return com.elmakers.mine.bukkit.effect.EffectPlayer.loadEffects(getPlugin(), configuration, effectKey, getLogger(), logContext, parameterMap);
}
public void resetLoading(CommandSender sender) {
synchronized (logger) {
com.elmakers.mine.bukkit.effect.EffectPlayer.debugEffects(debugEffectLib);
if (sender != null) {
List<LogMessage> errors = logger.getErrors();
List<LogMessage> warnings = logger.getWarnings();
if (!warnings.isEmpty()) {
if (warnings.size() == 1) {
sender.sendMessage(ChatColor.YELLOW + "WARNING: " + ChatColor.WHITE + warnings.get(0).getMessage());
} else {
sender.sendMessage(ChatColor.YELLOW + "WARNINGS: " + ChatColor.WHITE + warnings.size());
for (int i = 0; i < warnings.size() && i < MAX_WARNINGS; i++) {
sender.sendMessage(ChatColor.WHITE + " " + warnings.get(i).getMessage());
}
if (warnings.size() > MAX_WARNINGS) {
sender.sendMessage(ChatColor.GRAY + " ...");
}
}
}
if (!errors.isEmpty()) {
if (errors.size() == 1) {
sender.sendMessage(ChatColor.RED + "ERROR: " + ChatColor.WHITE + errors.get(0).getMessage());
} else {
sender.sendMessage(ChatColor.RED + "ERRORS: " + ChatColor.WHITE + errors.size());
for (int i = 0; i < errors.size() && i < MAX_ERRORS; i++) {
sender.sendMessage(ChatColor.WHITE + " " + errors.get(i).getMessage());
}
if (errors.size() > MAX_ERRORS) {
sender.sendMessage(ChatColor.GRAY + " ...");
}
}
}
if (warnings.isEmpty() && errors.isEmpty()) {
sender.sendMessage(ChatColor.GREEN + "Finished loading, No issues found!");
} else {
if (!errors.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Finished loading " + ChatColor.DARK_RED + "with errors");
} else {
sender.sendMessage(ChatColor.GOLD + "Finished loading " + ChatColor.YELLOW + "with warnings");
}
}
}
logger.enableCapture(false);
if (logWatchdogTimer != null) {
logWatchdogTimer.cancel();
logWatchdogTimer = null;
}
}
}
@Override
public void loadConfigurationQuietly(CommandSender sender) {
loadConfiguration(sender, false, false);
}
public void loadConfiguration() {
loadConfiguration(null);
}
public void loadConfiguration(CommandSender sender) {
if (sender != null && !loaded) {
getLogger().warning("Can't reload configuration, Magic did not start up properly. Please restart your server.");
return;
}
loadConfiguration(sender, false);
}
public void loadConfiguration(CommandSender sender, boolean forceSynchronous) {
loadConfiguration(sender, forceSynchronous, true);
}
public void loadConfiguration(CommandSender sender, boolean forceSynchronous, boolean verboseLogging) {
if (!plugin.isEnabled()) return;
if (sender != null) {
synchronized (logger) {
com.elmakers.mine.bukkit.effect.EffectPlayer.debugEffects(true);
logger.enableCapture(true);
if (logWatchdogTimer != null) {
logWatchdogTimer.cancel();
}
logWatchdogTimer = plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new LogWatchdogTask(this, sender), LOG_WATCHDOG_TIMEOUT / 50);
sender.sendMessage(ChatColor.DARK_AQUA + "Please wait while the configuration is reloaded and validated");
}
}
reloadVerboseLogging = verboseLogging;
loading = true;
ConfigurationLoadTask loadTask = new ConfigurationLoadTask(this, sender);
loadTask.setVerbose(verboseLogging);
if (loaded && !forceSynchronous) {
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, loadTask);
} else {
loadTask.runNow();
}
}
@Override
public void updateConfiguration(CommandSender sender) {
updateExternalExamples(sender);
}
public void loadConfigurationExamples(CommandSender sender) {
showExampleInstructions = true;
loadConfiguration(sender, false, false);
}
protected void loadSpellData() {
try {
ConfigurationSection configNode = loadDataFile(SPELLS_DATA_FILE);
if (configNode == null) return;
Set<String> keys = configNode.getKeys(false);
for (String key : keys) {
ConfigurationSection node = configNode.getConfigurationSection(key);
SpellKey spellKey = new SpellKey(key);
SpellData templateData = templateDataMap.get(spellKey.getBaseKey());
if (templateData == null) {
templateData = new SpellData(spellKey.getBaseKey());
templateDataMap.put(templateData.getKey().getBaseKey(), templateData);
}
templateData.setCastCount(templateData.getCastCount() + node.getLong("cast_count", 0));
templateData.setLastCast(Math.max(templateData.getLastCast(), node.getLong("last_cast", 0)));
}
} catch (Exception ex) {
getLogger().warning("Failed to load spell metrics");
}
}
public void load() {
loadConfiguration();
loadData();
}
protected void loadData() {
loadSpellData();
Bukkit.getScheduler().runTaskLater(plugin, new LoadDataTask(this), 2);
}
public void finishLoadData() {
if (!loaded) {
getLogger().info("Magic did not load properly, skipping data load");
return;
}
loadSpellData();
loadLostWands();
loadAutomata();
loadNPCs();
// Load URL Map Data
try {
maps.resetAll();
maps.loadConfiguration();
} catch (Exception ex) {
ex.printStackTrace();
}
ConfigurationSection warps = loadDataFile(WARPS_FILE);
if (warps != null) {
warpController.load(warps);
info("Loaded " + warpController.getCustomWarps().size() + " warps");
}
getLogger().info("Finished loading data.");
dataLoaded = true;
}
public void migratePlayerData(CommandSender sender) {
if (migrateDataTask == null) {
if (migrateDataStore != null) {
migrateDataTask = new MigrateDataTask(this, mageDataStore, migrateDataStore, sender);
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, migrateDataTask);
} else {
sender.sendMessage(ChatColor.RED + "You must first configure 'migrate_data_store' in config.yml");
}
} else {
sender.sendMessage(ChatColor.YELLOW + "Data migration is already in progress");
}
}
public void finishMigratingPlayerData() {
migrateDataTask = null;
}
public void checkForMigration() {
checkForMigration(plugin.getServer().getConsoleSender());
}
public void checkForMigration(CommandSender sender) {
if (migrateDataStore != null) {
Collection<String> ids = migrateDataStore.getAllIds();
if (ids.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Migration is complete, please remove migrate_data_store from config.yml");
} else {
sender.sendMessage(ChatColor.YELLOW + "Please use the command 'magic migrate' to migrate player data");
}
}
}
protected void loadLostWands() {
try {
ConfigurationSection lostWandConfiguration = loadDataFile(LOST_WANDS_FILE);
if (lostWandConfiguration != null) {
Set<String> wandIds = lostWandConfiguration.getKeys(false);
for (String wandId : wandIds) {
if (wandId == null || wandId.length() == 0) continue;
LostWand lostWand = new LostWand(wandId, lostWandConfiguration.getConfigurationSection(wandId));
if (!lostWand.isValid()) {
getLogger().info("Skipped invalid entry in lostwands.yml file, entry will be deleted. The wand is really lost now!");
continue;
}
addLostWand(lostWand);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
info("Loaded " + lostWands.size() + " lost wands");
}
public void checkNPCs(World world) {
if (this.invalidNPCs.isEmpty()) return;
List<ConfigurationSection> check = this.invalidNPCs;
this.invalidNPCs = new ArrayList<>();
int npcCount = loadNPCs(check);
if (npcCount > 0) {
info("Loaded " + npcCount + " NPCs in world " + world.getName());
for (Chunk chunk : world.getLoadedChunks()) {
restoreNPCs(chunk);
}
}
}
protected void loadNPCs() {
ConfigurationSection npcData = loadDataFile(NPC_DATA_FILE);
if (npcData != null) {
Collection<ConfigurationSection> list = ConfigurationUtils.getNodeList(npcData, "npcs");
int npcCount = loadNPCs(list);
if (npcCount > 0) {
for (World world : Bukkit.getWorlds()) {
for (Chunk chunk : world.getLoadedChunks()) {
restoreNPCs(chunk);
}
}
info("Loaded " + npcCount + " NPCs");
}
}
}
protected int loadNPCs(Collection<ConfigurationSection> list) {
int npcCount = 0;
try {
for (ConfigurationSection node : list) {
MagicNPC npc = new MagicNPC(this, node);
if (!npc.isValid()) {
invalidNPCs.add(node);
continue;
}
String chunkId = getChunkKey(npc.getLocation());
if (chunkId == null) {
invalidNPCs.add(node);
continue;
}
List<MagicNPC> restoreChunk = npcsByChunk.get(chunkId);
if (restoreChunk == null) {
restoreChunk = new ArrayList<>();
npcsByChunk.put(chunkId, restoreChunk);
}
npcCount++;
restoreChunk.add(npc);
npcs.put(npc.getId(), npc);
}
} catch (Exception ex) {
getLogger().log(Level.SEVERE, "Something went wrong loading NPC data", ex);
}
return npcCount;
}
public void checkAutomata(World world) {
if (this.invalidAutomata.isEmpty()) return;
List<ConfigurationSection> check = this.invalidAutomata;
this.invalidAutomata = new ArrayList<>();
int automataCount = loadAutomata(check);
if (automataCount > 0) {
info("Loaded " + automataCount + " automata in world " + world.getName());
for (Chunk chunk : world.getLoadedChunks()) {
resumeAutomata(chunk);
}
}
}
protected void loadAutomata() {
ConfigurationSection toggleBlockData = loadDataFile(AUTOMATA_DATA_FILE);
if (toggleBlockData != null) {
Collection<ConfigurationSection> list = ConfigurationUtils.getNodeList(toggleBlockData, "automata");
int automataCount = loadAutomata(list);
if (automataCount > 0) {
info("Loaded " + automataCount + " automata");
for (World world : Bukkit.getWorlds()) {
for (Chunk chunk : world.getLoadedChunks()) {
resumeAutomata(chunk);
}
}
}
}
}
protected int loadAutomata(Collection<ConfigurationSection> list) {
int automataCount = 0;
try {
for (ConfigurationSection node : list) {
Automaton automaton = new Automaton(this, node);
if (!automaton.isValid()) {
invalidAutomata.add(node);
continue;
}
String chunkId = getChunkKey(automaton.getLocation());
if (chunkId == null) {
invalidAutomata.add(node);
continue;
}
Map<Long, Automaton> restoreChunk = automata.get(chunkId);
if (restoreChunk == null) {
restoreChunk = new HashMap<>();
automata.put(chunkId, restoreChunk);
}
long id = automaton.getId();
Automaton existing = restoreChunk.get(id);
if (existing != null) {
getLogger().warning("Duplicate automata exist at " + automaton.getLocation() + ", one will be removed!");
continue;
}
automataCount++;
restoreChunk.put(id, automaton);
}
} catch (Exception ex) {
getLogger().log(Level.SEVERE, "Something went wrong loading automata data", ex);
}
return automataCount;
}
protected void saveWarps(Collection<YamlDataFile> stores) {
try {
YamlDataFile warpData = createDataFile(WARPS_FILE);
warpController.save(warpData);
stores.add(warpData);
} catch (Exception ex) {
ex.printStackTrace();
}
}
protected void saveAutomata(Collection<YamlDataFile> stores) {
try {
YamlDataFile automataData = createDataFile(AUTOMATA_DATA_FILE);
List<ConfigurationSection> nodes = new ArrayList<>();
for (Entry<String, Map<Long, Automaton>> toggleEntry : automata.entrySet()) {
Collection<Automaton> blocks = toggleEntry.getValue().values();
if (blocks.size() > 0) {
for (Automaton block : blocks) {
ConfigurationSection node = ConfigurationUtils.newConfigurationSection();
block.save(node);
nodes.add(node);
}
}
}
nodes.addAll(invalidAutomata);
automataData.set("automata", nodes);
stores.add(automataData);
} catch (Exception ex) {
ex.printStackTrace();
}
}
protected void saveNPCs(Collection<YamlDataFile> stores) {
try {
YamlDataFile npcData = createDataFile(NPC_DATA_FILE);
List<ConfigurationSection> nodes = new ArrayList<>();
for (MagicNPC npc : npcs.values()) {
ConfigurationSection node = ConfigurationUtils.newConfigurationSection();
npc.save(node);
nodes.add(node);
}
nodes.addAll(invalidNPCs);
npcData.set("npcs", nodes);
stores.add(npcData);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void moveAutomaton(Automaton automaton, Location location) {
unregisterAutomaton(automaton);
automaton.setLocation(location);
registerAutomaton(automaton);
}
public void registerAutomaton(Automaton automaton) {
String chunkId = getChunkKey(automaton.getLocation());
if (chunkId == null) return;
Map<Long, Automaton> chunkAutomata = automata.get(chunkId);
if (chunkAutomata == null) {
chunkAutomata = new HashMap<>();
automata.put(chunkId, chunkAutomata);
}
long id = automaton.getId();
chunkAutomata.put(id, automaton);
if (automaton.inActiveChunk()) {
activeAutomata.put(id, automaton);
automaton.resume();
}
}
public boolean unregisterAutomaton(Automaton automaton) {
boolean removed = false;
String chunkId = getChunkKey(automaton.getLocation());
long id = automaton.getId();
Map<Long, Automaton> chunkAutomata = automata.get(chunkId);
if (chunkAutomata != null) {
removed = chunkAutomata.remove(id) != null;
if (chunkAutomata.size() == 0) {
automata.remove(chunkId);
}
}
if (activeAutomata.remove(id) != null) {
automaton.pause();
}
automaton.removed();
return removed;
}
public void resumeAutomata(final Chunk chunk) {
String chunkKey = getChunkKey(chunk);
Map<Long, Automaton> chunkData = automata.get(chunkKey);
if (chunkData != null) {
activeAutomata.putAll(chunkData);
for (Automaton automaton : chunkData.values()) {
if (!automaton.isAlwaysActive()) {
automaton.resume();
}
}
}
}
public void pauseAutomata(final Chunk chunk) {
String chunkKey = getChunkKey(chunk);
Map<Long, Automaton> chunkData = automata.get(chunkKey);
if (chunkData != null) {
for (Automaton automaton : chunkData.values()) {
if (!automaton.isAlwaysActive()) {
automaton.pause();
activeAutomata.remove(automaton.getId());
}
}
}
}
public void tickAutomata() {
for (Automaton automaton : activeAutomata.values()) {
automaton.tick();
}
}
@Override
@Nullable
public Automaton addAutomaton(@Nonnull Location location, @Nonnull String templateKey, String creatorId, String creatorName, @Nullable ConfigurationSection parameters) {
if (!isAutomataTemplate(templateKey)) {
return null;
}
Automaton existing = getAutomatonAt(location);
if (existing != null) {
return null;
}
Automaton automaton = new Automaton(this, location, templateKey, creatorId, creatorName, parameters);
registerAutomaton(automaton);
return automaton;
}
protected void saveSpellData(Collection<YamlDataFile> stores) {
String lastKey = "";
try {
YamlDataFile spellsDataFile = createDataFile(SPELLS_DATA_FILE, false);
for (SpellData data : templateDataMap.values()) {
lastKey = data.getKey().getBaseKey();
ConfigurationSection spellNode = spellsDataFile.createSection(lastKey);
if (spellNode == null) {
getLogger().warning("Error saving spell data for " + lastKey);
continue;
}
spellNode.set("cast_count", data.getCastCount());
spellNode.set("last_cast", data.getLastCast());
}
stores.add(spellsDataFile);
} catch (Throwable ex) {
getLogger().warning("Error saving spell data for " + lastKey);
ex.printStackTrace();
}
}
protected void saveLostWands(Collection<YamlDataFile> stores) {
String lastKey = "";
try {
YamlDataFile lostWandsConfiguration = createDataFile(LOST_WANDS_FILE, false);
for (Entry<String, LostWand> wandEntry : lostWands.entrySet()) {
lastKey = wandEntry.getKey();
if (lastKey == null || lastKey.length() == 0) continue;
ConfigurationSection wandNode = lostWandsConfiguration.createSection(lastKey);
if (wandNode == null) {
getLogger().warning("Error saving lost wand data for " + lastKey);
continue;
}
if (!wandEntry.getValue().isValid()) {
getLogger().warning("Invalid lost and data for " + lastKey);
continue;
}
wandEntry.getValue().save(wandNode);
}
stores.add(lostWandsConfiguration);
} catch (Throwable ex) {
getLogger().warning("Error saving lost wand data for " + lastKey);
ex.printStackTrace();
}
}
@Nullable
protected String getChunkKey(Block block) {
return getChunkKey(block.getLocation());
}
@Nullable
protected String getChunkKey(Location location) {
World world = location.getWorld();
if (world == null) return null;
return world.getName() + "|" + (location.getBlockX() >> 4) + "," + (location.getBlockZ() >> 4);
}
protected String getChunkKey(Chunk chunk) {
return chunk.getWorld().getName() + "|" + chunk.getX() + "," + chunk.getZ();
}
public boolean addLostWand(LostWand lostWand) {
lostWands.put(lostWand.getId(), lostWand);
try {
String chunkKey = getChunkKey(lostWand.getLocation());
if (chunkKey == null) return false;
Set<String> chunkWands = lostWandChunks.get(chunkKey);
if (chunkWands == null) {
chunkWands = new HashSet<>();
lostWandChunks.put(chunkKey, chunkWands);
}
chunkWands.add(lostWand.getId());
if (dynmapShowWands) {
addLostWandMarker(lostWand);
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error loading lost wand id " + lostWand.getId() + " - is it in an unloaded world?", ex);
}
return true;
}
public boolean addLostWand(Wand wand, Location dropLocation) {
addLostWand(wand.makeLost(dropLocation));
return true;
}
public boolean removeLostWand(String wandId) {
if (wandId == null || wandId.length() == 0 || !lostWands.containsKey(wandId)) return false;
LostWand lostWand = lostWands.get(wandId);
lostWands.remove(wandId);
String chunkKey = getChunkKey(lostWand.getLocation());
if (chunkKey == null) return false;
Set<String> chunkWands = lostWandChunks.get(chunkKey);
if (chunkWands != null) {
chunkWands.remove(wandId);
if (chunkWands.size() == 0) {
lostWandChunks.remove(chunkKey);
}
}
if (dynmapShowWands) {
if (removeMarker("wand-" + wandId, "wands")) {
info("Wand removed from map");
}
}
return true;
}
public WandMode getDefaultWandMode() {
return defaultWandMode;
}
public WandMode getDefaultBrushMode() {
return defaultBrushMode;
}
public String getDefaultWandPath() {
return defaultWandPath;
}
protected void saveMageData(Collection<MageData> stores) {
try {
for (Entry<String, ? extends Mage> mageEntry : mages.entrySet()) {
Mage mage = mageEntry.getValue();
if (!mage.isPlayer() && !saveNonPlayerMages) {
continue;
}
if (!mage.isLoading()) {
MageData mageData = new MageData(mage.getId());
if (mage.save(mageData)) {
stores.add(mageData);
}
} else {
getLogger().info("Skipping save of mage, already loading: " + mage.getName());
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void save() {
save(false);
}
public void save(boolean asynchronous) {
if (!loaded || !dataLoaded) return;
maps.save(asynchronous);
final List<YamlDataFile> saveData = new ArrayList<>();
final List<MageData> saveMages = new ArrayList<>();
// Player data will be saved as each player quits on shutdown, so skip it here.
if (savePlayerData && mageDataStore != null && !shuttingDown) {
saveMageData(saveMages);
info("Saving " + saveMages.size() + " players");
}
saveSpellData(saveData);
saveLostWands(saveData);
saveAutomata(saveData);
saveWarps(saveData);
saveNPCs(saveData);
if (mageDataStore != null && !shuttingDown) {
if (asynchronous) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new SaveMageDataTask(this, saveMages));
} else {
persistMageData(saveMages);
}
}
if (asynchronous) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new SaveDataTask(this, saveData));
} else {
saveData(saveData);
}
SaveEvent saveEvent = new SaveEvent(asynchronous);
Bukkit.getPluginManager().callEvent(saveEvent);
}
public void saveData(Collection<YamlDataFile> saveData) {
synchronized (saveLock) {
for (YamlDataFile config : saveData) {
config.save();
}
info("Finished saving");
}
}
public void persistMageData(Collection<MageData> saveMages) {
synchronized (saveLock) {
for (MageData mageData : saveMages) {
mageDataStore.save(mageData, null, false);
}
}
}
public void addSpell(Spell variant) {
SpellTemplate conflict = spells.get(variant.getKey());
if (conflict != null) {
getLogger().log(Level.WARNING, "Duplicate spell key: '" + conflict.getKey() + "'");
} else {
SpellKey spellKey = variant.getSpellKey();
spells.put(spellKey.getKey(), variant);
if (spellKey.getLevel() > 1) {
Integer currentMax = maxSpellLevels.get(spellKey.getBaseKey());
if (currentMax == null || spellKey.getLevel() > currentMax) {
maxSpellLevels.put(spellKey.getBaseKey(), spellKey.getLevel());
}
}
SpellData data = templateDataMap.get(variant.getSpellKey().getBaseKey());
if (data == null) {
data = new SpellData(variant.getSpellKey().getBaseKey());
templateDataMap.put(variant.getSpellKey().getBaseKey(), data);
}
if (variant instanceof MageSpell) {
((MageSpell) variant).setSpellData(data);
}
String alias = variant.getAlias();
if (alias != null && alias.length() > 0) {
spellAliases.put(alias, variant);
}
}
}
@Nullable
@Override
public String getReflectiveMaterials(Mage mage, Location location) {
return worldGuardManager.getReflective(mage.getPlayer(), location);
}
@Nullable
@Override
public String getDestructibleMaterials(Mage mage, Location location) {
return worldGuardManager.getDestructible(mage.getPlayer(), location);
}
@Override
@Deprecated
public Set<Material> getDestructibleMaterials() {
return MaterialSets.toLegacyNN(destructibleMaterials);
}
@Nullable
@Override
public Set<String> getSpellOverrides(Mage mage, Location location) {
return worldGuardManager.getSpellOverrides(mage.getPlayer(), location);
}
public boolean isOffhandMaterial(ItemStack itemStack) {
return (!CompatibilityUtils.isEmpty(itemStack) && offhandMaterials.testItem(itemStack));
}
public boolean hasAddedExamples() {
return addExamples != null && addExamples.size() > 0;
}
@Nullable
private MageDataStore loadMageDataStore(ConfigurationSection configuration) {
MageDataStore mageDataStore = null;
String dataStoreClassName = configuration.getString("class");
if (!dataStoreClassName.contains(".")) {
dataStoreClassName = DEFAULT_DATASTORE_PACKAGE + "." + dataStoreClassName + "MageDataStore";
}
try {
Class<?> dataStoreClass = Class.forName(dataStoreClassName);
Object dataStore = dataStoreClass.getDeclaredConstructor().newInstance();
if (dataStore == null || !(dataStore instanceof MageDataStore)) {
getLogger().log(Level.WARNING, "Invalid player_data_store class " + dataStoreClassName + ", does it implement MageDataStore? Player data saving is disabled!");
mageDataStore = null;
} else {
mageDataStore = (MageDataStore) dataStore;
mageDataStore.initialize(this, configuration);
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Failed to create player_data_store class from " + dataStoreClassName, ex);
mageDataStore = null;
}
return mageDataStore;
}
protected void loadMobEggs(ConfigurationSection skins) {
mobEggs.clear();
Set<String> keys = skins.getKeys(false);
for (String key : keys) {
try {
EntityType entityType = EntityType.valueOf(key.toUpperCase());
Material material = getVersionedMaterial(skins, key);
if (material != null) {
mobEggs.put(entityType, material);
}
} catch (Exception ignore) {
}
}
}
protected void loadMobSkins(ConfigurationSection skins) {
mobSkins.clear();
Set<String> keys = skins.getKeys(false);
for (String key : keys) {
try {
EntityType entityType = EntityType.valueOf(key.toUpperCase());
mobSkins.put(entityType, skins.getString(key));
} catch (Exception ignore) {
}
}
}
protected void loadBlockSkins(ConfigurationSection skins) {
blockSkins.clear();
Set<String> keys = skins.getKeys(false);
for (String key : keys) {
try {
Material material = Material.getMaterial(key.toUpperCase());
blockSkins.put(material, skins.getString(key));
} catch (Exception ignore) {
}
}
}
@Nullable
protected Material getVersionedMaterial(ConfigurationSection configuration, String key) {
Material material = null;
Collection<String> candidates = ConfigurationUtils.getStringList(configuration, key);
for (String candidate : candidates) {
try {
material = Material.valueOf(candidate.toUpperCase());
break;
} catch (Exception ignore) {
}
}
return material;
}
@Nullable
protected MaterialAndData getVersionedMaterialAndData(ConfigurationSection configuration, String key) {
Collection<String> candidates = ConfigurationUtils.getStringList(configuration, key);
for (String candidate : candidates) {
MaterialAndData test = new MaterialAndData(candidate);
if (test.isValid()) {
return test;
}
}
return null;
}
protected void loadOtherMaterials(ConfigurationSection configuration) {
DefaultMaterials defaultMaterials = DefaultMaterials.getInstance();
defaultMaterials.setGroundSignBlock(getVersionedMaterial(configuration, "ground_sign_block"));
defaultMaterials.setWallSignBlock(getVersionedMaterial(configuration, "wall_sign_block"));
defaultMaterials.setFirework(getVersionedMaterial(configuration, "firework"));
defaultMaterials.setWallTorch(getVersionedMaterialAndData(configuration, "wall_torch"));
defaultMaterials.setRedstoneTorchOn(getVersionedMaterialAndData(configuration, "redstone_torch_on"));
defaultMaterials.setRedstoneTorchOff(getVersionedMaterialAndData(configuration, "redstone_torch_off"));
defaultMaterials.setRedstoneWallTorchOn(getVersionedMaterialAndData(configuration, "redstone_wall_torch_on"));
defaultMaterials.setRedstoneWallTorchOff(getVersionedMaterialAndData(configuration, "redstone_wall_torch_off"));
defaultMaterials.setMobSpawner(getVersionedMaterial(configuration, "mob_spawner"));
defaultMaterials.setNetherPortal(getVersionedMaterial(configuration, "nether_portal"));
defaultMaterials.setWriteableBook(getVersionedMaterial(configuration, "writable_book"));
defaultMaterials.setFilledMap(getVersionedMaterial(configuration, "filled_map"));
}
protected void loadSkulls(ConfigurationSection skulls) {
skullItems.clear();
skullGroundBlocks.clear();
skullWallBlocks.clear();
Set<String> keys = skulls.getKeys(false);
for (String key : keys) {
try {
ConfigurationSection types = skulls.getConfigurationSection(key);
EntityType entityType = EntityType.valueOf(key.toUpperCase());
MaterialAndData item = parseSkullCandidate(types, "item");
if (item != null) {
skullItems.put(entityType, item);
}
MaterialAndData floor = parseSkullCandidate(types, "ground");
if (item != null) {
skullGroundBlocks.put(entityType, floor);
}
MaterialAndData wall = parseSkullCandidate(types, "wall");
if (item != null) {
skullWallBlocks.put(entityType, wall);
}
} catch (Exception ignore) {
}
}
}
@Nullable
protected MaterialAndData parseSkullCandidate(ConfigurationSection section, String key) {
Collection<String> candidates = ConfigurationUtils.getStringList(section, key);
for (String candidate : candidates) {
MaterialAndData test = new MaterialAndData(candidate.trim());
if (test.isValid()) {
return test;
}
}
return null;
}
protected void populateEntityTypes(Set<EntityType> entityTypes, ConfigurationSection configuration, String key) {
entityTypes.clear();
if (configuration.contains(key)) {
Collection<String> typeStrings = ConfigurationUtils.getStringList(configuration, key);
for (String typeString : typeStrings) {
try {
entityTypes.add(EntityType.valueOf(typeString.toUpperCase()));
} catch (Exception ex) {
getLogger().warning("Unknown entity type: " + typeString + " in " + key);
}
}
}
}
protected void addCurrency(Currency currency) {
currencies.put(currency.getKey(), currency);
}
protected void registerPreLoad(ConfigurationSection configuration) {
// Setup custom providers
currencies.clear();
attributeProviders.clear();
teamProviders.clear();
requirementProcessors.clear();
// Set up Break/Build/PVP Managers
blockBreakManagers.clear();
blockBuildManagers.clear();
pvpManagers.clear();
castManagers.clear();
playerWarpManagers.clear();
targetingProviders.clear();
registeredAttributes.clear();
PreLoadEvent loadEvent = new PreLoadEvent(this);
Bukkit.getPluginManager().callEvent(loadEvent);
blockBreakManagers.addAll(loadEvent.getBlockBreakManagers());
blockBuildManagers.addAll(loadEvent.getBlockBuildManagers());
pvpManagers.addAll(loadEvent.getPVPManagers());
attributeProviders.addAll(loadEvent.getAttributeProviders());
teamProviders.addAll(loadEvent.getTeamProviders());
castManagers.addAll(loadEvent.getCastManagers());
targetingProviders.addAll(loadEvent.getTargetingManagers());
teamProviders.addAll(loadEvent.getTeamProviders());
playerWarpManagers.putAll(loadEvent.getWarpManagers());
// Use legacy currency configs if present
ConfigurationSection currencyConfiguration = configuration.getConfigurationSection("builtin_currency");
ConfigurationSection spSection = currencyConfiguration.getConfigurationSection("sp");
ConfigurationSection xpSection = currencyConfiguration.getConfigurationSection("xp");
String skillPointIcon = configuration.getString("sp_item_icon_url");
if (skillPointIcon != null) {
getLogger().warning("The config option sp_item_icon_url is deprecated, see builtin_currencies section");
spSection.set("icon", "skull:" + skillPointIcon);
}
if (configuration.contains("sp_max")) {
getLogger().warning("The config option sp_max is deprecated, see builtin_currencies section");
spSection.set("max", configuration.getInt("sp_max"));
}
if (configuration.contains("worth_sp")) {
getLogger().warning("The config option worth_sp is deprecated, see builtin_currencies section");
spSection.set("worth", configuration.getInt("worth_sp"));
}
if (configuration.contains("sp_default")) {
getLogger().warning("The config option sp_default is deprecated, see builtin_currencies section");
spSection.set("default", configuration.getInt("sp_default"));
}
if (configuration.contains("worth_xp")) {
getLogger().warning("The config option worth_xp is deprecated, see builtin_currencies section");
xpSection.set("worth", configuration.getDouble("worth_xp"));
}
ConfigurationSection legacyItemCurrency = configuration.getConfigurationSection("currency");
if (legacyItemCurrency != null) {
ConfigurationSection itemConfiguration = currencyConfiguration.getConfigurationSection("item");
getLogger().warning("The config section currency is deprecated, see builtin_currencies.item section");
Collection<String> worthItemKeys = legacyItemCurrency.getKeys(false);
for (String worthItemKey : worthItemKeys) {
ConfigurationSection currencyConfig = legacyItemCurrency.getConfigurationSection(worthItemKey);
if (!currencyConfig.getBoolean("enabled", true)) continue;
itemConfiguration.set("item", worthItemKey);
itemConfiguration.set("worth", currencyConfig.getDouble("worth"));
// This is kind of a hack, but makes it easier to override the default ... (heldover from legacy configs)
if (!worthItemKey.equals("emerald")) {
break;
}
}
}
// Load builtin default currencies
addCurrency(new ItemCurrency(this, currencyConfiguration.getConfigurationSection("item")));
addCurrency(new ManaCurrency(this, currencyConfiguration.getConfigurationSection("mana")));
addCurrency(new ExperienceCurrency(this, xpSection));
addCurrency(new HealthCurrency(this, currencyConfiguration.getConfigurationSection("health")));
addCurrency(new HungerCurrency(this, currencyConfiguration.getConfigurationSection("hunger")));
addCurrency(new LevelCurrency(this, currencyConfiguration.getConfigurationSection("levels")));
addCurrency(new SpellPointCurrency(this, spSection));
addCurrency(new VaultCurrency(this, currencyConfiguration.getConfigurationSection("currency")));
// Custom currencies can override the defaults
for (Currency currency : loadEvent.getCurrencies()) {
addCurrency(currency);
}
// Configured currencies override everything else
currencyConfiguration = configuration.getConfigurationSection("custom_currency");
Set<String> keys = currencyConfiguration.getKeys(false);
for (String key : keys) {
addCurrency(new CustomCurrency(this, key, currencyConfiguration.getConfigurationSection(key)));
}
// Re-register any providers previously registered by external plugins via register()
for (MagicProvider provider : externalProviders) {
register(provider);
}
// Don't allow overriding Magic requirements
checkMagicRequirements();
}
private void finalizeAttributes() {
registeredAttributes.addAll(builtinMageAttributes);
registeredAttributes.addAll(builtinAttributes);
registeredAttributes.addAll(this.attributes.keySet());
for (AttributeProvider provider : attributeProviders) {
Set<String> providerAttributes = provider.getAllAttributes();
if (providerAttributes != null) {
registeredAttributes.addAll(providerAttributes);
}
}
MageParameters.initializeAttributes(registeredAttributes);
MageParameters.setLogger(getLogger());
log("Registered attributes: " + registeredAttributes);
}
private void checkMagicRequirements() {
if (requirementProcessors.containsKey(Requirement.DEFAULT_TYPE)) {
getLogger().warning("Something tried to register requirements for the " + Requirement.DEFAULT_TYPE + " type, but that is Magic's job.");
}
requirementProcessors.put(Requirement.DEFAULT_TYPE, requirementsController);
}
@Override
public boolean register(MagicProvider provider) {
boolean added = false;
if (provider instanceof EntityTargetingManager) {
added = true;
targetingProviders.add((EntityTargetingManager) provider);
}
if (provider instanceof AttributeProvider) {
added = true;
AttributeProvider attributes = (AttributeProvider) provider;
attributeProviders.add(attributes);
if (!loading) {
Set<String> providerAttributes = attributes.getAllAttributes();
if (providerAttributes != null) {
registeredAttributes.addAll(providerAttributes);
MageParameters.initializeAttributes(registeredAttributes);
log("Registered additional attributes: " + providerAttributes);
}
}
}
if (provider instanceof TeamProvider) {
added = true;
teamProviders.add((TeamProvider) provider);
}
if (provider instanceof Currency) {
added = true;
addCurrency((Currency) provider);
}
if (provider instanceof RequirementsProvider) {
added = true;
RequirementsProvider requirements = (RequirementsProvider) provider;
requirementProcessors.put(requirements.getKey(), requirements);
if (!loading) {
checkMagicRequirements();
}
}
if (provider instanceof PlayerWarpProvider) {
added = true;
PlayerWarpProvider warp = (PlayerWarpProvider) provider;
playerWarpManagers.put(warp.getKey(), warp);
}
if (provider instanceof BlockBreakManager) {
added = true;
blockBreakManagers.add((BlockBreakManager) provider);
}
if (provider instanceof PVPManager) {
added = true;
pvpManagers.add((PVPManager) provider);
}
if (provider instanceof BlockBuildManager) {
added = true;
blockBuildManagers.add((BlockBuildManager) provider);
}
if (provider instanceof CastPermissionManager) {
added = true;
castManagers.add((CastPermissionManager) provider);
}
if (added && !loading) {
externalProviders.add(provider);
}
return added;
}
protected void clear() {
if (!loaded) {
return;
}
Collection<Mage> saveMages = new ArrayList<>(mages.values());
for (Mage mage : saveMages) {
playerQuit(mage);
}
mages.clear();
pendingConstruction.clear();
spells.clear();
loaded = false;
}
protected void unregisterPhysicsHandler(Listener listener) {
BlockPhysicsEvent.getHandlerList().unregister(listener);
physicsHandler = null;
}
@Override
public void scheduleUndo(UndoList undoList) {
undoList.setHasBeenScheduled();
scheduledUndo.add(undoList);
}
@Override
public void cancelScheduledUndo(UndoList undoList) {
scheduledUndo.remove(undoList);
}
public boolean hasWandPermission(Player player) {
return hasPermission(player, "Magic.wand.use");
}
public boolean hasWandPermission(Player player, Wand wand) {
if (hasBypassPermission(player)) return true;
if (wand.isSuperPowered() && !player.hasPermission("Magic.wand.use.powered")) return false;
if (wand.isSuperProtected() && !player.hasPermission("Magic.wand.use.protected")) return false;
String template = wand.getTemplateKey();
if (template != null && !template.isEmpty()) {
String pNode = "Magic.use." + template;
if (!hasPermission(player, pNode)) return false;
}
Location location = player.getLocation();
Boolean override = worldGuardManager.getWandPermission(player, wand, location);
return override == null || override;
}
@Override
public boolean hasCastPermission(CommandSender sender, SpellTemplate spell) {
if (sender == null) return true;
if (hasBypassPermission(sender)) {
return true;
}
String categoryPermission = spell.getCategoryPermissionNode();
if (categoryPermission != null && !hasPermission(sender, categoryPermission)) {
return false;
}
return hasPermission(sender, spell.getPermissionNode());
}
@Nullable
@Override
public Boolean getRegionCastPermission(Player player, SpellTemplate spell, Location location) {
if (hasBypassPermission(player)) return true;
Boolean result = null;
for (CastPermissionManager manager : castManagers) {
Boolean managerResult = manager.getRegionCastPermission(player, spell, location);
if (managerResult != null) {
if (!managerResult) {
return false;
}
if (result == null) {
result = managerResult;
}
}
}
return result;
}
@Nullable
@Override
public Boolean getPersonalCastPermission(Player player, SpellTemplate spell, Location location) {
if (hasBypassPermission(player)) return true;
Boolean result = null;
for (CastPermissionManager manager : castManagers) {
Boolean managerResult = manager.getPersonalCastPermission(player, spell, location);
if (managerResult != null) {
if (!managerResult) {
return false;
}
if (result == null) {
result = managerResult;
}
}
}
return result;
}
@Override
public boolean hasBypassPermission(CommandSender sender) {
if (sender == null) return false;
if (sender instanceof Player && sender.hasPermission("Magic.bypass")) return true;
Mage mage = getRegisteredMage(sender);
if (mage == null) return false;
return mage.isBypassEnabled();
}
@Override
public boolean inTaggedRegion(Location location, Set<String> tags) {
Boolean inRegion = worldGuardManager.inTaggedRegion(location, tags);
return inRegion != null && inRegion;
}
public boolean hasPermission(Player player, String pNode, boolean defaultValue) {
// Should this return defaultValue? Can't give perms to console.
if (player == null) return true;
// The GM won't handle this properly because we are unable to register
// dynamic lists (spells, wands, brushes) in plugin.yml
if (pNode.contains(".")) {
String parentNode = pNode.substring(0, pNode.lastIndexOf('.') + 1) + "*";
boolean isParentSet = player.isPermissionSet(parentNode);
if (isParentSet) {
defaultValue = player.hasPermission(parentNode);
}
}
boolean isSet = player.isPermissionSet(pNode);
return isSet ? player.hasPermission(pNode) : defaultValue;
}
public boolean hasPermission(Player player, String pNode) {
return hasPermission(player, pNode, false);
}
@Override
public boolean hasPermission(CommandSender sender, String pNode) {
if (!(sender instanceof Player)) return true;
return hasPermission((Player) sender, pNode, false);
}
@Override
public boolean hasPermission(CommandSender sender, String pNode, boolean defaultValue) {
if (!(sender instanceof Player)) return true;
return hasPermission((Player) sender, pNode, defaultValue);
}
public void registerFallingBlock(Entity fallingBlock, Block block) {
UndoList undoList = getPendingUndo(fallingBlock.getLocation());
if (undoList != null) {
undoList.fall(fallingBlock, block);
}
}
@Nullable
public UndoList getEntityUndo(Entity entity) {
UndoList blockList = null;
if (entity == null) return null;
blockList = com.elmakers.mine.bukkit.block.UndoList.getUndoList(entity);
if (blockList != null) return blockList;
if (entity instanceof Projectile) {
Projectile projectile = (Projectile) entity;
ProjectileSource source = projectile.getShooter();
if (source instanceof Entity) {
entity = (Entity) source;
blockList = com.elmakers.mine.bukkit.block.UndoList.getUndoList(entity);
if (blockList != null) return blockList;
}
}
Mage mage = getRegisteredMage(entity);
if (mage != null) {
UndoList undoList = mage.getLastUndoList();
if (undoList != null) {
long now = System.currentTimeMillis();
if (undoList.getModifiedTime() > now - undoTimeWindow) {
blockList = undoList;
}
}
}
return blockList;
}
public boolean isBindOnGive() {
return bindOnGive;
}
@Override
public void giveItemToPlayer(Player player, ItemStack itemStack) {
Mage mage = getMage(player);
mage.giveItem(itemStack);
}
@Override
public boolean commitOnQuit() {
return commitOnQuit;
}
public void onShutdown() {
shuttingDown = true;
if (despawnMagicMobs) {
for (Mage mobMage : getMobMages()) {
Entity entity = mobMage.getEntity();
if (entity != null) {
entity.remove();
}
}
}
if (mageDataStore != null) {
mageDataStore.close();
}
if (migrateDataStore != null) {
migrateDataStore.close();
}
}
public void undoScheduled() {
int undid = 0;
while (!scheduledUndo.isEmpty()) {
UndoList undoList = scheduledUndo.poll();
undoList.undoScheduled(true);
}
if (undid > 0) {
info("Undid " + undid + " pending spells");
}
}
protected void mageQuit(final Mage mage, final MageDataCallback callback) {
com.elmakers.mine.bukkit.api.wand.Wand wand = mage.getActiveWand();
final boolean isOpen = wand != null && wand.isInventoryOpen();
com.elmakers.mine.bukkit.magic.Mage implementation = null;
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
implementation = (com.elmakers.mine.bukkit.magic.Mage) mage;
implementation.flagForReactivation();
}
mage.deactivate();
mage.undoScheduled();
mage.deactivateClasses();
mage.deactivateModifiers();
// Delay removal one tick to avoid issues with plugins that kill
// players on logout (CombatTagPlus, etc)
// Don't delay on shutdown, though.
if (loaded && implementation != null && !shuttingDown) {
final com.elmakers.mine.bukkit.magic.Mage quitMage = implementation;
quitMage.setUnloading(true);
plugin.getServer().getScheduler().runTaskLater(plugin, new MageQuitTask(this, quitMage, callback, isOpen), 1);
} else {
finalizeMageQuit(mage, callback, isOpen);
}
}
public void finalizeMageQuit(final Mage mage, final MageDataCallback callback, final boolean isOpen) {
// Unregister
if (!externalPlayerData || !mage.isPlayer()) {
removeMage(mage);
}
if (!mage.isLoading() && (mage.isPlayer() || saveNonPlayerMages) && loaded) {
// Save synchronously on shutdown
saveMage(mage, !shuttingDown, callback, isOpen, true);
} else if (callback != null) {
callback.run(null);
}
}
protected void playerQuit(Mage mage, MageDataCallback callback) {
// Make sure they get their portraits re-rendered on relogin.
maps.resend(mage.getName());
mageQuit(mage, callback);
}
public void playerQuit(Mage mage) {
playerQuit(mage, null);
}
@Override
public void forgetMage(Mage mage) {
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
((com.elmakers.mine.bukkit.magic.Mage) mage).setForget(true);
}
}
@Override
public void removeMage(Mage mage) {
removeMage(mage.getId());
}
@Override
public void removeMage(String id) {
Mage mage = mages.remove(id);
if (mage != null) {
mage.removed();
}
}
public void saveMage(Mage mage, boolean asynchronous) {
saveMage(mage, asynchronous, null);
}
public void saveMage(Mage mage, boolean asynchronous, final MageDataCallback callback) {
saveMage(mage, asynchronous, callback, false, false);
}
public void saveMage(Mage mage, boolean asynchronous, final MageDataCallback callback, boolean wandInventoryOpen, boolean releaseLock) {
if (!savePlayerData) {
if (callback != null) {
callback.run(null);
}
return;
}
asynchronous = asynchronous && asynchronousSaving;
info("Saving player data for " + mage.getName() + " (" + mage.getId() + ") " + ((asynchronous ? "" : " synchronously ") + "at " + System.currentTimeMillis()));
final MageData mageData = new MageData(mage.getId());
if (mageDataStore != null && mage.save(mageData)) {
if (wandInventoryOpen) {
mageData.setOpenWand(true);
}
if (asynchronous) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new SaveMageTask(this, mageData, callback, releaseLock));
} else {
doSaveMage(mageData, callback, releaseLock);
}
} else if (releaseLock && mageDataStore != null) {
getLogger().warning("Player logging out, but data never loaded. Force-releasing lock");
mageDataStore.releaseLock(mageData);
}
}
public void doSaveMage(MageData mageData, MageDataCallback callback, boolean releaseLock) {
synchronized (saveLock) {
try {
mageDataStore.save(mageData, callback, releaseLock);
} catch (Exception ex) {
getLogger().log(Level.SEVERE, "Error saving mage data for mage " + mageData.getId(), ex);
}
}
}
@Nullable
public ItemStack removeItemFromWand(Wand wand, ItemStack droppedItem) {
if (wand == null || droppedItem == null || Wand.isWand(droppedItem)) {
return null;
}
if (Wand.isSpell(droppedItem)) {
String spellKey = Wand.getSpell(droppedItem);
wand.removeSpell(spellKey);
// Update the item for proper naming and lore
SpellTemplate spell = getSpellTemplate(spellKey);
if (spell != null) {
Wand.updateSpellItem(messages, droppedItem, spell, "", null, null, true);
}
} else if (Wand.isBrush(droppedItem)) {
String brushKey = Wand.getBrush(droppedItem);
wand.removeBrush(brushKey);
// Update the item for proper naming and lore
Wand.updateBrushItem(getMessages(), droppedItem, brushKey, null);
}
return droppedItem;
}
public void onArmorUpdated(final com.elmakers.mine.bukkit.magic.Mage mage) {
plugin.getServer().getScheduler().runTaskLater(plugin, new ArmorUpdatedTask(mage), 1);
}
@Override
public boolean isLocked(Block block) {
return protectLocked && containerMaterials.testBlock(block) && CompatibilityUtils.isLocked(block);
}
protected boolean addLostWandMarker(LostWand lostWand) {
if (!dynmapShowWands) {
return false;
}
Location location = lostWand.getLocation();
return addMarker("wand-" + lostWand.getId(), "wand", "wands", lostWand.getName(), location.getWorld().getName(),
location.getBlockX(), location.getBlockY(), location.getBlockZ(), lostWand.getDescription()
);
}
public void toggleCastCommandOverrides(Mage apiMage, CommandSender sender, boolean override) {
// Don't track command-line casts
// Reach into internals a bit here.
if (apiMage instanceof com.elmakers.mine.bukkit.magic.Mage) {
com.elmakers.mine.bukkit.magic.Mage mage = (com.elmakers.mine.bukkit.magic.Mage) apiMage;
if (sender != null && sender instanceof BlockCommandSender) {
mage.setCostFree(override && castCommandCostFree);
mage.setCooldownFree(override && castCommandCooldownFree);
mage.setPowerMultiplier(override ? castCommandPowerMultiplier : 1);
} else {
mage.setCostFree(override && castConsoleCostFree);
mage.setCooldownFree(override && castConsoleCooldownFree);
mage.setPowerMultiplier(override ? castConsolePowerMultiplier : 1);
}
}
}
public float getCooldownReduction() {
return cooldownReduction;
}
public float getCostReduction() {
return costReduction;
}
public Material getDefaultMaterial() {
return defaultMaterial;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.wand.LostWand> getLostWands() {
return new ArrayList<>(lostWands.values());
}
@Override
public boolean cast(String spellName, String[] parameters) {
return cast(spellName, parameters, Bukkit.getConsoleSender(), null);
}
public boolean cast(String spellName, String[] parameters, CommandSender sender, Entity entity) {
ConfigurationSection config = null;
if (parameters != null && parameters.length > 0) {
config = ConfigurationUtils.newConfigurationSection();
ConfigurationUtils.addParameters(parameters, config);
}
return cast(null, spellName, config, sender, entity);
}
public boolean cast(Mage mage, String spellName, ConfigurationSection parameters, CommandSender sender, Entity entity) {
Player usePermissions = (sender == entity && entity instanceof Player) ? (Player) entity
: (sender instanceof Player ? (Player) sender : null);
if (entity == null && sender instanceof Player) {
entity = (Player) sender;
}
Location targetLocation = null;
if (mage == null) {
CommandSender mageController = (entity != null && entity instanceof Player) ? (Player) entity : sender;
if (sender != null && sender instanceof BlockCommandSender) {
targetLocation = ((BlockCommandSender) sender).getBlock().getLocation();
}
if (entity == null) {
mage = getMage(mageController);
} else {
mage = getMageFromEntity(entity, mageController);
}
}
SpellTemplate template = getSpellTemplate(spellName);
if (template == null || !template.hasCastPermission(usePermissions)) {
if (sender != null) {
sender.sendMessage("Spell " + spellName + " unknown");
}
return false;
}
com.elmakers.mine.bukkit.api.spell.Spell spell = mage.getSpell(spellName);
if (spell == null) {
if (sender != null) {
sender.sendMessage("Spell " + spellName + " unknown");
}
return false;
}
// TODO: Load configured list of parameters!
// Make it free and skip cooldowns, if configured to do so.
toggleCastCommandOverrides(mage, sender, true);
boolean success = false;
try {
success = spell.cast(parameters, targetLocation);
} catch (Exception ex) {
ex.printStackTrace();
}
toggleCastCommandOverrides(mage, sender, false);
// Removed sending messages here due to the log spam in WG region messages
// Maybe should be a parameter option or something?
return success;
}
public void onCast(Mage mage, com.elmakers.mine.bukkit.api.spell.Spell spell, SpellResult result) {
if (dynmapShowSpells && dynmap != null && result.isSuccess()) {
if (dynmapOnlyPlayerSpells && (mage == null || !mage.isPlayer())) {
return;
}
dynmap.showCastMarker(mage, spell, result);
}
if (result.isSuccess() && getShowCastHoloText()) {
mage.showHoloText(mage.getEyeLocation(), spell.getName(), 10000);
}
}
@Override
public Messages getMessages() {
return messages;
}
@Override
public MapController getMaps() {
return maps;
}
public String getWelcomeWand() {
return welcomeWand;
}
@Override
public void sendToMages(String message, Location location) {
sendToMages(message, location, toggleMessageRange);
}
public void sendToMages(String message, Location location, int range) {
int rangeSquared = range * range;
if (message != null && message.length() > 0) {
for (Mage mage : mages.values()) {
if (!mage.isPlayer() || mage.isDead() || !mage.isOnline() || !mage.hasLocation()) continue;
if (!mage.getLocation().getWorld().equals(location.getWorld())) continue;
if (mage.getLocation().toVector().distanceSquared(location.toVector()) < rangeSquared) {
mage.sendMessage(message);
}
}
}
}
@Override
public boolean isNPC(Entity entity) {
if (isMagicNPC(entity)) {
return true;
}
return npcSuppliers.isNPC(entity);
}
@Override
public boolean isStaticNPC(Entity entity) {
if (isMagicNPC(entity)) {
return true;
}
return npcSuppliers.isStaticNPC(entity);
}
@Override
public boolean isPet(Entity entity) {
// This currently only looks for pets from SimplePets
return entity.hasMetadata("pet");
}
@Override
public boolean isMagicNPC(Entity entity) {
return npcsByEntity.containsKey(entity.getUniqueId());
}
@Override
public boolean isVanished(Entity entity) {
if (entity == null) return false;
Mage mage = getRegisteredMage(entity);
if (mage != null && mage.isVanished()) {
return true;
}
if (essentialsController != null && essentialsController.isVanished(entity)) {
return true;
}
for (MetadataValue meta : entity.getMetadata("vanished")) {
return meta.asBoolean();
}
return false;
}
@Override
public void updateBlock(Block block) {
updateBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ());
}
@Override
public void updateBlock(String worldName, int x, int y, int z) {
if (dynmap != null && dynmapUpdate) {
dynmap.triggerRenderOfBlock(worldName, x, y, z);
}
}
@Override
public void updateVolume(String worldName, int minx, int miny, int minz, int maxx, int maxy, int maxz) {
if (dynmap != null && dynmapUpdate && worldName != null && worldName.length() > 0) {
dynmap.triggerRenderOfVolume(worldName, minx, miny, minz, maxx, maxy, maxz);
}
}
public void update(String worldName, BoundingBox area) {
if (dynmap != null && dynmapUpdate && area != null && worldName != null && worldName.length() > 0) {
dynmap.triggerRenderOfVolume(worldName,
area.getMin().getBlockX(), area.getMin().getBlockY(), area.getMin().getBlockZ(),
area.getMax().getBlockX(), area.getMax().getBlockY(), area.getMax().getBlockZ());
}
}
@Override
public void update(com.elmakers.mine.bukkit.api.block.BlockList blockList) {
if (blockList != null) {
for (Map.Entry<String, ? extends BoundingBox> entry : blockList.getAreas().entrySet()) {
update(entry.getKey(), entry.getValue());
}
}
}
@Override
public void cleanItem(ItemStack item) {
InventoryUtils.removeMeta(item, Wand.WAND_KEY);
InventoryUtils.removeMeta(item, Wand.UPGRADE_KEY);
InventoryUtils.removeMeta(item, "spell");
InventoryUtils.removeMeta(item, "skill");
InventoryUtils.removeMeta(item, "brush");
InventoryUtils.removeMeta(item, "sp");
InventoryUtils.removeMeta(item, "keep");
InventoryUtils.removeMeta(item, "temporary");
InventoryUtils.removeMeta(item, "undroppable");
InventoryUtils.removeMeta(item, "unplaceable");
InventoryUtils.removeMeta(item, "unstashable");
InventoryUtils.removeMeta(item, "unmoveable");
}
@Override
public boolean canCreateWorlds() {
return createWorldsEnabled;
}
@Override
public int getMaxUndoPersistSize() {
return undoMaxPersistSize;
}
@Override
public MagicPlugin getPlugin() {
return plugin;
}
@Override
public MagicAPI getAPI() {
return plugin;
}
public Collection<? extends Mage> getMutableMages() {
return mages.values();
}
@Override
public Collection<Mage> getMages() {
Collection<? extends Mage> values = mages.values();
return Collections.unmodifiableCollection(values);
}
@Override
@Deprecated
public Set<Material> getBuildingMaterials() {
return MaterialSets.toLegacyNN(buildingMaterials);
}
@Override
public Collection<Mage> getMobMages() {
Collection<Mage> mobMages = new ArrayList<>();
for (Mage mage : mages.values()) {
if (mage.getEntityData() != null) {
mobMages.add(mage);
}
}
return Collections.unmodifiableCollection(mobMages);
}
@Override
public Collection<Entity> getActiveMobs() {
return mobs.getActiveMobs();
}
@Override
@Deprecated
public Set<Material> getRestrictedMaterials() {
return MaterialSets.toLegacyNN(restrictedMaterials);
}
@Override
public MaterialSet getBuildingMaterialSet() {
return buildingMaterials;
}
@Override
public MaterialSet getDestructibleMaterialSet() {
return destructibleMaterials;
}
@Override
public MaterialSet getRestrictedMaterialSet() {
return restrictedMaterials;
}
@Override
public int getMessageThrottle() {
return messageThrottle;
}
// TODO: Remove the if and replace it with a precondition
// once we're sure nothing is calling this with a null value.
@SuppressWarnings({"null", "unused"})
@Override
public boolean isMage(Entity entity) {
if (entity == null) return false;
String id = mageIdentifier.fromEntity(entity);
return mages.containsKey(id);
}
@Override
public MaterialSetManager getMaterialSetManager() {
return materialSetManager;
}
@Override
@Deprecated
public Collection<String> getMaterialSets() {
return getMaterialSetManager().getMaterialSets();
}
@Nullable
@Override
@Deprecated
public Set<Material> getMaterialSet(String string) {
return MaterialSets.toLegacy(getMaterialSetManager().fromConfig(string));
}
@Override
public Collection<String> getPlayerNames() {
List<String> playerNames = new ArrayList<>();
Collection<? extends Player> players = plugin.getServer().getOnlinePlayers();
for (Player player : players) {
if (isNPC(player)) continue;
playerNames.add(player.getName());
}
return playerNames;
}
@Override
public void disablePhysics(int interval) {
if (physicsHandler == null && interval > 0) {
physicsHandler = new PhysicsHandler(this);
Bukkit.getPluginManager().registerEvents(physicsHandler, plugin);
}
if (physicsHandler != null) {
physicsHandler.setInterval(interval);
}
}
@Override
public boolean commitAll() {
boolean undid = false;
for (Mage mage : mages.values()) {
undid = mage.commit() || undid;
}
com.elmakers.mine.bukkit.block.UndoList.commitAll();
return undid;
}
@Override
public boolean canTarget(Entity attacker, Entity entity) {
// We can always target ourselves at this level
if (attacker == entity) return true;
// We don't handle non-entities here
if (attacker == null || entity == null) return true;
// We can't target our friends (bypassing happens at a higher level)
if (isFriendly(attacker, entity, false)) {
return false;
}
for (EntityTargetingManager manager : targetingProviders) {
if (!manager.canTarget(attacker, entity)) {
return false;
}
}
return true;
}
@Override
public boolean isFriendly(Entity attacker, Entity entity) {
return isFriendly(attacker, entity, true);
}
public boolean isFriendly(Entity attacker, Entity entity, boolean friendlyByDefault) {
// We are always friends with ourselves
if (attacker == entity) return true;
for (TeamProvider provider : teamProviders) {
if (provider.isFriendly(attacker, entity)) {
return true;
}
}
if (friendlyByDefault) {
// Mobs can always target players, just to avoid any confusion there.
if (!(attacker instanceof Player)) return true;
// Player vs Player is controlled by a special config flag
if (entity instanceof Player) return defaultFriendly;
// Otherwise we look at the friendly entity types
return friendlyEntityTypes.contains(entity.getType());
}
return false;
}
@Nullable
@Override
public Location getWarp(String warpName) {
Location location = null;
if (warpController != null) {
try {
location = warpController.getWarp(warpName);
} catch (Exception ex) {
location = null;
}
}
return location;
}
public WarpController getWarps() {
return warpController;
}
@Nullable
@Override
public Location getTownLocation(Player player) {
return townyManager.getTownLocation(player);
}
@Nullable
@Override
public Map<String, Location> getHomeLocations(Player player) {
return preciousStonesManager.getFieldLocations(player);
}
@Nonnull
@Override
public Set<String> getPlayerWarpProviderKeys() {
return playerWarpManagers.keySet();
}
@Nullable
@Override
public Collection<PlayerWarp> getPlayerWarps(Player player, String key) {
PlayerWarpManager manager = playerWarpManagers.get(key);
if (manager == null) {
return null;
}
return manager.getWarps(player);
}
public TownyManager getTowny() {
return townyManager;
}
public PreciousStonesManager getPreciousStones() {
return preciousStonesManager;
}
@Override
public boolean sendMail(CommandSender sender, String fromPlayer, String toPlayer, String message) {
if (mailer != null) {
return mailer.sendMail(sender, fromPlayer, toPlayer, message);
}
return false;
}
@Nullable
@Override
public UndoList undoAny(Block target) {
for (Mage mage : mages.values()) {
UndoList undid = mage.undo(target);
if (undid != null) {
return undid;
}
}
return null;
}
@Nullable
@Override
public UndoList undoRecent(Block target, int timeout) {
for (Mage mage : mages.values()) {
com.elmakers.mine.bukkit.api.block.UndoQueue queue = mage.getUndoQueue();
UndoList undid = queue.undoRecent(target, timeout);
if (undid != null) {
return undid;
}
}
return null;
}
@Nullable
@Override
public Wand getIfWand(ItemStack itemStack) {
if (Wand.isWand(itemStack)) {
return getWand(itemStack);
}
return null;
}
@Override
public Wand getWand(ItemStack itemStack) {
@SuppressWarnings("deprecation")
Wand wand = new Wand(this, itemStack);
return wand;
}
@Override
public Wand getWand(ConfigurationSection config) {
return new Wand(this, config);
}
@Nullable
@Override
public Wand createWand(String wandKey) {
return Wand.createWand(this, wandKey);
}
@Override
@Nonnull
public Wand createWand(@Nonnull ItemStack itemStack) {
return Wand.createWand(this, itemStack);
}
@Nullable
@Override
public WandTemplate getWandTemplate(String key) {
if (key == null || key.isEmpty()) return null;
return wandTemplates.get(key);
}
@Override
public Collection<com.elmakers.mine.bukkit.api.wand.WandTemplate> getWandTemplates() {
return new ArrayList<>(wandTemplates.values());
}
@Override
@Nullable
public String getAutoWandKey(@Nonnull Material material) {
return autoWands.get(material);
}
@Nullable
public ItemStack getAutoWand(ItemStack itemStack) {
if (itemStack == null) return null;
String templateKey = getAutoWandKey(itemStack.getType());
if (templateKey != null && !templateKey.isEmpty()) {
Wand wand = createWand(templateKey);
if (wand == null) {
getLogger().warning("Invalid wand template in auto_wands config: " + templateKey);
} else {
return wand.getItem();
}
}
return null;
}
@Nullable
protected ConfigurationSection resolveConfiguration(String key, ConfigurationSection properties, Map<String, ConfigurationSection> configurations) {
resolvingKeys.clear();
return resolveConfiguration(key, properties, configurations, resolvingKeys);
}
@Nullable
protected ConfigurationSection resolveConfiguration(String key, ConfigurationSection properties, Map<String, ConfigurationSection> configurations, Set<String> resolving) {
// Catch circular dependencies
if (resolving.contains(key)) {
getLogger().log(Level.WARNING, "Circular dependency detected: " + StringUtils.join(resolving, " -> ") + " -> " + key);
return properties;
}
resolving.add(key);
ConfigurationSection configuration = configurations.get(key);
if (configuration == null) {
configuration = properties.getConfigurationSection(key);
if (configuration == null) {
return null;
}
String inherits = configuration.getString("inherit");
if (inherits != null) {
ConfigurationSection baseConfiguration = resolveConfiguration(inherits, properties, configurations, resolving);
if (baseConfiguration != null) {
ConfigurationSection newConfiguration = ConfigurationUtils.cloneConfiguration(baseConfiguration);
ConfigurationUtils.addConfigurations(newConfiguration, configuration);
// Some properties don't inherit, this is kind of hacky.
newConfiguration.set("hidden", configuration.get("hidden"));
configuration = newConfiguration;
}
}
configurations.put(key, configuration);
}
return configuration;
}
public void loadMageClasses(ConfigurationSection properties) {
mageClasses.clear();
Set<String> classKeys = properties.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
for (String key : classKeys) {
logger.setContext("classes." + key);
ConfigurationSection classConfig = resolveConfiguration(key, properties, templateConfigurations);
classConfig = MagicConfiguration.getKeyed(this, classConfig, "class", key);
loadMageClassTemplate(key, classConfig);
}
// Resolve parents, we don't check for an inherited "parent" property, so it's important
// to use the original un-inherited configs for parenting.
for (String key : classKeys) {
logger.setContext("classes." + key);
MageClassTemplate template = mageClasses.get(key);
if (template != null) {
String parentKey = properties.getConfigurationSection(key).getString("parent");
if (parentKey != null) {
MageClassTemplate parent = mageClasses.get(parentKey);
if (parent == null) {
getLogger().warning("Class '" + key + "' has unknown parent: " + parentKey);
} else {
template.setParent(parent);
}
}
}
}
// Update registered mages so their classes are current
for (Mage mage : mages.values()) {
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
((com.elmakers.mine.bukkit.magic.Mage) mage).reloadClasses();
}
}
}
public void loadModifiers(ConfigurationSection properties) {
modifiers.clear();
Set<String> modifierKeys = properties.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
for (String key : modifierKeys) {
logger.setContext("modifiers." + key);
ConfigurationSection modifierConfig = resolveConfiguration(key, properties, templateConfigurations);
modifierConfig = MagicConfiguration.getKeyed(this, modifierConfig, "modifier", key);
loadModifierTemplate(key, modifierConfig);
}
// Resolve parents, we don't check for an inherited "parent" property, so it's important
// to use the original un-inherited configs for parenting.
for (String key : modifierKeys) {
logger.setContext("modifiers." + key);
ModifierTemplate template = modifiers.get(key);
if (template != null) {
String parentKey = properties.getConfigurationSection(key).getString("parent");
if (parentKey != null) {
ModifierTemplate parent = modifiers.get(parentKey);
if (parent == null) {
getLogger().warning("Modifier '" + key + "' has unknown parent: " + parentKey);
} else {
template.setParent(parent);
}
}
}
}
// Update registered mages so their classes are current
for (Mage mage : mages.values()) {
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
((com.elmakers.mine.bukkit.magic.Mage) mage).reloadModifiers();
}
}
}
@Override
public Set<String> getMageClassKeys() {
return mageClasses.keySet();
}
@Nonnull
public MageClassTemplate getMageClass(String key) {
MageClassTemplate template = mageClasses.get(key);
if (template == null) {
ConfigurationSection configuration = ConfigurationUtils.newConfigurationSection();
template = new MageClassTemplate(this, key, configuration);
mageClasses.put(key, template);
}
return template;
}
public void loadMageClassTemplate(String key, ConfigurationSection classNode) {
if (ConfigurationUtils.isEnabled(classNode)) {
mageClasses.put(key, new MageClassTemplate(this, key, classNode));
}
}
public void loadModifierTemplate(String key, ConfigurationSection modifierNode) {
if (ConfigurationUtils.isEnabled(modifierNode)) {
modifiers.put(key, new ModifierTemplate(this, key, modifierNode));
}
}
public void loadWandTemplates(ConfigurationSection properties) {
wandTemplates.clear();
Set<String> wandKeys = properties.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
for (String key : wandKeys) {
logger.setContext("wands." + key);
loadWandTemplate(key, resolveConfiguration(key, properties, templateConfigurations));
}
}
public void loadMobs(ConfigurationSection properties) {
mobs.clear();
Set<String> mobKeys = properties.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
for (String key : mobKeys) {
logger.setContext("mobs." + key);
ConfigurationSection mobConfig = resolveConfiguration(key, properties, templateConfigurations);
mobConfig = MagicConfiguration.getKeyed(this, mobConfig, "mob", key);
mobs.load(key, mobConfig);
}
}
public void loadWorlds(ConfigurationSection properties) {
Set<String> worldKeys = properties.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
for (String key : worldKeys) {
if (key.equalsIgnoreCase("worlds")) continue;
logger.setContext("worlds." + key);
ConfigurationSection worldConfig = resolveConfiguration(key, properties, templateConfigurations);
worldConfig = MagicConfiguration.getKeyed(this, worldConfig, "world", key);
properties.set(key, worldConfig);
}
worldController.loadWorlds(properties);
}
@Override
public MageClassTemplate getMageClassTemplate(String key) {
return mageClasses.get(key);
}
@Override
@Nullable
public ModifierTemplate getModifierTemplate(String key) {
return modifiers.get(key);
}
@Override
@Nonnull
public Collection<String> getModifierTemplateKeys() {
return modifiers.keySet();
}
@Override
public void loadWandTemplate(String key, ConfigurationSection wandNode) {
if (ConfigurationUtils.isEnabled(wandNode)) {
wandNode = MagicConfiguration.getKeyed(this, wandNode, "wand", key);
wandTemplates.put(key, new com.elmakers.mine.bukkit.wand.WandTemplate(this, key, wandNode));
}
}
@Override
public void unloadWandTemplate(String key) {
wandTemplates.remove(key);
}
@Override
public Collection<String> getWandTemplateKeys() {
return wandTemplates.keySet();
}
@Nullable
public ConfigurationSection getWandTemplateConfiguration(String key) {
WandTemplate template = getWandTemplate(key);
return template == null ? null : template.getConfiguration();
}
@Override
public boolean elementalsEnabled() {
return (elementals != null);
}
@Override
public boolean createElemental(Location location, String templateName, CommandSender creator) {
return elementals.createElemental(location, templateName, creator);
}
@Override
public boolean isElemental(Entity entity) {
if (elementals == null || entity.getType() != EntityType.FALLING_BLOCK) return false;
return elementals.isElemental(entity);
}
@Override
public boolean damageElemental(Entity entity, double damage, int fireTicks, CommandSender attacker) {
if (elementals == null) return false;
return elementals.damageElemental(entity, damage, fireTicks, attacker);
}
@Override
public boolean setElementalScale(Entity entity, double scale) {
if (elementals == null) return false;
return elementals.setElementalScale(entity, scale);
}
@Override
public double getElementalScale(Entity entity) {
if (elementals == null) return 0;
return elementals.getElementalScale(entity);
}
@Nullable
@Override
public com.elmakers.mine.bukkit.api.spell.SpellCategory getCategory(String key) {
if (key == null || key.isEmpty()) {
return null;
}
SpellCategory category = categories.get(key);
if (category == null) {
category = new com.elmakers.mine.bukkit.spell.SpellCategory(key, this);
categories.put(key, category);
}
return category;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.spell.SpellCategory> getCategories() {
List<com.elmakers.mine.bukkit.api.spell.SpellCategory> allCategories = new ArrayList<>();
allCategories.addAll(categories.values());
return allCategories;
}
@Override
public Collection<String> getSpellTemplateKeys() {
return spells.keySet();
}
@Override
public Collection<SpellTemplate> getSpellTemplates() {
return getSpellTemplates(false);
}
@Override
public Collection<SpellTemplate> getSpellTemplates(boolean showHidden) {
List<SpellTemplate> allSpells = new ArrayList<>();
for (SpellTemplate spell : spells.values()) {
if (showHidden || !spell.isHidden()) {
allSpells.add(spell);
}
}
return allSpells;
}
@Nullable
@Override
public SpellTemplate getSpellTemplate(String name) {
if (name == null || name.length() == 0) return null;
SpellTemplate spell = spellAliases.get(name);
if (spell == null) {
spell = spells.get(name);
}
if (spell == null && name.startsWith("heroes*")) {
if (heroesManager == null) return null;
spell = heroesManager.createSkillSpell(this, name.substring(7));
if (spell != null) {
spells.put(name, spell);
}
}
return spell;
}
protected void loadSpells(CommandSender sender, ConfigurationSection spellConfigs) {
if (spellConfigs == null) return;
// Reset existing spells.
spells.clear();
spellAliases.clear();
categories.clear();
maxSpellLevels.clear();
Set<String> keys = spellConfigs.getKeys(false);
for (String key : keys) {
if (key.equals("default") || key.equals("override")) continue;
logger.setContext("spells." + key);
ConfigurationSection spellNode = spellConfigs.getConfigurationSection(key);
if (!(spellNode instanceof MagicConfiguration)) {
spellNode = MagicConfiguration.getKeyed(this, spellNode, "spell", key);
spellConfigs.set(key, spellNode);
}
Spell newSpell = null;
try {
newSpell = loadSpell(key, spellNode, this);
} catch (Exception ex) {
newSpell = null;
ex.printStackTrace();
}
if (newSpell == null) {
getLogger().warning("Magic: Error loading spell " + key);
continue;
}
if (!newSpell.hasIcon()) {
String icon = spellNode.getString("icon");
if (icon != null && !icon.isEmpty()) {
getLogger().info("Couldn't load spell icon '" + icon + "' for spell: " + newSpell.getKey());
}
}
addSpell(newSpell);
}
// Second pass to fulfill requirements, which needs all spells loaded
for (String key : keys) {
logger.setContext("spells." + key);
SpellTemplate template = getSpellTemplate(key);
if (template != null) {
template.loadPrerequisites(spellConfigs.getConfigurationSection(key));
}
}
// Update registered mages so their spells are current
for (Mage mage : mages.values()) {
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
((com.elmakers.mine.bukkit.magic.Mage) mage).loadSpells(spellConfigs);
}
}
}
public SpellKey unalias(SpellKey spellKey) {
SpellTemplate spell = spellAliases.get(spellKey.getBaseKey());
if (spell != null) {
return new SpellKey(spell.getSpellKey().getBaseKey(), spellKey.getLevel());
}
return spellKey;
}
@Override
public String getEntityDisplayName(Entity target) {
return getEntityName(target, true);
}
@Override
public String getEntityName(Entity target) {
return getEntityName(target, false);
}
protected String getEntityName(Entity target, boolean display) {
if (target == null) {
return "Unknown";
}
if (target instanceof Player) {
return display ? ((Player) target).getDisplayName() : target.getName();
}
if (isElemental(target)) {
return "Elemental";
}
if (display) {
if (target instanceof LivingEntity) {
LivingEntity li = (LivingEntity) target;
String customName = li.getCustomName();
if (customName != null && customName.length() > 0) {
return customName;
}
} else if (target instanceof Item) {
Item item = (Item) target;
ItemStack itemStack = item.getItemStack();
if (itemStack.hasItemMeta()) {
ItemMeta meta = itemStack.getItemMeta();
if (meta.hasDisplayName()) {
return meta.getDisplayName();
}
}
MaterialAndData material = new MaterialAndData(itemStack);
return material.getName(getMessages());
}
}
String localizedName = messages.get("entities." + target.getType().name().toLowerCase(), "");
if (!localizedName.isEmpty()) {
return localizedName;
}
return target.getType().name().toLowerCase().replace('_', ' ');
}
public boolean getShowCastHoloText() {
return showCastHoloText;
}
public boolean getShowActivateHoloText() {
return showActivateHoloText;
}
public int getCastHoloTextRange() {
return castHoloTextRange;
}
public int getActiveHoloTextRange() {
return activateHoloTextRange;
}
public ItemStack getSpellBook(com.elmakers.mine.bukkit.api.spell.SpellCategory category, int count) {
Map<String, List<SpellTemplate>> categories = new HashMap<>();
Collection<SpellTemplate> spellVariants = spells.values();
String categoryKey = category == null ? null : category.getKey();
for (SpellTemplate spell : spellVariants) {
if (spell.isHidden() || spell.getSpellKey().isVariant()) continue;
com.elmakers.mine.bukkit.api.spell.SpellCategory spellCategory = spell.getCategory();
if (spellCategory == null) continue;
String spellCategoryKey = spellCategory.getKey();
if (categoryKey == null || spellCategoryKey.equalsIgnoreCase(categoryKey)) {
List<SpellTemplate> categorySpells = categories.get(spellCategoryKey);
if (categorySpells == null) {
categorySpells = new ArrayList<>();
categories.put(spellCategoryKey, categorySpells);
}
categorySpells.add(spell);
}
}
List<String> categoryKeys = new ArrayList<>(categories.keySet());
Collections.sort(categoryKeys);
ItemStack bookItem = new ItemStack(Material.WRITTEN_BOOK, count);
BookMeta book = (BookMeta) bookItem.getItemMeta();
book.setAuthor(messages.get("books.default.author"));
String title = null;
if (category != null) {
title = messages.get("books.default.title").replace("$category", category.getName());
} else {
title = messages.get("books.all.title");
}
book.setTitle(title);
List<String> pages = new ArrayList<>();
for (String key : categoryKeys) {
category = getCategory(key);
title = messages.get("books.default.title").replace("$category", category.getName());
String description = "" + ChatColor.BOLD + ChatColor.BLUE + title + "\n\n";
description += "" + ChatColor.RESET + ChatColor.DARK_BLUE + category.getDescription();
pages.add(description);
List<SpellTemplate> categorySpells = categories.get(key);
Collections.sort(categorySpells);
for (SpellTemplate spell : categorySpells) {
List<String> lines = getSpellBookDescription(spell);
pages.add(StringUtils.join(lines, "\n"));
}
}
book.setPages(pages);
bookItem.setItemMeta(book);
return bookItem;
}
public ItemStack getSpellBook(com.elmakers.mine.bukkit.api.spell.SpellTemplate spell, int count) {
ItemStack bookItem = new ItemStack(Material.WRITTEN_BOOK, count);
BookMeta book = (BookMeta) bookItem.getItemMeta();
book.setAuthor(messages.get("books.default.author"));
book.setTitle(messages.get("books.spell.title").replace("$spell", spell.getName()));
List<String> pages = new ArrayList<>();
List<String> lines = getSpellBookDescription(spell);
pages.add(StringUtils.join(lines, "\n"));
book.setPages(pages);
bookItem.setItemMeta(book);
return bookItem;
}
protected List<String> getSpellBookDescription(SpellTemplate spell) {
Set<String> paths = WandUpgradePath.getPathKeys();
List<String> lines = new ArrayList<>();
lines.add("" + ChatColor.GOLD + ChatColor.BOLD + spell.getName());
lines.add("" + ChatColor.RESET);
String spellDescription = spell.getDescription();
if (spellDescription != null && spellDescription.length() > 0) {
lines.add("" + ChatColor.BLACK + spellDescription);
lines.add("");
}
String spellCooldownDescription = spell.getCooldownDescription();
if (spellCooldownDescription != null && spellCooldownDescription.length() > 0) {
spellCooldownDescription = messages.get("cooldown.description").replace("$time", spellCooldownDescription);
lines.add("" + ChatColor.DARK_PURPLE + spellCooldownDescription);
}
String spellMageCooldownDescription = spell.getMageCooldownDescription();
if (spellMageCooldownDescription != null && spellMageCooldownDescription.length() > 0) {
spellMageCooldownDescription = messages.get("cooldown.mage_description").replace("$time", spellMageCooldownDescription);
lines.add("" + ChatColor.RED + spellMageCooldownDescription);
}
Collection<CastingCost> costs = spell.getCosts();
if (costs != null) {
for (CastingCost cost : costs) {
if (!cost.isEmpty()) {
lines.add(ChatColor.DARK_PURPLE + messages.get("wand.costs_description").replace("$description", cost.getFullDescription(messages)));
}
}
}
Collection<CastingCost> activeCosts = spell.getActiveCosts();
if (activeCosts != null) {
for (CastingCost cost : activeCosts) {
if (!cost.isEmpty()) {
lines.add(ChatColor.DARK_PURPLE + messages.get("wand.active_costs_description").replace("$description", cost.getFullDescription(messages)));
}
}
}
for (String pathKey : paths) {
WandUpgradePath checkPath = WandUpgradePath.getPath(pathKey);
if (!checkPath.isHidden() && (checkPath.hasSpell(spell.getKey()) || checkPath.hasExtraSpell(spell.getKey()))) {
lines.add(ChatColor.DARK_BLUE + messages.get("spell.available_path").replace("$path", checkPath.getName()));
break;
}
}
for (String pathKey : paths) {
WandUpgradePath checkPath = WandUpgradePath.getPath(pathKey);
if (checkPath.requiresSpell(spell.getKey())) {
lines.add(ChatColor.DARK_RED + messages.get("spell.required_path").replace("$path", checkPath.getName()));
break;
}
}
String duration = spell.getDurationDescription(messages);
if (duration != null) {
lines.add(ChatColor.DARK_GREEN + duration);
} else if (spell.showUndoable()) {
if (spell.isUndoable()) {
String undoable = messages.get("spell.undoable", "");
if (undoable != null && !undoable.isEmpty()) {
lines.add(undoable);
}
} else {
String notUndoable = messages.get("spell.not_undoable", "");
if (notUndoable != null && !notUndoable.isEmpty()) {
lines.add(notUndoable);
}
}
}
if (spell.usesBrush()) {
lines.add(ChatColor.DARK_GRAY + messages.get("spell.brush"));
}
SpellKey baseKey = spell.getSpellKey();
SpellKey upgradeKey = new SpellKey(baseKey.getBaseKey(), baseKey.getLevel() + 1);
SpellTemplate upgradeSpell = getSpellTemplate(upgradeKey.getKey());
int spellLevels = 0;
while (upgradeSpell != null) {
spellLevels++;
upgradeKey = new SpellKey(upgradeKey.getBaseKey(), upgradeKey.getLevel() + 1);
upgradeSpell = getSpellTemplate(upgradeKey.getKey());
}
if (spellLevels > 0) {
spellLevels++;
lines.add(ChatColor.DARK_AQUA + messages.get("spell.levels_available").replace("$levels", Integer.toString(spellLevels)));
}
String usage = spell.getUsage();
if (usage != null && usage.length() > 0) {
lines.add("" + ChatColor.GRAY + ChatColor.ITALIC + usage + ChatColor.RESET);
lines.add("");
}
String spellExtendedDescription = spell.getExtendedDescription();
if (spellExtendedDescription != null && spellExtendedDescription.length() > 0) {
lines.add("" + ChatColor.BLACK + spellExtendedDescription);
lines.add("");
}
return lines;
}
public ItemStack getLearnSpellBook(SpellTemplate spell, int amount) {
ConfigurationSection wandConfiguration = ConfigurationUtils.newConfigurationSection();
wandConfiguration.set("template", "learnspell");
wandConfiguration.set("icon", "book:" + spell.getKey());
wandConfiguration.set("name", messages.get("books.learnspell.name").replace("$spell", spell.getName()));
wandConfiguration.set("description", messages.get("books.learnspell.description").replace("$spell", spell.getName()));
wandConfiguration.set("overrides", "spell " + spell.getKey());
Wand wand = new Wand(this, wandConfiguration);
ItemStack item = wand.getItem();
item.setAmount(amount);
return item;
}
@Override
public MaterialAndData getRedstoneReplacement() {
return redstoneReplacement;
}
@Override
public Set<EntityType> getUndoEntityTypes() {
return undoEntityTypes;
}
@Override
public String describeItem(ItemStack item) {
return messages.describeItem(item);
}
public boolean checkForItem(Player player, ItemStack requireItem, boolean take) {
boolean foundItem = false;
ItemStack[] contents = player.getInventory().getContents();
for (int i = 0; i < contents.length; i++) {
ItemStack item = contents[i];
if (itemsAreEqual(item, requireItem)) {
Wand wand = null;
if (Wand.isWand(item) && Wand.isBound(item)) {
wand = getWand(item);
if (!wand.canUse(player)) continue;
}
if (take) {
player.getInventory().setItem(i, null);
if (wand != null) {
wand.unbind();
}
}
foundItem = true;
break;
}
}
return foundItem;
}
@Override
public boolean hasItem(Player player, ItemStack requireItem) {
return checkForItem(player, requireItem, false);
}
@Override
public boolean takeItem(Player player, ItemStack requireItem) {
return checkForItem(player, requireItem, true);
}
@Override
public boolean isWand(ItemStack item) {
return Wand.isWand(item);
}
@Override
public boolean isWandUpgrade(ItemStack item) {
return Wand.isUpgrade(item);
}
@Override
public boolean isSkill(ItemStack item) {
return Wand.isSkill(item);
}
@Override
public boolean isMagic(ItemStack item) {
return Wand.isSpecial(item);
}
@Nullable
@Override
public String getWandKey(ItemStack item) {
if (Wand.isWand(item)) {
return Wand.getWandTemplate(item);
}
return null;
}
@Override
public String getItemKey(ItemStack item) {
if (item == null) {
return "";
}
if (Wand.isUpgrade(item)) {
return "upgrade:" + Wand.getWandTemplate(item);
}
if (Wand.isWand(item)) {
return "wand:" + Wand.getWandTemplate(item);
}
if (Wand.isSpell(item)) {
return "spell:" + Wand.getSpell(item);
}
if (Wand.isBrush(item)) {
return "brush:" + Wand.getBrush(item);
}
ItemData mappedItem = getItem(item);
if (mappedItem != null) {
return mappedItem.getKey();
}
MaterialAndData material = new MaterialAndData(item);
return material.getKey();
}
@Nullable
@Override
public ItemStack createItem(String magicItemKey) {
return createItem(magicItemKey, false);
}
@Nullable
@Override
public ItemStack createItem(String magicItemKey, boolean brief) {
return createItem(magicItemKey, null, brief, null);
}
@Nullable
@Override
public ItemStack createItem(String magicItemKey, Mage mage, boolean brief, ItemUpdatedCallback callback) {
ItemStack itemStack = null;
if (magicItemKey == null || magicItemKey.isEmpty()) {
if (callback != null) {
callback.updated(null);
}
return null;
}
if (magicItemKey.contains("skill:")) {
String spellKey = magicItemKey.substring(6);
itemStack = Wand.createSpellItem(spellKey, this, mage, null, false);
InventoryUtils.setMeta(itemStack, "skill", "true");
if (callback != null) {
callback.updated(itemStack);
}
return itemStack;
}
// Check for amounts
int amount = 1;
if (magicItemKey.contains("@")) {
String[] pieces = StringUtils.split(magicItemKey, '@');
magicItemKey = pieces[0];
try {
amount = Integer.parseInt(pieces[1]);
} catch (Exception ignored) {
}
}
// Handle : or | as delimiter
magicItemKey = magicItemKey.replace("|", ":");
String[] pieces = StringUtils.split(magicItemKey, ":", 2);
String itemKey = pieces[0];
if (pieces.length > 1) {
String itemData = pieces[1];
try {
switch (itemKey) {
case "book": {
com.elmakers.mine.bukkit.api.spell.SpellCategory category;
if (!itemData.isEmpty() && !itemData.equalsIgnoreCase("all")) {
category = categories.get(itemData);
if (category == null) {
SpellTemplate spell = getSpellTemplate(itemData);
if (spell == null) {
if (callback != null) {
callback.updated(null);
}
return null;
} else {
itemStack = getSpellBook(spell, amount);
}
} else {
itemStack = getSpellBook(category, amount);
}
}
}
break;
case "learnbook": {
SpellTemplate spell = getSpellTemplate(itemData);
if (spell == null) {
if (callback != null) {
callback.updated(null);
}
return null;
}
itemStack = getLearnSpellBook(spell, amount);
}
break;
case "recipe": {
itemStack = CompatibilityUtils.getKnowledgeBook();
if (itemStack != null) {
if (itemData.equals("*")) {
Collection<String> keys = crafting.getRecipeKeys();
for (String key : keys) {
CompatibilityUtils.addRecipeToBook(itemStack, plugin, key);
}
} else {
String[] recipeKeys = StringUtils.split(itemData, ",");
for (String recipe : recipeKeys) {
CompatibilityUtils.addRecipeToBook(itemStack, plugin, recipe);
}
}
}
}
break;
case "recipes": {
itemStack = CompatibilityUtils.getKnowledgeBook();
if (itemStack != null) {
if (itemData.equals("*")) {
Collection<String> keys = crafting.getRecipeKeys();
for (String key : keys) {
CompatibilityUtils.addRecipeToBook(itemStack, plugin, key);
}
} else {
String[] recipeKeys = StringUtils.split(itemData, ",");
for (String recipe : recipeKeys) {
MageClassTemplate mageClass = getMageClassTemplate(recipe);
if (mageClass != null) {
for (String key : mageClass.getRecipies()) {
CompatibilityUtils.addRecipeToBook(itemStack, plugin, key);
}
}
}
}
}
}
break;
case "spell": {
// Fix delimiter replaced above, to handle spell levels
String spellKey = itemData.replace(":", "|");
itemStack = createSpellItem(spellKey, brief);
}
break;
case "wand": {
com.elmakers.mine.bukkit.api.wand.Wand wand = createWand(itemData);
if (wand != null) {
itemStack = wand.getItem();
}
}
break;
case "upgrade": {
com.elmakers.mine.bukkit.api.wand.Wand wand = createWand(itemData);
if (wand != null) {
wand.makeUpgrade();
itemStack = wand.getItem();
}
}
break;
case "brush": {
itemStack = createBrushItem(itemData);
}
break;
case "item": {
itemStack = createGenericItem(itemData);
}
break;
default: {
// Currency
Currency currency = currencies.get(itemKey);
com.elmakers.mine.bukkit.api.block.MaterialAndData currencyIcon = currency == null ? null : currency.getIcon();
if (pieces.length > 1 && currencyIcon != null) {
itemStack = currencyIcon.getItemStack(1);
ItemMeta meta = itemStack.getItemMeta();
String name = currency.getName(messages);
String itemName = messages.get("currency." + itemKey + ".item_name", messages.get("currency.default.item_name"));
itemName = itemName.replace("$type", name);
itemName = itemName.replace("$amount", itemData);
meta.setDisplayName(itemName);
int intAmount;
try {
intAmount = Integer.parseInt(itemData);
} catch (Exception ex) {
getLogger().warning("Invalid amount '" + itemData + "' in " + currency.getKey() + " cost: " + magicItemKey);
if (callback != null) {
callback.updated(null);
}
return null;
}
String currencyDescription = messages.get("currency." + itemKey + ".description", messages.get("currency.default.description"));
if (currencyDescription.length() > 0) {
currencyDescription = currencyDescription.replace("$type", name);
currencyDescription = currencyDescription.replace("$amount", itemData);
List<String> lore = new ArrayList<>();
InventoryUtils.wrapText(ChatColor.translateAlternateColorCodes('&', currencyDescription), lore);
meta.setLore(lore);
}
itemStack.setItemMeta(meta);
itemStack = CompatibilityUtils.makeReal(itemStack);
InventoryUtils.makeUnbreakable(itemStack);
InventoryUtils.hideFlags(itemStack, 63);
Object currencyNode = InventoryUtils.createNode(itemStack, "currency");
InventoryUtils.setMetaInt(currencyNode, "amount", intAmount);
InventoryUtils.setMeta(currencyNode, "type", itemKey);
}
}
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error creating item: " + magicItemKey, ex);
}
}
// Final fallback, may be a plain item without any data, a
// custom item key, or some form of MaterialAnData
// also as some fallbacks for wands and classes wtihout a prefix
if (itemStack == null && items != null) {
try {
ItemData customItem = items.get(magicItemKey);
if (customItem != null) {
itemStack = customItem.getItemStack(amount);
if (callback != null) {
callback.updated(itemStack);
}
return itemStack;
}
MaterialAndData item = new MaterialAndData(magicItemKey);
if (item.isValid() && CompatibilityUtils.isLegacy(item.getMaterial())) {
short convertData = (item.getData() == null ? 0 : item.getData());
item = new MaterialAndData(CompatibilityUtils.migrateMaterial(item.getMaterial(), (byte) convertData));
}
if (item.isValid()) {
return item.getItemStack(amount, callback);
}
com.elmakers.mine.bukkit.api.wand.Wand wand = createWand(magicItemKey);
if (wand != null) {
ItemStack wandItem = wand.getItem();
if (wandItem != null) {
wandItem.setAmount(amount);
}
if (callback != null) {
callback.updated(wandItem);
}
return wandItem;
}
// Spells may be using the | delimiter for levels
// I am regretting overloading this delimiter!
String spellKey = magicItemKey.replace(":", "|");
itemStack = createSpellItem(spellKey, brief);
if (itemStack != null) {
itemStack.setAmount(amount);
if (callback != null) {
callback.updated(itemStack);
}
return itemStack;
}
itemStack = createBrushItem(magicItemKey);
if (itemStack != null) {
itemStack.setAmount(amount);
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error creating item: " + magicItemKey, ex);
}
}
if (callback != null) {
callback.updated(itemStack);
}
return itemStack;
}
@Nullable
@Override
public ItemStack createGenericItem(String key) {
ConfigurationSection template = getWandTemplateConfiguration(key);
if (template == null || !template.contains("icon")) {
return null;
}
MaterialAndData icon = ConfigurationUtils.toMaterialAndData(template.getString("icon"));
ItemStack item = icon.getItemStack(1);
ItemMeta meta = item.getItemMeta();
if (template.contains("name")) {
meta.setDisplayName(template.getString("name"));
} else {
String name = messages.get("wands." + key + ".name");
if (name != null && !name.isEmpty()) {
meta.setDisplayName(name);
}
}
List<String> lore = new ArrayList<>();
if (template.contains("description")) {
lore.add(template.getString("description"));
} else {
String description = messages.get("wands." + key + ".description");
if (description != null && !description.isEmpty()) {
lore.add(description);
}
}
meta.setLore(lore);
item.setItemMeta(meta);
return item;
}
@Override
public com.elmakers.mine.bukkit.api.wand.Wand createUpgrade(String wandKey) {
Wand wand = Wand.createWand(this, wandKey);
if (!wand.isUpgrade()) {
wand.makeUpgrade();
}
return wand;
}
@Nullable
@Override
public ItemStack createSpellItem(String spellKey) {
return Wand.createSpellItem(spellKey, this, null, true);
}
@Nullable
@Override
public ItemStack createSpellItem(String spellKey, boolean brief) {
return Wand.createSpellItem(spellKey, this, null, !brief);
}
@Nullable
@Override
public ItemStack createBrushItem(String brushKey) {
return Wand.createBrushItem(brushKey, this, null, true);
}
@Nullable
@Override
public ItemStack createBrushItem(String materialKey, com.elmakers.mine.bukkit.api.wand.Wand wand, boolean isItem) {
return Wand.createBrushItem(materialKey, this, (Wand) wand, isItem);
}
public boolean isSameItem(ItemStack first, ItemStack second) {
if (first.getType() != second.getType()) return false;
if (first.getDurability() != second.getDurability()) return false;
if (first.hasItemMeta() != second.hasItemMeta()) return false;
if (!first.hasItemMeta()) return true;
return first.getItemMeta().equals(second.getItemMeta());
}
@Override
public boolean itemsAreEqual(ItemStack first, ItemStack second) {
return itemsAreEqual(first, second, false);
}
@Override
public boolean itemsAreEqual(ItemStack first, ItemStack second, boolean ignoreDamage) {
boolean firstIsEmpty = CompatibilityUtils.isEmpty(first);
boolean secondIsEmpty = CompatibilityUtils.isEmpty(second);
if (secondIsEmpty && firstIsEmpty) return true;
if (secondIsEmpty || firstIsEmpty) return false;
if (first.getType() != second.getType()) return false;
if (!ignoreDamage && first.getDurability() != second.getDurability()) return false;
boolean firstIsWand = Wand.isWandOrUpgrade(first);
boolean secondIsWand = Wand.isWandOrUpgrade(second);
if (firstIsWand || secondIsWand) {
if (!firstIsWand || !secondIsWand) return false;
Wand firstWand = getWand(InventoryUtils.getCopy(first));
Wand secondWand = getWand(InventoryUtils.getCopy(second));
String firstTemplate = firstWand.getTemplateKey();
String secondTemplate = secondWand.getTemplateKey();
if (firstTemplate == null || secondTemplate == null) return false;
return firstTemplate.equalsIgnoreCase(secondTemplate);
}
String firstSpellKey = Wand.getSpell(first);
String secondSpellKey = Wand.getSpell(second);
if (firstSpellKey != null || secondSpellKey != null) {
if (firstSpellKey == null || secondSpellKey == null) return false;
return firstSpellKey.equalsIgnoreCase(secondSpellKey);
}
String firstBrushKey = Wand.getBrush(first);
String secondBrushKey = Wand.getBrush(second);
if (firstBrushKey != null || secondBrushKey != null) {
if (firstBrushKey == null || secondBrushKey == null) return false;
return firstBrushKey.equalsIgnoreCase(secondBrushKey);
}
String firstName = first.hasItemMeta() ? first.getItemMeta().getDisplayName() : null;
String secondName = second.hasItemMeta() ? second.getItemMeta().getDisplayName() : null;
if (!Objects.equals(firstName, secondName)) {
return false;
}
MaterialAndData firstData = new MaterialAndData(first);
MaterialAndData secondData = new MaterialAndData(second);
return firstData.equals(secondData);
}
@Override
public Set<String> getWandPathKeys() {
return WandUpgradePath.getPathKeys();
}
@Override
public com.elmakers.mine.bukkit.api.wand.WandUpgradePath getPath(String key) {
return WandUpgradePath.getPath(key);
}
@Nullable
@Override
public ItemStack deserialize(ConfigurationSection root, String key) {
ConfigurationSection itemSection = root.getConfigurationSection(key);
if (itemSection == null) {
return null;
}
// Fix up busted items
if (itemSection.getInt("amount", 0) == 0) {
itemSection.set("amount", 1);
}
ItemStack item = itemSection.getItemStack("item");
if (item == null) {
return null;
}
if (itemSection.contains("wand")) {
item = InventoryUtils.makeReal(item);
Wand.configToItem(itemSection, item);
} else if (itemSection.contains("spell")) {
item = InventoryUtils.makeReal(item);
Object spellNode = CompatibilityUtils.createNode(item, "spell");
CompatibilityUtils.setMeta(spellNode, "key", itemSection.getString("spell"));
if (itemSection.contains("skill")) {
InventoryUtils.setMeta(item, "skill", "true");
}
} else if (itemSection.contains("brush")) {
item = InventoryUtils.makeReal(item);
InventoryUtils.setMeta(item, "brush", itemSection.getString("brush"));
}
return item;
}
@Override
public void serialize(ConfigurationSection root, String key, ItemStack item) {
ConfigurationSection itemSection = root.createSection(key);
itemSection.set("item", item);
if (Wand.isWandOrUpgrade(item)) {
ConfigurationSection stateNode = itemSection.createSection("wand");
Wand.itemToConfig(item, stateNode);
} else if (Wand.isSpell(item)) {
itemSection.set("spell", Wand.getSpell(item));
if (Wand.isSkill(item)) {
itemSection.set("skill", "true");
}
} else if (Wand.isBrush(item)) {
itemSection.set("brush", Wand.getBrush(item));
}
}
@Override
public void disableItemSpawn() {
entityController.setDisableItemSpawn(true);
}
@Override
public void enableItemSpawn() {
entityController.setDisableItemSpawn(false);
}
@Override
public void setForceSpawn(boolean force) {
entityController.setForceSpawn(force);
}
public HeroesManager getHeroes() {
return heroesManager;
}
@Nullable
public ManaController getManaController() {
if (useHeroesMana && heroesManager != null) return heroesManager;
if (useSkillAPIMana && skillAPIManager != null) return skillAPIManager;
return null;
}
public String getDefaultSkillIcon() {
return defaultSkillIcon;
}
public int getSkillInventoryRows() {
return skillInventoryRows;
}
public boolean usePermissionSkills() {
return skillsUsePermissions;
}
public boolean useHeroesSkills() {
return skillsUseHeroes;
}
@Override
public void addFlightExemption(Player player, int duration) {
ncpManager.addFlightExemption(player, duration);
CompatibilityUtils.addFlightExemption(player, duration * 20 / 1000);
}
@Override
public void addFlightExemption(Player player) {
ncpManager.addFlightExemption(player);
}
@Override
public void removeFlightExemption(Player player) {
ncpManager.removeFlightExemption(player);
}
public String getExtraSchematicFilePath() {
return extraSchematicFilePath;
}
@Override
public void warpPlayerToServer(Player player, String server, String warp) {
com.elmakers.mine.bukkit.magic.Mage mage = getMage(player);
mage.setDestinationWarp(warp);
info("Cross-server warping " + player.getName() + " to warp " + warp, 1);
sendPlayerToServer(player, server);
}
@Override
public void sendPlayerToServer(final Player player, final String server) {
MageDataCallback callback = new MageDataCallback() {
@Override
public void run(MageData data) {
Bukkit.getScheduler().runTaskLater(plugin, new ChangeServerTask(plugin, player, server), 1);
}
};
info("Moving " + player.getName() + " to server " + server, 1);
Mage mage = getRegisteredMage(player);
if (mage != null) {
playerQuit(mage, callback);
} else {
callback.run(null);
}
}
@Override
public boolean isDisguised(Entity entity) {
return libsDisguiseEnabled && libsDisguiseManager != null && entity != null && libsDisguiseManager.isDisguised(entity);
}
@Override
public boolean hasDisguises() {
return libsDisguiseEnabled && libsDisguiseManager != null;
}
@Override
public boolean disguise(Entity entity, ConfigurationSection configuration) {
if (!libsDisguiseEnabled || libsDisguiseManager == null || entity == null) {
return false;
}
return libsDisguiseManager.disguise(entity, configuration);
}
@Override
public boolean isPathUpgradingEnabled() {
return autoPathUpgradesEnabled;
}
@Override
public boolean isSpellUpgradingEnabled() {
return autoSpellUpgradesEnabled;
}
@Override
public boolean isSpellProgressionEnabled() {
return spellProgressionEnabled;
}
public boolean isLoaded() {
return loaded && !shuttingDown;
}
public boolean isDataLoaded() {
return loaded && dataLoaded && !shuttingDown;
}
public boolean areLocksProtected() {
return protectLocked;
}
public boolean isContainer(Block block) {
return block != null && containerMaterials.testBlock(block);
}
/**
* Checks if an item is a melee material, as specified by the {@code melee}
* list in {@code materials.yml}. This is primarily used to detect if left
* clicking an entity should indicate melee damage or a spell being cast.
*
* @param item The item to check.
* @return Whether or not this is a melee weapon.
*/
public boolean isMeleeWeapon(ItemStack item) {
return item != null && meleeMaterials.testItem(item);
}
public boolean isWearable(ItemStack item) {
return item != null && wearableMaterials.testItem(item);
}
public boolean isInteractible(Block block) {
return block != null && interactibleMaterials.testBlock(block);
}
public boolean isSpellDroppingEnabled() {
return spellDroppingEnabled;
}
@Override
public boolean isSPEnabled() {
return spEnabled;
}
@Override
public boolean isSPEarnEnabled() {
return spEarnEnabled;
}
@Override
public int getSPMaximum() {
return (int) getCurrency("sp").getMaxValue();
}
@Override
public boolean isVaultCurrencyEnabled() {
return VaultController.hasEconomy();
}
@Override
public void depositVaultCurrency(OfflinePlayer player, double amount) {
VaultController.getInstance().depositPlayer(player, amount);
}
@Override
public void deleteMage(final String id) {
final Mage mage = getRegisteredMage(id);
if (mage != null) {
playerQuit(mage, new MageDataCallback() {
@Override
public void run(MageData data) {
info("Deleted mage id " + id);
mageDataStore.delete(id);
// If this was a player and that player is online, reload them so they function normally.
Player player = mage.getPlayer();
if (player != null && player.isOnline()) {
getMage(player);
}
}
});
} else {
info("Deleted offline mage id " + id);
mageDataStore.delete(id);
}
}
public long getPhysicsTimeout() {
if (physicsHandler != null) {
return physicsHandler.getTimeout();
}
return 0;
}
@Nullable
@Override
public String getSpell(ItemStack item) {
return Wand.getSpell(item);
}
@Nullable
@Override
public String getSpellArgs(ItemStack item) {
return Wand.getSpellArgs(item);
}
@Override
public Set<String> getNPCKeys() {
Set<String> keys = new HashSet<>();
for (EntityData mob : mobs.getMobs()) {
if (mob.isNPC() && !mob.isHidden()) {
keys.add(mob.getKey());
}
}
return keys;
}
@Override
public Set<String> getMobKeys(boolean showHidden) {
if (showHidden) {
return mobs.getKeys();
}
return new HashSet<>(mobs.getMobs().stream()
.filter(mob -> !mob.isHidden())
.map(EntityData::getKey)
.collect(Collectors.toList()));
}
@Override
public Set<String> getMobKeys() {
return getMobKeys(false);
}
@Nullable
@Override
public Entity spawnMob(String key, Location location) {
EntityData mobType = mobs.get(key);
if (mobType != null) {
return mobType.spawn(location);
}
EntityType entityType = com.elmakers.mine.bukkit.entity.EntityData.parseEntityType(key);
if (entityType == null) {
return null;
}
return location.getWorld().spawnEntity(location, entityType);
}
@Nullable
@Override
public EntityData getMob(Entity entity) {
return mobs.getEntityData(entity);
}
@Override
@Nullable
public com.elmakers.mine.bukkit.entity.EntityData getMob(String key) {
if (key == null) return null;
// This null check is hopefully temporary, but deals with actions that look up a mob during interrogation.
com.elmakers.mine.bukkit.entity.EntityData mob = mobs == null ? null : mobs.get(key);
if (mob == null && mobs != null) {
EntityType entityType = com.elmakers.mine.bukkit.entity.EntityData.parseEntityType(key);
if (entityType != null) {
mob = mobs.getDefaultMob(entityType);
}
}
return mob;
}
@Override
@Nullable
public EntityData getMob(ConfigurationSection parameters) {
String mobType = parameters.getString("type");
com.elmakers.mine.bukkit.entity.EntityData mob = null;
if (mobType != null && !mobType.isEmpty()) {
mob = getMob(mobType);
}
if (mob != null && parameters != null && !parameters.getKeys(false).isEmpty()) {
mob = mob.clone();
ConfigurationSection effectiveParameters = ConfigurationUtils.cloneConfiguration(mob.getConfiguration());
// Have to preserve the mob type config, it can't be overridden
String originalType = effectiveParameters.getString("type", mobType);
effectiveParameters = ConfigurationUtils.addConfigurations(effectiveParameters, parameters);
effectiveParameters.set("type", originalType);
mob.load(effectiveParameters);
} else if (mob == null) {
mob = new com.elmakers.mine.bukkit.entity.EntityData(this, parameters);
}
return mob;
}
@Override
@Nullable
public EntityData getMobByName(String name) {
return mobs.getByName(name);
}
@Override
public EntityData loadMob(ConfigurationSection configuration) {
return new com.elmakers.mine.bukkit.entity.EntityData(this, configuration);
}
@Override
@Nullable
public Entity replaceMob(Entity targetEntity, EntityData replaceType, boolean force, CreatureSpawnEvent.SpawnReason reason) {
EntityData targetData = getMob(targetEntity);
EntityData newData = replaceType;
if (targetData != null) {
newData = targetData.clone();
ConfigurationSection effectiveParameters = ConfigurationUtils.cloneConfiguration(newData.getConfiguration());
ConfigurationSection newParameters = replaceType.getConfiguration();
effectiveParameters = ConfigurationUtils.addConfigurations(effectiveParameters, newParameters);
// Handle the replacement type being bare
effectiveParameters.set("type", replaceType.getType().name());
newData.load(effectiveParameters);
}
if (force) {
setForceSpawn(true);
}
Entity spawnedEntity = null;
try {
spawnedEntity = newData.spawn(targetEntity.getLocation(), reason);
} catch (Exception ex) {
ex.printStackTrace();
}
if (force) {
setForceSpawn(false);
}
if (spawnedEntity != null) {
targetEntity.remove();
}
return spawnedEntity;
}
@Override
public Set<String> getItemKeys() {
return items.getKeys();
}
@Override
@Nullable
public ItemData getItem(String key) {
return items.get(key);
}
@Override
@Nullable
public ItemData getItem(ItemStack match) {
return items.get(match);
}
@Nullable
@Override
public ItemData getOrCreateItem(String key) {
if (key == null || key.isEmpty()) {
return null;
}
return items.getOrCreate(key);
}
@Nullable
@Override
@Deprecated
public ItemData getOrCreateItemOrWand(String key) {
return getOrCreateItem(key);
}
@Nullable
@Override
@Deprecated
public ItemData getOrCreateMagicItem(String key) {
return getOrCreateItem(key);
}
public void updateOnEquip(ItemStack stack) {
items.updateOnEquip(stack);
}
@Override
public ItemData createItemData(ItemStack itemStack) {
return new com.elmakers.mine.bukkit.item.ItemData(itemStack, this);
}
@Nullable
public String getLockKey(ItemStack itemStack) {
if (itemStack == null) return null;
ItemData data = getItem(itemStack);
if (data == null) {
data = getItem(itemStack.getType().name().toLowerCase());
}
if (data != null && data.isLocked()) {
return data.getKey();
}
return null;
}
@Override
public void unloadItemTemplate(String key) {
items.remove(key);
}
@Override
public void loadItemTemplate(String key, ConfigurationSection configuration) {
items.loadItem(key, configuration);
}
@Nullable
@Override
public Double getWorth(ItemStack item) {
return getWorth(item, "currency");
}
@Nullable
@Override
public Double getWorth(ItemStack item, String inCurrencyKey) {
Currency toCurrency = getCurrency(inCurrencyKey);
if (toCurrency == null || toCurrency.getWorth() == 0) {
return null;
}
String spellKey = Wand.getSpell(item);
if (spellKey != null) {
Currency spellPointCurrency = getCurrency("sp");
SpellTemplate spell = getSpellTemplate(spellKey);
if (spell != null) {
double spWorth = spellPointCurrency == null ? 1 : spellPointCurrency.getWorth();
return spell.getWorth() * spWorth / toCurrency.getWorth();
}
}
int amount = item.getAmount();
item.setAmount(1);
ItemData configuredItem = items.get(item);
item.setAmount(amount);
if (configuredItem == null) {
Wand wand = getIfWand(item);
if (wand == null) {
InventoryUtils.CurrencyAmount currencyAmount = InventoryUtils.getCurrency(item);
Currency currency = currencyAmount == null ? null : getCurrency(currencyAmount.type);
if (currency != null) {
return currency.getWorth() * currencyAmount.amount * item.getAmount() / toCurrency.getWorth();
}
return null;
}
return (double) wand.getWorth() / toCurrency.getWorth();
}
return configuredItem.getWorth() * amount / toCurrency.getWorth();
}
@Nullable
@Override
public Double getEarns(ItemStack item) {
return getEarns(item, "currency");
}
@Nullable
@Override
public Double getEarns(ItemStack item, String inCurrencyKey) {
Currency toCurrency = getCurrency(inCurrencyKey);
if (toCurrency == null || toCurrency.getWorth() == 0) {
return null;
}
int amount = item.getAmount();
item.setAmount(1);
ItemData configuredItem = items.get(item);
item.setAmount(amount);
if (configuredItem == null) {
return null;
}
return configuredItem.getEarns() * amount / toCurrency.getWorth();
}
public boolean isInventoryBackupEnabled() {
return backupInventories;
}
@Nullable
@Override
public String getBlockSkin(Material blockType) {
return blockSkins.get(blockType);
}
@Override
@Nonnull
public Random getRandom() {
return random;
}
@Override
public boolean sendResourcePackToAllPlayers(CommandSender sender) {
return resourcePacks.sendResourcePackToAllPlayers(sender);
}
@Override
public boolean promptResourcePack(final Player player) {
return resourcePacks.promptResourcePack(player);
}
@Override
public boolean promptNoResourcePack(final Player player) {
return resourcePacks.promptNoResourcePack(player);
}
@Override
public boolean sendResourcePack(final Player player) {
return resourcePacks.sendResourcePack(player);
}
@Override
public void checkResourcePack(CommandSender sender) {
resourcePacks.clearChecked();
checkResourcePack(sender, false, true);
}
public boolean checkResourcePack(final CommandSender sender, final boolean quiet) {
return checkResourcePack(sender, quiet, false);
}
public boolean checkResourcePack(final CommandSender sender, final boolean quiet, final boolean force) {
return resourcePacks.checkResourcePack(sender, quiet, force, false);
}
@Override
public boolean isResourcePackEnabled() {
return resourcePacks.isResourcePackEnabled();
}
@Nullable
@Override
public Material getMobEgg(EntityType mobType) {
return mobEggs.get(mobType);
}
@Nullable
@Override
public String getMobSkin(EntityType mobType) {
return mobSkins.get(mobType);
}
@Nullable
@Override
public String getPlayerSkin(Player player) {
return libsDisguiseManager == null ? null : libsDisguiseManager.getSkin(player);
}
@Override
@Nonnull
public ItemStack getURLSkull(String url) {
try {
ItemStack stack = getURLSkull(new URL(url), InventoryUtils.SKULL_UUID);
return stack == null ? new ItemStack(Material.AIR) : stack;
} catch (MalformedURLException e) {
Bukkit.getLogger().log(Level.WARNING, "Malformed URL: " + url, e);
}
return new ItemStack(Material.AIR);
}
@Nullable
private ItemStack getURLSkull(URL url, UUID id) {
MaterialAndData skullType = skullItems.get(EntityType.PLAYER);
if (skullType == null) {
return new ItemStack(Material.AIR);
}
ItemStack skull = skullType.getItemStack(1);
return InventoryUtils.setSkullURL(skull, url, id);
}
@Override
public void setSkullOwner(Skull skull, String ownerName) {
DeprecatedUtils.setOwner(skull, ownerName);
}
@Override
public void setSkullOwner(Skull skull, UUID uuid) {
DeprecatedUtils.setOwner(skull, uuid);
}
@Override
@Nonnull
@Deprecated
public ItemStack getSkull(String ownerName, String itemName) {
return getSkull(ownerName, itemName, null);
}
@Override
@Nonnull
public ItemStack getSkull(String ownerName, String itemName, final ItemUpdatedCallback callback) {
MaterialAndData skullType = skullItems.get(EntityType.PLAYER);
if (skullType == null) {
ItemStack air = new ItemStack(Material.AIR);
if (callback != null) {
callback.updated(air);
}
return air;
}
ItemStack skull = skullType.getItemStack(1);
ItemMeta meta = skull.getItemMeta();
if (itemName != null) {
meta.setDisplayName(itemName);
}
skull.setItemMeta(meta);
SkullLoadedCallback skullCallback = null;
if (callback != null) {
skullCallback = new SkullLoadedCallback() {
@Override
public void updated(ItemStack itemStack) {
callback.updated(itemStack);
}
};
}
DeprecatedUtils.setSkullOwner(skull, ownerName, skullCallback);
return skull;
}
@Override
@Nonnull
public ItemStack getSkull(UUID uuid, String itemName, ItemUpdatedCallback callback) {
MaterialAndData skullType = skullItems.get(EntityType.PLAYER);
if (skullType == null) {
return new ItemStack(Material.AIR);
}
ItemStack skull = skullType.getItemStack(1);
ItemMeta meta = skull.getItemMeta();
if (itemName != null) {
meta.setDisplayName(itemName);
}
skull.setItemMeta(meta);
SkullLoadedCallback skullCallback = null;
if (callback != null) {
skullCallback = new SkullLoadedCallback() {
@Override
public void updated(ItemStack itemStack) {
callback.updated(itemStack);
}
};
}
DeprecatedUtils.setSkullOwner(skull, uuid, skullCallback);
return skull;
}
@Override
@Nonnull
public ItemStack getSkull(Player player, String itemName) {
MaterialAndData skullType = skullItems.get(EntityType.PLAYER);
if (skullType == null) {
return new ItemStack(Material.AIR);
}
ItemStack skull = skullType.getItemStack(1);
ItemMeta meta = skull.getItemMeta();
if (itemName != null) {
meta.setDisplayName(itemName);
}
skull.setItemMeta(meta);
DeprecatedUtils.setSkullOwner(skull, player.getName(), null);
return skull;
}
@Override
@Nonnull
@Deprecated
public ItemStack getSkull(Entity entity, String itemName) {
if (entity instanceof Player) {
return getSkull((Player) entity, itemName);
}
return getSkull(entity, itemName, null);
}
@Override
@Nonnull
public ItemStack getSkull(Entity entity, String itemName, ItemUpdatedCallback callback) {
String ownerName = null;
MaterialAndData skullType = skullItems.get(entity.getType());
if (skullType == null) {
ownerName = getMobSkin(entity.getType());
skullType = skullItems.get(EntityType.PLAYER);
if (skullType == null || ownerName == null) {
ItemStack air = new ItemStack(Material.AIR);
if (callback != null) {
callback.updated(air);
}
return air;
}
}
if (entity instanceof Player) {
ownerName = entity.getName();
}
ItemStack skull = skullType.getItemStack(1);
ItemMeta meta = skull.getItemMeta();
if (itemName != null) {
meta.setDisplayName(itemName);
}
skull.setItemMeta(meta);
if (ownerName != null) {
SkullLoadedCallback skullCallback = null;
if (callback != null) {
skullCallback = new SkullLoadedCallback() {
@Override
public void updated(ItemStack itemStack) {
callback.updated(itemStack);
}
};
}
if (ownerName.startsWith("http")) {
skull = InventoryUtils.setSkullURL(skull, ownerName);
if (callback != null) {
callback.updated(skull);
}
} else {
DeprecatedUtils.setSkullOwner(skull, ownerName, skullCallback);
}
} else if (callback != null) {
callback.updated(skull);
}
return skull;
}
@Nonnull
@Override
public ItemStack getMap(int mapId) {
short durability = NMSUtils.isCurrentVersion() ? 0 : (short) mapId;
ItemStack mapItem = new ItemStack(DefaultMaterials.getFilledMap(), 1, durability);
if (NMSUtils.isCurrentVersion()) {
mapItem = CompatibilityUtils.makeReal(mapItem);
InventoryUtils.setMetaInt(mapItem, "map", mapId);
}
return mapItem;
}
@Override
public void managePlayerData(boolean external, boolean backupInventories) {
savePlayerData = !external;
externalPlayerData = external;
this.backupInventories = backupInventories;
}
public void initializeWorldGuardFlags() {
worldGuardManager.initializeFlags(plugin);
}
@Override
public String getDefaultWandTemplate() {
return Wand.DEFAULT_WAND_TEMPLATE;
}
@Nullable
@Override
public Object getWandProperty(ItemStack item, String key) {
Preconditions.checkNotNull(key, "key");
if (InventoryUtils.isEmpty(item)) return null;
Object wandNode = InventoryUtils.getNode(item, Wand.WAND_KEY);
if (wandNode == null) return null;
Object value = InventoryUtils.getMetaObject(wandNode, key);
if (value == null) {
WandTemplate template = getWandTemplate(InventoryUtils.getMetaString(wandNode, "template"));
if (template != null) {
value = template.getProperty(key);
}
}
return value;
}
@Override
public <T> T getWandProperty(ItemStack item, String key, T defaultValue) {
Preconditions.checkNotNull(key, "key");
Preconditions.checkNotNull(defaultValue, "defaultValue");
if (InventoryUtils.isEmpty(item)) {
return defaultValue;
}
Object wandNode = InventoryUtils.getNode(item, Wand.WAND_KEY);
if (wandNode == null) {
return defaultValue;
}
// Obtain the type via the default value.
// (This is unchecked because of type erasure)
@SuppressWarnings("unchecked")
Class<? extends T> clazz = (Class<? extends T>) defaultValue.getClass();
// Value directly stored on wand
Object value = InventoryUtils.getMetaObject(wandNode, key);
if (value != null) {
if (clazz.isInstance(value)) {
return clazz.cast(value);
}
return defaultValue;
}
String tplName = InventoryUtils.getMetaString(wandNode, "template");
WandTemplate template = getWandTemplate(tplName);
if (template != null) {
return template.getProperty(key, defaultValue);
}
return defaultValue;
}
public boolean useHeroesMana() {
return useHeroesMana;
}
public boolean useSkillAPIMana() {
return useSkillAPIMana;
}
public @Nonnull
MageIdentifier getMageIdentifier() {
return mageIdentifier;
}
public void setMageIdentifier(@Nonnull MageIdentifier mageIdentifier) {
Preconditions.checkNotNull(mageIdentifier, "mageIdentifier");
this.mageIdentifier = mageIdentifier;
}
@Override
public String getHeroesSkillPrefix() {
return heroesSkillPrefix;
}
public List<AttributeProvider> getAttributeProviders() {
return attributeProviders;
}
@Override
@Nullable
public MagicAttribute getAttribute(String attributeKey) {
return attributes.get(attributeKey);
}
@Override
public boolean createLight(Location location, int lightLevel, boolean async) {
if (lightAPIManager == null) return false;
long blockId = BlockData.getBlockId(location);
String chunkId = getChunkKey(location);
Integer chunkRefs = lightChunks.get(chunkId);
if (chunkRefs == null) {
lightChunks.put(chunkId, 1);
} else {
lightChunks.put(chunkId, chunkRefs + 1);
}
Integer refCount = lightBlocks.get(blockId);
if (refCount != null) {
lightBlocks.put(blockId, refCount + 1);
return false;
}
lightBlocks.put(blockId, 1);
return lightAPIManager.createLight(location, lightLevel, async);
}
@Override
public boolean deleteLight(Location location, boolean async) {
if (lightAPIManager == null) return false;
long blockId = BlockData.getBlockId(location);
Integer refCount = lightBlocks.get(blockId);
String chunkId = getChunkKey(location);
Integer chunkRefs = lightChunks.get(chunkId);
if (chunkRefs != null) {
if (chunkRefs <= 1) {
lightChunks.remove(chunkId);
} else {
lightChunks.put(chunkId, chunkRefs - 1);
}
}
if (refCount != null) {
if (refCount <= 1) {
lightBlocks.remove(blockId);
} else {
lightBlocks.put(blockId, refCount - 1);
return false;
}
}
return lightAPIManager.deleteLight(location, async);
}
@Override
public boolean updateLight(Location location) {
return updateLight(location, true);
}
@Override
public boolean updateLight(Location location, boolean force) {
if (lightAPIManager == null) return false;
if (!force) {
String chunkId = getChunkKey(location);
Integer chunkRefs = lightChunks.get(chunkId);
if (chunkRefs != null) return false;
}
return lightAPIManager.updateChunks(location);
}
@Override
public int getLightCount() {
return lightBlocks.size();
}
@Override
public boolean isLightingAvailable() {
return lightAPIManager != null;
}
@Override
public @Nullable
String checkRequirements(@Nonnull MageContext context, @Nullable Collection<Requirement> requirements) {
if (requirements == null) return null;
for (Requirement requirement : requirements) {
String type = requirement.getType();
RequirementsProcessor processor = requirementProcessors.get(type);
if (processor != null) {
if (!processor.checkRequirement(context, requirement)) {
String message = processor.getRequirementDescription(context, requirement);
if (message == null || message.isEmpty()) {
message = messages.get("requirements.unknown");
}
return message;
}
}
}
return null;
}
@Override
public @Nonnull
Collection<String> getLoadedExamples() {
List<String> examples = new ArrayList<>();
if (exampleDefaults != null && !exampleDefaults.isEmpty()) examples.add(exampleDefaults);
if (addExamples != null) examples.addAll(addExamples);
return examples;
}
@Nullable
@Override
public String getExample() {
return exampleDefaults != null && exampleDefaults.isEmpty() ? null : exampleDefaults;
}
@Nonnull
@Override
public Collection<String> getExamples() {
List<String> examples = new ArrayList<>();
try {
CodeSource src = MagicController.class.getProtectionDomain().getCodeSource();
if (src != null) {
URL jar = src.getLocation();
try (InputStream is = jar.openStream();
ZipInputStream zip = new ZipInputStream(is)) {
while (true) {
ZipEntry e = zip.getNextEntry();
if (e == null)
break;
String name = e.getName();
if (!name.equals("examples/")
&& !name.equals("examples/localizations/")
&& name.startsWith("examples/")
&& name.endsWith("/") && !name.contains(".")) {
examples.add(name.replace("examples/", "").replace("/", ""));
}
}
}
}
} catch (IOException ex) {
plugin.getLogger().log(Level.WARNING, "Error scanning example files", ex);
}
examples.addAll(getDownloadedExternalExamples());
return examples;
}
@Nonnull
@Override
public Collection<String> getLocalizations() {
List<String> examples = new ArrayList<>();
try {
CodeSource src = MagicController.class.getProtectionDomain().getCodeSource();
if (src != null) {
URL jar = src.getLocation();
try (InputStream is = jar.openStream();
ZipInputStream zip = new ZipInputStream(is)) {
while (true) {
ZipEntry e = zip.getNextEntry();
if (e == null)
break;
String name = e.getName();
if (!name.equals("examples/")
&& !name.equals("examples/localizations/")
&& name.startsWith("examples/localizations/messages.")
&& name.endsWith(".yml")) {
examples.add(name.replace("examples/localizations/messages.", "").replace(".yml", ""));
}
}
}
}
} catch (IOException ex) {
plugin.getLogger().log(Level.WARNING, "Error scanning example files", ex);
}
return examples;
}
@Nonnull
@Override
public Collection<String> getExternalExamples() {
Set<String> examples = getDownloadedExternalExamples();
examples.addAll(builtinExternalExamples.keySet());
return examples;
}
public Set<String> getDownloadedExternalExamples() {
Set<String> examples = new HashSet<>();
File examplesFolder = new File(getPlugin().getDataFolder(), "examples");
if (examplesFolder.exists()) {
for (File file : examplesFolder.listFiles()) {
if (!file.isDirectory() || file.getName().contains(".")) continue;
examples.add(file.getName());
}
}
return examples;
}
public void updateExternalExamples(CommandSender sender) {
Collection<String> examples = getDownloadedExternalExamples();
if (examples.isEmpty()) {
loadConfiguration(sender);
return;
}
Set<String> loadedExamples = new HashSet<>(getLoadedExamples());
sender.sendMessage(getMessages().get("commands.mconfig.example.fetch.wait_all").replace("$count", Integer.toString(examples.size())));
UpdateAllExamplesCallback callback = new UpdateAllExamplesCallback(sender, this);
for (String exampleKey : examples) {
if (!loadedExamples.contains(exampleKey)) {
sender.sendMessage(getMessages().get("commands.mconfig.example.fetch.skip").replace("$example", exampleKey));
continue;
}
String url = getExternalExampleURL(exampleKey);
if (url == null || url.isEmpty()) {
continue;
}
callback.loading();
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new FetchExampleRunnable(this, sender, exampleKey, url, callback, true));
}
callback.check();
}
@Nullable
@Override
public String getExternalExampleURL(String exampleKey) {
String url = null;
File exampleFolder = new File(getPlugin().getDataFolder(), "examples");
exampleFolder = new File(exampleFolder, exampleKey);
File urlFile = new File(exampleFolder, "url.txt");
if (urlFile.exists()) {
try {
url = new String(Files.readAllBytes(Paths.get(urlFile.getAbsolutePath())), StandardCharsets.UTF_8);
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error loading example url from file: " + urlFile.getAbsolutePath(), ex);
}
}
if (url == null) {
url = builtinExternalExamples.get(exampleKey);
}
return url;
}
@Override
public double getBlockDurability(@Nonnull Block block) {
double durability = CompatibilityUtils.getDurability(block.getType());
if (citadelManager != null) {
Integer reinforcement = citadelManager.getDurability(block.getLocation());
if (reinforcement != null) {
durability += reinforcement;
}
}
return durability;
}
@Override
@Nonnull
public String getSkillsSpell() {
return skillsSpell;
}
@Override
@Nonnull
public Collection<EffectPlayer> getEffects(@Nonnull String effectKey) {
Collection<EffectPlayer> effectList = effects.get(effectKey);
if (effectList == null) {
effectList = new ArrayList<>();
}
return effectList;
}
@Override
public void playEffects(@Nonnull String effectKey, @Nonnull Location sourceLocation, @Nonnull Location targetLocation) {
Collection<EffectPlayer> effectPlayers = effects.get(effectKey);
if (effectPlayers == null) return;
for (EffectPlayer player : effectPlayers) {
player.start(sourceLocation, targetLocation);
}
}
@Override
public void playEffects(@Nonnull String effectKey, @Nonnull EffectContext context) {
Collection<EffectPlayer> effectPlayers = effects.get(effectKey);
if (effectPlayers == null) return;
for (EffectPlayer player : effectPlayers) {
player.start(context);
}
}
@Override
@Nonnull
public Collection<String> getEffectKeys() {
return effects.keySet();
}
@Override
public Collection<String> getRecipeKeys() {
return crafting.getRecipeKeys();
}
@Override
public Collection<String> getAutoDiscoverRecipeKeys() {
return crafting.getAutoDiscoverRecipeKeys();
}
public void checkVanished(Player player) {
for (Mage mage : mages.values()) {
if (mage.isVanished()) {
DeprecatedUtils.hidePlayer(plugin, player, mage.getPlayer());
}
}
}
@Override
public void logBlockChange(@Nonnull Mage mage, @Nonnull BlockState priorState, @Nonnull BlockState newState) {
if (logBlockManager != null) {
Entity entity = mage.getEntity();
if (entity != null) {
logBlockManager.logBlockChange(entity, priorState, newState);
}
}
}
@Override
public boolean isFileLockingEnabled() {
return isFileLockingEnabled;
}
/**
* @return The supplier set that is used.
*/
public NPCSupplierSet getNPCSuppliers() {
return npcSuppliers;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.npc.MagicNPC> getNPCs() {
return new ArrayList<>(npcs.values());
}
@Override
public void removeNPC(com.elmakers.mine.bukkit.api.npc.MagicNPC npc) {
unregisterNPC(npc);
npc.remove();
npcs.remove(npc.getId());
npcsByEntity.remove(npc.getEntityId());
}
public void unregisterNPC(com.elmakers.mine.bukkit.api.npc.MagicNPC npc) {
String chunkId = getChunkKey(npc.getLocation());
if (chunkId == null) return;
List<MagicNPC> chunkNPCs = npcsByChunk.get(chunkId);
if (chunkNPCs == null) {
return;
}
Iterator<MagicNPC> it = chunkNPCs.iterator();
while (it.hasNext()) {
if (it.next().getId().equals(npc.getId())) {
it.remove();
break;
}
}
}
@Override
@Nullable
public MagicNPC addNPC(com.elmakers.mine.bukkit.api.magic.Mage creator, String name) {
EntityData template = mobs.get(name);
MagicNPC npc;
if (template != null && template instanceof com.elmakers.mine.bukkit.entity.EntityData) {
npc = new MagicNPC(this, creator, creator.getLocation(), (com.elmakers.mine.bukkit.entity.EntityData) template);
} else {
npc = new MagicNPC(this, creator, creator.getLocation(), name);
}
if (!registerNPC(npc)) {
return null;
}
return npc;
}
public boolean registerNPC(MagicNPC npc) {
Location location = npc.getLocation();
String chunkId = getChunkKey(location);
if (chunkId == null) {
return false;
}
List<MagicNPC> chunkNPCs = npcsByChunk.get(chunkId);
if (chunkNPCs == null) {
chunkNPCs = new ArrayList<>();
npcsByChunk.put(chunkId, chunkNPCs);
}
chunkNPCs.add(npc);
npcs.put(npc.getId(), npc);
activateNPC(npc);
return true;
}
@Override
@Nullable
public MagicNPC getNPC(@Nullable Entity entity) {
return npcsByEntity.get(entity.getUniqueId());
}
@Override
@Nullable
public MagicNPC getNPC(UUID id) {
return npcs.get(id);
}
public void restoreNPCs(final Chunk chunk) {
String chunkKey = getChunkKey(chunk);
List<MagicNPC> chunkData = npcsByChunk.get(chunkKey);
if (chunkData != null) {
for (MagicNPC npc : chunkData) {
npc.restore();
activateNPC(npc);
}
}
}
public void activateNPC(MagicNPC npc) {
npcsByEntity.put(npc.getEntityId(), npc);
}
@Override
@Nullable
public String getPlaceholder(Player player, String namespace, String placeholder) {
return placeholderAPIManager == null ? null : placeholderAPIManager.getPlaceholder(player, namespace, placeholder);
}
@Override
@Nonnull
public String setPlaceholders(Player player, String message) {
return placeholderAPIManager == null ? message : placeholderAPIManager.setPlaceholders(player, message);
}
@Override
public void registerMob(@Nonnull Entity entity, @Nonnull EntityData entityData) {
mobs.register(entity, (com.elmakers.mine.bukkit.entity.EntityData) entityData);
}
public CitizensController getCitizensController() {
return citizens;
}
@Override
public void lockChunk(Chunk chunk) {
Integer locked = lockedChunks.get(chunk);
if (locked == null) {
lockedChunks.put(chunk, 1);
CompatibilityUtils.lockChunk(chunk, plugin);
} else {
lockedChunks.put(chunk, locked + 1);
}
}
@Override
public void unlockChunk(Chunk chunk) {
Integer locked = lockedChunks.get(chunk);
if (locked == null || locked <= 1) {
lockedChunks.remove(chunk);
CompatibilityUtils.unlockChunk(chunk, plugin);
} else {
lockedChunks.put(chunk, locked - 1);
}
}
@Override
@Nonnull
public Collection<Chunk> getLockedChunks() {
return lockedChunks.keySet();
}
@Override
@Nullable
public String getResourcePackURL() {
return resourcePacks.getDefaultResourcePackURL();
}
@Override
@Nullable
public String getResourcePackURL(CommandSender sender) {
return resourcePacks.getResourcePackURL(sender);
}
@Override
public boolean isUrlIconsEnabled() {
return urlIconsEnabled;
}
@Override
public boolean isLegacyIconsEnabled() {
return legacyIconsEnabled;
}
public boolean resourcePackUsesSkulls(String pack) {
Boolean packOverride = resourcePacks.resourcePackUsesSkulls(pack);
return packOverride == null ? urlIconsEnabled : packOverride;
}
@Override
public Collection<String> getAlternateResourcePacks() {
return resourcePacks.getAlternateResourcePacks();
}
@Override
public boolean isResourcePackEnabledByDefault() {
return resourcePacks.isResourcePackEnabledByDefault();
}
@Override
public boolean showConsoleCastFeedback() {
return castConsoleFeedback;
}
public String getEditorURL() {
return editorURL;
}
public void setReloadingMage(Mage mage) {
this.reloadingMage = mage;
}
public boolean useAnimationEvents(Player player) {
if (swingType == SwingType.ANIMATE) return true;
if (swingType == SwingType.INTERACT) return false;
return player.getGameMode() == GameMode.ADVENTURE;
}
@Override
@Nullable
public List<DeathLocation> getDeathLocations(Player player) {
List<DeathLocation> locations = null;
if (deadSoulsController != null) {
locations = new ArrayList<>();
deadSoulsController.getSoulLocations(player, locations);
}
return locations;
}
public boolean isDespawnMagicMobs() {
return despawnMagicMobs;
}
public void checkLogs(CommandSender sender) {
logger.notify(messages, sender);
}
public MagicWorld getMagicWorld(String name) {
return worldController.getWorld(name);
}
public WorldController getWorlds() {
return worldController;
}
@Override
public int getMaxHeight(World world) {
MagicWorld magicWorld = getMagicWorld(world.getName());
int maxHeight = CompatibilityUtils.getMaxHeight(world);
if (magicWorld != null) {
maxHeight = magicWorld.getMaxHeight(maxHeight);
}
return maxHeight;
}
@Override
public int getMinHeight(World world) {
MagicWorld magicWorld = getMagicWorld(world.getName());
int minHeight = CompatibilityUtils.getMinHeight(world);
if (magicWorld != null) {
minHeight = magicWorld.getMinHeight(minHeight);
}
return minHeight;
}
public boolean isDisableSpawnReplacement() {
return disableSpawnReplacement > 0;
}
@Override
public void setDisableSpawnReplacement(boolean disable) {
if (disable) {
disableSpawnReplacement++;
} else {
disableSpawnReplacement--;
}
}
@Override
@Nullable
public MagicWarp getMagicWarp(String warpKey) {
return warpController.getMagicWarp(warpKey);
}
@Override
@Nonnull
public Collection<? extends MagicWarp> getMagicWarps() {
return warpController.getMagicWarps();
}
public void finalizeIntegration() {
final PluginManager pluginManager = plugin.getServer().getPluginManager();
blockController.finalizeIntegration();
// Check for SkillAPI
Plugin skillAPIPlugin = pluginManager.getPlugin("SkillAPI");
if (skillAPIPlugin != null && skillAPIEnabled && skillAPIPlugin.isEnabled()) {
skillAPIManager = new SkillAPIManager(this, skillAPIPlugin);
if (skillAPIManager.initialize()) {
getLogger().info("SkillAPI found, attributes can be used in spell parameters. Classes and skills can be used in requirements.");
if (useSkillAPIAllies) {
getLogger().info("SKillAPI allies will be respected in friendly fire checks");
}
if (useSkillAPIMana) {
getLogger().info("SkillAPI mana will be used by spells and wands");
}
} else {
skillAPIManager = null;
getLogger().warning("SkillAPI integration failed");
}
} else if (!skillAPIEnabled) {
skillAPIManager = null;
getLogger().info("SkillAPI integration disabled");
}
// Check for BattleArenas
Plugin battleArenaPlugin = pluginManager.getPlugin("BattleArena");
if (battleArenaPlugin != null) {
if (useBattleArenaTeams) {
try {
battleArenaManager = new BattleArenaManager();
} catch (Throwable ex) {
getLogger().log(Level.SEVERE, "Error integrating with BattleArena", ex);
}
getLogger().info("BattleArena found, teams will be respected in friendly fire checks");
} else {
battleArenaManager = null;
getLogger().info("BattleArena integration disabled");
}
}
// Check for WildStacker
if (pluginManager.isPluginEnabled("WildStacker")) {
if (useWildStacker) {
getLogger().info("Wild Stacker integration enabled");
pluginManager.registerEvents(new WildStackerListener(), plugin);
} else {
getLogger().info("Wild Stacker found, but integration disabled");
}
}
// Try to link to Heroes:
try {
Plugin heroesPlugin = pluginManager.getPlugin("Heroes");
if (heroesPlugin != null) {
heroesManager = new HeroesManager(plugin, heroesPlugin);
} else {
heroesManager = null;
}
} catch (Throwable ex) {
getLogger().warning(ex.getMessage());
}
// Vault integration
if (!vaultEnabled) {
getLogger().info("Vault integration disabled");
} else {
Plugin vaultPlugin = pluginManager.getPlugin("Vault");
if (vaultPlugin == null || !vaultPlugin.isEnabled()) {
getLogger().info("Vault not found, 'currency' cost types unavailable");
} else {
if (!VaultController.initialize(plugin, vaultPlugin)) {
getLogger().warning("Vault integration failed");
}
}
}
// Check for Minigames
Plugin minigamesPlugin = pluginManager.getPlugin("Minigames");
if (minigamesPlugin != null && minigamesPlugin.isEnabled()) {
pluginManager.registerEvents(new MinigamesListener(this), plugin);
getLogger().info("Minigames found, wands will deactivate before joining a minigame");
}
// Check for LibsDisguise
Plugin libsDisguisePlugin = pluginManager.getPlugin("LibsDisguises");
if (libsDisguisePlugin == null || !libsDisguisePlugin.isEnabled()) {
getLogger().info("LibsDisguises not found, magic mob disguises will not be available");
} else if (libsDisguiseEnabled) {
if (!LibsDisguiseManager.isCurrentVersion()) {
getLogger().info("Using legacy LibsDisguise integration, please update");
libsDisguiseManager = new LegacyLibsDisguiseManager(getPlugin(), libsDisguisePlugin);
} else {
libsDisguiseManager = new ModernLibsDisguiseManager(this, libsDisguisePlugin);
}
if (libsDisguiseManager.initialize()) {
getLogger().info("LibsDisguises found, mob disguises and disguise_restricted features enabled");
} else {
getLogger().warning("LibsDisguises integration failed");
}
} else {
libsDisguiseManager = null;
getLogger().info("LibsDisguises integration disabled");
}
// Check for MobArena
Plugin mobArenaPlugin = pluginManager.getPlugin("MobArena");
if (mobArenaPlugin == null) {
getLogger().info("MobArena not found");
} else if (mobArenaConfiguration.getBoolean("enabled", true)) {
try {
mobArenaManager = new MobArenaManager(this, mobArenaPlugin, mobArenaConfiguration);
getLogger().info("Integrated with MobArena, use \"magic:<itemkey>\" in arena configs for Magic items, magic mobs can be used in monster configurations");
} catch (Throwable ex) {
getLogger().warning("MobArena integration failed, you may need to update the MobArena plugin to use Magic items");
}
} else {
getLogger().info("MobArena integration disabled");
}
// Check for LogBlock
Plugin logBlockPlugin = pluginManager.getPlugin("LogBlock");
if (logBlockPlugin == null || !logBlockPlugin.isEnabled()) {
getLogger().info("LogBlock not found");
} else if (logBlockEnabled) {
try {
logBlockManager = new LogBlockManager(plugin, logBlockPlugin);
getLogger().info("Integrated with LogBlock, engineering magic will be logged");
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "LogBlock integration failed", ex);
}
} else {
getLogger().info("LogBlock integration disabled");
}
// Try to link to Essentials:
Plugin essentials = pluginManager.getPlugin("Essentials");
essentialsController = null;
hasEssentials = essentials != null && essentials.isEnabled();
if (hasEssentials) {
essentialsController = EssentialsController.initialize(essentials);
if (essentialsController == null) {
getLogger().warning("Error integrating with Essentials");
} else {
getLogger().info("Integrating with Essentials for vanish detection");
}
if (warpController.setEssentials(essentials)) {
getLogger().info("Integrating with Essentials for Recall warps");
}
try {
mailer = new Mailer(essentials);
} catch (Exception ex) {
getLogger().warning("Essentials found, but failed to hook up to Mailer");
mailer = null;
}
}
if (essentialsSignsEnabled) {
try {
if (essentials != null) {
Class<?> essentialsClass = essentials.getClass();
essentialsClass.getMethod("getItemDb");
if (MagicItemDb.register(this, essentials)) {
getLogger().info("Essentials found, hooked up custom item handler");
} else {
getLogger().warning("Essentials found, but something went wrong hooking up the custom item handler");
}
}
} catch (Throwable ex) {
getLogger().warning("Essentials found, but is not up to date. Magic item integration will not work with this version of Magic. Please upgrade EssentialsX or downgrade Magic to 7.6.19");
}
}
// Try to link to CommandBook
hasCommandBook = false;
try {
Plugin commandBookPlugin = plugin.getServer().getPluginManager().getPlugin("CommandBook");
if (commandBookPlugin != null && commandBookPlugin.isEnabled()) {
if (warpController.setCommandBook(commandBookPlugin)) {
getLogger().info("CommandBook found, integrating for Recall warps");
hasCommandBook = true;
} else {
getLogger().warning("CommandBook integration failed");
}
}
} catch (Throwable ignored) {
}
// Link to factions
factionsManager.initialize(plugin);
// Try to (dynamically) link to WorldGuard:
worldGuardManager.initialize(plugin);
// Link to PvpManager
pvpManager.initialize(plugin);
// Link to Multiverse
multiverseManager.initialize(plugin);
// Link to DeadSouls
Plugin deadSoulsPlugin = plugin.getServer().getPluginManager().getPlugin("DeadSouls");
if (deadSoulsPlugin != null) {
try {
deadSoulsController = new DeadSoulsManager(this);
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error integrating with DeadSouls, is it up to date? Version 1.6 or higher required.", ex);
}
}
// Link to PreciousStones
preciousStonesManager.initialize(plugin);
// Link to Towny
townyManager.initialize(plugin);
// Link to Lockette
locketteManager.initialize(plugin);
// Link to GriefPrevention
griefPreventionManager.initialize(plugin);
// Link to NoCheatPlus
ncpManager.initialize(plugin);
// Try to link to dynmap:
try {
Plugin dynmapPlugin = plugin.getServer().getPluginManager().getPlugin("dynmap");
if (dynmapPlugin != null && dynmapPlugin.isEnabled()) {
dynmap = new DynmapController(plugin, dynmapPlugin, messages);
} else {
dynmap = null;
}
} catch (Throwable ex) {
getLogger().warning(ex.getMessage());
}
if (dynmap == null) {
getLogger().info("dynmap not found, not integrating.");
} else {
getLogger().info("dynmap found, integrating.");
}
// Try to link to Elementals:
try {
Plugin elementalsPlugin = plugin.getServer().getPluginManager().getPlugin("Splateds_Elementals");
if (elementalsPlugin != null && elementalsPlugin.isEnabled()) {
elementals = new ElementalsController(elementalsPlugin);
} else {
elementals = null;
}
} catch (Throwable ex) {
getLogger().warning(ex.getMessage());
}
if (elementals != null) {
getLogger().info("Elementals found, integrating.");
}
// Check for Shopkeepers, this is an optimization to avoid scanning for metadata if the plugin is not
// present
hasShopkeepers = pluginManager.isPluginEnabled("Shopkeepers");
if (hasShopkeepers) {
npcSuppliers.register(new GenericMetadataNPCSupplier("shopkeeper"));
}
// Try to link to Citizens
try {
Plugin citizensPlugin = plugin.getServer().getPluginManager().getPlugin("Citizens");
if (citizensPlugin != null && citizensPlugin.isEnabled()) {
citizens = new CitizensController(citizensPlugin, this, citizensEnabled);
new MagicTraitCommandExecutor(MagicPlugin.getAPI(), citizens).register(plugin);
} else {
citizens = null;
getLogger().info("Citizens not found, Magic trait unavailable.");
}
} catch (Throwable ex) {
citizens = null;
getLogger().warning("Error integrating with Citizens");
getLogger().warning(ex.getMessage());
}
if (citizens != null) {
npcSuppliers.register(citizens);
}
// Placeholder API
if (placeholdersEnabled) {
if (pluginManager.isPluginEnabled("PlaceholderAPI")) {
try {
// Can only register this once
if (placeholderAPIManager == null) {
placeholderAPIManager = new PlaceholderAPIManager(this);
}
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with PlaceholderAPI", ex);
}
}
} else {
getLogger().info("PlaceholderAPI integration disabled.");
}
// Light API
if (lightAPIEnabled) {
if (pluginManager.isPluginEnabled("LightAPI")) {
try {
lightAPIManager = new LightAPIManager(plugin);
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with LightAPI", ex);
}
} else {
getLogger().info("LightAPI not found, Light action will not work");
}
} else {
lightAPIManager = null;
getLogger().info("LightAPI integration disabled.");
}
// Geyser
if (pluginManager.isPluginEnabled("Geyser-Spigot")) {
try {
geyserManager = new GeyserManager(this);
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with Geyser", ex);
}
}
// Skript
if (skriptEnabled) {
if (pluginManager.isPluginEnabled("Skript")) {
try {
new SkriptManager(this);
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with Skript", ex);
}
}
} else {
getLogger().info("Skript integration disabled.");
}
// ajParkour
if (ajParkourConfiguration.getBoolean("enabled")) {
if (pluginManager.isPluginEnabled("ajParkour")) {
try {
ajParkourManager = new AJParkourManager(this);
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with ajParkour", ex);
}
}
} else {
getLogger().info("ajParkour integration disabled.");
}
// Citadel
if (citadelConfiguration.getBoolean("enabled")) {
if (pluginManager.isPluginEnabled("Citadel")) {
try {
citadelManager = new CitadelManager(this, citadelConfiguration);
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with Citadel", ex);
}
}
} else {
getLogger().info("Citadel integration disabled.");
}
// Residence
if (residenceConfiguration.getBoolean("enabled")) {
if (pluginManager.isPluginEnabled("Residence")) {
try {
residenceManager = new ResidenceManager(pluginManager.getPlugin("Residence"), this, residenceConfiguration);
getLogger().info("Integrated with residence for build/break/pvp/target checks");
getLogger().info("Disable warping to residences in recall config with allow_residence: false");
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with Residence", ex);
}
}
} else {
getLogger().info("Residence integration disabled.");
}
// RedProtect
if (redProtectConfiguration.getBoolean("enabled")) {
if (pluginManager.isPluginEnabled("RedProtect")) {
try {
redProtectManager = new RedProtectManager(pluginManager.getPlugin("RedProtect"), this, redProtectConfiguration);
getLogger().info("Integrated with RedProtect for build/break/pvp/target checks");
getLogger().info("Disable warping to fields in recall config with allow_redprotect: false");
if (redProtectManager.isFlagsEnabled()) {
getLogger().info("Added custom flags: " + StringUtils.join(RedProtectManager.flags, ','));
}
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with RedProtect", ex);
}
}
} else {
getLogger().info("RedProtect integration disabled.");
}
// Set up the Mage update timer
final MageUpdateTask mageTask = new MageUpdateTask(this);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, mageTask, 0, mageUpdateFrequency);
// Set up the Block update timer
final BatchUpdateTask blockTask = new BatchUpdateTask(this);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, blockTask, 0, workFrequency);
// Set up the Automata timer
final AutomataUpdateTask automataTaks = new AutomataUpdateTask(this);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, automataTaks, 0, automataUpdateFrequency);
// Set up the Update check timer
final UndoUpdateTask undoTask = new UndoUpdateTask(this);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, undoTask, 0, undoFrequency);
}
protected void loadProperties(CommandSender sender, ConfigurationSection properties) {
if (properties == null) return;
// Delegate to resource pack handler
resourcePacks.load(properties, sender, !loaded);
logVerbosity = properties.getInt("log_verbosity", 0);
SkinUtils.DEBUG = logVerbosity >= 5;
LOG_WATCHDOG_TIMEOUT = properties.getInt("load_watchdog_timeout", 30000);
logger.setColorize(properties.getBoolean("colored_logs", true));
// Cancel any pending save tasks
if (autoSaveTaskId > 0) {
Bukkit.getScheduler().cancelTask(autoSaveTaskId);
autoSaveTaskId = 0;
}
if (configCheckTask != null) {
configCheckTask.cancel();
configCheckTask = null;
}
if (logNotifyTask != null) {
logNotifyTask.cancel();
logNotifyTask = null;
}
debugEffectLib = properties.getBoolean("debug_effects", false);
com.elmakers.mine.bukkit.effect.EffectPlayer.debugEffects(debugEffectLib);
boolean effectLibStackTraces = properties.getBoolean("debug_effects_stack_traces", false);
com.elmakers.mine.bukkit.effect.EffectPlayer.showStackTraces(effectLibStackTraces);
CompatibilityUtils.USE_MAGIC_DAMAGE = properties.getBoolean("use_magic_damage", CompatibilityUtils.USE_MAGIC_DAMAGE);
com.elmakers.mine.bukkit.effect.EffectPlayer.setParticleRange(properties.getInt("particle_range", com.elmakers.mine.bukkit.effect.EffectPlayer.PARTICLE_RANGE));
showCastHoloText = properties.getBoolean("show_cast_holotext", showCastHoloText);
showActivateHoloText = properties.getBoolean("show_activate_holotext", showCastHoloText);
castHoloTextRange = properties.getInt("cast_holotext_range", castHoloTextRange);
activateHoloTextRange = properties.getInt("activate_holotext_range", activateHoloTextRange);
urlIconsEnabled = properties.getBoolean("url_icons_enabled", urlIconsEnabled);
legacyIconsEnabled = properties.getBoolean("legacy_icons_enabled", legacyIconsEnabled);
spellProgressionEnabled = properties.getBoolean("enable_spell_progression", spellProgressionEnabled);
autoSpellUpgradesEnabled = properties.getBoolean("enable_automatic_spell_upgrades", autoSpellUpgradesEnabled);
autoPathUpgradesEnabled = properties.getBoolean("enable_automatic_spell_upgrades", autoPathUpgradesEnabled);
undoQueueDepth = properties.getInt("undo_depth", undoQueueDepth);
workPerUpdate = properties.getInt("work_per_update", workPerUpdate);
workFrequency = properties.getInt("work_frequency", workFrequency);
automataUpdateFrequency = properties.getInt("automata_update_frequency", automataUpdateFrequency);
mageUpdateFrequency = properties.getInt("mage_update_frequency", mageUpdateFrequency);
undoFrequency = properties.getInt("undo_frequency", undoFrequency);
pendingQueueDepth = properties.getInt("pending_depth", pendingQueueDepth);
undoMaxPersistSize = properties.getInt("undo_max_persist_size", undoMaxPersistSize);
commitOnQuit = properties.getBoolean("commit_on_quit", commitOnQuit);
saveNonPlayerMages = properties.getBoolean("save_non_player_mages", saveNonPlayerMages);
defaultWandPath = properties.getString("default_wand_path", "");
Wand.DEFAULT_WAND_TEMPLATE = properties.getString("default_wand", "");
defaultWandMode = Wand.parseWandMode(properties.getString("default_wand_mode", ""), defaultWandMode);
defaultBrushMode = Wand.parseWandMode(properties.getString("default_brush_mode", ""), defaultBrushMode);
backupInventories = properties.getBoolean("backup_player_inventory", true);
Wand.brushSelectSpell = properties.getString("brush_select_spell", Wand.brushSelectSpell);
showMessages = properties.getBoolean("show_messages", showMessages);
showCastMessages = properties.getBoolean("show_cast_messages", showCastMessages);
messageThrottle = properties.getInt("message_throttle", 0);
soundsEnabled = properties.getBoolean("sounds", soundsEnabled);
fillingEnabled = properties.getBoolean("fill_wands", fillingEnabled);
Wand.FILL_CREATOR = properties.getBoolean("fill_wand_creator", Wand.FILL_CREATOR);
Wand.CREATIVE_CHEST_MODE = properties.getBoolean("wand_creative_chest_switch", Wand.CREATIVE_CHEST_MODE);
maxFillLevel = properties.getInt("fill_wand_level", maxFillLevel);
welcomeWand = properties.getString("welcome_wand", "");
maxDamagePowerMultiplier = (float) properties.getDouble("max_power_damage_multiplier", maxDamagePowerMultiplier);
maxConstructionPowerMultiplier = (float) properties.getDouble("max_power_construction_multiplier", maxConstructionPowerMultiplier);
maxRangePowerMultiplier = (float) properties.getDouble("max_power_range_multiplier", maxRangePowerMultiplier);
maxRangePowerMultiplierMax = (float) properties.getDouble("max_power_range_multiplier_max", maxRangePowerMultiplierMax);
maxRadiusPowerMultiplier = (float) properties.getDouble("max_power_radius_multiplier", maxRadiusPowerMultiplier);
maxRadiusPowerMultiplierMax = (float) properties.getDouble("max_power_radius_multiplier_max", maxRadiusPowerMultiplierMax);
materialColors = ConfigurationUtils.getNodeList(properties, "material_colors");
materialVariants = ConfigurationUtils.getList(properties, "material_variants");
blockItems = properties.getConfigurationSection("block_items");
loadBlockSkins(properties.getConfigurationSection("block_skins"));
loadMobSkins(properties.getConfigurationSection("mob_skins"));
loadMobEggs(properties.getConfigurationSection("mob_eggs"));
loadSkulls(properties.getConfigurationSection("skulls"));
loadOtherMaterials(properties);
WandCommandExecutor.CONSOLE_BYPASS_LOCKED = properties.getBoolean("console_bypass_locked_wands", true);
maxPower = (float) properties.getDouble("max_power", maxPower);
ConfigurationSection damageTypes = properties.getConfigurationSection("damage_types");
if (damageTypes != null) {
Set<String> typeKeys = damageTypes.getKeys(false);
for (String typeKey : typeKeys) {
ConfigurationSection damageType = damageTypes.getConfigurationSection(typeKey);
this.damageTypes.put(typeKey, new DamageType(damageType));
}
}
maxCostReduction = (float) properties.getDouble("max_cost_reduction", maxCostReduction);
maxCooldownReduction = (float) properties.getDouble("max_cooldown_reduction", maxCooldownReduction);
maxMana = properties.getInt("max_mana", maxMana);
maxManaRegeneration = properties.getInt("max_mana_regeneration", maxManaRegeneration);
worthBase = properties.getDouble("worth_base", 1);
com.elmakers.mine.bukkit.item.ItemData.EARN_SCALE = properties.getDouble("default_earn_scale", 0.5);
SafetyUtils.MAX_VELOCITY = properties.getDouble("max_velocity", 10);
HitboxUtils.setHitboxScale(properties.getDouble("hitbox_scale", 1.0));
HitboxUtils.setHitboxScaleY(properties.getDouble("hitbox_scale_y", 1.0));
HitboxUtils.setHitboxSneakScaleY(properties.getDouble("hitbox_sneaking_scale_y", 0.75));
if (properties.contains("hitboxes")) {
HitboxUtils.configureHitboxes(properties.getConfigurationSection("hitboxes"));
}
if (properties.contains("head_sizes")) {
HitboxUtils.configureHeadSizes(properties.getConfigurationSection("head_sizes"));
}
if (properties.contains("max_height")) {
HitboxUtils.configureMaxHeights(properties.getConfigurationSection("max_height"));
}
// These were changed from set values to multipliers, we're going to translate for backwards compatibility.
// The default configs used to have these set to either 0 or 100, where 100 indicated that we should be
// turning off the costs/cooldowns.
if (properties.contains("cast_command_cost_reduction")) {
castCommandCostFree = (properties.getDouble("cast_command_cost_reduction") > 0);
} else {
castCommandCostFree = properties.getBoolean("cast_command_cost_free", castCommandCostFree);
}
if (properties.contains("cast_command_cooldown_reduction")) {
castCommandCooldownFree = (properties.getDouble("cast_command_cooldown_reduction") > 0);
} else {
castCommandCooldownFree = properties.getBoolean("cast_command_cooldown_free", castCommandCooldownFree);
}
if (properties.contains("cast_console_cost_reduction")) {
castConsoleCostFree = (properties.getDouble("cast_console_cost_reduction") > 0);
} else {
castConsoleCostFree = properties.getBoolean("cast_console_cost_free", castConsoleCostFree);
}
if (properties.contains("cast_console_cooldown_reduction")) {
castConsoleCooldownFree = (properties.getDouble("cast_console_cooldown_reduction") > 0);
} else {
castConsoleCooldownFree = properties.getBoolean("cast_console_cooldown_free", castConsoleCooldownFree);
}
castConsoleFeedback = properties.getBoolean("cast_console_feedback", false);
editorURL = properties.getString("editor_url");
castCommandPowerMultiplier = (float) properties.getDouble("cast_command_power_multiplier", castCommandPowerMultiplier);
castConsolePowerMultiplier = (float) properties.getDouble("cast_console_power_multiplier", castConsolePowerMultiplier);
maps.setAnimationAllowed(properties.getBoolean("enable_map_animations", true));
costReduction = (float) properties.getDouble("cost_reduction", costReduction);
cooldownReduction = (float) properties.getDouble("cooldown_reduction", cooldownReduction);
autoUndo = properties.getInt("auto_undo", autoUndo);
spellDroppingEnabled = properties.getBoolean("allow_spell_dropping", spellDroppingEnabled);
essentialsSignsEnabled = properties.getBoolean("enable_essentials_signs", essentialsSignsEnabled);
logBlockEnabled = properties.getBoolean("logblock_enabled", logBlockEnabled);
citizensEnabled = properties.getBoolean("enable_citizens", citizensEnabled);
dynmapShowWands = properties.getBoolean("dynmap_show_wands", dynmapShowWands);
dynmapShowSpells = properties.getBoolean("dynmap_show_spells", dynmapShowSpells);
dynmapOnlyPlayerSpells = properties.getBoolean("dynmap_only_player_spells", dynmapOnlyPlayerSpells);
dynmapUpdate = properties.getBoolean("dynmap_update", dynmapUpdate);
protectLocked = properties.getBoolean("protect_locked", protectLocked);
bindOnGive = properties.getBoolean("bind_on_give", bindOnGive);
bypassBuildPermissions = properties.getBoolean("bypass_build", bypassBuildPermissions);
bypassBreakPermissions = properties.getBoolean("bypass_break", bypassBreakPermissions);
bypassPvpPermissions = properties.getBoolean("bypass_pvp", bypassPvpPermissions);
bypassFriendlyFire = properties.getBoolean("bypass_friendly_fire", bypassFriendlyFire);
useScoreboardTeams = properties.getBoolean("use_scoreboard_teams", useScoreboardTeams);
defaultFriendly = properties.getBoolean("default_friendly", defaultFriendly);
extraSchematicFilePath = properties.getString("schematic_files", extraSchematicFilePath);
createWorldsEnabled = properties.getBoolean("enable_world_creation", createWorldsEnabled);
defaultSkillIcon = properties.getString("default_skill_icon", defaultSkillIcon);
skillInventoryRows = properties.getInt("skill_inventory_max_rows", skillInventoryRows);
skillsSpell = properties.getString("mskills_spell", skillsSpell);
InventoryUtils.MAX_LORE_LENGTH = properties.getInt("lore_wrap_limit", InventoryUtils.MAX_LORE_LENGTH);
libsDisguiseEnabled = properties.getBoolean("enable_libsdisguises", libsDisguiseEnabled);
skillAPIEnabled = properties.getBoolean("skillapi_enabled", skillAPIEnabled);
useSkillAPIMana = properties.getBoolean("use_skillapi_mana", useSkillAPIMana);
placeholdersEnabled = properties.getBoolean("placeholder_api_enabled", placeholdersEnabled);
lightAPIEnabled = properties.getBoolean("light_api_enabled", lightAPIEnabled);
skriptEnabled = properties.getBoolean("skript_enabled", skriptEnabled);
vaultEnabled = properties.getConfigurationSection("vault").getBoolean("enabled");
citadelConfiguration = properties.getConfigurationSection("citadel");
mobArenaConfiguration = properties.getConfigurationSection("mobarena");
residenceConfiguration = properties.getConfigurationSection("residence");
redProtectConfiguration = properties.getConfigurationSection("redprotect");
ajParkourConfiguration = properties.getConfigurationSection("ajparkour");
if (mobArenaManager != null) {
mobArenaManager.configure(mobArenaConfiguration);
}
String swingTypeString = properties.getString("left_click_type");
try {
swingType = SwingType.valueOf(swingTypeString.toUpperCase());
} catch (Exception ex) {
getLogger().warning("Invalid left_click_type: " + swingTypeString);
}
List<? extends Object> permissionTeams = properties.getList("permission_teams");
if (permissionTeams != null) {
this.permissionTeams = new ArrayList<>();
for (Object o : permissionTeams) {
if (o instanceof List) {
@SuppressWarnings("unchecked")
List<String> stringList = (List<String>) o;
this.permissionTeams.add(stringList);
} else if (o instanceof String) {
List<String> newList = new ArrayList<>();
newList.add((String) o);
this.permissionTeams.add(newList);
}
}
}
String defaultSpellIcon = properties.getString("default_spell_icon");
try {
BaseSpell.DEFAULT_SPELL_ICON = Material.valueOf(defaultSpellIcon.toUpperCase());
} catch (Exception ex) {
getLogger().warning("Invalid default_spell_icon: " + defaultSpellIcon);
}
skillsUseHeroes = properties.getBoolean("skills_use_heroes", skillsUseHeroes);
useHeroesParties = properties.getBoolean("use_heroes_parties", useHeroesParties);
useSkillAPIAllies = properties.getBoolean("use_skillapi_allies", useSkillAPIAllies);
useBattleArenaTeams = properties.getBoolean("use_battlearena_teams", useBattleArenaTeams);
useHeroesMana = properties.getBoolean("use_heroes_mana", useHeroesMana);
heroesSkillPrefix = properties.getString("heroes_skill_prefix", heroesSkillPrefix);
skillsUsePermissions = properties.getBoolean("skills_use_permissions", skillsUsePermissions);
messagePrefix = properties.getString("message_prefix", messagePrefix);
castMessagePrefix = properties.getString("cast_message_prefix", castMessagePrefix);
Messages.RANGE_FORMATTER = new DecimalFormat(properties.getString("range_formatter"));
Messages.MOMENT_SECONDS_FORMATTER = new DecimalFormat(properties.getString("moment_seconds_formatter"));
Messages.MOMENT_MILLISECONDS_FORMATTER = new DecimalFormat(properties.getString("moment_milliseconds_formatter"));
Messages.SECONDS_FORMATTER = new DecimalFormat(properties.getString("seconds_formatter"));
Messages.MINUTES_FORMATTER = new DecimalFormat(properties.getString("minutes_formatter"));
Messages.HOURS_FORMATTER = new DecimalFormat(properties.getString("hours_formatter"));
redstoneReplacement = ConfigurationUtils.getMaterialAndData(properties, "redstone_replacement", redstoneReplacement);
messagePrefix = ChatColor.translateAlternateColorCodes('&', messagePrefix);
castMessagePrefix = ChatColor.translateAlternateColorCodes('&', castMessagePrefix);
worldGuardManager.setEnabled(properties.getBoolean("region_manager_enabled", worldGuardManager.isEnabled()));
factionsManager.setEnabled(properties.getBoolean("factions_enabled", factionsManager.isEnabled()));
pvpManager.setEnabled(properties.getBoolean("pvp_manager_enabled", pvpManager.isEnabled()));
multiverseManager.setEnabled(properties.getBoolean("multiverse_enabled", multiverseManager.isEnabled()));
preciousStonesManager.setEnabled(properties.getBoolean("precious_stones_enabled", preciousStonesManager.isEnabled()));
preciousStonesManager.setOverride(properties.getBoolean("precious_stones_override", true));
townyManager.setEnabled(properties.getBoolean("towny_enabled", townyManager.isEnabled()));
townyManager.setWildernessBypass(properties.getBoolean("towny_wilderness_bypass", true));
locketteManager.setEnabled(properties.getBoolean("lockette_enabled", locketteManager.isEnabled()));
griefPreventionManager.setEnabled(properties.getBoolean("grief_prevention_enabled", griefPreventionManager.isEnabled()));
ncpManager.setEnabled(properties.getBoolean("ncp_enabled", false));
useWildStacker = properties.getBoolean("wildstacker.enabled", true);
com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CLASS = properties.getString("default_mage_class", "");
metricsLevel = properties.getInt("metrics_level", metricsLevel);
ConfigurationSection autoWandsConfig = properties.getConfigurationSection("auto_wands");
Set<String> autoWandsKeys = autoWandsConfig.getKeys(false);
autoWands.clear();
for (String autoWandKey : autoWandsKeys) {
try {
Material autoWandMaterial = Material.valueOf(autoWandKey.toUpperCase());
autoWands.put(autoWandMaterial, autoWandsConfig.getString(autoWandKey));
} catch (Exception ex) {
getLogger().warning("Invalid material in auto_wands config: " + autoWandKey);
}
}
ConfigurationSection builtinExampleConfigs = properties.getConfigurationSection("external_examples");
Set<String> exampleKeys = builtinExampleConfigs.getKeys(false);
builtinExternalExamples.clear();
for (String exampleKey : exampleKeys) {
builtinExternalExamples.put(exampleKey, builtinExampleConfigs.getString(exampleKey));
}
Wand.regenWhileInactive = properties.getBoolean("regenerate_while_inactive", Wand.regenWhileInactive);
if (properties.contains("mana_display")) {
String manaDisplay = properties.getString("mana_display");
if (manaDisplay.equalsIgnoreCase("bar") || manaDisplay.equalsIgnoreCase("hybrid")) {
Wand.manaMode = WandManaMode.BAR;
} else if (manaDisplay.equalsIgnoreCase("number")) {
Wand.manaMode = WandManaMode.NUMBER;
} else if (manaDisplay.equalsIgnoreCase("durability")) {
Wand.manaMode = WandManaMode.DURABILITY;
} else if (manaDisplay.equalsIgnoreCase("glow")) {
Wand.manaMode = WandManaMode.GLOW;
} else if (manaDisplay.equalsIgnoreCase("none")) {
Wand.manaMode = WandManaMode.NONE;
}
}
if (properties.contains("sp_display")) {
String spDisplay = properties.getString("sp_display");
if (spDisplay.equalsIgnoreCase("number")) {
Wand.currencyMode = WandManaMode.NUMBER;
} else {
Wand.currencyMode = WandManaMode.NONE;
}
}
spEnabled = properties.getBoolean("sp_enabled", true);
spEarnEnabled = properties.getBoolean("sp_earn_enabled", true);
populateEntityTypes(undoEntityTypes, properties, "entity_undo_types");
populateEntityTypes(friendlyEntityTypes, properties, "friendly_entity_types");
ActionHandler.setRestrictedActions(properties.getStringList("restricted_spell_actions"));
String defaultLocationString = properties.getString("default_cast_location");
try {
com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_LOCATION = CastSourceLocation.valueOf(defaultLocationString.toUpperCase());
} catch (Exception ex) {
com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_LOCATION = CastSourceLocation.MAINHAND;
getLogger().warning("Invalid default_cast_location: " + defaultLocationString);
}
com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_OFFSET.setZ(properties.getDouble("default_cast_location_offset", com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_OFFSET.getZ()));
com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_OFFSET.setY(properties.getDouble("default_cast_location_offset_vertical", com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_OFFSET.getY()));
com.elmakers.mine.bukkit.magic.Mage.OFFHAND_CAST_COOLDOWN = properties.getInt("offhand_cast_cooldown", com.elmakers.mine.bukkit.magic.Mage.OFFHAND_CAST_COOLDOWN);
com.elmakers.mine.bukkit.magic.Mage.SNEAKING_CAST_OFFSET = properties.getDouble("sneaking_cast_location_offset_vertical", com.elmakers.mine.bukkit.magic.Mage.SNEAKING_CAST_OFFSET);
com.elmakers.mine.bukkit.magic.Mage.CURRENCY_MESSAGE_DELAY = properties.getInt("currency_message_delay", com.elmakers.mine.bukkit.magic.Mage.CURRENCY_MESSAGE_DELAY);
// Parse wand settings
Wand.DefaultUpgradeMaterial = ConfigurationUtils.getMaterial(properties, "wand_upgrade_item", Wand.DefaultUpgradeMaterial);
Wand.SpellGlow = properties.getBoolean("spell_glow", Wand.SpellGlow);
Wand.LiveHotbarSkills = properties.getBoolean("live_hotbar_skills", Wand.LiveHotbarSkills);
Wand.LiveHotbar = properties.getBoolean("live_hotbar", Wand.LiveHotbar);
Wand.LiveHotbarCooldown = properties.getBoolean("live_hotbar_cooldown", Wand.LiveHotbarCooldown);
Wand.LiveHotbarMana = properties.getBoolean("live_hotbar_mana", Wand.LiveHotbarMana);
Wand.BrushGlow = properties.getBoolean("brush_glow", Wand.BrushGlow);
Wand.BrushItemGlow = properties.getBoolean("brush_item_glow", Wand.BrushItemGlow);
Wand.WAND_KEY = properties.getString("wand_key", "wand");
Wand.UPGRADE_KEY = properties.getString("wand_upgrade_key", "wand");
Wand.WAND_SELF_DESTRUCT_KEY = properties.getString("wand_self_destruct_key", "");
if (Wand.WAND_SELF_DESTRUCT_KEY.isEmpty()) {
Wand.WAND_SELF_DESTRUCT_KEY = null;
}
Wand.HIDE_FLAGS = (byte) properties.getInt("wand_hide_flags", Wand.HIDE_FLAGS);
Wand.Unbreakable = properties.getBoolean("wand_unbreakable", Wand.Unbreakable);
Wand.Unstashable = properties.getBoolean("wand_undroppable", properties.getBoolean("wand_unstashable", Wand.Unstashable));
MaterialBrush.CopyMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "copy_item", legacyIconsEnabled, MaterialBrush.CopyMaterial);
MaterialBrush.EraseMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "erase_item", legacyIconsEnabled, MaterialBrush.EraseMaterial);
MaterialBrush.CloneMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "clone_item", legacyIconsEnabled, MaterialBrush.CloneMaterial);
MaterialBrush.ReplicateMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "replicate_item", legacyIconsEnabled, MaterialBrush.ReplicateMaterial);
MaterialBrush.SchematicMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "schematic_item", legacyIconsEnabled, MaterialBrush.SchematicMaterial);
MaterialBrush.MapMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "map_item", legacyIconsEnabled, MaterialBrush.MapMaterial);
MaterialBrush.DefaultBrushMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "default_brush_item", legacyIconsEnabled, MaterialBrush.DefaultBrushMaterial);
MaterialBrush.configureReplacements(properties.getConfigurationSection("brush_replacements"));
MaterialBrush.CopyCustomIcon = properties.getString("copy_icon_url", MaterialBrush.CopyCustomIcon);
MaterialBrush.EraseCustomIcon = properties.getString("erase_icon_url", MaterialBrush.EraseCustomIcon);
MaterialBrush.CloneCustomIcon = properties.getString("clone_icon_url", MaterialBrush.CloneCustomIcon);
MaterialBrush.ReplicateCustomIcon = properties.getString("replicate_icon_url", MaterialBrush.ReplicateCustomIcon);
MaterialBrush.SchematicCustomIcon = properties.getString("schematic_icon_url", MaterialBrush.SchematicCustomIcon);
MaterialBrush.MapCustomIcon = properties.getString("map_icon_url", MaterialBrush.MapCustomIcon);
MaterialBrush.DefaultBrushCustomIcon = properties.getString("default_brush_icon_url", MaterialBrush.DefaultBrushCustomIcon);
BaseSpell.DEFAULT_DISABLED_ICON_URL = properties.getString("disabled_icon_url", BaseSpell.DEFAULT_DISABLED_ICON_URL);
Wand.DEFAULT_CAST_OFFSET.setZ(properties.getDouble("wand_location_offset", Wand.DEFAULT_CAST_OFFSET.getZ()));
Wand.DEFAULT_CAST_OFFSET.setY(properties.getDouble("wand_location_offset_vertical", Wand.DEFAULT_CAST_OFFSET.getY()));
com.elmakers.mine.bukkit.magic.Mage.JUMP_EFFECT_FLIGHT_EXEMPTION_DURATION = properties.getInt("jump_exemption", 0);
com.elmakers.mine.bukkit.magic.Mage.CHANGE_WORLD_EQUIP_COOLDOWN = properties.getInt("change_world_equip_cooldown", 0);
com.elmakers.mine.bukkit.magic.Mage.DEACTIVATE_WAND_ON_WORLD_CHANGE = properties.getBoolean("close_wand_on_world_change", false);
Wand.inventoryOpenSound = ConfigurationUtils.toSoundEffect(properties.getString("wand_inventory_open_sound"));
Wand.inventoryCloseSound = ConfigurationUtils.toSoundEffect(properties.getString("wand_inventory_close_sound"));
Wand.inventoryCycleSound = ConfigurationUtils.toSoundEffect(properties.getString("wand_inventory_cycle_sound"));
Wand.noActionSound = ConfigurationUtils.toSoundEffect(properties.getString("wand_no_action_sound"));
Wand.itemPickupSound = ConfigurationUtils.toSoundEffect(properties.getString("wand_pickup_item_sound"));
// Configure sub-controllers
explosionController.loadProperties(properties);
inventoryController.loadProperties(properties);
entityController.loadProperties(properties);
playerController.loadProperties(properties);
blockController.loadProperties(properties);
// Set up other systems
com.elmakers.mine.bukkit.effect.EffectPlayer.SOUNDS_ENABLED = soundsEnabled;
// Set up auto-save timer
int autoSaveIntervalTicks = properties.getInt("auto_save", 0) * 20 / 1000;
if (autoSaveIntervalTicks > 1) {
final AutoSaveTask autoSave = new AutoSaveTask(this);
autoSaveTaskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, autoSave,
autoSaveIntervalTicks, autoSaveIntervalTicks);
}
savePlayerData = properties.getBoolean("save_player_data", true);
externalPlayerData = properties.getBoolean("external_player_data", false);
if (externalPlayerData) {
getLogger().info("Magic is expecting player data to be loaded from an external source");
} else if (!savePlayerData) {
getLogger().info("Magic player data saving is disabled");
}
asynchronousSaving = properties.getBoolean("save_player_data_asynchronously", true);
isFileLockingEnabled = properties.getBoolean("use_file_locking", false);
fileLoadDelay = properties.getInt("file_load_delay", 0);
despawnMagicMobs = properties.getBoolean("despawn_magic_mobs", false);
MobController.REMOVE_INVULNERABLE = properties.getBoolean("remove_invulnerable_mobs", false);
com.elmakers.mine.bukkit.effect.EffectPlayer.ENABLE_VANILLA_SOUNDS = properties.getBoolean("enable_vanilla_sounds", true);
ConfigurationSection blockExchange = properties.getConfigurationSection("block_exchange");
if (blockExchange != null) {
if (blockExchange.getBoolean("enabled", true)) {
blockExchangeCurrency = blockExchange.getString("currency");
if (blockExchangeCurrency != null && blockExchangeCurrency.isEmpty()) {
blockExchangeCurrency = null;
}
} else {
blockExchangeCurrency = null;
}
} else {
blockExchangeCurrency = null;
}
// Set up mage data store
if (mageDataStore != null) {
mageDataStore.close();
}
ConfigurationSection mageDataStoreConfiguration = properties.getConfigurationSection("player_data_store");
if (mageDataStoreConfiguration != null) {
mageDataStore = loadMageDataStore(mageDataStoreConfiguration);
if (mageDataStore == null) {
getLogger().log(Level.WARNING, "Failed to load player_data_store configuration, player data saving disabled!");
}
} else {
getLogger().log(Level.WARNING, "Missing player_data_store configuration, player data saving disabled!");
mageDataStore = null;
}
ConfigurationSection migrateDataStoreConfiguration = properties.getConfigurationSection("migrate_data_store");
if (migrateDataStoreConfiguration != null) {
migrateDataStore = loadMageDataStore(migrateDataStoreConfiguration);
if (migrateDataStore == null) {
getLogger().log(Level.WARNING, "Failed to load migrate_data_store configuration, migration will not work");
}
} else {
migrateDataStore = null;
}
if (migrateDataStore != null) {
migrateDataStore.close();
}
// Semi-deprecated Wand defaults
Wand.DefaultWandMaterial = ConfigurationUtils.getMaterial(properties, "wand_item", Wand.DefaultWandMaterial);
Wand.EnchantableWandMaterial = ConfigurationUtils.getMaterial(properties, "wand_item_enchantable", Wand.EnchantableWandMaterial);
// Load sub-controllers
enchanting.setEnabled(properties.getBoolean("enable_enchanting", enchanting.isEnabled()));
if (enchanting.isEnabled()) {
log("Wand enchanting is enabled");
}
crafting.loadMainConfiguration(properties);
if (crafting.isEnabled()) {
log("Wand crafting is enabled");
}
anvil.load(properties);
if (anvil.isCombiningEnabled()) {
log("Wand anvil combining is enabled");
}
if (anvil.isOrganizingEnabled()) {
log("Wand anvil organizing is enabled");
}
if (isUrlIconsEnabled()) {
log("Skin-based spell icons enabled");
} else {
log("Skin-based spell icons disabled");
}
// Set up sandbox config update timer
int configUpdateInterval = properties.getInt("config_update_interval");
if (configUpdateInterval > 0) {
log("Sandbox enabled, will check for updates from the web UI");
final ConfigCheckTask configCheck = new ConfigCheckTask(this);
configCheckTask = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, configCheck,
configUpdateInterval * 20 / 1000, configUpdateInterval * 20 / 1000);
}
// Set up log notify timer
logger.clearNotify();
int logNotifyInterval = properties.getInt("log_notify_interval");
if (logNotifyInterval > 0) {
final LogNotifyTask logNotify = new LogNotifyTask(this);
logNotifyTask = Bukkit.getScheduler().runTaskTimer(plugin, logNotify,
logNotifyInterval * 20 / 1000, logNotifyInterval * 20 / 1000);
}
// Configure world generation and spawn replacement
worldController.load(properties.getConfigurationSection("world_modification"));
// Link to generic protection plugins
protectionManager.initialize(plugin, ConfigurationUtils.getStringList(properties, "generic_protection"));
}
protected void loadMaterials(ConfigurationSection materialNode) {
if (materialNode == null)
return;
materialSetManager.loadMaterials(materialNode);
DefaultMaterials defaultMaterials = DefaultMaterials.getInstance();
defaultMaterials.initialize(materialSetManager);
defaultMaterials.loadColors(materialColors);
defaultMaterials.loadVariants(materialVariants);
defaultMaterials.loadBlockItems(blockItems);
defaultMaterials.setPlayerSkullItem(skullItems.get(EntityType.PLAYER));
defaultMaterials.setPlayerSkullWallBlock(skullWallBlocks.get(EntityType.PLAYER));
defaultMaterials.setSkeletonSkullItem(skullItems.get(EntityType.SKELETON));
buildingMaterials = materialSetManager.getMaterialSetEmpty("building");
indestructibleMaterials = materialSetManager
.getMaterialSetEmpty("indestructible");
restrictedMaterials = materialSetManager
.getMaterialSetEmpty("restricted");
destructibleMaterials = materialSetManager
.getMaterialSetEmpty("destructible");
interactibleMaterials = materialSetManager
.getMaterialSetEmpty("interactible");
containerMaterials = materialSetManager
.getMaterialSetEmpty("containers");
climbableMaterials = materialSetManager.getMaterialSetEmpty("climbable");
undoableMaterials = materialSetManager.getMaterialSetEmpty("undoable");
wearableMaterials = materialSetManager.getMaterialSetEmpty("wearable");
meleeMaterials = materialSetManager.getMaterialSetEmpty("melee");
offhandMaterials = materialSetManager.getMaterialSetEmpty("offhand");
com.elmakers.mine.bukkit.block.UndoList.attachables = materialSetManager
.getMaterialSetEmpty("attachable");
com.elmakers.mine.bukkit.block.UndoList.attachablesWall = materialSetManager
.getMaterialSetEmpty("attachable_wall");
com.elmakers.mine.bukkit.block.UndoList.attachablesDouble = materialSetManager
.getMaterialSetEmpty("attachable_double");
}
@Override
@Nullable
public Currency getBlockExchangeCurrency() {
return blockExchangeCurrency == null ? null : getCurrency(blockExchangeCurrency);
}
public int getMaxLevel(String spellName) {
Integer maxLevel = maxSpellLevels.get(spellName);
return maxLevel == null ? 1 : maxLevel;
}
@Nullable
public Double getBuiltinAttribute(String attributeKey) {
switch (attributeKey) {
case "weeks":
return (double) 604800000;
case "days":
return (double) 86400000;
case "hours":
return (double) 3600000;
case "minutes":
return (double) 60000;
case "seconds":
return (double) 1000;
case "epoch":
return (double) System.currentTimeMillis();
case "pi":
return Math.PI;
default:
return null;
}
}
public ClientPlatform getClientPlatform(Player player) {
return geyserManager != null && geyserManager.isBedrock(player.getUniqueId()) ? ClientPlatform.BEDROCk : ClientPlatform.JAVA;
}
}
| Magic/src/main/java/com/elmakers/mine/bukkit/magic/MagicController.java | package com.elmakers.mine.bukkit.magic;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.text.DecimalFormat;
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.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.bstats.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Skull;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.scheduler.BukkitTask;
import com.elmakers.mine.bukkit.action.ActionHandler;
import com.elmakers.mine.bukkit.api.attributes.AttributeProvider;
import com.elmakers.mine.bukkit.api.block.BoundingBox;
import com.elmakers.mine.bukkit.api.block.Schematic;
import com.elmakers.mine.bukkit.api.block.UndoList;
import com.elmakers.mine.bukkit.api.data.MageData;
import com.elmakers.mine.bukkit.api.data.MageDataCallback;
import com.elmakers.mine.bukkit.api.data.MageDataStore;
import com.elmakers.mine.bukkit.api.data.SpellData;
import com.elmakers.mine.bukkit.api.economy.Currency;
import com.elmakers.mine.bukkit.api.effect.EffectContext;
import com.elmakers.mine.bukkit.api.effect.EffectPlayer;
import com.elmakers.mine.bukkit.api.entity.EntityData;
import com.elmakers.mine.bukkit.api.entity.TeamProvider;
import com.elmakers.mine.bukkit.api.event.LoadEvent;
import com.elmakers.mine.bukkit.api.event.PreLoadEvent;
import com.elmakers.mine.bukkit.api.event.SaveEvent;
import com.elmakers.mine.bukkit.api.integration.ClientPlatform;
import com.elmakers.mine.bukkit.api.item.ItemData;
import com.elmakers.mine.bukkit.api.item.ItemUpdatedCallback;
import com.elmakers.mine.bukkit.api.magic.CastSourceLocation;
import com.elmakers.mine.bukkit.api.magic.DeathLocation;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageContext;
import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.api.magic.MagicAPI;
import com.elmakers.mine.bukkit.api.magic.MagicAttribute;
import com.elmakers.mine.bukkit.api.magic.MagicProvider;
import com.elmakers.mine.bukkit.api.magic.MaterialSet;
import com.elmakers.mine.bukkit.api.magic.MaterialSetManager;
import com.elmakers.mine.bukkit.api.protection.BlockBreakManager;
import com.elmakers.mine.bukkit.api.protection.BlockBuildManager;
import com.elmakers.mine.bukkit.api.protection.CastPermissionManager;
import com.elmakers.mine.bukkit.api.protection.EntityTargetingManager;
import com.elmakers.mine.bukkit.api.protection.PVPManager;
import com.elmakers.mine.bukkit.api.protection.PlayerWarp;
import com.elmakers.mine.bukkit.api.protection.PlayerWarpManager;
import com.elmakers.mine.bukkit.api.protection.PlayerWarpProvider;
import com.elmakers.mine.bukkit.api.requirements.Requirement;
import com.elmakers.mine.bukkit.api.requirements.RequirementsProcessor;
import com.elmakers.mine.bukkit.api.requirements.RequirementsProvider;
import com.elmakers.mine.bukkit.api.spell.CastingCost;
import com.elmakers.mine.bukkit.api.spell.MageSpell;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellKey;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.api.spell.SpellTemplate;
import com.elmakers.mine.bukkit.automata.Automaton;
import com.elmakers.mine.bukkit.automata.AutomatonTemplate;
import com.elmakers.mine.bukkit.block.BlockData;
import com.elmakers.mine.bukkit.block.DefaultMaterials;
import com.elmakers.mine.bukkit.block.LegacySchematic;
import com.elmakers.mine.bukkit.block.MaterialAndData;
import com.elmakers.mine.bukkit.block.MaterialBrush;
import com.elmakers.mine.bukkit.citizens.CitizensController;
import com.elmakers.mine.bukkit.configuration.MageParameters;
import com.elmakers.mine.bukkit.configuration.MagicConfiguration;
import com.elmakers.mine.bukkit.data.YamlDataFile;
import com.elmakers.mine.bukkit.dynmap.DynmapController;
import com.elmakers.mine.bukkit.economy.BaseMagicCurrency;
import com.elmakers.mine.bukkit.economy.CustomCurrency;
import com.elmakers.mine.bukkit.economy.ExperienceCurrency;
import com.elmakers.mine.bukkit.economy.HealthCurrency;
import com.elmakers.mine.bukkit.economy.HungerCurrency;
import com.elmakers.mine.bukkit.economy.ItemCurrency;
import com.elmakers.mine.bukkit.economy.LevelCurrency;
import com.elmakers.mine.bukkit.economy.ManaCurrency;
import com.elmakers.mine.bukkit.economy.SpellPointCurrency;
import com.elmakers.mine.bukkit.economy.VaultCurrency;
import com.elmakers.mine.bukkit.elementals.ElementalsController;
import com.elmakers.mine.bukkit.entity.PermissionsTeamProvider;
import com.elmakers.mine.bukkit.entity.ScoreboardTeamProvider;
import com.elmakers.mine.bukkit.essentials.EssentialsController;
import com.elmakers.mine.bukkit.essentials.MagicItemDb;
import com.elmakers.mine.bukkit.essentials.Mailer;
import com.elmakers.mine.bukkit.heroes.HeroesManager;
import com.elmakers.mine.bukkit.integration.BattleArenaManager;
import com.elmakers.mine.bukkit.integration.GenericMetadataNPCSupplier;
import com.elmakers.mine.bukkit.integration.GeyserManager;
import com.elmakers.mine.bukkit.integration.LegacyLibsDisguiseManager;
import com.elmakers.mine.bukkit.integration.LibsDisguiseManager;
import com.elmakers.mine.bukkit.integration.LightAPIManager;
import com.elmakers.mine.bukkit.integration.LogBlockManager;
import com.elmakers.mine.bukkit.integration.ModernLibsDisguiseManager;
import com.elmakers.mine.bukkit.integration.NPCSupplierSet;
import com.elmakers.mine.bukkit.integration.PlaceholderAPIManager;
import com.elmakers.mine.bukkit.integration.SkillAPIManager;
import com.elmakers.mine.bukkit.integration.SkriptManager;
import com.elmakers.mine.bukkit.integration.VaultController;
import com.elmakers.mine.bukkit.integration.mobarena.MobArenaManager;
import com.elmakers.mine.bukkit.kit.KitController;
import com.elmakers.mine.bukkit.kit.MagicKit;
import com.elmakers.mine.bukkit.magic.command.MagicTabExecutor;
import com.elmakers.mine.bukkit.magic.command.MagicTraitCommandExecutor;
import com.elmakers.mine.bukkit.magic.command.WandCommandExecutor;
import com.elmakers.mine.bukkit.magic.command.config.FetchExampleRunnable;
import com.elmakers.mine.bukkit.magic.command.config.UpdateAllExamplesCallback;
import com.elmakers.mine.bukkit.magic.listener.AnvilController;
import com.elmakers.mine.bukkit.magic.listener.BlockController;
import com.elmakers.mine.bukkit.magic.listener.CraftingController;
import com.elmakers.mine.bukkit.magic.listener.EnchantingController;
import com.elmakers.mine.bukkit.magic.listener.EntityController;
import com.elmakers.mine.bukkit.magic.listener.ErrorNotifier;
import com.elmakers.mine.bukkit.magic.listener.ExplosionController;
import com.elmakers.mine.bukkit.magic.listener.HangingController;
import com.elmakers.mine.bukkit.magic.listener.InventoryController;
import com.elmakers.mine.bukkit.magic.listener.ItemController;
import com.elmakers.mine.bukkit.magic.listener.JumpController;
import com.elmakers.mine.bukkit.magic.listener.MinigamesListener;
import com.elmakers.mine.bukkit.magic.listener.MobController;
import com.elmakers.mine.bukkit.magic.listener.MobController2;
import com.elmakers.mine.bukkit.magic.listener.PlayerController;
import com.elmakers.mine.bukkit.magic.listener.WildStackerListener;
import com.elmakers.mine.bukkit.maps.MapController;
import com.elmakers.mine.bukkit.materials.MaterialSets;
import com.elmakers.mine.bukkit.materials.SimpleMaterialSetManager;
import com.elmakers.mine.bukkit.npc.MagicNPC;
import com.elmakers.mine.bukkit.protection.AJParkourManager;
import com.elmakers.mine.bukkit.protection.CitadelManager;
import com.elmakers.mine.bukkit.protection.DeadSoulsManager;
import com.elmakers.mine.bukkit.protection.FactionsManager;
import com.elmakers.mine.bukkit.protection.GriefPreventionManager;
import com.elmakers.mine.bukkit.protection.LocketteManager;
import com.elmakers.mine.bukkit.protection.MultiverseManager;
import com.elmakers.mine.bukkit.protection.NCPManager;
import com.elmakers.mine.bukkit.protection.PreciousStonesManager;
import com.elmakers.mine.bukkit.protection.ProtectionManager;
import com.elmakers.mine.bukkit.protection.PvPManagerManager;
import com.elmakers.mine.bukkit.protection.RedProtectManager;
import com.elmakers.mine.bukkit.protection.ResidenceManager;
import com.elmakers.mine.bukkit.protection.TownyManager;
import com.elmakers.mine.bukkit.protection.WorldGuardManager;
import com.elmakers.mine.bukkit.requirements.RequirementsController;
import com.elmakers.mine.bukkit.resourcepack.ResourcePackManager;
import com.elmakers.mine.bukkit.spell.BaseSpell;
import com.elmakers.mine.bukkit.spell.SpellCategory;
import com.elmakers.mine.bukkit.tasks.ArmorUpdatedTask;
import com.elmakers.mine.bukkit.tasks.AutoSaveTask;
import com.elmakers.mine.bukkit.tasks.AutomataUpdateTask;
import com.elmakers.mine.bukkit.tasks.BatchUpdateTask;
import com.elmakers.mine.bukkit.tasks.ChangeServerTask;
import com.elmakers.mine.bukkit.tasks.ConfigCheckTask;
import com.elmakers.mine.bukkit.tasks.ConfigurationLoadTask;
import com.elmakers.mine.bukkit.tasks.DoMageLoadTask;
import com.elmakers.mine.bukkit.tasks.FinalizeIntegrationTask;
import com.elmakers.mine.bukkit.tasks.FinishGenericIntegrationTask;
import com.elmakers.mine.bukkit.tasks.LoadDataTask;
import com.elmakers.mine.bukkit.tasks.LogNotifyTask;
import com.elmakers.mine.bukkit.tasks.LogWatchdogTask;
import com.elmakers.mine.bukkit.tasks.MageQuitTask;
import com.elmakers.mine.bukkit.tasks.MageUpdateTask;
import com.elmakers.mine.bukkit.tasks.MigrateDataTask;
import com.elmakers.mine.bukkit.tasks.MigrationTask;
import com.elmakers.mine.bukkit.tasks.PostStartupLoadTask;
import com.elmakers.mine.bukkit.tasks.SaveDataTask;
import com.elmakers.mine.bukkit.tasks.SaveMageDataTask;
import com.elmakers.mine.bukkit.tasks.SaveMageTask;
import com.elmakers.mine.bukkit.tasks.UndoUpdateTask;
import com.elmakers.mine.bukkit.tasks.ValidateSpellsTask;
import com.elmakers.mine.bukkit.utility.CompatibilityUtils;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
import com.elmakers.mine.bukkit.utility.DeprecatedUtils;
import com.elmakers.mine.bukkit.utility.EntityMetadataUtils;
import com.elmakers.mine.bukkit.utility.HitboxUtils;
import com.elmakers.mine.bukkit.utility.InventoryUtils;
import com.elmakers.mine.bukkit.utility.LogMessage;
import com.elmakers.mine.bukkit.utility.MagicLogger;
import com.elmakers.mine.bukkit.utility.Messages;
import com.elmakers.mine.bukkit.utility.NMSUtils;
import com.elmakers.mine.bukkit.utility.SafetyUtils;
import com.elmakers.mine.bukkit.utility.SchematicUtils;
import com.elmakers.mine.bukkit.utility.SkinUtils;
import com.elmakers.mine.bukkit.utility.SkullLoadedCallback;
import com.elmakers.mine.bukkit.wand.LostWand;
import com.elmakers.mine.bukkit.wand.Wand;
import com.elmakers.mine.bukkit.wand.WandManaMode;
import com.elmakers.mine.bukkit.wand.WandMode;
import com.elmakers.mine.bukkit.wand.WandTemplate;
import com.elmakers.mine.bukkit.wand.WandUpgradePath;
import com.elmakers.mine.bukkit.warp.MagicWarp;
import com.elmakers.mine.bukkit.warp.WarpController;
import com.elmakers.mine.bukkit.world.MagicWorld;
import com.elmakers.mine.bukkit.world.WorldController;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import de.slikey.effectlib.math.EquationStore;
public class MagicController implements MageController {
private static final String BUILTIN_SPELL_CLASSPATH = "com.elmakers.mine.bukkit.spell.builtin";
private static final String LOST_WANDS_FILE = "lostwands";
private static final String WARPS_FILE = "warps";
private static final String SPELLS_DATA_FILE = "spells";
private static final String AUTOMATA_DATA_FILE = "automata";
private static final String NPC_DATA_FILE = "npcs";
private static final String URL_MAPS_FILE = "imagemaps";
private static final String DEFAULT_DATASTORE_PACKAGE = "com.elmakers.mine.bukkit.data";
private static final long MAGE_CACHE_EXPIRY = 10000;
private static final int MAX_WARNINGS = 10;
private static long LOG_WATCHDOG_TIMEOUT = 30000;
private static final int MAX_ERRORS = 10;
protected static Random random = new Random();
private final Set<String> builtinMageAttributes = ImmutableSet.of(
"health", "health_max", "target_health", "target_health_max",
"location_x", "location_y", "location_z",
"target_location_x", "target_location_y", "target_location_z",
"time", "moon",
"mana", "mana_max", "xp", "level", "bowpull", "bowpower", "damage", "damage_dealt",
"target_mana", "target_mana_max",
"fall_distance",
"air", "air_max", "target_air", "target_air_max",
"hunger", "target_hunger", "play_time"
);
private final Set<String> builtinAttributes = ImmutableSet.of(
"epoch",
// For interval parsing
"hours", "minutes", "seconds", "days", "weeks",
// Other constants
"pi"
);
private final Map<String, AutomatonTemplate> automatonTemplates = new HashMap<>();
private final Map<String, WandTemplate> wandTemplates = new HashMap<>();
private final Map<String, MageClassTemplate> mageClasses = new HashMap<>();
private final Map<String, ModifierTemplate> modifiers = new HashMap<>();
private final Map<String, SpellTemplate> spells = new HashMap<>();
private final Map<String, SpellTemplate> spellAliases = new HashMap<>();
private final Map<String, SpellData> templateDataMap = new HashMap<>();
private final Map<String, SpellCategory> categories = new HashMap<>();
private final Map<String, MagicAttribute> attributes = new HashMap<>();
private final Set<String> registeredAttributes = new HashSet<>();
private final Map<String, com.elmakers.mine.bukkit.magic.Mage> mages = Maps.newConcurrentMap();
private final Set<Mage> pendingConstruction = new HashSet<>();
private final PriorityQueue<UndoList> scheduledUndo = new PriorityQueue<>();
private final Map<String, WeakReference<Schematic>> schematics = new HashMap<>();
private final Map<String, Collection<EffectPlayer>> effects = new HashMap<>();
private final Map<Chunk, Integer> lockedChunks = new HashMap<>();
private final MagicLogger logger;
private final File configFolder;
private final File dataFolder;
private final File defaultsFolder;
private final Map<String, String> exampleKeyNames = new HashMap<>();
// Synchronization
private final Object saveLock = new Object();
private final SimpleMaterialSetManager materialSetManager = new SimpleMaterialSetManager();
private final Map<String, Integer> maxSpellLevels = new HashMap<>();
private final int undoTimeWindow = 6000;
private final Map<String, DamageType> damageTypes = new HashMap<>();
private final Map<Material, String> blockSkins = new HashMap<>();
private final Map<EntityType, String> mobSkins = new HashMap<>();
private final Map<EntityType, MaterialAndData> skullItems = new HashMap<>();
private final Map<EntityType, MaterialAndData> skullWallBlocks = new HashMap<>();
private final Map<EntityType, MaterialAndData> skullGroundBlocks = new HashMap<>();
private final Map<EntityType, Material> mobEggs = new HashMap<>();
private final int toggleMessageRange = 1024;
private final Material defaultMaterial = Material.DIRT;
private final Set<EntityType> undoEntityTypes = new HashSet<>();
private final Set<EntityType> friendlyEntityTypes = new HashSet<>();
private final Map<String, Currency> currencies = new HashMap<>();
private final Map<String, List<MagicNPC>> npcsByChunk = new HashMap<>();
private final Map<UUID, MagicNPC> npcsByEntity = new HashMap<>();
private final Map<UUID, MagicNPC> npcs = new HashMap<>();
private final Map<String, Map<Long, Automaton>> automata = new HashMap<>();
private final Map<Long, Automaton> activeAutomata = new HashMap<>();
private final Map<String, LostWand> lostWands = new HashMap<>();
private final Map<String, Set<String>> lostWandChunks = new HashMap<>();
private final Map<Long, Integer> lightBlocks = new HashMap<>();
private final Map<String, Integer> lightChunks = new HashMap<>();
private final boolean hasDynmap = false;
private final Messages messages = new Messages();
private final Set<String> resolvingKeys = new LinkedHashSet<>();
private final Map<String, MageData> mageDataPreCache = new ConcurrentHashMap<>();
private final FactionsManager factionsManager = new FactionsManager();
private final LocketteManager locketteManager = new LocketteManager();
private final WorldGuardManager worldGuardManager = new WorldGuardManager();
private final PvPManagerManager pvpManager = new PvPManagerManager();
private final MultiverseManager multiverseManager = new MultiverseManager();
private final PreciousStonesManager preciousStonesManager = new PreciousStonesManager();
private final TownyManager townyManager = new TownyManager();
private final GriefPreventionManager griefPreventionManager = new GriefPreventionManager();
private final NCPManager ncpManager = new NCPManager();
private final ProtectionManager protectionManager = new ProtectionManager();
private final Set<MagicProvider> externalProviders = new HashSet<>();
private final List<BlockBreakManager> blockBreakManagers = new ArrayList<>();
private final List<BlockBuildManager> blockBuildManagers = new ArrayList<>();
private final List<PVPManager> pvpManagers = new ArrayList<>();
private final List<CastPermissionManager> castManagers = new ArrayList<>();
private final List<AttributeProvider> attributeProviders = new ArrayList<>();
private final List<TeamProvider> teamProviders = new ArrayList<>();
private final List<EntityTargetingManager> targetingProviders = new ArrayList<>();
private final NPCSupplierSet npcSuppliers = new NPCSupplierSet();
private final Map<String, RequirementsProcessor> requirementProcessors = new HashMap<>();
private final Map<String, PlayerWarpManager> playerWarpManagers = new HashMap<>();
private final Map<Material, String> autoWands = new HashMap<>();
private final Map<String, String> builtinExternalExamples = new HashMap<>();
private MaterialAndData redstoneReplacement = new MaterialAndData(Material.OBSIDIAN);
private @Nonnull
MaterialSet buildingMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet indestructibleMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet restrictedMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet destructibleMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet interactibleMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet containerMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet wearableMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet meleeMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet climbableMaterials = MaterialSets.empty();
private @Nonnull
MaterialSet undoableMaterials = MaterialSets.wildcard();
private boolean backupInventories = true;
private int undoQueueDepth = 256;
private int pendingQueueDepth = 16;
private int undoMaxPersistSize = 0;
private boolean commitOnQuit = false;
private boolean saveNonPlayerMages = false;
private String defaultWandPath = "";
private WandMode defaultWandMode = WandMode.NONE;
private WandMode defaultBrushMode = WandMode.CHEST;
private boolean showMessages = true;
private boolean showCastMessages = false;
private String messagePrefix = "";
private String castMessagePrefix = "";
private boolean soundsEnabled = true;
private String welcomeWand = "";
private int messageThrottle = 0;
private boolean spellDroppingEnabled = false;
private boolean fillingEnabled = false;
private int maxFillLevel = 0;
private boolean essentialsSignsEnabled = false;
private boolean dynmapUpdate = true;
private boolean dynmapShowWands = true;
private boolean dynmapOnlyPlayerSpells = false;
private boolean dynmapShowSpells = true;
private boolean createWorldsEnabled = true;
private float maxDamagePowerMultiplier = 2.0f;
private float maxConstructionPowerMultiplier = 5.0f;
private float maxRadiusPowerMultiplier = 2.5f;
private float maxRadiusPowerMultiplierMax = 4.0f;
private float maxRangePowerMultiplier = 3.0f;
private float maxRangePowerMultiplierMax = 5.0f;
private float maxPower = 100.0f;
private float maxCostReduction = 0.5f;
private float maxCooldownReduction = 0.5f;
private int maxMana = 1000;
private int maxManaRegeneration = 100;
private double worthBase = 1;
private boolean spEnabled = true;
private boolean spEarnEnabled = true;
private boolean castCommandCostFree = false;
private boolean castCommandCooldownFree = false;
private float castCommandPowerMultiplier = 0.0f;
private boolean castConsoleCostFree = false;
private boolean castConsoleCooldownFree = false;
private float castConsolePowerMultiplier = 0.0f;
private float costReduction = 0.0f;
private float cooldownReduction = 0.0f;
private int autoUndo = 0;
private int autoSaveTaskId = 0;
private BukkitTask configCheckTask = null;
private BukkitTask logNotifyTask = null;
private boolean savePlayerData = true;
private boolean externalPlayerData = false;
private boolean asynchronousSaving = true;
private boolean debugEffectLib = false;
private WarpController warpController = null;
private KitController kitController = null;
private Collection<ConfigurationSection> materialColors = null;
private List<Object> materialVariants = null;
private ConfigurationSection blockItems = null;
private MageDataStore mageDataStore = null;
private MageDataStore migrateDataStore = null;
private MigrateDataTask migrateDataTask = null;
private BukkitTask logWatchdogTimer = null;
private MagicPlugin plugin = null;
private int automataUpdateFrequency = 1;
private int mageUpdateFrequency = 5;
private int workFrequency = 1;
private int undoFrequency = 10;
private int workPerUpdate = 5000;
private int logVerbosity = 0;
private boolean showCastHoloText = false;
private boolean showActivateHoloText = false;
private int castHoloTextRange = 0;
private int activateHoloTextRange = 0;
private boolean urlIconsEnabled = true;
private boolean legacyIconsEnabled = false;
private boolean autoSpellUpgradesEnabled = true;
private boolean autoPathUpgradesEnabled = true;
private boolean spellProgressionEnabled = true;
private boolean bypassBuildPermissions = false;
private boolean bypassBreakPermissions = false;
private boolean bypassPvpPermissions = false;
private boolean bypassFriendlyFire = false;
private boolean useScoreboardTeams = false;
private boolean defaultFriendly = true;
private boolean protectLocked = true;
private boolean bindOnGive = false;
private List<List<String>> permissionTeams = null;
private String extraSchematicFilePath = null;
private Mailer mailer = null;
private PhysicsHandler physicsHandler = null;
private List<ConfigurationSection> invalidNPCs = new ArrayList<>();
private List<ConfigurationSection> invalidAutomata = new ArrayList<>();
private int metricsLevel = 5;
private Metrics metrics = null;
private boolean hasEssentials = false;
private boolean hasCommandBook = false;
private String exampleDefaults = null;
private Collection<String> addExamples = null;
private boolean loaded = false;
private boolean shuttingDown = false;
private boolean dataLoaded = false;
private String defaultSkillIcon = "stick";
private boolean despawnMagicMobs = false;
private int skillInventoryRows = 6;
private boolean skillsUseHeroes = true;
private boolean useHeroesMana = true;
private boolean useHeroesParties = true;
private boolean useSkillAPIAllies = true;
private boolean useBattleArenaTeams = true;
private boolean skillsUsePermissions = false;
private boolean useWildStacker = true;
private String heroesSkillPrefix = "";
private String skillsSpell = "";
private boolean isFileLockingEnabled = false;
private int fileLoadDelay = 0;
private Mage reloadingMage = null;
private ResourcePackManager resourcePacks = null;
// Sub-Controllers
private CraftingController crafting = null;
private MobController mobs = null;
private MobController2 mobs2 = null;
private ItemController items = null;
private EnchantingController enchanting = null;
private AnvilController anvil = null;
private MapController maps = null;
private DynmapController dynmap = null;
private ElementalsController elementals = null;
private CitizensController citizens = null;
private BlockController blockController = null;
private HangingController hangingController = null;
private PlayerController playerController = null;
private EntityController entityController = null;
private InventoryController inventoryController = null;
private ExplosionController explosionController = null;
private JumpController jumpController = null;
private WorldController worldController = null;
private @Nonnull
MageIdentifier mageIdentifier = new MageIdentifier();
private boolean citizensEnabled = true;
private boolean logBlockEnabled = true;
private boolean libsDisguiseEnabled = true;
private boolean skillAPIEnabled = true;
private boolean useSkillAPIMana = false;
private boolean placeholdersEnabled = true;
private boolean lightAPIEnabled = true;
private boolean skriptEnabled = true;
private boolean vaultEnabled = true;
private ConfigurationSection residenceConfiguration = null;
private ConfigurationSection redProtectConfiguration = null;
private ConfigurationSection citadelConfiguration = null;
private ConfigurationSection mobArenaConfiguration = null;
private ConfigurationSection ajParkourConfiguration = null;
private boolean castConsoleFeedback = false;
private String editorURL = null;
private boolean reloadVerboseLogging = true;
private boolean hasShopkeepers = false;
private AJParkourManager ajParkourManager = null;
private CitadelManager citadelManager = null;
private ResidenceManager residenceManager = null;
private RedProtectManager redProtectManager = null;
private RequirementsController requirementsController = null;
private HeroesManager heroesManager = null;
private LibsDisguiseManager libsDisguiseManager = null;
private SkillAPIManager skillAPIManager = null;
private BattleArenaManager battleArenaManager = null;
private PlaceholderAPIManager placeholderAPIManager = null;
private LightAPIManager lightAPIManager = null;
private MobArenaManager mobArenaManager = null;
private LogBlockManager logBlockManager = null;
private EssentialsController essentialsController = null;
private DeadSoulsManager deadSoulsController = null;
private boolean loading = false;
private boolean showExampleInstructions = false;
private int disableSpawnReplacement = 0;
private SwingType swingType = SwingType.ANIMATE_IF_ADVENTURE;
private String blockExchangeCurrency = null;
private @Nonnull
MaterialSet offhandMaterials = MaterialSets.empty();
private GeyserManager geyserManager = null;
// Special constructor used for interrogation
public MagicController() {
configFolder = null;
dataFolder = null;
defaultsFolder = null;
this.logger = new MagicLogger(Logger.getLogger("Magic"));
this.materialSetManager.setLogger(logger);
}
public MagicController(final MagicPlugin plugin) {
this.plugin = plugin;
this.logger = new MagicLogger(plugin.getLogger());
resourcePacks = new ResourcePackManager(this);
configFolder = plugin.getDataFolder();
configFolder.mkdirs();
dataFolder = new File(configFolder, "data");
dataFolder.mkdirs();
defaultsFolder = new File(configFolder, "defaults");
defaultsFolder.mkdirs();
}
@Nullable
public static Spell loadSpell(String name, ConfigurationSection node, MageController controller) {
String className = node.getString("class");
if (className == null || className.equalsIgnoreCase("action") || className.equalsIgnoreCase("actionspell")) {
className = "com.elmakers.mine.bukkit.spell.ActionSpell";
} else if (className.indexOf('.') <= 0) {
className = BUILTIN_SPELL_CLASSPATH + "." + className;
}
Class<?> spellClass = null;
try {
spellClass = Class.forName(className);
} catch (Throwable ex) {
controller.getLogger().log(Level.WARNING, "Error loading spell: " + className, ex);
return null;
}
if (spellClass.getAnnotation(Deprecated.class) != null) {
controller.getLogger().warning("Spell " + name + " is using a deprecated spell class " + className + ". This will be removed in the future, please see the default configs for alternatives.");
}
Object newObject;
try {
newObject = spellClass.getDeclaredConstructor().newInstance();
} catch (Throwable ex) {
controller.getLogger().log(Level.WARNING, "Error loading spell: " + className, ex);
return null;
}
if (newObject == null || !(newObject instanceof MageSpell)) {
controller.getLogger().warning("Error loading spell: " + className + ", does it implement MageSpell?");
return null;
}
MageSpell newSpell = (MageSpell) newObject;
newSpell.initialize(controller);
newSpell.loadTemplate(name, node);
com.elmakers.mine.bukkit.api.spell.SpellCategory category = newSpell.getCategory();
if (category instanceof SpellCategory) {
((SpellCategory) category).addSpellTemplate(newSpell);
}
return newSpell;
}
public boolean registerNMSBindings() {
if (!NMSUtils.initialize(getLogger())) {
return false;
}
SkinUtils.initialize(plugin);
EntityMetadataUtils.initialize(plugin);
return true;
}
public void onPlayerJump(Player player) {
if (climbableMaterials.testBlock(player.getLocation().getBlock())) {
return;
}
Mage mage = getRegisteredMage(player);
if (mage != null) {
mage.trigger("jump");
}
}
@Nullable
@Override
public com.elmakers.mine.bukkit.magic.Mage getRegisteredMage(String mageId) {
checkNotNull(mageId);
if (!loaded || shuttingDown) {
return null;
}
return mages.get(mageId);
}
@Nullable
public com.elmakers.mine.bukkit.magic.Mage getRegisteredMage(@Nonnull CommandSender commandSender) {
checkNotNull(commandSender);
if (commandSender instanceof Player) {
return getRegisteredMage((Player) commandSender);
}
String mageId = mageIdentifier.fromCommandSender(commandSender);
return getRegisteredMage(mageId);
}
@Nullable
@Override
public com.elmakers.mine.bukkit.magic.Mage getRegisteredMage(@Nonnull Entity entity) {
checkNotNull(entity);
String id = mageIdentifier.fromEntity(entity);
return mages.get(id);
}
@Nonnull
protected com.elmakers.mine.bukkit.magic.Mage getMageFromEntity(
@Nonnull Entity entity, @Nullable CommandSender commandSender) {
checkNotNull(entity);
String id = mageIdentifier.fromEntity(entity);
return getMage(id, commandSender, entity);
}
@Override
public com.elmakers.mine.bukkit.magic.Mage getAutomaton(String mageId, String mageName) {
checkNotNull(mageId);
checkNotNull(mageName);
com.elmakers.mine.bukkit.magic.Mage mage = getMage(mageId, mageName, null, null);
mage.setIsAutomaton(true);
return mage;
}
@Override
public com.elmakers.mine.bukkit.magic.Mage getMage(String mageId, String mageName) {
checkNotNull(mageId);
checkNotNull(mageName);
return getMage(mageId, mageName, null, null);
}
@Nonnull
public com.elmakers.mine.bukkit.magic.Mage getMage(
@Nonnull String mageId,
@Nullable CommandSender commandSender, @Nullable Entity entity) {
checkState(
commandSender != null || entity != null,
"Need to provide either an entity or a command sender for a non-automata mage.");
return getMage(mageId, null, commandSender, entity);
}
@Nonnull
@Override
public com.elmakers.mine.bukkit.magic.Mage getMage(@Nonnull Player player) {
checkNotNull(player);
return getMageFromEntity(player, player);
}
@Nonnull
@Override
public com.elmakers.mine.bukkit.magic.Mage getMage(@Nonnull Entity entity) {
checkNotNull(entity);
CommandSender commandSender = (entity instanceof Player) ? (Player) entity : null;
return getMageFromEntity(entity, commandSender);
}
@Nonnull
@Override
public com.elmakers.mine.bukkit.magic.Mage getMage(@Nonnull CommandSender commandSender) {
checkNotNull(commandSender);
if (commandSender instanceof Player) {
return getMage((Player) commandSender);
}
String mageId = mageIdentifier.fromCommandSender(commandSender);
return getMage(mageId, commandSender, null);
}
@Nonnull
protected com.elmakers.mine.bukkit.magic.Mage getMage(
@Nonnull String mageId, @Nullable String mageName,
@Nullable CommandSender commandSender, @Nullable Entity entity)
throws PluginNotLoadedException, NoSuchMageException {
checkNotNull(mageId);
if (!loaded) {
if (entity instanceof Player) {
getLogger().warning("Player data request for " + mageId + " (" + commandSender.getName() + ") failed, plugin not loaded yet");
}
throw new PluginNotLoadedException();
}
com.elmakers.mine.bukkit.magic.Mage apiMage = null;
if (!mages.containsKey(mageId)) {
if (shuttingDown) {
if (entity instanceof Player) {
getLogger().warning("Player data request for " + mageId + " (" + commandSender.getName() + ") failed, plugin is shutting down");
}
throw new PluginNotLoadedException();
}
if (entity instanceof Player && !((Player) entity).isOnline() && !isNPC(entity)) {
getLogger().warning("Player data for " + mageId + " (" + entity.getName() + ") loaded while offline!");
Thread.dumpStack();
// This will cause some really bad things to happen if using file locking, so we're going to just skip it.
if (isFileLockingEnabled) {
getLogger().warning("Returning dummy Mage to avoid locking issues");
return new com.elmakers.mine.bukkit.magic.Mage(mageId, this);
}
}
final com.elmakers.mine.bukkit.magic.Mage mage = new com.elmakers.mine.bukkit.magic.Mage(mageId, this);
mages.put(mageId, mage);
mage.setName(mageName);
mage.setCommandSender(commandSender);
mage.setEntity(entity);
if (entity instanceof Player) {
mage.setPlayer((Player) entity);
}
// Check for existing data file
// For now we only do async loads for Players
boolean isPlayer = (entity instanceof Player);
isPlayer = (isPlayer && !isNPC(entity));
if (savePlayerData && mageDataStore != null) {
if (isPlayer) {
mage.setLoading(true);
plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new DoMageLoadTask(this, mage), fileLoadDelay * 20 / 1000);
} else if (saveNonPlayerMages) {
info("Loading mage data for " + mage.getName() + " (" + mage.getId() + ") synchronously");
doLoadData(mage);
} else {
mage.load(null);
}
} else if (externalPlayerData && (isPlayer || saveNonPlayerMages)) {
mage.setLoading(true);
} else {
mage.load(null);
}
apiMage = mage;
} else {
apiMage = mages.get(mageId);
com.elmakers.mine.bukkit.magic.Mage mage = apiMage;
// In case of rapid relog, this mage may have been marked for removal already
mage.setUnloading(false);
// Re-set mage properties
mage.setName(mageName);
mage.setCommandSender(commandSender);
mage.setEntity(entity);
if (entity instanceof Player) {
mage.setPlayer((Player) entity);
}
}
if (apiMage == null) {
getLogger().warning("getMage returning null mage for " + entity + " and " + commandSender);
throw new NoSuchMageException(mageId);
}
return apiMage;
}
public void doSynchronizedLoadData(Mage mage) {
synchronized (saveLock) {
info("Loading mage data for " + mage.getName() + " (" + mage.getId() + ") at " + System.currentTimeMillis());
doLoadData(mage);
}
}
private void doLoadData(Mage mage) {
getMageData(mage.getId(), new MageDataCallback() {
@Override
public void run(MageData data) {
mage.load(data);
}
});
}
public void onPreLogin(AsyncPlayerPreLoginEvent event) {
String id = mageIdentifier.fromPreLogin(event);
Iterator<Map.Entry<String, MageData>> it = mageDataPreCache.entrySet().iterator();
while (it.hasNext()) {
MageData data = it.next().getValue();
if (data.getId().equals(id)) continue;
if (data.getCachedTimestamp() < System.currentTimeMillis() - MAGE_CACHE_EXPIRY) {
it.remove();
info("Removed expired pre-login mage data cache for id " + data.getId());
}
}
if (mageDataPreCache.containsKey(id)) return;
getMageData(id, new MageDataCallback() {
@Override
public void run(MageData data) {
if (data != null) {
info("Cached preloaded mage data cache for id " + data.getId());
mageDataPreCache.put(id, data);
}
}
});
}
private void getMageData(String id, MageDataCallback callback) {
synchronized (saveLock) {
MageData cached = mageDataPreCache.get(id);
if (cached != null) {
info("Loaded preloaded mage data from cache for id " + id);
mageDataPreCache.remove(id);
callback.run(cached);
return;
}
if (mageDataStore == null) {
callback.run(null);
return;
}
try {
mageDataStore.load(id, new MageDataCallback() {
@Override
public void run(MageData data) {
if (data == null && migrateDataStore != null) {
info(" Checking migration data store for mage data for " + id);
migrateDataStore.load(id, new MageDataCallback() {
@Override
public void run(MageData data) {
if (data != null) {
migrateDataStore.migrate(id);
info(" Auto-migrated mage data for " + id + " on load");
}
callback.run(data);
info(" Finished Loading mage data for " + id + " from migration store at " + System.currentTimeMillis());
}
});
} else {
callback.run(data);
info(" Finished Loading mage data for " + id + " at " + System.currentTimeMillis());
}
}
});
} catch (Exception ex) {
getLogger().warning("Failed to load mage data for " + id);
ex.printStackTrace();
}
}
}
public void finalizeMageLoad(com.elmakers.mine.bukkit.magic.Mage mage) {
if (mage.isPlayer()) {
kitController.onJoin(mage);
}
}
@Override
public MagicKit getKit(String key) {
return kitController.getKit(key);
}
@Override
public Set<String> getKitKeys() {
return kitController.getKitKeys();
}
@Nonnull
@Override
public Mage getConsoleMage() {
return getMage(plugin.getServer().getConsoleSender());
}
public void log(String message) {
info(message, 0);
}
@Override
public void info(String message) {
info(message, 1);
}
@Override
public void info(String message, int verbosity) {
if (loading && !reloadVerboseLogging) {
return;
}
if (logVerbosity >= verbosity) {
getLogger().info(message);
}
}
public float getMaxDamagePowerMultiplier() {
return maxDamagePowerMultiplier;
}
public float getMaxConstructionPowerMultiplier() {
return maxConstructionPowerMultiplier;
}
public float getMaxRadiusPowerMultiplier() {
return maxRadiusPowerMultiplier;
}
public float getMaxRadiusPowerMultiplierMax() {
return maxRadiusPowerMultiplierMax;
}
public float getMaxRangePowerMultiplier() {
return maxRangePowerMultiplier;
}
public float getMaxRangePowerMultiplierMax() {
return maxRangePowerMultiplierMax;
}
public int getAutoUndoInterval() {
return autoUndo;
}
public float getMaxPower() {
return maxPower;
}
public double getMaxDamageReduction(String protectionType) {
DamageType damageType = damageTypes.get(protectionType);
return damageType == null ? 0 : damageType.getMaxReduction();
}
public double getMaxAttackMultiplier(String protectionType) {
DamageType damageType = damageTypes.get(protectionType);
return damageType == null ? 1 : damageType.getMaxAttackMultiplier();
}
public double getMaxDefendMultiplier(String protectionType) {
DamageType damageType = damageTypes.get(protectionType);
return damageType == null ? 1 : damageType.getMaxDefendMultiplier();
}
@Override
public @Nonnull
Set<String> getDamageTypes() {
return damageTypes.keySet();
}
@Override
public @Nonnull
Set<String> getAttributes() {
return registeredAttributes;
}
@Override
public @Nonnull
Set<String> getInternalAttributes() {
return attributes.keySet();
}
public float getMaxCostReduction() {
return maxCostReduction;
}
public float getMaxCooldownReduction() {
return maxCooldownReduction;
}
public int getMaxMana() {
return maxMana;
}
public int getMaxManaRegeneration() {
return maxManaRegeneration;
}
@Override
public double getWorthBase() {
return worthBase;
}
@Override
public double getWorthXP() {
return getCurrency("xp").getWorth();
}
@Override
public double getWorthSkillPoints() {
return getCurrency("sp").getWorth();
}
/*
* Undo system
*/
@Nullable
@Override
public ItemStack getWorthItem() {
Currency itemCurrency = getCurrency("item");
if (itemCurrency == null || !(itemCurrency instanceof ItemCurrency)) {
return null;
}
return ((ItemCurrency) itemCurrency).getItem();
}
@Override
public double getWorthItemAmount() {
return getCurrency("item").getWorth();
}
/*
* Random utility functions
*/
@Override
@Nullable
public Currency getCurrency(String key) {
return currencies.get(key);
}
@Override
@Nonnull
public Set<String> getCurrencyKeys() {
return currencies.keySet();
}
public int getUndoQueueDepth() {
return undoQueueDepth;
}
public int getPendingQueueDepth() {
return pendingQueueDepth;
}
@Override
public String getMessagePrefix() {
return messagePrefix;
}
public String getCastMessagePrefix() {
return castMessagePrefix;
}
public boolean showCastMessages() {
return showCastMessages;
}
public boolean showMessages() {
return showMessages;
}
@Override
public boolean soundsEnabled() {
return soundsEnabled;
}
public boolean fillWands() {
return fillingEnabled;
}
@Override
public int getMaxWandFillLevel() {
return maxFillLevel;
}
/*
* Get the log, if you need to debug or log errors.
*/
@Override
public MagicLogger getLogger() {
return logger;
}
public boolean isIndestructible(Location location) {
return isIndestructible(location.getBlock());
}
public boolean isIndestructible(Block block) {
return indestructibleMaterials.testBlock(block);
}
public boolean isDestructible(Block block) {
return destructibleMaterials.testBlock(block);
}
@Override
public boolean isUndoable(Material material) {
return undoableMaterials.testMaterial(material);
}
@Deprecated // Material
protected boolean isRestricted(Material material) {
return restrictedMaterials.testMaterial(material);
}
protected boolean isRestricted(Material material, @Nullable Short data) {
if (restrictedMaterials.testMaterial(material)) {
// Fast path
return true;
}
MaterialAndData materialAndData = new MaterialAndData(material, data);
return restrictedMaterials.testMaterialAndData(materialAndData);
}
public boolean hasBuildPermission(Player player, Location location) {
return hasBuildPermission(player, location.getBlock());
}
public boolean hasBuildPermission(Player player, Block block) {
// Check all protection plugins
if (bypassBuildPermissions) return true;
if (player != null && player.hasPermission("Magic.bypass_build")) return true;
if (hasBypassPermission(player)) return true;
boolean allowed = true;
for (BlockBuildManager manager : blockBuildManagers) {
if (!manager.hasBuildPermission(player, block)) {
allowed = false;
break;
}
}
return allowed;
}
public boolean hasBreakPermission(Player player, Block block) {
// This is the same has hasBuildPermission for everything but Towny!
if (bypassBreakPermissions) return true;
if (player != null && player.hasPermission("Magic.bypass_break")) return true;
if (hasBypassPermission(player)) return true;
boolean allowed = true;
for (BlockBreakManager manager : blockBreakManagers) {
if (!manager.hasBreakPermission(player, block)) {
allowed = false;
break;
}
}
return allowed;
}
@Override
public boolean isExitAllowed(Player player, Location location) {
if (location == null) return true;
return worldGuardManager.isExitAllowed(player, location);
}
@Override
public boolean isPVPAllowed(Player player, Location location) {
if (location == null) return true;
if (bypassPvpPermissions) return true;
if (player != null && player.hasPermission("Magic.bypass_pvp")) return true;
boolean allowed = true;
for (PVPManager manager : pvpManagers) {
if (!manager.isPVPAllowed(player, location)) {
allowed = false;
break;
}
}
return allowed;
}
public void clearCache() {
schematics.clear();
for (Mage mage : mages.values()) {
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
((com.elmakers.mine.bukkit.magic.Mage) mage).clearCache();
}
}
maps.clearCache();
maps.resetAll();
}
/*
* Internal functions - don't call these, or really anything below here.
*/
@Nullable
protected InputStream findSchematic(String schematicName, String extension) {
InputStream inputSchematic;
try {
// Check extra path first
File extraSchematicFile = null;
File magicSchematicFolder = new File(plugin.getDataFolder(), "schematics");
if (magicSchematicFolder.exists()) {
extraSchematicFile = new File(magicSchematicFolder, schematicName + "." + extension);
info("Checking for schematic: " + extraSchematicFile.getAbsolutePath(), 2);
if (!extraSchematicFile.exists()) {
extraSchematicFile = null;
}
}
if (extraSchematicFile == null && extraSchematicFilePath != null && extraSchematicFilePath.length() > 0) {
File schematicFolder = new File(configFolder, "../" + extraSchematicFilePath);
if (schematicFolder.exists()) {
extraSchematicFile = new File(schematicFolder, schematicName + "." + extension);
info("Checking for external schematic: " + extraSchematicFile.getAbsolutePath(), 2);
}
}
if (extraSchematicFile != null && extraSchematicFile.exists()) {
inputSchematic = new FileInputStream(extraSchematicFile);
info("Loading file: " + extraSchematicFile.getAbsolutePath());
} else {
String fileName = schematicName + "." + extension;
inputSchematic = plugin.getResource("schematics/" + fileName);
info("Loading builtin schematic: " + fileName);
}
if (inputSchematic == null) {
throw new FileNotFoundException();
}
} catch (Exception ignored) {
inputSchematic = null;
}
return inputSchematic;
}
@Nullable
@Override
public Schematic loadSchematic(String schematicName) {
if (schematicName == null || schematicName.length() == 0) return null;
if (schematics.containsKey(schematicName)) {
WeakReference<Schematic> schematic = schematics.get(schematicName);
if (schematic != null) {
Schematic cached = schematic.get();
if (cached != null) {
return cached;
}
}
}
// Look for new schematic format first
if (CompatibilityUtils.hasBlockDataSupport()) {
final InputStream inputSchematic = findSchematic(schematicName, "schem");
if (inputSchematic != null) {
com.elmakers.mine.bukkit.block.Schematic schematic = new com.elmakers.mine.bukkit.block.Schematic(this);
schematics.put(schematicName, new WeakReference<>(schematic));
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
SchematicUtils.loadSchematic(inputSchematic, schematic, getLogger());
info("Finished loading schematic");
} catch (Exception ex) {
ex.printStackTrace();
}
});
return schematic;
}
}
// Look for legacy schematic
final InputStream legacySchematic = findSchematic(schematicName, "schematic");
if (legacySchematic == null) {
return null;
}
LegacySchematic schematic = new LegacySchematic(this);
schematics.put(schematicName, new WeakReference<>(schematic));
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
try {
SchematicUtils.loadLegacySchematic(legacySchematic, schematic);
info("Finished loading schematic");
} catch (Exception ex) {
ex.printStackTrace();
}
});
if (schematic == null) {
getLogger().warning("Could not load schematic: " + schematicName);
}
return schematic;
}
@Override
public Collection<String> getBrushKeys() {
List<String> names = new ArrayList<>();
Material[] materials = Material.values();
for (Material material : materials) {
// Only show blocks
if (material.isBlock()) {
names.add(material.name().toLowerCase());
}
}
// Add special materials
for (String brushName : MaterialBrush.SPECIAL_MATERIAL_KEYS) {
names.add(brushName.toLowerCase());
}
// Add schematics
Collection<String> schematics = getSchematicNames();
for (String schematic : schematics) {
names.add("schematic:" + schematic);
}
return names;
}
public Collection<String> getSchematicNames() {
Collection<String> schematicNames = new ArrayList<>();
// Load internal schematics.. this may be a bit expensive.
try {
CodeSource codeSource = MagicTabExecutor.class.getProtectionDomain().getCodeSource();
if (codeSource != null) {
URL jar = codeSource.getLocation();
try (ZipInputStream zip = new ZipInputStream(jar.openStream())) {
ZipEntry entry = zip.getNextEntry();
while (entry != null) {
String name = entry.getName();
if (name.startsWith("schematics/") && (name.endsWith(".schem") || name.endsWith(".schematic"))) {
String schematicName = name
.replace(".schematic", "")
.replace(".schem", "")
.replace("schematics/", "");
schematicNames.add(schematicName);
}
entry = zip.getNextEntry();
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
// Load external schematics
try {
// Check extra path first
if (extraSchematicFilePath != null && extraSchematicFilePath.length() > 0) {
File schematicFolder = new File(configFolder, "../" + extraSchematicFilePath);
for (File schematicFile : schematicFolder.listFiles()) {
if (schematicFile.getName().endsWith(".schematic") || schematicFile.getName().endsWith(".schem")) {
String schematicName = schematicFile.getName()
.replace(".schematic", "")
.replace(".schem", "");
schematicNames.add(schematicName);
}
}
}
} catch (Exception ignored) {
}
return schematicNames;
}
/*
* Saving and loading
*/
public void initialize() {
warpController = new WarpController(this);
kitController = new KitController(this);
crafting = new CraftingController(this);
mobs = new MobController(this);
items = new ItemController(this);
enchanting = new EnchantingController(this);
anvil = new AnvilController(this);
blockController = new BlockController(this);
hangingController = new HangingController(this);
entityController = new EntityController(this);
playerController = new PlayerController(this);
inventoryController = new InventoryController(this);
explosionController = new ExplosionController(this);
requirementsController = new RequirementsController(this);
worldController = new WorldController(this);
if (NMSUtils.hasStatistics()) {
jumpController = new JumpController(this);
}
if (NMSUtils.hasEntityTransformEvent()) {
mobs2 = new MobController2(this);
}
File examplesFolder = new File(getPlugin().getDataFolder(), "examples");
examplesFolder.mkdirs();
File urlMapFile = getDataFile(URL_MAPS_FILE);
File imageCache = new File(dataFolder, "imagemapcache");
imageCache.mkdirs();
maps = new MapController(plugin, urlMapFile, imageCache);
// Initialize EffectLib.
if (com.elmakers.mine.bukkit.effect.EffectPlayer.initialize(plugin, getLogger())) {
getLogger().info("EffectLib initialized");
} else {
getLogger().warning("Failed to initialize EffectLib");
}
// Pre-create schematic folder
File magicSchematicFolder = new File(plugin.getDataFolder(), "schematics");
magicSchematicFolder.mkdirs();
// One-time migration of enchanting.yml
File legacyPathConfig = new File(configFolder, "enchanting.yml");
File pathConfig = new File(configFolder, "paths.yml");
if (!pathConfig.exists() && legacyPathConfig.exists()) {
getLogger().info("Renaming enchanting.yml to paths.yml, please update paths.yml from now on");
legacyPathConfig.renameTo(pathConfig);
}
load();
resourcePacks.startResourcePackChecks();
}
protected void postLoadIntegration() {
if (mobArenaManager != null) {
mobArenaManager.loaded();
}
}
public void processUndo() {
long now = System.currentTimeMillis();
while (scheduledUndo.size() > 0) {
UndoList undo = scheduledUndo.peek();
if (now < undo.getScheduledTime()) {
break;
}
scheduledUndo.poll();
undo.undoScheduled();
}
}
public void processPendingBatches() {
int remainingWork = workPerUpdate;
if (pendingConstruction.isEmpty()) return;
List<Mage> pending = new ArrayList<>(pendingConstruction);
while (remainingWork > 0 && !pending.isEmpty()) {
int workPerMage = Math.max(10, remainingWork / pending.size());
for (Iterator<Mage> iterator = pending.iterator(); iterator.hasNext(); ) {
Mage apiMage = iterator.next();
if (apiMage instanceof com.elmakers.mine.bukkit.magic.Mage) {
com.elmakers.mine.bukkit.magic.Mage mage = ((com.elmakers.mine.bukkit.magic.Mage) apiMage);
int workPerformed = mage.processPendingBatches(workPerMage);
if (!mage.hasPendingBatches()) {
iterator.remove();
pendingConstruction.remove(mage);
} else if (workPerformed < workPerMage) {
// Wait for next tick to process this action further since it's sleeping
iterator.remove();
}
remainingWork -= workPerformed;
}
}
}
}
protected void activateMetrics() {
// Activate Metrics
final MagicController controller = this;
metrics = null;
if (metricsLevel > 0) {
try {
metrics = new Metrics(plugin);
if (metricsLevel > 1) {
metrics.addCustomChart(new Metrics.MultiLineChart("Plugin Integration") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap) {
valueMap.put("Essentials", controller.hasEssentials ? 1 : 0);
valueMap.put("Dynmap", controller.hasDynmap ? 1 : 0);
valueMap.put("Factions", controller.factionsManager.isEnabled() ? 1 : 0);
valueMap.put("WorldGuard", controller.worldGuardManager.isEnabled() ? 1 : 0);
valueMap.put("Elementals", controller.elementalsEnabled() ? 1 : 0);
valueMap.put("Citizens", controller.citizens != null ? 1 : 0);
valueMap.put("CommandBook", controller.hasCommandBook ? 1 : 0);
valueMap.put("PvpManager", controller.pvpManager.isEnabled() ? 1 : 0);
valueMap.put("Multiverse-Core", controller.multiverseManager.isEnabled() ? 1 : 0);
valueMap.put("Towny", controller.townyManager.isEnabled() ? 1 : 0);
valueMap.put("GriefPrevention", controller.griefPreventionManager.isEnabled() ? 1 : 0);
valueMap.put("PreciousStones", controller.preciousStonesManager.isEnabled() ? 1 : 0);
valueMap.put("Lockette", controller.locketteManager.isEnabled() ? 1 : 0);
valueMap.put("NoCheatPlus", controller.ncpManager.isEnabled() ? 1 : 0);
return valueMap;
}
});
metrics.addCustomChart(new Metrics.MultiLineChart("Features Enabled") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap) {
valueMap.put("Crafting", controller.crafting.isEnabled() ? 1 : 0);
valueMap.put("Enchanting", controller.enchanting.isEnabled() ? 1 : 0);
valueMap.put("SP", controller.isSPEnabled() ? 1 : 0);
return valueMap;
}
});
}
if (metricsLevel > 2) {
metrics.addCustomChart(new Metrics.MultiLineChart("Total Casts by Category") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap) {
for (final SpellCategory category : categories.values()) {
valueMap.put(category.getName(), (int) category.getCastCount());
}
return valueMap;
}
});
}
if (metricsLevel > 3) {
metrics.addCustomChart(new Metrics.MultiLineChart("Total Casts") {
@Override
public HashMap<String, Integer> getValues(HashMap<String, Integer> valueMap) {
for (final SpellTemplate spell : spells.values()) {
if (!(spell instanceof Spell)) continue;
valueMap.put(spell.getName(), (int) spell.getCastCount());
}
return valueMap;
}
});
}
getLogger().info("Activated BStats");
} catch (Exception ex) {
getLogger().warning("Failed to load BStats: " + ex.getMessage());
}
}
}
protected void registerListeners() {
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(crafting, plugin);
pm.registerEvents(mobs, plugin);
pm.registerEvents(enchanting, plugin);
pm.registerEvents(anvil, plugin);
pm.registerEvents(blockController, plugin);
pm.registerEvents(hangingController, plugin);
pm.registerEvents(entityController, plugin);
pm.registerEvents(playerController, plugin);
pm.registerEvents(inventoryController, plugin);
pm.registerEvents(explosionController, plugin);
if (jumpController != null) {
pm.registerEvents(jumpController, plugin);
}
if (mobs2 != null) {
pm.registerEvents(mobs2, plugin);
}
worldController.registerEvents();
}
public Collection<Mage> getPending() {
return pendingConstruction;
}
public Collection<UndoList> getPendingUndo() {
return scheduledUndo;
}
@Nullable
public UndoList getPendingUndo(Location location) {
return com.elmakers.mine.bukkit.block.UndoList.getUndoList(location);
}
protected void addPending(Mage mage) {
pendingConstruction.add(mage);
}
public boolean removeMarker(String id, String group) {
boolean removed = false;
if (dynmap != null) {
return dynmap.removeMarker(id, group);
}
return removed;
}
public boolean addMarker(String id, String icon, String group, String title, Location location, String description) {
if (location == null || location.getWorld() == null) return false;
return addMarker(id, icon, group, title, location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ(), description);
}
public boolean addMarker(String id, String icon, String group, String title, String world, int x, int y, int z, String description) {
boolean created = false;
if (dynmap != null) {
created = dynmap.addMarker(id, icon, group, title, world, x, y, z, description);
}
return created;
}
@Nullable
public Collection<String> getMarkerIcons() {
if (dynmap == null) {
return null;
}
return dynmap.getIcons();
}
@Nullable
public Collection<String> getMarkerSets() {
if (dynmap == null) {
return null;
}
return dynmap.getSets();
}
@Override
public File getConfigFolder() {
return configFolder;
}
@Override
public File getDataFolder() {
return dataFolder;
}
protected File getDataFile(String fileName) {
return new File(dataFolder, fileName + ".yml");
}
@Nullable
protected ConfigurationSection loadDataFile(String fileName) {
File dataFile = getDataFile(fileName);
if (!dataFile.exists()) {
return null;
}
Configuration configuration = YamlConfiguration.loadConfiguration(dataFile);
return configuration;
}
protected YamlDataFile createDataFile(String fileName) {
return createDataFile(fileName, true);
}
protected YamlDataFile createDataFile(String fileName, boolean checkBackupSize) {
File dataFile = new File(dataFolder, fileName + ".yml");
YamlDataFile configuration = new YamlDataFile(getLogger(), dataFile, checkBackupSize);
return configuration;
}
protected void notify(CommandSender sender, String message) {
if (sender != null) {
sender.sendMessage(message);
}
for (Player player : Bukkit.getOnlinePlayers()) {
if (player != sender && player.hasPermission("Magic.notify")) {
player.sendMessage(message);
}
}
}
public void finalizeLoad(ConfigurationLoadTask loader, CommandSender sender) {
if (!loader.isSuccessful()) {
notify(sender, ChatColor.RED + "An error occurred reloading configurations, please check server logs!");
// Check for initial load failure on startup
if (!loaded) {
getLogger().severe("*** An error occurred while loading configurations ***");
getLogger().severe("*** Magic will be disabled until the next restart ***");
getLogger().severe("*** Please check the errors above, fix configs ***");
getLogger().severe("*** And restart the server ***");
getLogger().warning("");
getLogger().warning("Note that if you start the server with working configs and");
getLogger().warning("Then use /magic load to test changes, Magic won't break");
getLogger().warning("if there are config issues.");
PluginManager pm = plugin.getServer().getPluginManager();
pm.registerEvents(new ErrorNotifier(), plugin);
}
loading = false;
resetLoading(sender);
return;
}
// Clear some cache stuff... mainly this is for debugging/testing.
schematics.clear();
// Clear the equation store to flush out any equations that failed to parse
EquationStore.clear();
// Map aliases of loaded external examples
exampleKeyNames.clear();
exampleKeyNames.putAll(loader.getExampleKeyNames());
// Process loaded data
exampleDefaults = loader.getExampleDefaults();
addExamples = loader.getAddExamples();
// Main configuration
logger.setContext("config");
loadProperties(sender, loader.getMainConfiguration());
// Configurations that don't rely on any external integrations
logger.setContext("messages");
messages.load(loader.getMessages());
processMessages();
logger.setContext("materials");
loadMaterials(loader.getMaterials());
// Load worlds now, we're still in load=STARTUP time
logger.setContext("worlds");
loadWorlds(loader.getWorlds());
logger.setContext(null);
log("Loaded " + worldController.getCount() + " customized worlds");
// We'll need to delay everything else by one tick to let integrating plugins have a chance to load.
if (!loaded) {
// Some first-time registration that's safe to do at startup
activateMetrics();
registerListeners();
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new FinalizeIntegrationTask(this), 1);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new PostStartupLoadTask(this, loader, sender), 2);
} else {
finalizePostStartupLoad(loader, sender);
}
}
public void finalizePostStartupLoad(ConfigurationLoadTask loader, CommandSender sender) {
// Finalize integrations, we only do this one time at startup.
logger.setContext("integration");
// Register currencies and other preload integrations
registerPreLoad(loader.getMainConfiguration());
log("Registered currencies: " + StringUtils.join(currencies.keySet(), ","));
// Load custom attributes, do this prior to loadAttributes
logger.setContext("attributes");
loadAttributes(loader.getAttributes());
logger.setContext(null);
log("Loaded " + attributes.size() + " attributes");
// Do this before spell loading in case of attribute or requirement providers
logger.setContext("integration");
registerManagers();
logger.setContext("effects");
loadEffects(loader.getEffects());
logger.setContext(null);
log("Loaded " + effects.size() + " effect lists");
logger.setContext("items");
items.load(loader.getItems());
logger.setContext(null);
log("Loaded " + items.getCount() + " items");
logger.setContext("wands");
loadWandTemplates(loader.getWands());
logger.setContext(null);
log("Loaded " + getWandTemplates().size() + " wands");
logger.setContext("spells");
loadSpells(sender, loader.getSpells());
logger.setContext(null);
log("Loaded " + spells.size() + " spells");
logger.setContext("kits");
kitController.load(loader.getKits());
logger.setContext(null);
log("Loaded " + kitController.getCount() + " kits");
logger.setContext("classes");
loadMageClasses(loader.getClasses());
logger.setContext(null);
log("Loaded " + mageClasses.size() + " classes");
logger.setContext("modifiers");
loadModifiers(loader.getModifiers());
logger.setContext(null);
log("Loaded " + modifiers.size() + " classes");
logger.setContext("paths");
loadPaths(loader.getPaths());
logger.setContext(null);
log("Loaded " + getPathCount() + " progression paths");
logger.setContext("mobs");
loadMobs(loader.getMobs());
logger.setContext(null);
log("Loaded " + mobs.getCount() + " mob templates");
logger.setContext("automata");
loadAutomatonTemplates(loader.getAutomata());
logger.setContext(null);
log("Loaded " + automatonTemplates.size() + " automata templates");
logger.setContext("crafting");
crafting.load(loader.getCrafting());
// Register crafting recipes
crafting.register(this, plugin);
MagicRecipe.FIRST_REGISTER = false;
logger.setContext(null);
log("Loaded " + crafting.getCount() + " crafting recipes");
if (!loaded) {
postLoadIntegration();
}
// Notify plugins that we've finished loading.
logger.setContext(null);
LoadEvent loadEvent = new LoadEvent(this);
Bukkit.getPluginManager().callEvent(loadEvent);
loaded = true;
loading = false;
// Activate/load any active player Mages
Collection<? extends Player> allPlayers = plugin.getServer().getOnlinePlayers();
for (Player player : allPlayers) {
getMage(player);
}
if (!(sender instanceof ConsoleCommandSender)) {
getLogger().info("Finished loading configuration");
}
if (sender != null && logger.isCapturing() && isLoaded()) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new ValidateSpellsTask(this, sender));
} else {
resetLoading(sender);
notify(sender, ChatColor.AQUA + "Magic " + ChatColor.DARK_AQUA + "configuration reloaded.");
}
if (reloadingMage != null) {
Player player = reloadingMage.getPlayer();
if (!player.hasPermission("Magic.notify")) {
player.sendMessage(ChatColor.AQUA + "Spells reloaded.");
}
reloadingMage.deactivate();
reloadingMage.checkWand();
reloadingMage = null;
}
if (showExampleInstructions) {
showExampleInstructions = false;
showExampleInstructions(sender);
}
Bukkit.getScheduler().runTaskLater(plugin, new MigrationTask(this), 20 * 5);
}
private void processMessages() {
BaseMagicCurrency.formatter = new DecimalFormat(messages.get("numbers.decimal", "#,###.00"));
BaseMagicCurrency.intFormatter = new DecimalFormat(messages.get("numbers.integer", "#,###"));
}
private void registerManagers() {
// Cast Managers
if (worldGuardManager.isEnabled()) castManagers.add(worldGuardManager);
if (preciousStonesManager.isEnabled()) castManagers.add(preciousStonesManager);
if (redProtectManager != null && redProtectManager.isFlagsEnabled()) castManagers.add(redProtectManager);
// Entity Targeting Managers
if (preciousStonesManager.isEnabled()) targetingProviders.add(preciousStonesManager);
if (townyManager.isEnabled()) targetingProviders.add(townyManager);
if (residenceManager != null) targetingProviders.add(residenceManager);
if (redProtectManager != null) targetingProviders.add(redProtectManager);
// PVP Managers
if (worldGuardManager.isEnabled()) pvpManagers.add(worldGuardManager);
if (pvpManager.isEnabled()) pvpManagers.add(pvpManager);
if (multiverseManager.isEnabled()) pvpManagers.add(multiverseManager);
if (preciousStonesManager.isEnabled()) pvpManagers.add(preciousStonesManager);
if (townyManager.isEnabled()) pvpManagers.add(townyManager);
if (griefPreventionManager.isEnabled()) pvpManagers.add(griefPreventionManager);
if (factionsManager.isEnabled()) pvpManagers.add(factionsManager);
if (residenceManager != null) pvpManagers.add(residenceManager);
if (redProtectManager != null) pvpManagers.add(redProtectManager);
// Build Managers
if (worldGuardManager.isEnabled()) blockBuildManagers.add(worldGuardManager);
if (factionsManager.isEnabled()) blockBuildManagers.add(factionsManager);
if (locketteManager.isEnabled()) blockBuildManagers.add(locketteManager);
if (preciousStonesManager.isEnabled()) blockBuildManagers.add(preciousStonesManager);
if (townyManager.isEnabled()) blockBuildManagers.add(townyManager);
if (griefPreventionManager.isEnabled()) blockBuildManagers.add(griefPreventionManager);
if (mobArenaManager != null && mobArenaManager.isProtected()) blockBuildManagers.add(mobArenaManager);
if (residenceManager != null) blockBuildManagers.add(residenceManager);
if (redProtectManager != null) blockBuildManagers.add(redProtectManager);
// Break Managers
if (worldGuardManager.isEnabled()) blockBreakManagers.add(worldGuardManager);
if (factionsManager.isEnabled()) blockBreakManagers.add(factionsManager);
if (locketteManager.isEnabled()) blockBreakManagers.add(locketteManager);
if (preciousStonesManager.isEnabled()) blockBreakManagers.add(preciousStonesManager);
if (townyManager.isEnabled()) blockBreakManagers.add(townyManager);
if (griefPreventionManager.isEnabled()) blockBreakManagers.add(griefPreventionManager);
if (mobArenaManager != null && mobArenaManager.isProtected()) blockBreakManagers.add(mobArenaManager);
if (citadelManager != null) blockBreakManagers.add(citadelManager);
if (residenceManager != null) blockBreakManagers.add(residenceManager);
if (redProtectManager != null) blockBreakManagers.add(redProtectManager);
// Attribute providers
if (skillAPIManager != null) {
attributeProviders.add(skillAPIManager);
}
if (heroesManager != null) {
attributeProviders.add(heroesManager);
}
// We should be done adding attributes now
finalizeAttributes();
// Requirements providers
if (skillAPIManager != null) {
requirementProcessors.put("skillapi", skillAPIManager);
}
// Team providers
if (heroesManager != null && useHeroesParties) {
teamProviders.add(heroesManager);
}
if (skillAPIManager != null && useSkillAPIAllies) {
teamProviders.add(skillAPIManager);
}
if (useScoreboardTeams) {
teamProviders.add(new ScoreboardTeamProvider());
}
if (permissionTeams != null && !permissionTeams.isEmpty()) {
teamProviders.add(new PermissionsTeamProvider(permissionTeams));
}
if (factionsManager != null) {
teamProviders.add(factionsManager);
}
if (battleArenaManager != null && useBattleArenaTeams) {
teamProviders.add(battleArenaManager);
}
// Player warp providers
if (preciousStonesManager != null && preciousStonesManager.isEnabled()) {
playerWarpManagers.put("fields", preciousStonesManager);
}
if (redProtectManager != null) {
playerWarpManagers.put("redprotect", redProtectManager);
}
if (residenceManager != null) {
playerWarpManagers.put("residence", residenceManager);
}
Runnable genericIntegrationTask = new FinishGenericIntegrationTask(this);
// Delay loading generic integration by one tick since we can't add depends: for these plugins
if (!loaded) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, genericIntegrationTask, 1);
} else {
genericIntegrationTask.run();
}
}
public void finishGenericIntegration() {
protectionManager.check();
if (protectionManager.isEnabled()) {
blockBreakManagers.add(protectionManager);
blockBuildManagers.add(protectionManager);
}
}
public void showExampleInstructions(CommandSender sender) {
Mage mage = getMage(sender);
List<String> instructions = new ArrayList<>();
for (String example : getLoadedExamples()) {
String exampleKey = exampleKeyNames.get(example);
if (exampleKey == null || exampleKey.isEmpty()) {
exampleKey = example;
}
String exampleInstructions = messages.get("examples." + exampleKey + ".instructions", "");
if (exampleInstructions != null && !exampleInstructions.isEmpty()) {
instructions.add(exampleInstructions);
}
}
if (!instructions.isEmpty()) {
mage.sendMessage(messages.get("examples.instructions_header"));
for (String exampleInstructions : instructions) {
mage.sendMessage(exampleInstructions);
}
mage.sendMessage(messages.get("examples.instructions_footer"));
}
}
private int getPathCount() {
return WandUpgradePath.getPathKeys().size();
}
private void loadPaths(ConfigurationSection pathConfiguration) {
WandUpgradePath.loadPaths(this, pathConfiguration);
}
private void loadAttributes(ConfigurationSection attributeConfiguration) {
Set<String> keys = attributeConfiguration.getKeys(false);
attributes.clear();
for (String key : keys) {
logger.setContext("attribute." + key);
MagicAttribute attribute = new MagicAttribute(key, attributeConfiguration.getConfigurationSection(key));
attributes.put(key, attribute);
}
}
private void loadAutomatonTemplates(ConfigurationSection automataConfiguration) {
Set<String> keys = automataConfiguration.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
automatonTemplates.clear();
for (String key : keys) {
logger.setContext("automata." + key);
ConfigurationSection config = resolveConfiguration(key, automataConfiguration, templateConfigurations);
if (!ConfigurationUtils.isEnabled(config)) continue;
config = MagicConfiguration.getKeyed(this, config, "automaton", key);
AutomatonTemplate template = new AutomatonTemplate(this, key, config);
automatonTemplates.put(key, template);
}
// Update existing automata
for (Automaton active : activeAutomata.values()) {
active.pause();
}
for (Map<Long, Automaton> chunk : automata.values()) {
for (Automaton automaton : chunk.values()) {
automaton.reload();
}
}
for (Automaton active : activeAutomata.values()) {
active.resume();
}
}
public boolean isAutomataTemplate(@Nonnull String key) {
return automatonTemplates.containsKey(key);
}
@Nonnull
@Override
public Collection<String> getAutomatonTemplateKeys() {
return automatonTemplates.keySet();
}
@Nonnull
public Collection<Automaton> getActiveAutomata() {
return activeAutomata.values();
}
public Automaton getActiveAutomaton(long id) {
return activeAutomata.get(id);
}
public Collection<Automaton> getAutomata() {
List<Automaton> list = new ArrayList<>();
for (Map<Long, Automaton> chunk : automata.values()) {
list.addAll(chunk.values());
}
return list;
}
public Collection<Mage> getAutomataMages() {
Collection<Mage> all = new ArrayList<>();
for (Mage mage : mages.values()) {
if (mage.isAutomaton()) {
all.add(mage);
}
}
return all;
}
public boolean isActive(@Nonnull Automaton automaton) {
return activeAutomata.containsKey(automaton.getId());
}
@Nullable
public Automaton getAutomatonAt(@Nonnull Location location) {
String chunkId = getChunkKey(location);
if (chunkId == null) {
return null;
}
Map<Long, Automaton> restoreChunk = automata.get(chunkId);
if (restoreChunk == null) {
return null;
}
long blockId = BlockData.getBlockId(location);
return restoreChunk.get(blockId);
}
public boolean checkAutomatonBreak(Block block) {
Automaton automaton = getAutomatonAt(block.getLocation());
if (automaton != null && automaton.removeWhenBroken()) {
unregisterAutomaton(automaton);
return true;
}
return false;
}
@Nullable
public AutomatonTemplate getAutomatonTemplate(String key) {
return automatonTemplates.get(key);
}
private void loadEffects(ConfigurationSection effectsNode) {
effects.clear();
effectsNode = MagicConfiguration.getKeyed(this, effectsNode, "effects");
Collection<String> effectKeys = effectsNode.getKeys(false);
for (String effectKey : effectKeys) {
logger.setContext("effects." + effectKey);
effects.put(effectKey, loadEffects(effectsNode, effectKey));
}
}
@Override
@Nullable
public Collection<EffectPlayer> loadEffects(ConfigurationSection configuration, String effectKey) {
return loadEffects(configuration, effectKey, null);
}
@Override
@Nullable
public Collection<EffectPlayer> loadEffects(ConfigurationSection configuration, String effectKey, String logContext) {
return loadEffects(configuration, effectKey, null, null);
}
@Override
@Nullable
public Collection<EffectPlayer> loadEffects(ConfigurationSection configuration, String effectKey, String logContext, ConfigurationSection parameterMap) {
if (configuration.isString(effectKey)) {
return getEffects(configuration.getString(effectKey));
}
return com.elmakers.mine.bukkit.effect.EffectPlayer.loadEffects(getPlugin(), configuration, effectKey, getLogger(), logContext, parameterMap);
}
public void resetLoading(CommandSender sender) {
synchronized (logger) {
com.elmakers.mine.bukkit.effect.EffectPlayer.debugEffects(debugEffectLib);
if (sender != null) {
List<LogMessage> errors = logger.getErrors();
List<LogMessage> warnings = logger.getWarnings();
if (!warnings.isEmpty()) {
if (warnings.size() == 1) {
sender.sendMessage(ChatColor.YELLOW + "WARNING: " + ChatColor.WHITE + warnings.get(0).getMessage());
} else {
sender.sendMessage(ChatColor.YELLOW + "WARNINGS: " + ChatColor.WHITE + warnings.size());
for (int i = 0; i < warnings.size() && i < MAX_WARNINGS; i++) {
sender.sendMessage(ChatColor.WHITE + " " + warnings.get(i).getMessage());
}
if (warnings.size() > MAX_WARNINGS) {
sender.sendMessage(ChatColor.GRAY + " ...");
}
}
}
if (!errors.isEmpty()) {
if (errors.size() == 1) {
sender.sendMessage(ChatColor.RED + "ERROR: " + ChatColor.WHITE + errors.get(0).getMessage());
} else {
sender.sendMessage(ChatColor.RED + "ERRORS: " + ChatColor.WHITE + errors.size());
for (int i = 0; i < errors.size() && i < MAX_ERRORS; i++) {
sender.sendMessage(ChatColor.WHITE + " " + errors.get(i).getMessage());
}
if (errors.size() > MAX_ERRORS) {
sender.sendMessage(ChatColor.GRAY + " ...");
}
}
}
if (warnings.isEmpty() && errors.isEmpty()) {
sender.sendMessage(ChatColor.GREEN + "Finished loading, No issues found!");
} else {
if (!errors.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Finished loading " + ChatColor.DARK_RED + "with errors");
} else {
sender.sendMessage(ChatColor.GOLD + "Finished loading " + ChatColor.YELLOW + "with warnings");
}
}
}
logger.enableCapture(false);
if (logWatchdogTimer != null) {
logWatchdogTimer.cancel();
logWatchdogTimer = null;
}
}
}
@Override
public void loadConfigurationQuietly(CommandSender sender) {
loadConfiguration(sender, false, false);
}
public void loadConfiguration() {
loadConfiguration(null);
}
public void loadConfiguration(CommandSender sender) {
if (sender != null && !loaded) {
getLogger().warning("Can't reload configuration, Magic did not start up properly. Please restart your server.");
return;
}
loadConfiguration(sender, false);
}
public void loadConfiguration(CommandSender sender, boolean forceSynchronous) {
loadConfiguration(sender, forceSynchronous, true);
}
public void loadConfiguration(CommandSender sender, boolean forceSynchronous, boolean verboseLogging) {
if (!plugin.isEnabled()) return;
if (sender != null) {
synchronized (logger) {
com.elmakers.mine.bukkit.effect.EffectPlayer.debugEffects(true);
logger.enableCapture(true);
if (logWatchdogTimer != null) {
logWatchdogTimer.cancel();
}
logWatchdogTimer = plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new LogWatchdogTask(this, sender), LOG_WATCHDOG_TIMEOUT / 50);
sender.sendMessage(ChatColor.DARK_AQUA + "Please wait while the configuration is reloaded and validated");
}
}
reloadVerboseLogging = verboseLogging;
loading = true;
ConfigurationLoadTask loadTask = new ConfigurationLoadTask(this, sender);
loadTask.setVerbose(verboseLogging);
if (loaded && !forceSynchronous) {
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, loadTask);
} else {
loadTask.runNow();
}
}
@Override
public void updateConfiguration(CommandSender sender) {
updateExternalExamples(sender);
}
public void loadConfigurationExamples(CommandSender sender) {
showExampleInstructions = true;
loadConfiguration(sender, false, false);
}
protected void loadSpellData() {
try {
ConfigurationSection configNode = loadDataFile(SPELLS_DATA_FILE);
if (configNode == null) return;
Set<String> keys = configNode.getKeys(false);
for (String key : keys) {
ConfigurationSection node = configNode.getConfigurationSection(key);
SpellKey spellKey = new SpellKey(key);
SpellData templateData = templateDataMap.get(spellKey.getBaseKey());
if (templateData == null) {
templateData = new SpellData(spellKey.getBaseKey());
templateDataMap.put(templateData.getKey().getBaseKey(), templateData);
}
templateData.setCastCount(templateData.getCastCount() + node.getLong("cast_count", 0));
templateData.setLastCast(Math.max(templateData.getLastCast(), node.getLong("last_cast", 0)));
}
} catch (Exception ex) {
getLogger().warning("Failed to load spell metrics");
}
}
public void load() {
loadConfiguration();
loadData();
}
protected void loadData() {
loadSpellData();
Bukkit.getScheduler().runTaskLater(plugin, new LoadDataTask(this), 2);
}
public void finishLoadData() {
if (!loaded) {
getLogger().info("Magic did not load properly, skipping data load");
return;
}
loadSpellData();
loadLostWands();
loadAutomata();
loadNPCs();
// Load URL Map Data
try {
maps.resetAll();
maps.loadConfiguration();
} catch (Exception ex) {
ex.printStackTrace();
}
ConfigurationSection warps = loadDataFile(WARPS_FILE);
if (warps != null) {
warpController.load(warps);
info("Loaded " + warpController.getCustomWarps().size() + " warps");
}
getLogger().info("Finished loading data.");
dataLoaded = true;
}
public void migratePlayerData(CommandSender sender) {
if (migrateDataTask == null) {
if (migrateDataStore != null) {
migrateDataTask = new MigrateDataTask(this, mageDataStore, migrateDataStore, sender);
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, migrateDataTask);
} else {
sender.sendMessage(ChatColor.RED + "You must first configure 'migrate_data_store' in config.yml");
}
} else {
sender.sendMessage(ChatColor.YELLOW + "Data migration is already in progress");
}
}
public void finishMigratingPlayerData() {
migrateDataTask = null;
}
public void checkForMigration() {
checkForMigration(plugin.getServer().getConsoleSender());
}
public void checkForMigration(CommandSender sender) {
if (migrateDataStore != null) {
Collection<String> ids = migrateDataStore.getAllIds();
if (ids.isEmpty()) {
sender.sendMessage(ChatColor.RED + "Migration is complete, please remove migrate_data_store from config.yml");
} else {
sender.sendMessage(ChatColor.YELLOW + "Please use the command 'magic migrate' to migrate player data");
}
}
}
protected void loadLostWands() {
try {
ConfigurationSection lostWandConfiguration = loadDataFile(LOST_WANDS_FILE);
if (lostWandConfiguration != null) {
Set<String> wandIds = lostWandConfiguration.getKeys(false);
for (String wandId : wandIds) {
if (wandId == null || wandId.length() == 0) continue;
LostWand lostWand = new LostWand(wandId, lostWandConfiguration.getConfigurationSection(wandId));
if (!lostWand.isValid()) {
getLogger().info("Skipped invalid entry in lostwands.yml file, entry will be deleted. The wand is really lost now!");
continue;
}
addLostWand(lostWand);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
info("Loaded " + lostWands.size() + " lost wands");
}
public void checkNPCs(World world) {
if (this.invalidNPCs.isEmpty()) return;
List<ConfigurationSection> check = this.invalidNPCs;
this.invalidNPCs = new ArrayList<>();
int npcCount = loadNPCs(check);
if (npcCount > 0) {
info("Loaded " + npcCount + " NPCs in world " + world.getName());
for (Chunk chunk : world.getLoadedChunks()) {
restoreNPCs(chunk);
}
}
}
protected void loadNPCs() {
ConfigurationSection npcData = loadDataFile(NPC_DATA_FILE);
if (npcData != null) {
Collection<ConfigurationSection> list = ConfigurationUtils.getNodeList(npcData, "npcs");
int npcCount = loadNPCs(list);
if (npcCount > 0) {
for (World world : Bukkit.getWorlds()) {
for (Chunk chunk : world.getLoadedChunks()) {
restoreNPCs(chunk);
}
}
info("Loaded " + npcCount + " NPCs");
}
}
}
protected int loadNPCs(Collection<ConfigurationSection> list) {
int npcCount = 0;
try {
for (ConfigurationSection node : list) {
MagicNPC npc = new MagicNPC(this, node);
if (!npc.isValid()) {
invalidNPCs.add(node);
continue;
}
String chunkId = getChunkKey(npc.getLocation());
if (chunkId == null) {
invalidNPCs.add(node);
continue;
}
List<MagicNPC> restoreChunk = npcsByChunk.get(chunkId);
if (restoreChunk == null) {
restoreChunk = new ArrayList<>();
npcsByChunk.put(chunkId, restoreChunk);
}
npcCount++;
restoreChunk.add(npc);
npcs.put(npc.getId(), npc);
}
} catch (Exception ex) {
getLogger().log(Level.SEVERE, "Something went wrong loading NPC data", ex);
}
return npcCount;
}
public void checkAutomata(World world) {
if (this.invalidAutomata.isEmpty()) return;
List<ConfigurationSection> check = this.invalidAutomata;
this.invalidAutomata = new ArrayList<>();
int automataCount = loadAutomata(check);
if (automataCount > 0) {
info("Loaded " + automataCount + " automata in world " + world.getName());
for (Chunk chunk : world.getLoadedChunks()) {
resumeAutomata(chunk);
}
}
}
protected void loadAutomata() {
ConfigurationSection toggleBlockData = loadDataFile(AUTOMATA_DATA_FILE);
if (toggleBlockData != null) {
Collection<ConfigurationSection> list = ConfigurationUtils.getNodeList(toggleBlockData, "automata");
int automataCount = loadAutomata(list);
if (automataCount > 0) {
info("Loaded " + automataCount + " automata");
for (World world : Bukkit.getWorlds()) {
for (Chunk chunk : world.getLoadedChunks()) {
resumeAutomata(chunk);
}
}
}
}
}
protected int loadAutomata(Collection<ConfigurationSection> list) {
int automataCount = 0;
try {
for (ConfigurationSection node : list) {
Automaton automaton = new Automaton(this, node);
if (!automaton.isValid()) {
invalidAutomata.add(node);
continue;
}
String chunkId = getChunkKey(automaton.getLocation());
if (chunkId == null) {
invalidAutomata.add(node);
continue;
}
Map<Long, Automaton> restoreChunk = automata.get(chunkId);
if (restoreChunk == null) {
restoreChunk = new HashMap<>();
automata.put(chunkId, restoreChunk);
}
long id = automaton.getId();
Automaton existing = restoreChunk.get(id);
if (existing != null) {
getLogger().warning("Duplicate automata exist at " + automaton.getLocation() + ", one will be removed!");
continue;
}
automataCount++;
restoreChunk.put(id, automaton);
}
} catch (Exception ex) {
getLogger().log(Level.SEVERE, "Something went wrong loading automata data", ex);
}
return automataCount;
}
protected void saveWarps(Collection<YamlDataFile> stores) {
try {
YamlDataFile warpData = createDataFile(WARPS_FILE);
warpController.save(warpData);
stores.add(warpData);
} catch (Exception ex) {
ex.printStackTrace();
}
}
protected void saveAutomata(Collection<YamlDataFile> stores) {
try {
YamlDataFile automataData = createDataFile(AUTOMATA_DATA_FILE);
List<ConfigurationSection> nodes = new ArrayList<>();
for (Entry<String, Map<Long, Automaton>> toggleEntry : automata.entrySet()) {
Collection<Automaton> blocks = toggleEntry.getValue().values();
if (blocks.size() > 0) {
for (Automaton block : blocks) {
ConfigurationSection node = ConfigurationUtils.newConfigurationSection();
block.save(node);
nodes.add(node);
}
}
}
nodes.addAll(invalidAutomata);
automataData.set("automata", nodes);
stores.add(automataData);
} catch (Exception ex) {
ex.printStackTrace();
}
}
protected void saveNPCs(Collection<YamlDataFile> stores) {
try {
YamlDataFile npcData = createDataFile(NPC_DATA_FILE);
List<ConfigurationSection> nodes = new ArrayList<>();
for (MagicNPC npc : npcs.values()) {
ConfigurationSection node = ConfigurationUtils.newConfigurationSection();
npc.save(node);
nodes.add(node);
}
nodes.addAll(invalidNPCs);
npcData.set("npcs", nodes);
stores.add(npcData);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void moveAutomaton(Automaton automaton, Location location) {
unregisterAutomaton(automaton);
automaton.setLocation(location);
registerAutomaton(automaton);
}
public void registerAutomaton(Automaton automaton) {
String chunkId = getChunkKey(automaton.getLocation());
if (chunkId == null) return;
Map<Long, Automaton> chunkAutomata = automata.get(chunkId);
if (chunkAutomata == null) {
chunkAutomata = new HashMap<>();
automata.put(chunkId, chunkAutomata);
}
long id = automaton.getId();
chunkAutomata.put(id, automaton);
if (automaton.inActiveChunk()) {
activeAutomata.put(id, automaton);
automaton.resume();
}
}
public boolean unregisterAutomaton(Automaton automaton) {
boolean removed = false;
String chunkId = getChunkKey(automaton.getLocation());
long id = automaton.getId();
Map<Long, Automaton> chunkAutomata = automata.get(chunkId);
if (chunkAutomata != null) {
removed = chunkAutomata.remove(id) != null;
if (chunkAutomata.size() == 0) {
automata.remove(chunkId);
}
}
if (activeAutomata.remove(id) != null) {
automaton.pause();
}
automaton.removed();
return removed;
}
public void resumeAutomata(final Chunk chunk) {
String chunkKey = getChunkKey(chunk);
Map<Long, Automaton> chunkData = automata.get(chunkKey);
if (chunkData != null) {
activeAutomata.putAll(chunkData);
for (Automaton automaton : chunkData.values()) {
if (!automaton.isAlwaysActive()) {
automaton.resume();
}
}
}
}
public void pauseAutomata(final Chunk chunk) {
String chunkKey = getChunkKey(chunk);
Map<Long, Automaton> chunkData = automata.get(chunkKey);
if (chunkData != null) {
for (Automaton automaton : chunkData.values()) {
if (!automaton.isAlwaysActive()) {
automaton.pause();
activeAutomata.remove(automaton.getId());
}
}
}
}
public void tickAutomata() {
for (Automaton automaton : activeAutomata.values()) {
automaton.tick();
}
}
@Override
@Nullable
public Automaton addAutomaton(@Nonnull Location location, @Nonnull String templateKey, String creatorId, String creatorName, @Nullable ConfigurationSection parameters) {
if (!isAutomataTemplate(templateKey)) {
return null;
}
Automaton existing = getAutomatonAt(location);
if (existing != null) {
return null;
}
Automaton automaton = new Automaton(this, location, templateKey, creatorId, creatorName, parameters);
registerAutomaton(automaton);
return automaton;
}
protected void saveSpellData(Collection<YamlDataFile> stores) {
String lastKey = "";
try {
YamlDataFile spellsDataFile = createDataFile(SPELLS_DATA_FILE, false);
for (SpellData data : templateDataMap.values()) {
lastKey = data.getKey().getBaseKey();
ConfigurationSection spellNode = spellsDataFile.createSection(lastKey);
if (spellNode == null) {
getLogger().warning("Error saving spell data for " + lastKey);
continue;
}
spellNode.set("cast_count", data.getCastCount());
spellNode.set("last_cast", data.getLastCast());
}
stores.add(spellsDataFile);
} catch (Throwable ex) {
getLogger().warning("Error saving spell data for " + lastKey);
ex.printStackTrace();
}
}
protected void saveLostWands(Collection<YamlDataFile> stores) {
String lastKey = "";
try {
YamlDataFile lostWandsConfiguration = createDataFile(LOST_WANDS_FILE, false);
for (Entry<String, LostWand> wandEntry : lostWands.entrySet()) {
lastKey = wandEntry.getKey();
if (lastKey == null || lastKey.length() == 0) continue;
ConfigurationSection wandNode = lostWandsConfiguration.createSection(lastKey);
if (wandNode == null) {
getLogger().warning("Error saving lost wand data for " + lastKey);
continue;
}
if (!wandEntry.getValue().isValid()) {
getLogger().warning("Invalid lost and data for " + lastKey);
continue;
}
wandEntry.getValue().save(wandNode);
}
stores.add(lostWandsConfiguration);
} catch (Throwable ex) {
getLogger().warning("Error saving lost wand data for " + lastKey);
ex.printStackTrace();
}
}
@Nullable
protected String getChunkKey(Block block) {
return getChunkKey(block.getLocation());
}
@Nullable
protected String getChunkKey(Location location) {
World world = location.getWorld();
if (world == null) return null;
return world.getName() + "|" + (location.getBlockX() >> 4) + "," + (location.getBlockZ() >> 4);
}
protected String getChunkKey(Chunk chunk) {
return chunk.getWorld().getName() + "|" + chunk.getX() + "," + chunk.getZ();
}
public boolean addLostWand(LostWand lostWand) {
lostWands.put(lostWand.getId(), lostWand);
try {
String chunkKey = getChunkKey(lostWand.getLocation());
if (chunkKey == null) return false;
Set<String> chunkWands = lostWandChunks.get(chunkKey);
if (chunkWands == null) {
chunkWands = new HashSet<>();
lostWandChunks.put(chunkKey, chunkWands);
}
chunkWands.add(lostWand.getId());
if (dynmapShowWands) {
addLostWandMarker(lostWand);
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error loading lost wand id " + lostWand.getId() + " - is it in an unloaded world?", ex);
}
return true;
}
public boolean addLostWand(Wand wand, Location dropLocation) {
addLostWand(wand.makeLost(dropLocation));
return true;
}
public boolean removeLostWand(String wandId) {
if (wandId == null || wandId.length() == 0 || !lostWands.containsKey(wandId)) return false;
LostWand lostWand = lostWands.get(wandId);
lostWands.remove(wandId);
String chunkKey = getChunkKey(lostWand.getLocation());
if (chunkKey == null) return false;
Set<String> chunkWands = lostWandChunks.get(chunkKey);
if (chunkWands != null) {
chunkWands.remove(wandId);
if (chunkWands.size() == 0) {
lostWandChunks.remove(chunkKey);
}
}
if (dynmapShowWands) {
if (removeMarker("wand-" + wandId, "wands")) {
info("Wand removed from map");
}
}
return true;
}
public WandMode getDefaultWandMode() {
return defaultWandMode;
}
public WandMode getDefaultBrushMode() {
return defaultBrushMode;
}
public String getDefaultWandPath() {
return defaultWandPath;
}
protected void saveMageData(Collection<MageData> stores) {
try {
for (Entry<String, ? extends Mage> mageEntry : mages.entrySet()) {
Mage mage = mageEntry.getValue();
if (!mage.isPlayer() && !saveNonPlayerMages) {
continue;
}
if (!mage.isLoading()) {
MageData mageData = new MageData(mage.getId());
if (mage.save(mageData)) {
stores.add(mageData);
}
} else {
getLogger().info("Skipping save of mage, already loading: " + mage.getName());
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void save() {
save(false);
}
public void save(boolean asynchronous) {
if (!loaded || !dataLoaded) return;
maps.save(asynchronous);
final List<YamlDataFile> saveData = new ArrayList<>();
final List<MageData> saveMages = new ArrayList<>();
// Player data will be saved as each player quits on shutdown, so skip it here.
if (savePlayerData && mageDataStore != null && !shuttingDown) {
saveMageData(saveMages);
info("Saving " + saveMages.size() + " players");
}
saveSpellData(saveData);
saveLostWands(saveData);
saveAutomata(saveData);
saveWarps(saveData);
saveNPCs(saveData);
if (mageDataStore != null && !shuttingDown) {
if (asynchronous) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new SaveMageDataTask(this, saveMages));
} else {
persistMageData(saveMages);
}
}
if (asynchronous) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new SaveDataTask(this, saveData));
} else {
saveData(saveData);
}
SaveEvent saveEvent = new SaveEvent(asynchronous);
Bukkit.getPluginManager().callEvent(saveEvent);
}
public void saveData(Collection<YamlDataFile> saveData) {
synchronized (saveLock) {
for (YamlDataFile config : saveData) {
config.save();
}
info("Finished saving");
}
}
public void persistMageData(Collection<MageData> saveMages) {
synchronized (saveLock) {
for (MageData mageData : saveMages) {
mageDataStore.save(mageData, null, false);
}
}
}
public void addSpell(Spell variant) {
SpellTemplate conflict = spells.get(variant.getKey());
if (conflict != null) {
getLogger().log(Level.WARNING, "Duplicate spell key: '" + conflict.getKey() + "'");
} else {
SpellKey spellKey = variant.getSpellKey();
spells.put(spellKey.getKey(), variant);
if (spellKey.getLevel() > 1) {
Integer currentMax = maxSpellLevels.get(spellKey.getBaseKey());
if (currentMax == null || spellKey.getLevel() > currentMax) {
maxSpellLevels.put(spellKey.getBaseKey(), spellKey.getLevel());
}
}
SpellData data = templateDataMap.get(variant.getSpellKey().getBaseKey());
if (data == null) {
data = new SpellData(variant.getSpellKey().getBaseKey());
templateDataMap.put(variant.getSpellKey().getBaseKey(), data);
}
if (variant instanceof MageSpell) {
((MageSpell) variant).setSpellData(data);
}
String alias = variant.getAlias();
if (alias != null && alias.length() > 0) {
spellAliases.put(alias, variant);
}
}
}
@Nullable
@Override
public String getReflectiveMaterials(Mage mage, Location location) {
return worldGuardManager.getReflective(mage.getPlayer(), location);
}
@Nullable
@Override
public String getDestructibleMaterials(Mage mage, Location location) {
return worldGuardManager.getDestructible(mage.getPlayer(), location);
}
@Override
@Deprecated
public Set<Material> getDestructibleMaterials() {
return MaterialSets.toLegacyNN(destructibleMaterials);
}
@Nullable
@Override
public Set<String> getSpellOverrides(Mage mage, Location location) {
return worldGuardManager.getSpellOverrides(mage.getPlayer(), location);
}
public boolean isOffhandMaterial(ItemStack itemStack) {
return (!CompatibilityUtils.isEmpty(itemStack) && offhandMaterials.testItem(itemStack));
}
public boolean hasAddedExamples() {
return addExamples != null && addExamples.size() > 0;
}
@Nullable
private MageDataStore loadMageDataStore(ConfigurationSection configuration) {
MageDataStore mageDataStore = null;
String dataStoreClassName = configuration.getString("class");
if (!dataStoreClassName.contains(".")) {
dataStoreClassName = DEFAULT_DATASTORE_PACKAGE + "." + dataStoreClassName + "MageDataStore";
}
try {
Class<?> dataStoreClass = Class.forName(dataStoreClassName);
Object dataStore = dataStoreClass.getDeclaredConstructor().newInstance();
if (dataStore == null || !(dataStore instanceof MageDataStore)) {
getLogger().log(Level.WARNING, "Invalid player_data_store class " + dataStoreClassName + ", does it implement MageDataStore? Player data saving is disabled!");
mageDataStore = null;
} else {
mageDataStore = (MageDataStore) dataStore;
mageDataStore.initialize(this, configuration);
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Failed to create player_data_store class from " + dataStoreClassName, ex);
mageDataStore = null;
}
return mageDataStore;
}
protected void loadMobEggs(ConfigurationSection skins) {
mobEggs.clear();
Set<String> keys = skins.getKeys(false);
for (String key : keys) {
try {
EntityType entityType = EntityType.valueOf(key.toUpperCase());
Material material = getVersionedMaterial(skins, key);
if (material != null) {
mobEggs.put(entityType, material);
}
} catch (Exception ignore) {
}
}
}
protected void loadMobSkins(ConfigurationSection skins) {
mobSkins.clear();
Set<String> keys = skins.getKeys(false);
for (String key : keys) {
try {
EntityType entityType = EntityType.valueOf(key.toUpperCase());
mobSkins.put(entityType, skins.getString(key));
} catch (Exception ignore) {
}
}
}
protected void loadBlockSkins(ConfigurationSection skins) {
blockSkins.clear();
Set<String> keys = skins.getKeys(false);
for (String key : keys) {
try {
Material material = Material.getMaterial(key.toUpperCase());
blockSkins.put(material, skins.getString(key));
} catch (Exception ignore) {
}
}
}
@Nullable
protected Material getVersionedMaterial(ConfigurationSection configuration, String key) {
Material material = null;
Collection<String> candidates = ConfigurationUtils.getStringList(configuration, key);
for (String candidate : candidates) {
try {
material = Material.valueOf(candidate.toUpperCase());
break;
} catch (Exception ignore) {
}
}
return material;
}
@Nullable
protected MaterialAndData getVersionedMaterialAndData(ConfigurationSection configuration, String key) {
Collection<String> candidates = ConfigurationUtils.getStringList(configuration, key);
for (String candidate : candidates) {
MaterialAndData test = new MaterialAndData(candidate);
if (test.isValid()) {
return test;
}
}
return null;
}
protected void loadOtherMaterials(ConfigurationSection configuration) {
DefaultMaterials defaultMaterials = DefaultMaterials.getInstance();
defaultMaterials.setGroundSignBlock(getVersionedMaterial(configuration, "ground_sign_block"));
defaultMaterials.setWallSignBlock(getVersionedMaterial(configuration, "wall_sign_block"));
defaultMaterials.setFirework(getVersionedMaterial(configuration, "firework"));
defaultMaterials.setWallTorch(getVersionedMaterialAndData(configuration, "wall_torch"));
defaultMaterials.setRedstoneTorchOn(getVersionedMaterialAndData(configuration, "redstone_torch_on"));
defaultMaterials.setRedstoneTorchOff(getVersionedMaterialAndData(configuration, "redstone_torch_off"));
defaultMaterials.setRedstoneWallTorchOn(getVersionedMaterialAndData(configuration, "redstone_wall_torch_on"));
defaultMaterials.setRedstoneWallTorchOff(getVersionedMaterialAndData(configuration, "redstone_wall_torch_off"));
defaultMaterials.setMobSpawner(getVersionedMaterial(configuration, "mob_spawner"));
defaultMaterials.setNetherPortal(getVersionedMaterial(configuration, "nether_portal"));
defaultMaterials.setWriteableBook(getVersionedMaterial(configuration, "writable_book"));
defaultMaterials.setFilledMap(getVersionedMaterial(configuration, "filled_map"));
}
protected void loadSkulls(ConfigurationSection skulls) {
skullItems.clear();
skullGroundBlocks.clear();
skullWallBlocks.clear();
Set<String> keys = skulls.getKeys(false);
for (String key : keys) {
try {
ConfigurationSection types = skulls.getConfigurationSection(key);
EntityType entityType = EntityType.valueOf(key.toUpperCase());
MaterialAndData item = parseSkullCandidate(types, "item");
if (item != null) {
skullItems.put(entityType, item);
}
MaterialAndData floor = parseSkullCandidate(types, "ground");
if (item != null) {
skullGroundBlocks.put(entityType, floor);
}
MaterialAndData wall = parseSkullCandidate(types, "wall");
if (item != null) {
skullWallBlocks.put(entityType, wall);
}
} catch (Exception ignore) {
}
}
}
@Nullable
protected MaterialAndData parseSkullCandidate(ConfigurationSection section, String key) {
Collection<String> candidates = ConfigurationUtils.getStringList(section, key);
for (String candidate : candidates) {
MaterialAndData test = new MaterialAndData(candidate.trim());
if (test.isValid()) {
return test;
}
}
return null;
}
protected void populateEntityTypes(Set<EntityType> entityTypes, ConfigurationSection configuration, String key) {
entityTypes.clear();
if (configuration.contains(key)) {
Collection<String> typeStrings = ConfigurationUtils.getStringList(configuration, key);
for (String typeString : typeStrings) {
try {
entityTypes.add(EntityType.valueOf(typeString.toUpperCase()));
} catch (Exception ex) {
getLogger().warning("Unknown entity type: " + typeString + " in " + key);
}
}
}
}
protected void addCurrency(Currency currency) {
currencies.put(currency.getKey(), currency);
}
protected void registerPreLoad(ConfigurationSection configuration) {
// Setup custom providers
currencies.clear();
attributeProviders.clear();
teamProviders.clear();
requirementProcessors.clear();
// Set up Break/Build/PVP Managers
blockBreakManagers.clear();
blockBuildManagers.clear();
pvpManagers.clear();
castManagers.clear();
playerWarpManagers.clear();
targetingProviders.clear();
registeredAttributes.clear();
PreLoadEvent loadEvent = new PreLoadEvent(this);
Bukkit.getPluginManager().callEvent(loadEvent);
blockBreakManagers.addAll(loadEvent.getBlockBreakManagers());
blockBuildManagers.addAll(loadEvent.getBlockBuildManagers());
pvpManagers.addAll(loadEvent.getPVPManagers());
attributeProviders.addAll(loadEvent.getAttributeProviders());
teamProviders.addAll(loadEvent.getTeamProviders());
castManagers.addAll(loadEvent.getCastManagers());
targetingProviders.addAll(loadEvent.getTargetingManagers());
teamProviders.addAll(loadEvent.getTeamProviders());
playerWarpManagers.putAll(loadEvent.getWarpManagers());
// Use legacy currency configs if present
ConfigurationSection currencyConfiguration = configuration.getConfigurationSection("builtin_currency");
ConfigurationSection spSection = currencyConfiguration.getConfigurationSection("sp");
ConfigurationSection xpSection = currencyConfiguration.getConfigurationSection("xp");
String skillPointIcon = configuration.getString("sp_item_icon_url");
if (skillPointIcon != null) {
getLogger().warning("The config option sp_item_icon_url is deprecated, see builtin_currencies section");
spSection.set("icon", "skull:" + skillPointIcon);
}
if (configuration.contains("sp_max")) {
getLogger().warning("The config option sp_max is deprecated, see builtin_currencies section");
spSection.set("max", configuration.getInt("sp_max"));
}
if (configuration.contains("worth_sp")) {
getLogger().warning("The config option worth_sp is deprecated, see builtin_currencies section");
spSection.set("worth", configuration.getInt("worth_sp"));
}
if (configuration.contains("sp_default")) {
getLogger().warning("The config option sp_default is deprecated, see builtin_currencies section");
spSection.set("default", configuration.getInt("sp_default"));
}
if (configuration.contains("worth_xp")) {
getLogger().warning("The config option worth_xp is deprecated, see builtin_currencies section");
xpSection.set("worth", configuration.getDouble("worth_xp"));
}
ConfigurationSection legacyItemCurrency = configuration.getConfigurationSection("currency");
if (legacyItemCurrency != null) {
ConfigurationSection itemConfiguration = currencyConfiguration.getConfigurationSection("item");
getLogger().warning("The config section currency is deprecated, see builtin_currencies.item section");
Collection<String> worthItemKeys = legacyItemCurrency.getKeys(false);
for (String worthItemKey : worthItemKeys) {
ConfigurationSection currencyConfig = legacyItemCurrency.getConfigurationSection(worthItemKey);
if (!currencyConfig.getBoolean("enabled", true)) continue;
itemConfiguration.set("item", worthItemKey);
itemConfiguration.set("worth", currencyConfig.getDouble("worth"));
// This is kind of a hack, but makes it easier to override the default ... (heldover from legacy configs)
if (!worthItemKey.equals("emerald")) {
break;
}
}
}
// Load builtin default currencies
addCurrency(new ItemCurrency(this, currencyConfiguration.getConfigurationSection("item")));
addCurrency(new ManaCurrency(this, currencyConfiguration.getConfigurationSection("mana")));
addCurrency(new ExperienceCurrency(this, xpSection));
addCurrency(new HealthCurrency(this, currencyConfiguration.getConfigurationSection("health")));
addCurrency(new HungerCurrency(this, currencyConfiguration.getConfigurationSection("hunger")));
addCurrency(new LevelCurrency(this, currencyConfiguration.getConfigurationSection("levels")));
addCurrency(new SpellPointCurrency(this, spSection));
addCurrency(new VaultCurrency(this, currencyConfiguration.getConfigurationSection("currency")));
// Custom currencies can override the defaults
for (Currency currency : loadEvent.getCurrencies()) {
addCurrency(currency);
}
// Configured currencies override everything else
currencyConfiguration = configuration.getConfigurationSection("custom_currency");
Set<String> keys = currencyConfiguration.getKeys(false);
for (String key : keys) {
addCurrency(new CustomCurrency(this, key, currencyConfiguration.getConfigurationSection(key)));
}
// Re-register any providers previously registered by external plugins via register()
for (MagicProvider provider : externalProviders) {
register(provider);
}
// Don't allow overriding Magic requirements
checkMagicRequirements();
}
private void finalizeAttributes() {
registeredAttributes.addAll(builtinMageAttributes);
registeredAttributes.addAll(builtinAttributes);
registeredAttributes.addAll(this.attributes.keySet());
for (AttributeProvider provider : attributeProviders) {
Set<String> providerAttributes = provider.getAllAttributes();
if (providerAttributes != null) {
registeredAttributes.addAll(providerAttributes);
}
}
MageParameters.initializeAttributes(registeredAttributes);
MageParameters.setLogger(getLogger());
log("Registered attributes: " + registeredAttributes);
}
private void checkMagicRequirements() {
if (requirementProcessors.containsKey(Requirement.DEFAULT_TYPE)) {
getLogger().warning("Something tried to register requirements for the " + Requirement.DEFAULT_TYPE + " type, but that is Magic's job.");
}
requirementProcessors.put(Requirement.DEFAULT_TYPE, requirementsController);
}
@Override
public boolean register(MagicProvider provider) {
boolean added = false;
if (provider instanceof EntityTargetingManager) {
added = true;
targetingProviders.add((EntityTargetingManager) provider);
}
if (provider instanceof AttributeProvider) {
added = true;
AttributeProvider attributes = (AttributeProvider) provider;
attributeProviders.add(attributes);
if (!loading) {
Set<String> providerAttributes = attributes.getAllAttributes();
if (providerAttributes != null) {
registeredAttributes.addAll(providerAttributes);
MageParameters.initializeAttributes(registeredAttributes);
log("Registered additional attributes: " + providerAttributes);
}
}
}
if (provider instanceof TeamProvider) {
added = true;
teamProviders.add((TeamProvider) provider);
}
if (provider instanceof Currency) {
added = true;
addCurrency((Currency) provider);
}
if (provider instanceof RequirementsProvider) {
added = true;
RequirementsProvider requirements = (RequirementsProvider) provider;
requirementProcessors.put(requirements.getKey(), requirements);
if (!loading) {
checkMagicRequirements();
}
}
if (provider instanceof PlayerWarpProvider) {
added = true;
PlayerWarpProvider warp = (PlayerWarpProvider) provider;
playerWarpManagers.put(warp.getKey(), warp);
}
if (provider instanceof BlockBreakManager) {
added = true;
blockBreakManagers.add((BlockBreakManager) provider);
}
if (provider instanceof PVPManager) {
added = true;
pvpManagers.add((PVPManager) provider);
}
if (provider instanceof BlockBuildManager) {
added = true;
blockBuildManagers.add((BlockBuildManager) provider);
}
if (provider instanceof CastPermissionManager) {
added = true;
castManagers.add((CastPermissionManager) provider);
}
if (added && !loading) {
externalProviders.add(provider);
}
return added;
}
protected void clear() {
if (!loaded) {
return;
}
Collection<Mage> saveMages = new ArrayList<>(mages.values());
for (Mage mage : saveMages) {
playerQuit(mage);
}
mages.clear();
pendingConstruction.clear();
spells.clear();
loaded = false;
}
protected void unregisterPhysicsHandler(Listener listener) {
BlockPhysicsEvent.getHandlerList().unregister(listener);
physicsHandler = null;
}
@Override
public void scheduleUndo(UndoList undoList) {
undoList.setHasBeenScheduled();
scheduledUndo.add(undoList);
}
@Override
public void cancelScheduledUndo(UndoList undoList) {
scheduledUndo.remove(undoList);
}
public boolean hasWandPermission(Player player) {
return hasPermission(player, "Magic.wand.use");
}
public boolean hasWandPermission(Player player, Wand wand) {
if (hasBypassPermission(player)) return true;
if (wand.isSuperPowered() && !player.hasPermission("Magic.wand.use.powered")) return false;
if (wand.isSuperProtected() && !player.hasPermission("Magic.wand.use.protected")) return false;
String template = wand.getTemplateKey();
if (template != null && !template.isEmpty()) {
String pNode = "Magic.use." + template;
if (!hasPermission(player, pNode)) return false;
}
Location location = player.getLocation();
Boolean override = worldGuardManager.getWandPermission(player, wand, location);
return override == null || override;
}
@Override
public boolean hasCastPermission(CommandSender sender, SpellTemplate spell) {
if (sender == null) return true;
if (hasBypassPermission(sender)) {
return true;
}
String categoryPermission = spell.getCategoryPermissionNode();
if (categoryPermission != null && !hasPermission(sender, categoryPermission)) {
return false;
}
return hasPermission(sender, spell.getPermissionNode());
}
@Nullable
@Override
public Boolean getRegionCastPermission(Player player, SpellTemplate spell, Location location) {
if (hasBypassPermission(player)) return true;
Boolean result = null;
for (CastPermissionManager manager : castManagers) {
Boolean managerResult = manager.getRegionCastPermission(player, spell, location);
if (managerResult != null) {
if (!managerResult) {
return false;
}
if (result == null) {
result = managerResult;
}
}
}
return result;
}
@Nullable
@Override
public Boolean getPersonalCastPermission(Player player, SpellTemplate spell, Location location) {
if (hasBypassPermission(player)) return true;
Boolean result = null;
for (CastPermissionManager manager : castManagers) {
Boolean managerResult = manager.getPersonalCastPermission(player, spell, location);
if (managerResult != null) {
if (!managerResult) {
return false;
}
if (result == null) {
result = managerResult;
}
}
}
return result;
}
@Override
public boolean hasBypassPermission(CommandSender sender) {
if (sender == null) return false;
if (sender instanceof Player && sender.hasPermission("Magic.bypass")) return true;
Mage mage = getRegisteredMage(sender);
if (mage == null) return false;
return mage.isBypassEnabled();
}
@Override
public boolean inTaggedRegion(Location location, Set<String> tags) {
Boolean inRegion = worldGuardManager.inTaggedRegion(location, tags);
return inRegion != null && inRegion;
}
public boolean hasPermission(Player player, String pNode, boolean defaultValue) {
// Should this return defaultValue? Can't give perms to console.
if (player == null) return true;
// The GM won't handle this properly because we are unable to register
// dynamic lists (spells, wands, brushes) in plugin.yml
if (pNode.contains(".")) {
String parentNode = pNode.substring(0, pNode.lastIndexOf('.') + 1) + "*";
boolean isParentSet = player.isPermissionSet(parentNode);
if (isParentSet) {
defaultValue = player.hasPermission(parentNode);
}
}
boolean isSet = player.isPermissionSet(pNode);
return isSet ? player.hasPermission(pNode) : defaultValue;
}
public boolean hasPermission(Player player, String pNode) {
return hasPermission(player, pNode, false);
}
@Override
public boolean hasPermission(CommandSender sender, String pNode) {
if (!(sender instanceof Player)) return true;
return hasPermission((Player) sender, pNode, false);
}
@Override
public boolean hasPermission(CommandSender sender, String pNode, boolean defaultValue) {
if (!(sender instanceof Player)) return true;
return hasPermission((Player) sender, pNode, defaultValue);
}
public void registerFallingBlock(Entity fallingBlock, Block block) {
UndoList undoList = getPendingUndo(fallingBlock.getLocation());
if (undoList != null) {
undoList.fall(fallingBlock, block);
}
}
@Nullable
public UndoList getEntityUndo(Entity entity) {
UndoList blockList = null;
if (entity == null) return null;
blockList = com.elmakers.mine.bukkit.block.UndoList.getUndoList(entity);
if (blockList != null) return blockList;
if (entity instanceof Projectile) {
Projectile projectile = (Projectile) entity;
ProjectileSource source = projectile.getShooter();
if (source instanceof Entity) {
entity = (Entity) source;
blockList = com.elmakers.mine.bukkit.block.UndoList.getUndoList(entity);
if (blockList != null) return blockList;
}
}
Mage mage = getRegisteredMage(entity);
if (mage != null) {
UndoList undoList = mage.getLastUndoList();
if (undoList != null) {
long now = System.currentTimeMillis();
if (undoList.getModifiedTime() > now - undoTimeWindow) {
blockList = undoList;
}
}
}
return blockList;
}
public boolean isBindOnGive() {
return bindOnGive;
}
@Override
public void giveItemToPlayer(Player player, ItemStack itemStack) {
Mage mage = getMage(player);
mage.giveItem(itemStack);
}
@Override
public boolean commitOnQuit() {
return commitOnQuit;
}
public void onShutdown() {
shuttingDown = true;
if (despawnMagicMobs) {
for (Mage mobMage : getMobMages()) {
Entity entity = mobMage.getEntity();
if (entity != null) {
entity.remove();
}
}
}
if (mageDataStore != null) {
mageDataStore.close();
}
if (migrateDataStore != null) {
migrateDataStore.close();
}
}
public void undoScheduled() {
int undid = 0;
while (!scheduledUndo.isEmpty()) {
UndoList undoList = scheduledUndo.poll();
undoList.undoScheduled(true);
}
if (undid > 0) {
info("Undid " + undid + " pending spells");
}
}
protected void mageQuit(final Mage mage, final MageDataCallback callback) {
com.elmakers.mine.bukkit.api.wand.Wand wand = mage.getActiveWand();
final boolean isOpen = wand != null && wand.isInventoryOpen();
com.elmakers.mine.bukkit.magic.Mage implementation = null;
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
implementation = (com.elmakers.mine.bukkit.magic.Mage) mage;
implementation.flagForReactivation();
}
mage.deactivate();
mage.undoScheduled();
mage.deactivateClasses();
mage.deactivateModifiers();
// Delay removal one tick to avoid issues with plugins that kill
// players on logout (CombatTagPlus, etc)
// Don't delay on shutdown, though.
if (loaded && implementation != null && !shuttingDown) {
final com.elmakers.mine.bukkit.magic.Mage quitMage = implementation;
quitMage.setUnloading(true);
plugin.getServer().getScheduler().runTaskLater(plugin, new MageQuitTask(this, quitMage, callback, isOpen), 1);
} else {
finalizeMageQuit(mage, callback, isOpen);
}
}
public void finalizeMageQuit(final Mage mage, final MageDataCallback callback, final boolean isOpen) {
// Unregister
if (!externalPlayerData || !mage.isPlayer()) {
removeMage(mage);
}
if (!mage.isLoading() && (mage.isPlayer() || saveNonPlayerMages) && loaded) {
// Save synchronously on shutdown
saveMage(mage, !shuttingDown, callback, isOpen, true);
} else if (callback != null) {
callback.run(null);
}
}
protected void playerQuit(Mage mage, MageDataCallback callback) {
// Make sure they get their portraits re-rendered on relogin.
maps.resend(mage.getName());
mageQuit(mage, callback);
}
public void playerQuit(Mage mage) {
playerQuit(mage, null);
}
@Override
public void forgetMage(Mage mage) {
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
((com.elmakers.mine.bukkit.magic.Mage) mage).setForget(true);
}
}
@Override
public void removeMage(Mage mage) {
removeMage(mage.getId());
}
@Override
public void removeMage(String id) {
Mage mage = mages.remove(id);
if (mage != null) {
mage.removed();
}
}
public void saveMage(Mage mage, boolean asynchronous) {
saveMage(mage, asynchronous, null);
}
public void saveMage(Mage mage, boolean asynchronous, final MageDataCallback callback) {
saveMage(mage, asynchronous, callback, false, false);
}
public void saveMage(Mage mage, boolean asynchronous, final MageDataCallback callback, boolean wandInventoryOpen, boolean releaseLock) {
if (!savePlayerData) {
if (callback != null) {
callback.run(null);
}
return;
}
asynchronous = asynchronous && asynchronousSaving;
info("Saving player data for " + mage.getName() + " (" + mage.getId() + ") " + ((asynchronous ? "" : " synchronously ") + "at " + System.currentTimeMillis()));
final MageData mageData = new MageData(mage.getId());
if (mageDataStore != null && mage.save(mageData)) {
if (wandInventoryOpen) {
mageData.setOpenWand(true);
}
if (asynchronous) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new SaveMageTask(this, mageData, callback, releaseLock));
} else {
doSaveMage(mageData, callback, releaseLock);
}
} else if (releaseLock && mageDataStore != null) {
getLogger().warning("Player logging out, but data never loaded. Force-releasing lock");
mageDataStore.releaseLock(mageData);
}
}
public void doSaveMage(MageData mageData, MageDataCallback callback, boolean releaseLock) {
synchronized (saveLock) {
try {
mageDataStore.save(mageData, callback, releaseLock);
} catch (Exception ex) {
getLogger().log(Level.SEVERE, "Error saving mage data for mage " + mageData.getId(), ex);
}
}
}
@Nullable
public ItemStack removeItemFromWand(Wand wand, ItemStack droppedItem) {
if (wand == null || droppedItem == null || Wand.isWand(droppedItem)) {
return null;
}
if (Wand.isSpell(droppedItem)) {
String spellKey = Wand.getSpell(droppedItem);
wand.removeSpell(spellKey);
// Update the item for proper naming and lore
SpellTemplate spell = getSpellTemplate(spellKey);
if (spell != null) {
Wand.updateSpellItem(messages, droppedItem, spell, "", null, null, true);
}
} else if (Wand.isBrush(droppedItem)) {
String brushKey = Wand.getBrush(droppedItem);
wand.removeBrush(brushKey);
// Update the item for proper naming and lore
Wand.updateBrushItem(getMessages(), droppedItem, brushKey, null);
}
return droppedItem;
}
public void onArmorUpdated(final com.elmakers.mine.bukkit.magic.Mage mage) {
plugin.getServer().getScheduler().runTaskLater(plugin, new ArmorUpdatedTask(mage), 1);
}
@Override
public boolean isLocked(Block block) {
return protectLocked && containerMaterials.testBlock(block) && CompatibilityUtils.isLocked(block);
}
protected boolean addLostWandMarker(LostWand lostWand) {
if (!dynmapShowWands) {
return false;
}
Location location = lostWand.getLocation();
return addMarker("wand-" + lostWand.getId(), "wand", "wands", lostWand.getName(), location.getWorld().getName(),
location.getBlockX(), location.getBlockY(), location.getBlockZ(), lostWand.getDescription()
);
}
public void toggleCastCommandOverrides(Mage apiMage, CommandSender sender, boolean override) {
// Don't track command-line casts
// Reach into internals a bit here.
if (apiMage instanceof com.elmakers.mine.bukkit.magic.Mage) {
com.elmakers.mine.bukkit.magic.Mage mage = (com.elmakers.mine.bukkit.magic.Mage) apiMage;
if (sender != null && sender instanceof BlockCommandSender) {
mage.setCostFree(override && castCommandCostFree);
mage.setCooldownFree(override && castCommandCooldownFree);
mage.setPowerMultiplier(override ? castCommandPowerMultiplier : 1);
} else {
mage.setCostFree(override && castConsoleCostFree);
mage.setCooldownFree(override && castConsoleCooldownFree);
mage.setPowerMultiplier(override ? castConsolePowerMultiplier : 1);
}
}
}
public float getCooldownReduction() {
return cooldownReduction;
}
public float getCostReduction() {
return costReduction;
}
public Material getDefaultMaterial() {
return defaultMaterial;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.wand.LostWand> getLostWands() {
return new ArrayList<>(lostWands.values());
}
@Override
public boolean cast(String spellName, String[] parameters) {
return cast(spellName, parameters, Bukkit.getConsoleSender(), null);
}
public boolean cast(String spellName, String[] parameters, CommandSender sender, Entity entity) {
ConfigurationSection config = null;
if (parameters != null && parameters.length > 0) {
config = ConfigurationUtils.newConfigurationSection();
ConfigurationUtils.addParameters(parameters, config);
}
return cast(null, spellName, config, sender, entity);
}
public boolean cast(Mage mage, String spellName, ConfigurationSection parameters, CommandSender sender, Entity entity) {
Player usePermissions = (sender == entity && entity instanceof Player) ? (Player) entity
: (sender instanceof Player ? (Player) sender : null);
if (entity == null && sender instanceof Player) {
entity = (Player) sender;
}
Location targetLocation = null;
if (mage == null) {
CommandSender mageController = (entity != null && entity instanceof Player) ? (Player) entity : sender;
if (sender != null && sender instanceof BlockCommandSender) {
targetLocation = ((BlockCommandSender) sender).getBlock().getLocation();
}
if (entity == null) {
mage = getMage(mageController);
} else {
mage = getMageFromEntity(entity, mageController);
}
}
SpellTemplate template = getSpellTemplate(spellName);
if (template == null || !template.hasCastPermission(usePermissions)) {
if (sender != null) {
sender.sendMessage("Spell " + spellName + " unknown");
}
return false;
}
com.elmakers.mine.bukkit.api.spell.Spell spell = mage.getSpell(spellName);
if (spell == null) {
if (sender != null) {
sender.sendMessage("Spell " + spellName + " unknown");
}
return false;
}
// TODO: Load configured list of parameters!
// Make it free and skip cooldowns, if configured to do so.
toggleCastCommandOverrides(mage, sender, true);
boolean success = false;
try {
success = spell.cast(parameters, targetLocation);
} catch (Exception ex) {
ex.printStackTrace();
}
toggleCastCommandOverrides(mage, sender, false);
// Removed sending messages here due to the log spam in WG region messages
// Maybe should be a parameter option or something?
return success;
}
public void onCast(Mage mage, com.elmakers.mine.bukkit.api.spell.Spell spell, SpellResult result) {
if (dynmapShowSpells && dynmap != null && result.isSuccess()) {
if (dynmapOnlyPlayerSpells && (mage == null || !mage.isPlayer())) {
return;
}
dynmap.showCastMarker(mage, spell, result);
}
if (result.isSuccess() && getShowCastHoloText()) {
mage.showHoloText(mage.getEyeLocation(), spell.getName(), 10000);
}
}
@Override
public Messages getMessages() {
return messages;
}
@Override
public MapController getMaps() {
return maps;
}
public String getWelcomeWand() {
return welcomeWand;
}
@Override
public void sendToMages(String message, Location location) {
sendToMages(message, location, toggleMessageRange);
}
public void sendToMages(String message, Location location, int range) {
int rangeSquared = range * range;
if (message != null && message.length() > 0) {
for (Mage mage : mages.values()) {
if (!mage.isPlayer() || mage.isDead() || !mage.isOnline() || !mage.hasLocation()) continue;
if (!mage.getLocation().getWorld().equals(location.getWorld())) continue;
if (mage.getLocation().toVector().distanceSquared(location.toVector()) < rangeSquared) {
mage.sendMessage(message);
}
}
}
}
@Override
public boolean isNPC(Entity entity) {
if (isMagicNPC(entity)) {
return true;
}
return npcSuppliers.isNPC(entity);
}
@Override
public boolean isStaticNPC(Entity entity) {
if (isMagicNPC(entity)) {
return true;
}
return npcSuppliers.isStaticNPC(entity);
}
@Override
public boolean isPet(Entity entity) {
// This currently only looks for pets from SimplePets
return entity.hasMetadata("pet");
}
@Override
public boolean isMagicNPC(Entity entity) {
return npcsByEntity.containsKey(entity.getUniqueId());
}
@Override
public boolean isVanished(Entity entity) {
if (entity == null) return false;
Mage mage = getRegisteredMage(entity);
if (mage != null && mage.isVanished()) {
return true;
}
if (essentialsController != null && essentialsController.isVanished(entity)) {
return true;
}
for (MetadataValue meta : entity.getMetadata("vanished")) {
return meta.asBoolean();
}
return false;
}
@Override
public void updateBlock(Block block) {
updateBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ());
}
@Override
public void updateBlock(String worldName, int x, int y, int z) {
if (dynmap != null && dynmapUpdate) {
dynmap.triggerRenderOfBlock(worldName, x, y, z);
}
}
@Override
public void updateVolume(String worldName, int minx, int miny, int minz, int maxx, int maxy, int maxz) {
if (dynmap != null && dynmapUpdate && worldName != null && worldName.length() > 0) {
dynmap.triggerRenderOfVolume(worldName, minx, miny, minz, maxx, maxy, maxz);
}
}
public void update(String worldName, BoundingBox area) {
if (dynmap != null && dynmapUpdate && area != null && worldName != null && worldName.length() > 0) {
dynmap.triggerRenderOfVolume(worldName,
area.getMin().getBlockX(), area.getMin().getBlockY(), area.getMin().getBlockZ(),
area.getMax().getBlockX(), area.getMax().getBlockY(), area.getMax().getBlockZ());
}
}
@Override
public void update(com.elmakers.mine.bukkit.api.block.BlockList blockList) {
if (blockList != null) {
for (Map.Entry<String, ? extends BoundingBox> entry : blockList.getAreas().entrySet()) {
update(entry.getKey(), entry.getValue());
}
}
}
@Override
public void cleanItem(ItemStack item) {
InventoryUtils.removeMeta(item, Wand.WAND_KEY);
InventoryUtils.removeMeta(item, Wand.UPGRADE_KEY);
InventoryUtils.removeMeta(item, "spell");
InventoryUtils.removeMeta(item, "skill");
InventoryUtils.removeMeta(item, "brush");
InventoryUtils.removeMeta(item, "sp");
InventoryUtils.removeMeta(item, "keep");
InventoryUtils.removeMeta(item, "temporary");
InventoryUtils.removeMeta(item, "undroppable");
InventoryUtils.removeMeta(item, "unplaceable");
InventoryUtils.removeMeta(item, "unstashable");
InventoryUtils.removeMeta(item, "unmoveable");
}
@Override
public boolean canCreateWorlds() {
return createWorldsEnabled;
}
@Override
public int getMaxUndoPersistSize() {
return undoMaxPersistSize;
}
@Override
public MagicPlugin getPlugin() {
return plugin;
}
@Override
public MagicAPI getAPI() {
return plugin;
}
public Collection<? extends Mage> getMutableMages() {
return mages.values();
}
@Override
public Collection<Mage> getMages() {
Collection<? extends Mage> values = mages.values();
return Collections.unmodifiableCollection(values);
}
@Override
@Deprecated
public Set<Material> getBuildingMaterials() {
return MaterialSets.toLegacyNN(buildingMaterials);
}
@Override
public Collection<Mage> getMobMages() {
Collection<Mage> mobMages = new ArrayList<>();
for (Mage mage : mages.values()) {
if (mage.getEntityData() != null) {
mobMages.add(mage);
}
}
return Collections.unmodifiableCollection(mobMages);
}
@Override
public Collection<Entity> getActiveMobs() {
return mobs.getActiveMobs();
}
@Override
@Deprecated
public Set<Material> getRestrictedMaterials() {
return MaterialSets.toLegacyNN(restrictedMaterials);
}
@Override
public MaterialSet getBuildingMaterialSet() {
return buildingMaterials;
}
@Override
public MaterialSet getDestructibleMaterialSet() {
return destructibleMaterials;
}
@Override
public MaterialSet getRestrictedMaterialSet() {
return restrictedMaterials;
}
@Override
public int getMessageThrottle() {
return messageThrottle;
}
// TODO: Remove the if and replace it with a precondition
// once we're sure nothing is calling this with a null value.
@SuppressWarnings({"null", "unused"})
@Override
public boolean isMage(Entity entity) {
if (entity == null) return false;
String id = mageIdentifier.fromEntity(entity);
return mages.containsKey(id);
}
@Override
public MaterialSetManager getMaterialSetManager() {
return materialSetManager;
}
@Override
@Deprecated
public Collection<String> getMaterialSets() {
return getMaterialSetManager().getMaterialSets();
}
@Nullable
@Override
@Deprecated
public Set<Material> getMaterialSet(String string) {
return MaterialSets.toLegacy(getMaterialSetManager().fromConfig(string));
}
@Override
public Collection<String> getPlayerNames() {
List<String> playerNames = new ArrayList<>();
Collection<? extends Player> players = plugin.getServer().getOnlinePlayers();
for (Player player : players) {
if (isNPC(player)) continue;
playerNames.add(player.getName());
}
return playerNames;
}
@Override
public void disablePhysics(int interval) {
if (physicsHandler == null && interval > 0) {
physicsHandler = new PhysicsHandler(this);
Bukkit.getPluginManager().registerEvents(physicsHandler, plugin);
}
if (physicsHandler != null) {
physicsHandler.setInterval(interval);
}
}
@Override
public boolean commitAll() {
boolean undid = false;
for (Mage mage : mages.values()) {
undid = mage.commit() || undid;
}
com.elmakers.mine.bukkit.block.UndoList.commitAll();
return undid;
}
@Override
public boolean canTarget(Entity attacker, Entity entity) {
// We can always target ourselves at this level
if (attacker == entity) return true;
// We don't handle non-entities here
if (attacker == null || entity == null) return true;
// We can't target our friends (bypassing happens at a higher level)
if (isFriendly(attacker, entity, false)) {
return false;
}
for (EntityTargetingManager manager : targetingProviders) {
if (!manager.canTarget(attacker, entity)) {
return false;
}
}
return true;
}
@Override
public boolean isFriendly(Entity attacker, Entity entity) {
return isFriendly(attacker, entity, true);
}
public boolean isFriendly(Entity attacker, Entity entity, boolean friendlyByDefault) {
// We are always friends with ourselves
if (attacker == entity) return true;
for (TeamProvider provider : teamProviders) {
if (provider.isFriendly(attacker, entity)) {
return true;
}
}
if (friendlyByDefault) {
// Mobs can always target players, just to avoid any confusion there.
if (!(attacker instanceof Player)) return true;
// Player vs Player is controlled by a special config flag
if (entity instanceof Player) return defaultFriendly;
// Otherwise we look at the friendly entity types
return friendlyEntityTypes.contains(entity.getType());
}
return false;
}
@Nullable
@Override
public Location getWarp(String warpName) {
Location location = null;
if (warpController != null) {
try {
location = warpController.getWarp(warpName);
} catch (Exception ex) {
location = null;
}
}
return location;
}
public WarpController getWarps() {
return warpController;
}
@Nullable
@Override
public Location getTownLocation(Player player) {
return townyManager.getTownLocation(player);
}
@Nullable
@Override
public Map<String, Location> getHomeLocations(Player player) {
return preciousStonesManager.getFieldLocations(player);
}
@Nonnull
@Override
public Set<String> getPlayerWarpProviderKeys() {
return playerWarpManagers.keySet();
}
@Nullable
@Override
public Collection<PlayerWarp> getPlayerWarps(Player player, String key) {
PlayerWarpManager manager = playerWarpManagers.get(key);
if (manager == null) {
return null;
}
return manager.getWarps(player);
}
public TownyManager getTowny() {
return townyManager;
}
public PreciousStonesManager getPreciousStones() {
return preciousStonesManager;
}
@Override
public boolean sendMail(CommandSender sender, String fromPlayer, String toPlayer, String message) {
if (mailer != null) {
return mailer.sendMail(sender, fromPlayer, toPlayer, message);
}
return false;
}
@Nullable
@Override
public UndoList undoAny(Block target) {
for (Mage mage : mages.values()) {
UndoList undid = mage.undo(target);
if (undid != null) {
return undid;
}
}
return null;
}
@Nullable
@Override
public UndoList undoRecent(Block target, int timeout) {
for (Mage mage : mages.values()) {
com.elmakers.mine.bukkit.api.block.UndoQueue queue = mage.getUndoQueue();
UndoList undid = queue.undoRecent(target, timeout);
if (undid != null) {
return undid;
}
}
return null;
}
@Nullable
@Override
public Wand getIfWand(ItemStack itemStack) {
if (Wand.isWand(itemStack)) {
return getWand(itemStack);
}
return null;
}
@Override
public Wand getWand(ItemStack itemStack) {
@SuppressWarnings("deprecation")
Wand wand = new Wand(this, itemStack);
return wand;
}
@Override
public Wand getWand(ConfigurationSection config) {
return new Wand(this, config);
}
@Nullable
@Override
public Wand createWand(String wandKey) {
return Wand.createWand(this, wandKey);
}
@Override
@Nonnull
public Wand createWand(@Nonnull ItemStack itemStack) {
return Wand.createWand(this, itemStack);
}
@Nullable
@Override
public WandTemplate getWandTemplate(String key) {
if (key == null || key.isEmpty()) return null;
return wandTemplates.get(key);
}
@Override
public Collection<com.elmakers.mine.bukkit.api.wand.WandTemplate> getWandTemplates() {
return new ArrayList<>(wandTemplates.values());
}
@Override
@Nullable
public String getAutoWandKey(@Nonnull Material material) {
return autoWands.get(material);
}
@Nullable
public ItemStack getAutoWand(ItemStack itemStack) {
if (itemStack == null) return null;
String templateKey = getAutoWandKey(itemStack.getType());
if (templateKey != null && !templateKey.isEmpty()) {
Wand wand = createWand(templateKey);
if (wand == null) {
getLogger().warning("Invalid wand template in auto_wands config: " + templateKey);
} else {
return wand.getItem();
}
}
return null;
}
@Nullable
protected ConfigurationSection resolveConfiguration(String key, ConfigurationSection properties, Map<String, ConfigurationSection> configurations) {
resolvingKeys.clear();
return resolveConfiguration(key, properties, configurations, resolvingKeys);
}
@Nullable
protected ConfigurationSection resolveConfiguration(String key, ConfigurationSection properties, Map<String, ConfigurationSection> configurations, Set<String> resolving) {
// Catch circular dependencies
if (resolving.contains(key)) {
getLogger().log(Level.WARNING, "Circular dependency detected: " + StringUtils.join(resolving, " -> ") + " -> " + key);
return properties;
}
resolving.add(key);
ConfigurationSection configuration = configurations.get(key);
if (configuration == null) {
configuration = properties.getConfigurationSection(key);
if (configuration == null) {
return null;
}
String inherits = configuration.getString("inherit");
if (inherits != null) {
ConfigurationSection baseConfiguration = resolveConfiguration(inherits, properties, configurations, resolving);
if (baseConfiguration != null) {
ConfigurationSection newConfiguration = ConfigurationUtils.cloneConfiguration(baseConfiguration);
ConfigurationUtils.addConfigurations(newConfiguration, configuration);
// Some properties don't inherit, this is kind of hacky.
newConfiguration.set("hidden", configuration.get("hidden"));
configuration = newConfiguration;
}
}
configurations.put(key, configuration);
}
return configuration;
}
public void loadMageClasses(ConfigurationSection properties) {
mageClasses.clear();
Set<String> classKeys = properties.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
for (String key : classKeys) {
logger.setContext("classes." + key);
ConfigurationSection classConfig = resolveConfiguration(key, properties, templateConfigurations);
classConfig = MagicConfiguration.getKeyed(this, classConfig, "class", key);
loadMageClassTemplate(key, classConfig);
}
// Resolve parents, we don't check for an inherited "parent" property, so it's important
// to use the original un-inherited configs for parenting.
for (String key : classKeys) {
logger.setContext("classes." + key);
MageClassTemplate template = mageClasses.get(key);
if (template != null) {
String parentKey = properties.getConfigurationSection(key).getString("parent");
if (parentKey != null) {
MageClassTemplate parent = mageClasses.get(parentKey);
if (parent == null) {
getLogger().warning("Class '" + key + "' has unknown parent: " + parentKey);
} else {
template.setParent(parent);
}
}
}
}
// Update registered mages so their classes are current
for (Mage mage : mages.values()) {
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
((com.elmakers.mine.bukkit.magic.Mage) mage).reloadClasses();
}
}
}
public void loadModifiers(ConfigurationSection properties) {
modifiers.clear();
Set<String> modifierKeys = properties.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
for (String key : modifierKeys) {
logger.setContext("modifiers." + key);
ConfigurationSection modifierConfig = resolveConfiguration(key, properties, templateConfigurations);
modifierConfig = MagicConfiguration.getKeyed(this, modifierConfig, "modifier", key);
loadModifierTemplate(key, modifierConfig);
}
// Resolve parents, we don't check for an inherited "parent" property, so it's important
// to use the original un-inherited configs for parenting.
for (String key : modifierKeys) {
logger.setContext("modifiers." + key);
ModifierTemplate template = modifiers.get(key);
if (template != null) {
String parentKey = properties.getConfigurationSection(key).getString("parent");
if (parentKey != null) {
ModifierTemplate parent = modifiers.get(parentKey);
if (parent == null) {
getLogger().warning("Modifier '" + key + "' has unknown parent: " + parentKey);
} else {
template.setParent(parent);
}
}
}
}
// Update registered mages so their classes are current
for (Mage mage : mages.values()) {
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
((com.elmakers.mine.bukkit.magic.Mage) mage).reloadModifiers();
}
}
}
@Override
public Set<String> getMageClassKeys() {
return mageClasses.keySet();
}
@Nonnull
public MageClassTemplate getMageClass(String key) {
MageClassTemplate template = mageClasses.get(key);
if (template == null) {
ConfigurationSection configuration = ConfigurationUtils.newConfigurationSection();
template = new MageClassTemplate(this, key, configuration);
mageClasses.put(key, template);
}
return template;
}
public void loadMageClassTemplate(String key, ConfigurationSection classNode) {
if (ConfigurationUtils.isEnabled(classNode)) {
mageClasses.put(key, new MageClassTemplate(this, key, classNode));
}
}
public void loadModifierTemplate(String key, ConfigurationSection modifierNode) {
if (ConfigurationUtils.isEnabled(modifierNode)) {
modifiers.put(key, new ModifierTemplate(this, key, modifierNode));
}
}
public void loadWandTemplates(ConfigurationSection properties) {
wandTemplates.clear();
Set<String> wandKeys = properties.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
for (String key : wandKeys) {
logger.setContext("wands." + key);
loadWandTemplate(key, resolveConfiguration(key, properties, templateConfigurations));
}
}
public void loadMobs(ConfigurationSection properties) {
mobs.clear();
Set<String> mobKeys = properties.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
for (String key : mobKeys) {
logger.setContext("mobs." + key);
ConfigurationSection mobConfig = resolveConfiguration(key, properties, templateConfigurations);
mobConfig = MagicConfiguration.getKeyed(this, mobConfig, "mob", key);
mobs.load(key, mobConfig);
}
}
public void loadWorlds(ConfigurationSection properties) {
Set<String> worldKeys = properties.getKeys(false);
Map<String, ConfigurationSection> templateConfigurations = new HashMap<>();
for (String key : worldKeys) {
if (key.equalsIgnoreCase("worlds")) continue;
logger.setContext("worlds." + key);
ConfigurationSection worldConfig = resolveConfiguration(key, properties, templateConfigurations);
worldConfig = MagicConfiguration.getKeyed(this, worldConfig, "world", key);
properties.set(key, worldConfig);
}
worldController.loadWorlds(properties);
}
@Override
public MageClassTemplate getMageClassTemplate(String key) {
return mageClasses.get(key);
}
@Override
@Nullable
public ModifierTemplate getModifierTemplate(String key) {
return modifiers.get(key);
}
@Override
@Nonnull
public Collection<String> getModifierTemplateKeys() {
return modifiers.keySet();
}
@Override
public void loadWandTemplate(String key, ConfigurationSection wandNode) {
if (ConfigurationUtils.isEnabled(wandNode)) {
wandNode = MagicConfiguration.getKeyed(this, wandNode, "wand", key);
wandTemplates.put(key, new com.elmakers.mine.bukkit.wand.WandTemplate(this, key, wandNode));
}
}
@Override
public void unloadWandTemplate(String key) {
wandTemplates.remove(key);
}
@Override
public Collection<String> getWandTemplateKeys() {
return wandTemplates.keySet();
}
@Nullable
public ConfigurationSection getWandTemplateConfiguration(String key) {
WandTemplate template = getWandTemplate(key);
return template == null ? null : template.getConfiguration();
}
@Override
public boolean elementalsEnabled() {
return (elementals != null);
}
@Override
public boolean createElemental(Location location, String templateName, CommandSender creator) {
return elementals.createElemental(location, templateName, creator);
}
@Override
public boolean isElemental(Entity entity) {
if (elementals == null || entity.getType() != EntityType.FALLING_BLOCK) return false;
return elementals.isElemental(entity);
}
@Override
public boolean damageElemental(Entity entity, double damage, int fireTicks, CommandSender attacker) {
if (elementals == null) return false;
return elementals.damageElemental(entity, damage, fireTicks, attacker);
}
@Override
public boolean setElementalScale(Entity entity, double scale) {
if (elementals == null) return false;
return elementals.setElementalScale(entity, scale);
}
@Override
public double getElementalScale(Entity entity) {
if (elementals == null) return 0;
return elementals.getElementalScale(entity);
}
@Nullable
@Override
public com.elmakers.mine.bukkit.api.spell.SpellCategory getCategory(String key) {
if (key == null || key.isEmpty()) {
return null;
}
SpellCategory category = categories.get(key);
if (category == null) {
category = new com.elmakers.mine.bukkit.spell.SpellCategory(key, this);
categories.put(key, category);
}
return category;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.spell.SpellCategory> getCategories() {
List<com.elmakers.mine.bukkit.api.spell.SpellCategory> allCategories = new ArrayList<>();
allCategories.addAll(categories.values());
return allCategories;
}
@Override
public Collection<String> getSpellTemplateKeys() {
return spells.keySet();
}
@Override
public Collection<SpellTemplate> getSpellTemplates() {
return getSpellTemplates(false);
}
@Override
public Collection<SpellTemplate> getSpellTemplates(boolean showHidden) {
List<SpellTemplate> allSpells = new ArrayList<>();
for (SpellTemplate spell : spells.values()) {
if (showHidden || !spell.isHidden()) {
allSpells.add(spell);
}
}
return allSpells;
}
@Nullable
@Override
public SpellTemplate getSpellTemplate(String name) {
if (name == null || name.length() == 0) return null;
SpellTemplate spell = spellAliases.get(name);
if (spell == null) {
spell = spells.get(name);
}
if (spell == null && name.startsWith("heroes*")) {
if (heroesManager == null) return null;
spell = heroesManager.createSkillSpell(this, name.substring(7));
if (spell != null) {
spells.put(name, spell);
}
}
return spell;
}
protected void loadSpells(CommandSender sender, ConfigurationSection spellConfigs) {
if (spellConfigs == null) return;
// Reset existing spells.
spells.clear();
spellAliases.clear();
categories.clear();
maxSpellLevels.clear();
Set<String> keys = spellConfigs.getKeys(false);
for (String key : keys) {
if (key.equals("default") || key.equals("override")) continue;
logger.setContext("spells." + key);
ConfigurationSection spellNode = spellConfigs.getConfigurationSection(key);
if (!(spellNode instanceof MagicConfiguration)) {
spellNode = MagicConfiguration.getKeyed(this, spellNode, "spell", key);
spellConfigs.set(key, spellNode);
}
Spell newSpell = null;
try {
newSpell = loadSpell(key, spellNode, this);
} catch (Exception ex) {
newSpell = null;
ex.printStackTrace();
}
if (newSpell == null) {
getLogger().warning("Magic: Error loading spell " + key);
continue;
}
if (!newSpell.hasIcon()) {
String icon = spellNode.getString("icon");
if (icon != null && !icon.isEmpty()) {
getLogger().info("Couldn't load spell icon '" + icon + "' for spell: " + newSpell.getKey());
}
}
addSpell(newSpell);
}
// Second pass to fulfill requirements, which needs all spells loaded
for (String key : keys) {
logger.setContext("spells." + key);
SpellTemplate template = getSpellTemplate(key);
if (template != null) {
template.loadPrerequisites(spellConfigs.getConfigurationSection(key));
}
}
// Update registered mages so their spells are current
for (Mage mage : mages.values()) {
if (mage instanceof com.elmakers.mine.bukkit.magic.Mage) {
((com.elmakers.mine.bukkit.magic.Mage) mage).loadSpells(spellConfigs);
}
}
}
public SpellKey unalias(SpellKey spellKey) {
SpellTemplate spell = spellAliases.get(spellKey.getBaseKey());
if (spell != null) {
return new SpellKey(spell.getSpellKey().getBaseKey(), spellKey.getLevel());
}
return spellKey;
}
@Override
public String getEntityDisplayName(Entity target) {
return getEntityName(target, true);
}
@Override
public String getEntityName(Entity target) {
return getEntityName(target, false);
}
protected String getEntityName(Entity target, boolean display) {
if (target == null) {
return "Unknown";
}
if (target instanceof Player) {
return display ? ((Player) target).getDisplayName() : target.getName();
}
if (isElemental(target)) {
return "Elemental";
}
if (display) {
if (target instanceof LivingEntity) {
LivingEntity li = (LivingEntity) target;
String customName = li.getCustomName();
if (customName != null && customName.length() > 0) {
return customName;
}
} else if (target instanceof Item) {
Item item = (Item) target;
ItemStack itemStack = item.getItemStack();
if (itemStack.hasItemMeta()) {
ItemMeta meta = itemStack.getItemMeta();
if (meta.hasDisplayName()) {
return meta.getDisplayName();
}
}
MaterialAndData material = new MaterialAndData(itemStack);
return material.getName(getMessages());
}
}
String localizedName = messages.get("entities." + target.getType().name().toLowerCase(), "");
if (!localizedName.isEmpty()) {
return localizedName;
}
return target.getType().name().toLowerCase().replace('_', ' ');
}
public boolean getShowCastHoloText() {
return showCastHoloText;
}
public boolean getShowActivateHoloText() {
return showActivateHoloText;
}
public int getCastHoloTextRange() {
return castHoloTextRange;
}
public int getActiveHoloTextRange() {
return activateHoloTextRange;
}
public ItemStack getSpellBook(com.elmakers.mine.bukkit.api.spell.SpellCategory category, int count) {
Map<String, List<SpellTemplate>> categories = new HashMap<>();
Collection<SpellTemplate> spellVariants = spells.values();
String categoryKey = category == null ? null : category.getKey();
for (SpellTemplate spell : spellVariants) {
if (spell.isHidden() || spell.getSpellKey().isVariant()) continue;
com.elmakers.mine.bukkit.api.spell.SpellCategory spellCategory = spell.getCategory();
if (spellCategory == null) continue;
String spellCategoryKey = spellCategory.getKey();
if (categoryKey == null || spellCategoryKey.equalsIgnoreCase(categoryKey)) {
List<SpellTemplate> categorySpells = categories.get(spellCategoryKey);
if (categorySpells == null) {
categorySpells = new ArrayList<>();
categories.put(spellCategoryKey, categorySpells);
}
categorySpells.add(spell);
}
}
List<String> categoryKeys = new ArrayList<>(categories.keySet());
Collections.sort(categoryKeys);
ItemStack bookItem = new ItemStack(Material.WRITTEN_BOOK, count);
BookMeta book = (BookMeta) bookItem.getItemMeta();
book.setAuthor(messages.get("books.default.author"));
String title = null;
if (category != null) {
title = messages.get("books.default.title").replace("$category", category.getName());
} else {
title = messages.get("books.all.title");
}
book.setTitle(title);
List<String> pages = new ArrayList<>();
for (String key : categoryKeys) {
category = getCategory(key);
title = messages.get("books.default.title").replace("$category", category.getName());
String description = "" + ChatColor.BOLD + ChatColor.BLUE + title + "\n\n";
description += "" + ChatColor.RESET + ChatColor.DARK_BLUE + category.getDescription();
pages.add(description);
List<SpellTemplate> categorySpells = categories.get(key);
Collections.sort(categorySpells);
for (SpellTemplate spell : categorySpells) {
List<String> lines = getSpellBookDescription(spell);
pages.add(StringUtils.join(lines, "\n"));
}
}
book.setPages(pages);
bookItem.setItemMeta(book);
return bookItem;
}
public ItemStack getSpellBook(com.elmakers.mine.bukkit.api.spell.SpellTemplate spell, int count) {
ItemStack bookItem = new ItemStack(Material.WRITTEN_BOOK, count);
BookMeta book = (BookMeta) bookItem.getItemMeta();
book.setAuthor(messages.get("books.default.author"));
book.setTitle(messages.get("books.spell.title").replace("$spell", spell.getName()));
List<String> pages = new ArrayList<>();
List<String> lines = getSpellBookDescription(spell);
pages.add(StringUtils.join(lines, "\n"));
book.setPages(pages);
bookItem.setItemMeta(book);
return bookItem;
}
protected List<String> getSpellBookDescription(SpellTemplate spell) {
Set<String> paths = WandUpgradePath.getPathKeys();
List<String> lines = new ArrayList<>();
lines.add("" + ChatColor.GOLD + ChatColor.BOLD + spell.getName());
lines.add("" + ChatColor.RESET);
String spellDescription = spell.getDescription();
if (spellDescription != null && spellDescription.length() > 0) {
lines.add("" + ChatColor.BLACK + spellDescription);
lines.add("");
}
String spellCooldownDescription = spell.getCooldownDescription();
if (spellCooldownDescription != null && spellCooldownDescription.length() > 0) {
spellCooldownDescription = messages.get("cooldown.description").replace("$time", spellCooldownDescription);
lines.add("" + ChatColor.DARK_PURPLE + spellCooldownDescription);
}
String spellMageCooldownDescription = spell.getMageCooldownDescription();
if (spellMageCooldownDescription != null && spellMageCooldownDescription.length() > 0) {
spellMageCooldownDescription = messages.get("cooldown.mage_description").replace("$time", spellMageCooldownDescription);
lines.add("" + ChatColor.RED + spellMageCooldownDescription);
}
Collection<CastingCost> costs = spell.getCosts();
if (costs != null) {
for (CastingCost cost : costs) {
if (!cost.isEmpty()) {
lines.add(ChatColor.DARK_PURPLE + messages.get("wand.costs_description").replace("$description", cost.getFullDescription(messages)));
}
}
}
Collection<CastingCost> activeCosts = spell.getActiveCosts();
if (activeCosts != null) {
for (CastingCost cost : activeCosts) {
if (!cost.isEmpty()) {
lines.add(ChatColor.DARK_PURPLE + messages.get("wand.active_costs_description").replace("$description", cost.getFullDescription(messages)));
}
}
}
for (String pathKey : paths) {
WandUpgradePath checkPath = WandUpgradePath.getPath(pathKey);
if (!checkPath.isHidden() && (checkPath.hasSpell(spell.getKey()) || checkPath.hasExtraSpell(spell.getKey()))) {
lines.add(ChatColor.DARK_BLUE + messages.get("spell.available_path").replace("$path", checkPath.getName()));
break;
}
}
for (String pathKey : paths) {
WandUpgradePath checkPath = WandUpgradePath.getPath(pathKey);
if (checkPath.requiresSpell(spell.getKey())) {
lines.add(ChatColor.DARK_RED + messages.get("spell.required_path").replace("$path", checkPath.getName()));
break;
}
}
String duration = spell.getDurationDescription(messages);
if (duration != null) {
lines.add(ChatColor.DARK_GREEN + duration);
} else if (spell.showUndoable()) {
if (spell.isUndoable()) {
String undoable = messages.get("spell.undoable", "");
if (undoable != null && !undoable.isEmpty()) {
lines.add(undoable);
}
} else {
String notUndoable = messages.get("spell.not_undoable", "");
if (notUndoable != null && !notUndoable.isEmpty()) {
lines.add(notUndoable);
}
}
}
if (spell.usesBrush()) {
lines.add(ChatColor.DARK_GRAY + messages.get("spell.brush"));
}
SpellKey baseKey = spell.getSpellKey();
SpellKey upgradeKey = new SpellKey(baseKey.getBaseKey(), baseKey.getLevel() + 1);
SpellTemplate upgradeSpell = getSpellTemplate(upgradeKey.getKey());
int spellLevels = 0;
while (upgradeSpell != null) {
spellLevels++;
upgradeKey = new SpellKey(upgradeKey.getBaseKey(), upgradeKey.getLevel() + 1);
upgradeSpell = getSpellTemplate(upgradeKey.getKey());
}
if (spellLevels > 0) {
spellLevels++;
lines.add(ChatColor.DARK_AQUA + messages.get("spell.levels_available").replace("$levels", Integer.toString(spellLevels)));
}
String usage = spell.getUsage();
if (usage != null && usage.length() > 0) {
lines.add("" + ChatColor.GRAY + ChatColor.ITALIC + usage + ChatColor.RESET);
lines.add("");
}
String spellExtendedDescription = spell.getExtendedDescription();
if (spellExtendedDescription != null && spellExtendedDescription.length() > 0) {
lines.add("" + ChatColor.BLACK + spellExtendedDescription);
lines.add("");
}
return lines;
}
public ItemStack getLearnSpellBook(SpellTemplate spell, int amount) {
ConfigurationSection wandConfiguration = ConfigurationUtils.newConfigurationSection();
wandConfiguration.set("template", "learnspell");
wandConfiguration.set("icon", "book:" + spell.getKey());
wandConfiguration.set("name", messages.get("books.learnspell.name").replace("$spell", spell.getName()));
wandConfiguration.set("description", messages.get("books.learnspell.description").replace("$spell", spell.getName()));
wandConfiguration.set("overrides", "spell " + spell.getKey());
Wand wand = new Wand(this, wandConfiguration);
ItemStack item = wand.getItem();
item.setAmount(amount);
return item;
}
@Override
public MaterialAndData getRedstoneReplacement() {
return redstoneReplacement;
}
@Override
public Set<EntityType> getUndoEntityTypes() {
return undoEntityTypes;
}
@Override
public String describeItem(ItemStack item) {
return messages.describeItem(item);
}
public boolean checkForItem(Player player, ItemStack requireItem, boolean take) {
boolean foundItem = false;
ItemStack[] contents = player.getInventory().getContents();
for (int i = 0; i < contents.length; i++) {
ItemStack item = contents[i];
if (itemsAreEqual(item, requireItem)) {
Wand wand = null;
if (Wand.isWand(item) && Wand.isBound(item)) {
wand = getWand(item);
if (!wand.canUse(player)) continue;
}
if (take) {
player.getInventory().setItem(i, null);
if (wand != null) {
wand.unbind();
}
}
foundItem = true;
break;
}
}
return foundItem;
}
@Override
public boolean hasItem(Player player, ItemStack requireItem) {
return checkForItem(player, requireItem, false);
}
@Override
public boolean takeItem(Player player, ItemStack requireItem) {
return checkForItem(player, requireItem, true);
}
@Override
public boolean isWand(ItemStack item) {
return Wand.isWand(item);
}
@Override
public boolean isWandUpgrade(ItemStack item) {
return Wand.isUpgrade(item);
}
@Override
public boolean isSkill(ItemStack item) {
return Wand.isSkill(item);
}
@Override
public boolean isMagic(ItemStack item) {
return Wand.isSpecial(item);
}
@Nullable
@Override
public String getWandKey(ItemStack item) {
if (Wand.isWand(item)) {
return Wand.getWandTemplate(item);
}
return null;
}
@Override
public String getItemKey(ItemStack item) {
if (item == null) {
return "";
}
if (Wand.isUpgrade(item)) {
return "upgrade:" + Wand.getWandTemplate(item);
}
if (Wand.isWand(item)) {
return "wand:" + Wand.getWandTemplate(item);
}
if (Wand.isSpell(item)) {
return "spell:" + Wand.getSpell(item);
}
if (Wand.isBrush(item)) {
return "brush:" + Wand.getBrush(item);
}
ItemData mappedItem = getItem(item);
if (mappedItem != null) {
return mappedItem.getKey();
}
MaterialAndData material = new MaterialAndData(item);
return material.getKey();
}
@Nullable
@Override
public ItemStack createItem(String magicItemKey) {
return createItem(magicItemKey, false);
}
@Nullable
@Override
public ItemStack createItem(String magicItemKey, boolean brief) {
return createItem(magicItemKey, null, brief, null);
}
@Nullable
@Override
public ItemStack createItem(String magicItemKey, Mage mage, boolean brief, ItemUpdatedCallback callback) {
ItemStack itemStack = null;
if (magicItemKey == null || magicItemKey.isEmpty()) {
if (callback != null) {
callback.updated(null);
}
return null;
}
if (magicItemKey.contains("skill:")) {
String spellKey = magicItemKey.substring(6);
itemStack = Wand.createSpellItem(spellKey, this, mage, null, false);
InventoryUtils.setMeta(itemStack, "skill", "true");
if (callback != null) {
callback.updated(itemStack);
}
return itemStack;
}
// Check for amounts
int amount = 1;
if (magicItemKey.contains("@")) {
String[] pieces = StringUtils.split(magicItemKey, '@');
magicItemKey = pieces[0];
try {
amount = Integer.parseInt(pieces[1]);
} catch (Exception ignored) {
}
}
// Handle : or | as delimiter
magicItemKey = magicItemKey.replace("|", ":");
String[] pieces = StringUtils.split(magicItemKey, ":", 2);
String itemKey = pieces[0];
if (pieces.length > 1) {
String itemData = pieces[1];
try {
switch (itemKey) {
case "book": {
com.elmakers.mine.bukkit.api.spell.SpellCategory category;
if (!itemData.isEmpty() && !itemData.equalsIgnoreCase("all")) {
category = categories.get(itemData);
if (category == null) {
SpellTemplate spell = getSpellTemplate(itemData);
if (spell == null) {
if (callback != null) {
callback.updated(null);
}
return null;
} else {
itemStack = getSpellBook(spell, amount);
}
} else {
itemStack = getSpellBook(category, amount);
}
}
}
break;
case "learnbook": {
SpellTemplate spell = getSpellTemplate(itemData);
if (spell == null) {
if (callback != null) {
callback.updated(null);
}
return null;
}
itemStack = getLearnSpellBook(spell, amount);
}
break;
case "recipe": {
itemStack = CompatibilityUtils.getKnowledgeBook();
if (itemStack != null) {
if (itemData.equals("*")) {
Collection<String> keys = crafting.getRecipeKeys();
for (String key : keys) {
CompatibilityUtils.addRecipeToBook(itemStack, plugin, key);
}
} else {
String[] recipeKeys = StringUtils.split(itemData, ",");
for (String recipe : recipeKeys) {
CompatibilityUtils.addRecipeToBook(itemStack, plugin, recipe);
}
}
}
}
break;
case "recipes": {
itemStack = CompatibilityUtils.getKnowledgeBook();
if (itemStack != null) {
if (itemData.equals("*")) {
Collection<String> keys = crafting.getRecipeKeys();
for (String key : keys) {
CompatibilityUtils.addRecipeToBook(itemStack, plugin, key);
}
} else {
String[] recipeKeys = StringUtils.split(itemData, ",");
for (String recipe : recipeKeys) {
MageClassTemplate mageClass = getMageClassTemplate(recipe);
if (mageClass != null) {
for (String key : mageClass.getRecipies()) {
CompatibilityUtils.addRecipeToBook(itemStack, plugin, key);
}
}
}
}
}
}
break;
case "spell": {
// Fix delimiter replaced above, to handle spell levels
String spellKey = itemData.replace(":", "|");
itemStack = createSpellItem(spellKey, brief);
}
break;
case "wand": {
com.elmakers.mine.bukkit.api.wand.Wand wand = createWand(itemData);
if (wand != null) {
itemStack = wand.getItem();
}
}
break;
case "upgrade": {
com.elmakers.mine.bukkit.api.wand.Wand wand = createWand(itemData);
if (wand != null) {
wand.makeUpgrade();
itemStack = wand.getItem();
}
}
break;
case "brush": {
itemStack = createBrushItem(itemData);
}
break;
case "item": {
itemStack = createGenericItem(itemData);
}
break;
default: {
// Currency
Currency currency = currencies.get(itemKey);
com.elmakers.mine.bukkit.api.block.MaterialAndData currencyIcon = currency == null ? null : currency.getIcon();
if (pieces.length > 1 && currencyIcon != null) {
itemStack = currencyIcon.getItemStack(1);
ItemMeta meta = itemStack.getItemMeta();
String name = currency.getName(messages);
String itemName = messages.get("currency." + itemKey + ".item_name", messages.get("currency.default.item_name"));
itemName = itemName.replace("$type", name);
itemName = itemName.replace("$amount", itemData);
meta.setDisplayName(itemName);
int intAmount;
try {
intAmount = Integer.parseInt(itemData);
} catch (Exception ex) {
getLogger().warning("Invalid amount '" + itemData + "' in " + currency.getKey() + " cost: " + magicItemKey);
if (callback != null) {
callback.updated(null);
}
return null;
}
String currencyDescription = messages.get("currency." + itemKey + ".description", messages.get("currency.default.description"));
if (currencyDescription.length() > 0) {
currencyDescription = currencyDescription.replace("$type", name);
currencyDescription = currencyDescription.replace("$amount", itemData);
List<String> lore = new ArrayList<>();
InventoryUtils.wrapText(ChatColor.translateAlternateColorCodes('&', currencyDescription), lore);
meta.setLore(lore);
}
itemStack.setItemMeta(meta);
itemStack = CompatibilityUtils.makeReal(itemStack);
InventoryUtils.makeUnbreakable(itemStack);
InventoryUtils.hideFlags(itemStack, 63);
Object currencyNode = InventoryUtils.createNode(itemStack, "currency");
InventoryUtils.setMetaInt(currencyNode, "amount", intAmount);
InventoryUtils.setMeta(currencyNode, "type", itemKey);
}
}
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error creating item: " + magicItemKey, ex);
}
}
// Final fallback, may be a plain item without any data, a
// custom item key, or some form of MaterialAnData
// also as some fallbacks for wands and classes wtihout a prefix
if (itemStack == null && items != null) {
try {
ItemData customItem = items.get(magicItemKey);
if (customItem != null) {
itemStack = customItem.getItemStack(amount);
if (callback != null) {
callback.updated(itemStack);
}
return itemStack;
}
MaterialAndData item = new MaterialAndData(magicItemKey);
if (item.isValid() && CompatibilityUtils.isLegacy(item.getMaterial())) {
short convertData = (item.getData() == null ? 0 : item.getData());
item = new MaterialAndData(CompatibilityUtils.migrateMaterial(item.getMaterial(), (byte) convertData));
}
if (item.isValid()) {
return item.getItemStack(amount, callback);
}
com.elmakers.mine.bukkit.api.wand.Wand wand = createWand(magicItemKey);
if (wand != null) {
ItemStack wandItem = wand.getItem();
if (wandItem != null) {
wandItem.setAmount(amount);
}
if (callback != null) {
callback.updated(wandItem);
}
return wandItem;
}
// Spells may be using the | delimiter for levels
// I am regretting overloading this delimiter!
String spellKey = magicItemKey.replace(":", "|");
itemStack = createSpellItem(spellKey, brief);
if (itemStack != null) {
itemStack.setAmount(amount);
if (callback != null) {
callback.updated(itemStack);
}
return itemStack;
}
itemStack = createBrushItem(magicItemKey);
if (itemStack != null) {
itemStack.setAmount(amount);
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error creating item: " + magicItemKey, ex);
}
}
if (callback != null) {
callback.updated(itemStack);
}
return itemStack;
}
@Nullable
@Override
public ItemStack createGenericItem(String key) {
ConfigurationSection template = getWandTemplateConfiguration(key);
if (template == null || !template.contains("icon")) {
return null;
}
MaterialAndData icon = ConfigurationUtils.toMaterialAndData(template.getString("icon"));
ItemStack item = icon.getItemStack(1);
ItemMeta meta = item.getItemMeta();
if (template.contains("name")) {
meta.setDisplayName(template.getString("name"));
} else {
String name = messages.get("wands." + key + ".name");
if (name != null && !name.isEmpty()) {
meta.setDisplayName(name);
}
}
List<String> lore = new ArrayList<>();
if (template.contains("description")) {
lore.add(template.getString("description"));
} else {
String description = messages.get("wands." + key + ".description");
if (description != null && !description.isEmpty()) {
lore.add(description);
}
}
meta.setLore(lore);
item.setItemMeta(meta);
return item;
}
@Override
public com.elmakers.mine.bukkit.api.wand.Wand createUpgrade(String wandKey) {
Wand wand = Wand.createWand(this, wandKey);
if (!wand.isUpgrade()) {
wand.makeUpgrade();
}
return wand;
}
@Nullable
@Override
public ItemStack createSpellItem(String spellKey) {
return Wand.createSpellItem(spellKey, this, null, true);
}
@Nullable
@Override
public ItemStack createSpellItem(String spellKey, boolean brief) {
return Wand.createSpellItem(spellKey, this, null, !brief);
}
@Nullable
@Override
public ItemStack createBrushItem(String brushKey) {
return Wand.createBrushItem(brushKey, this, null, true);
}
public boolean isSameItem(ItemStack first, ItemStack second) {
if (first.getType() != second.getType()) return false;
if (first.getDurability() != second.getDurability()) return false;
if (first.hasItemMeta() != second.hasItemMeta()) return false;
if (!first.hasItemMeta()) return true;
return first.getItemMeta().equals(second.getItemMeta());
}
@Override
public boolean itemsAreEqual(ItemStack first, ItemStack second) {
return itemsAreEqual(first, second, false);
}
@Override
public boolean itemsAreEqual(ItemStack first, ItemStack second, boolean ignoreDamage) {
boolean firstIsEmpty = CompatibilityUtils.isEmpty(first);
boolean secondIsEmpty = CompatibilityUtils.isEmpty(second);
if (secondIsEmpty && firstIsEmpty) return true;
if (secondIsEmpty || firstIsEmpty) return false;
if (first.getType() != second.getType()) return false;
if (!ignoreDamage && first.getDurability() != second.getDurability()) return false;
boolean firstIsWand = Wand.isWandOrUpgrade(first);
boolean secondIsWand = Wand.isWandOrUpgrade(second);
if (firstIsWand || secondIsWand) {
if (!firstIsWand || !secondIsWand) return false;
Wand firstWand = getWand(InventoryUtils.getCopy(first));
Wand secondWand = getWand(InventoryUtils.getCopy(second));
String firstTemplate = firstWand.getTemplateKey();
String secondTemplate = secondWand.getTemplateKey();
if (firstTemplate == null || secondTemplate == null) return false;
return firstTemplate.equalsIgnoreCase(secondTemplate);
}
String firstSpellKey = Wand.getSpell(first);
String secondSpellKey = Wand.getSpell(second);
if (firstSpellKey != null || secondSpellKey != null) {
if (firstSpellKey == null || secondSpellKey == null) return false;
return firstSpellKey.equalsIgnoreCase(secondSpellKey);
}
String firstBrushKey = Wand.getBrush(first);
String secondBrushKey = Wand.getBrush(second);
if (firstBrushKey != null || secondBrushKey != null) {
if (firstBrushKey == null || secondBrushKey == null) return false;
return firstBrushKey.equalsIgnoreCase(secondBrushKey);
}
String firstName = first.hasItemMeta() ? first.getItemMeta().getDisplayName() : null;
String secondName = second.hasItemMeta() ? second.getItemMeta().getDisplayName() : null;
if (!Objects.equals(firstName, secondName)) {
return false;
}
MaterialAndData firstData = new MaterialAndData(first);
MaterialAndData secondData = new MaterialAndData(second);
return firstData.equals(secondData);
}
@Override
public Set<String> getWandPathKeys() {
return WandUpgradePath.getPathKeys();
}
@Override
public com.elmakers.mine.bukkit.api.wand.WandUpgradePath getPath(String key) {
return WandUpgradePath.getPath(key);
}
@Nullable
@Override
public ItemStack deserialize(ConfigurationSection root, String key) {
ConfigurationSection itemSection = root.getConfigurationSection(key);
if (itemSection == null) {
return null;
}
// Fix up busted items
if (itemSection.getInt("amount", 0) == 0) {
itemSection.set("amount", 1);
}
ItemStack item = itemSection.getItemStack("item");
if (item == null) {
return null;
}
if (itemSection.contains("wand")) {
item = InventoryUtils.makeReal(item);
Wand.configToItem(itemSection, item);
} else if (itemSection.contains("spell")) {
item = InventoryUtils.makeReal(item);
Object spellNode = CompatibilityUtils.createNode(item, "spell");
CompatibilityUtils.setMeta(spellNode, "key", itemSection.getString("spell"));
if (itemSection.contains("skill")) {
InventoryUtils.setMeta(item, "skill", "true");
}
} else if (itemSection.contains("brush")) {
item = InventoryUtils.makeReal(item);
InventoryUtils.setMeta(item, "brush", itemSection.getString("brush"));
}
return item;
}
@Override
public void serialize(ConfigurationSection root, String key, ItemStack item) {
ConfigurationSection itemSection = root.createSection(key);
itemSection.set("item", item);
if (Wand.isWandOrUpgrade(item)) {
ConfigurationSection stateNode = itemSection.createSection("wand");
Wand.itemToConfig(item, stateNode);
} else if (Wand.isSpell(item)) {
itemSection.set("spell", Wand.getSpell(item));
if (Wand.isSkill(item)) {
itemSection.set("skill", "true");
}
} else if (Wand.isBrush(item)) {
itemSection.set("brush", Wand.getBrush(item));
}
}
@Override
public void disableItemSpawn() {
entityController.setDisableItemSpawn(true);
}
@Override
public void enableItemSpawn() {
entityController.setDisableItemSpawn(false);
}
@Override
public void setForceSpawn(boolean force) {
entityController.setForceSpawn(force);
}
public HeroesManager getHeroes() {
return heroesManager;
}
@Nullable
public ManaController getManaController() {
if (useHeroesMana && heroesManager != null) return heroesManager;
if (useSkillAPIMana && skillAPIManager != null) return skillAPIManager;
return null;
}
public String getDefaultSkillIcon() {
return defaultSkillIcon;
}
public int getSkillInventoryRows() {
return skillInventoryRows;
}
public boolean usePermissionSkills() {
return skillsUsePermissions;
}
public boolean useHeroesSkills() {
return skillsUseHeroes;
}
@Override
public void addFlightExemption(Player player, int duration) {
ncpManager.addFlightExemption(player, duration);
CompatibilityUtils.addFlightExemption(player, duration * 20 / 1000);
}
@Override
public void addFlightExemption(Player player) {
ncpManager.addFlightExemption(player);
}
@Override
public void removeFlightExemption(Player player) {
ncpManager.removeFlightExemption(player);
}
public String getExtraSchematicFilePath() {
return extraSchematicFilePath;
}
@Override
public void warpPlayerToServer(Player player, String server, String warp) {
com.elmakers.mine.bukkit.magic.Mage mage = getMage(player);
mage.setDestinationWarp(warp);
info("Cross-server warping " + player.getName() + " to warp " + warp, 1);
sendPlayerToServer(player, server);
}
@Override
public void sendPlayerToServer(final Player player, final String server) {
MageDataCallback callback = new MageDataCallback() {
@Override
public void run(MageData data) {
Bukkit.getScheduler().runTaskLater(plugin, new ChangeServerTask(plugin, player, server), 1);
}
};
info("Moving " + player.getName() + " to server " + server, 1);
Mage mage = getRegisteredMage(player);
if (mage != null) {
playerQuit(mage, callback);
} else {
callback.run(null);
}
}
@Override
public boolean isDisguised(Entity entity) {
return libsDisguiseEnabled && libsDisguiseManager != null && entity != null && libsDisguiseManager.isDisguised(entity);
}
@Override
public boolean hasDisguises() {
return libsDisguiseEnabled && libsDisguiseManager != null;
}
@Override
public boolean disguise(Entity entity, ConfigurationSection configuration) {
if (!libsDisguiseEnabled || libsDisguiseManager == null || entity == null) {
return false;
}
return libsDisguiseManager.disguise(entity, configuration);
}
@Override
public boolean isPathUpgradingEnabled() {
return autoPathUpgradesEnabled;
}
@Override
public boolean isSpellUpgradingEnabled() {
return autoSpellUpgradesEnabled;
}
@Override
public boolean isSpellProgressionEnabled() {
return spellProgressionEnabled;
}
public boolean isLoaded() {
return loaded && !shuttingDown;
}
public boolean isDataLoaded() {
return loaded && dataLoaded && !shuttingDown;
}
public boolean areLocksProtected() {
return protectLocked;
}
public boolean isContainer(Block block) {
return block != null && containerMaterials.testBlock(block);
}
/**
* Checks if an item is a melee material, as specified by the {@code melee}
* list in {@code materials.yml}. This is primarily used to detect if left
* clicking an entity should indicate melee damage or a spell being cast.
*
* @param item The item to check.
* @return Whether or not this is a melee weapon.
*/
public boolean isMeleeWeapon(ItemStack item) {
return item != null && meleeMaterials.testItem(item);
}
public boolean isWearable(ItemStack item) {
return item != null && wearableMaterials.testItem(item);
}
public boolean isInteractible(Block block) {
return block != null && interactibleMaterials.testBlock(block);
}
public boolean isSpellDroppingEnabled() {
return spellDroppingEnabled;
}
@Override
public boolean isSPEnabled() {
return spEnabled;
}
@Override
public boolean isSPEarnEnabled() {
return spEarnEnabled;
}
@Override
public int getSPMaximum() {
return (int) getCurrency("sp").getMaxValue();
}
@Override
public boolean isVaultCurrencyEnabled() {
return VaultController.hasEconomy();
}
@Override
public void depositVaultCurrency(OfflinePlayer player, double amount) {
VaultController.getInstance().depositPlayer(player, amount);
}
@Override
public void deleteMage(final String id) {
final Mage mage = getRegisteredMage(id);
if (mage != null) {
playerQuit(mage, new MageDataCallback() {
@Override
public void run(MageData data) {
info("Deleted mage id " + id);
mageDataStore.delete(id);
// If this was a player and that player is online, reload them so they function normally.
Player player = mage.getPlayer();
if (player != null && player.isOnline()) {
getMage(player);
}
}
});
} else {
info("Deleted offline mage id " + id);
mageDataStore.delete(id);
}
}
public long getPhysicsTimeout() {
if (physicsHandler != null) {
return physicsHandler.getTimeout();
}
return 0;
}
@Nullable
@Override
public String getSpell(ItemStack item) {
return Wand.getSpell(item);
}
@Nullable
@Override
public String getSpellArgs(ItemStack item) {
return Wand.getSpellArgs(item);
}
@Override
public Set<String> getNPCKeys() {
Set<String> keys = new HashSet<>();
for (EntityData mob : mobs.getMobs()) {
if (mob.isNPC() && !mob.isHidden()) {
keys.add(mob.getKey());
}
}
return keys;
}
@Override
public Set<String> getMobKeys(boolean showHidden) {
if (showHidden) {
return mobs.getKeys();
}
return new HashSet<>(mobs.getMobs().stream()
.filter(mob -> !mob.isHidden())
.map(EntityData::getKey)
.collect(Collectors.toList()));
}
@Override
public Set<String> getMobKeys() {
return getMobKeys(false);
}
@Nullable
@Override
public Entity spawnMob(String key, Location location) {
EntityData mobType = mobs.get(key);
if (mobType != null) {
return mobType.spawn(location);
}
EntityType entityType = com.elmakers.mine.bukkit.entity.EntityData.parseEntityType(key);
if (entityType == null) {
return null;
}
return location.getWorld().spawnEntity(location, entityType);
}
@Nullable
@Override
public EntityData getMob(Entity entity) {
return mobs.getEntityData(entity);
}
@Override
@Nullable
public com.elmakers.mine.bukkit.entity.EntityData getMob(String key) {
if (key == null) return null;
// This null check is hopefully temporary, but deals with actions that look up a mob during interrogation.
com.elmakers.mine.bukkit.entity.EntityData mob = mobs == null ? null : mobs.get(key);
if (mob == null && mobs != null) {
EntityType entityType = com.elmakers.mine.bukkit.entity.EntityData.parseEntityType(key);
if (entityType != null) {
mob = mobs.getDefaultMob(entityType);
}
}
return mob;
}
@Override
@Nullable
public EntityData getMob(ConfigurationSection parameters) {
String mobType = parameters.getString("type");
com.elmakers.mine.bukkit.entity.EntityData mob = null;
if (mobType != null && !mobType.isEmpty()) {
mob = getMob(mobType);
}
if (mob != null && parameters != null && !parameters.getKeys(false).isEmpty()) {
mob = mob.clone();
ConfigurationSection effectiveParameters = ConfigurationUtils.cloneConfiguration(mob.getConfiguration());
// Have to preserve the mob type config, it can't be overridden
String originalType = effectiveParameters.getString("type", mobType);
effectiveParameters = ConfigurationUtils.addConfigurations(effectiveParameters, parameters);
effectiveParameters.set("type", originalType);
mob.load(effectiveParameters);
} else if (mob == null) {
mob = new com.elmakers.mine.bukkit.entity.EntityData(this, parameters);
}
return mob;
}
@Override
@Nullable
public EntityData getMobByName(String name) {
return mobs.getByName(name);
}
@Override
public EntityData loadMob(ConfigurationSection configuration) {
return new com.elmakers.mine.bukkit.entity.EntityData(this, configuration);
}
@Override
@Nullable
public Entity replaceMob(Entity targetEntity, EntityData replaceType, boolean force, CreatureSpawnEvent.SpawnReason reason) {
EntityData targetData = getMob(targetEntity);
EntityData newData = replaceType;
if (targetData != null) {
newData = targetData.clone();
ConfigurationSection effectiveParameters = ConfigurationUtils.cloneConfiguration(newData.getConfiguration());
ConfigurationSection newParameters = replaceType.getConfiguration();
effectiveParameters = ConfigurationUtils.addConfigurations(effectiveParameters, newParameters);
// Handle the replacement type being bare
effectiveParameters.set("type", replaceType.getType().name());
newData.load(effectiveParameters);
}
if (force) {
setForceSpawn(true);
}
Entity spawnedEntity = null;
try {
spawnedEntity = newData.spawn(targetEntity.getLocation(), reason);
} catch (Exception ex) {
ex.printStackTrace();
}
if (force) {
setForceSpawn(false);
}
if (spawnedEntity != null) {
targetEntity.remove();
}
return spawnedEntity;
}
@Override
public Set<String> getItemKeys() {
return items.getKeys();
}
@Override
@Nullable
public ItemData getItem(String key) {
return items.get(key);
}
@Override
@Nullable
public ItemData getItem(ItemStack match) {
return items.get(match);
}
@Nullable
@Override
public ItemData getOrCreateItem(String key) {
if (key == null || key.isEmpty()) {
return null;
}
return items.getOrCreate(key);
}
@Nullable
@Override
@Deprecated
public ItemData getOrCreateItemOrWand(String key) {
return getOrCreateItem(key);
}
@Nullable
@Override
@Deprecated
public ItemData getOrCreateMagicItem(String key) {
return getOrCreateItem(key);
}
public void updateOnEquip(ItemStack stack) {
items.updateOnEquip(stack);
}
@Override
public ItemData createItemData(ItemStack itemStack) {
return new com.elmakers.mine.bukkit.item.ItemData(itemStack, this);
}
@Nullable
public String getLockKey(ItemStack itemStack) {
if (itemStack == null) return null;
ItemData data = getItem(itemStack);
if (data == null) {
data = getItem(itemStack.getType().name().toLowerCase());
}
if (data != null && data.isLocked()) {
return data.getKey();
}
return null;
}
@Override
public void unloadItemTemplate(String key) {
items.remove(key);
}
@Override
public void loadItemTemplate(String key, ConfigurationSection configuration) {
items.loadItem(key, configuration);
}
@Nullable
@Override
public Double getWorth(ItemStack item) {
return getWorth(item, "currency");
}
@Nullable
@Override
public Double getWorth(ItemStack item, String inCurrencyKey) {
Currency toCurrency = getCurrency(inCurrencyKey);
if (toCurrency == null || toCurrency.getWorth() == 0) {
return null;
}
String spellKey = Wand.getSpell(item);
if (spellKey != null) {
Currency spellPointCurrency = getCurrency("sp");
SpellTemplate spell = getSpellTemplate(spellKey);
if (spell != null) {
double spWorth = spellPointCurrency == null ? 1 : spellPointCurrency.getWorth();
return spell.getWorth() * spWorth / toCurrency.getWorth();
}
}
int amount = item.getAmount();
item.setAmount(1);
ItemData configuredItem = items.get(item);
item.setAmount(amount);
if (configuredItem == null) {
Wand wand = getIfWand(item);
if (wand == null) {
InventoryUtils.CurrencyAmount currencyAmount = InventoryUtils.getCurrency(item);
Currency currency = currencyAmount == null ? null : getCurrency(currencyAmount.type);
if (currency != null) {
return currency.getWorth() * currencyAmount.amount * item.getAmount() / toCurrency.getWorth();
}
return null;
}
return (double) wand.getWorth() / toCurrency.getWorth();
}
return configuredItem.getWorth() * amount / toCurrency.getWorth();
}
@Nullable
@Override
public Double getEarns(ItemStack item) {
return getEarns(item, "currency");
}
@Nullable
@Override
public Double getEarns(ItemStack item, String inCurrencyKey) {
Currency toCurrency = getCurrency(inCurrencyKey);
if (toCurrency == null || toCurrency.getWorth() == 0) {
return null;
}
int amount = item.getAmount();
item.setAmount(1);
ItemData configuredItem = items.get(item);
item.setAmount(amount);
if (configuredItem == null) {
return null;
}
return configuredItem.getEarns() * amount / toCurrency.getWorth();
}
public boolean isInventoryBackupEnabled() {
return backupInventories;
}
@Nullable
@Override
public String getBlockSkin(Material blockType) {
return blockSkins.get(blockType);
}
@Override
@Nonnull
public Random getRandom() {
return random;
}
@Override
public boolean sendResourcePackToAllPlayers(CommandSender sender) {
return resourcePacks.sendResourcePackToAllPlayers(sender);
}
@Override
public boolean promptResourcePack(final Player player) {
return resourcePacks.promptResourcePack(player);
}
@Override
public boolean promptNoResourcePack(final Player player) {
return resourcePacks.promptNoResourcePack(player);
}
@Override
public boolean sendResourcePack(final Player player) {
return resourcePacks.sendResourcePack(player);
}
@Override
public void checkResourcePack(CommandSender sender) {
resourcePacks.clearChecked();
checkResourcePack(sender, false, true);
}
public boolean checkResourcePack(final CommandSender sender, final boolean quiet) {
return checkResourcePack(sender, quiet, false);
}
public boolean checkResourcePack(final CommandSender sender, final boolean quiet, final boolean force) {
return resourcePacks.checkResourcePack(sender, quiet, force, false);
}
@Override
public boolean isResourcePackEnabled() {
return resourcePacks.isResourcePackEnabled();
}
@Nullable
@Override
public Material getMobEgg(EntityType mobType) {
return mobEggs.get(mobType);
}
@Nullable
@Override
public String getMobSkin(EntityType mobType) {
return mobSkins.get(mobType);
}
@Nullable
@Override
public String getPlayerSkin(Player player) {
return libsDisguiseManager == null ? null : libsDisguiseManager.getSkin(player);
}
@Override
@Nonnull
public ItemStack getURLSkull(String url) {
try {
ItemStack stack = getURLSkull(new URL(url), InventoryUtils.SKULL_UUID);
return stack == null ? new ItemStack(Material.AIR) : stack;
} catch (MalformedURLException e) {
Bukkit.getLogger().log(Level.WARNING, "Malformed URL: " + url, e);
}
return new ItemStack(Material.AIR);
}
@Nullable
private ItemStack getURLSkull(URL url, UUID id) {
MaterialAndData skullType = skullItems.get(EntityType.PLAYER);
if (skullType == null) {
return new ItemStack(Material.AIR);
}
ItemStack skull = skullType.getItemStack(1);
return InventoryUtils.setSkullURL(skull, url, id);
}
@Override
public void setSkullOwner(Skull skull, String ownerName) {
DeprecatedUtils.setOwner(skull, ownerName);
}
@Override
public void setSkullOwner(Skull skull, UUID uuid) {
DeprecatedUtils.setOwner(skull, uuid);
}
@Override
@Nonnull
@Deprecated
public ItemStack getSkull(String ownerName, String itemName) {
return getSkull(ownerName, itemName, null);
}
@Override
@Nonnull
public ItemStack getSkull(String ownerName, String itemName, final ItemUpdatedCallback callback) {
MaterialAndData skullType = skullItems.get(EntityType.PLAYER);
if (skullType == null) {
ItemStack air = new ItemStack(Material.AIR);
if (callback != null) {
callback.updated(air);
}
return air;
}
ItemStack skull = skullType.getItemStack(1);
ItemMeta meta = skull.getItemMeta();
if (itemName != null) {
meta.setDisplayName(itemName);
}
skull.setItemMeta(meta);
SkullLoadedCallback skullCallback = null;
if (callback != null) {
skullCallback = new SkullLoadedCallback() {
@Override
public void updated(ItemStack itemStack) {
callback.updated(itemStack);
}
};
}
DeprecatedUtils.setSkullOwner(skull, ownerName, skullCallback);
return skull;
}
@Override
@Nonnull
public ItemStack getSkull(UUID uuid, String itemName, ItemUpdatedCallback callback) {
MaterialAndData skullType = skullItems.get(EntityType.PLAYER);
if (skullType == null) {
return new ItemStack(Material.AIR);
}
ItemStack skull = skullType.getItemStack(1);
ItemMeta meta = skull.getItemMeta();
if (itemName != null) {
meta.setDisplayName(itemName);
}
skull.setItemMeta(meta);
SkullLoadedCallback skullCallback = null;
if (callback != null) {
skullCallback = new SkullLoadedCallback() {
@Override
public void updated(ItemStack itemStack) {
callback.updated(itemStack);
}
};
}
DeprecatedUtils.setSkullOwner(skull, uuid, skullCallback);
return skull;
}
@Override
@Nonnull
public ItemStack getSkull(Player player, String itemName) {
MaterialAndData skullType = skullItems.get(EntityType.PLAYER);
if (skullType == null) {
return new ItemStack(Material.AIR);
}
ItemStack skull = skullType.getItemStack(1);
ItemMeta meta = skull.getItemMeta();
if (itemName != null) {
meta.setDisplayName(itemName);
}
skull.setItemMeta(meta);
DeprecatedUtils.setSkullOwner(skull, player.getName(), null);
return skull;
}
@Override
@Nonnull
@Deprecated
public ItemStack getSkull(Entity entity, String itemName) {
if (entity instanceof Player) {
return getSkull((Player) entity, itemName);
}
return getSkull(entity, itemName, null);
}
@Override
@Nonnull
public ItemStack getSkull(Entity entity, String itemName, ItemUpdatedCallback callback) {
String ownerName = null;
MaterialAndData skullType = skullItems.get(entity.getType());
if (skullType == null) {
ownerName = getMobSkin(entity.getType());
skullType = skullItems.get(EntityType.PLAYER);
if (skullType == null || ownerName == null) {
ItemStack air = new ItemStack(Material.AIR);
if (callback != null) {
callback.updated(air);
}
return air;
}
}
if (entity instanceof Player) {
ownerName = entity.getName();
}
ItemStack skull = skullType.getItemStack(1);
ItemMeta meta = skull.getItemMeta();
if (itemName != null) {
meta.setDisplayName(itemName);
}
skull.setItemMeta(meta);
if (ownerName != null) {
SkullLoadedCallback skullCallback = null;
if (callback != null) {
skullCallback = new SkullLoadedCallback() {
@Override
public void updated(ItemStack itemStack) {
callback.updated(itemStack);
}
};
}
if (ownerName.startsWith("http")) {
skull = InventoryUtils.setSkullURL(skull, ownerName);
if (callback != null) {
callback.updated(skull);
}
} else {
DeprecatedUtils.setSkullOwner(skull, ownerName, skullCallback);
}
} else if (callback != null) {
callback.updated(skull);
}
return skull;
}
@Nonnull
@Override
public ItemStack getMap(int mapId) {
short durability = NMSUtils.isCurrentVersion() ? 0 : (short) mapId;
ItemStack mapItem = new ItemStack(DefaultMaterials.getFilledMap(), 1, durability);
if (NMSUtils.isCurrentVersion()) {
mapItem = CompatibilityUtils.makeReal(mapItem);
InventoryUtils.setMetaInt(mapItem, "map", mapId);
}
return mapItem;
}
@Override
public void managePlayerData(boolean external, boolean backupInventories) {
savePlayerData = !external;
externalPlayerData = external;
this.backupInventories = backupInventories;
}
public void initializeWorldGuardFlags() {
worldGuardManager.initializeFlags(plugin);
}
@Override
public String getDefaultWandTemplate() {
return Wand.DEFAULT_WAND_TEMPLATE;
}
@Nullable
@Override
public Object getWandProperty(ItemStack item, String key) {
Preconditions.checkNotNull(key, "key");
if (InventoryUtils.isEmpty(item)) return null;
Object wandNode = InventoryUtils.getNode(item, Wand.WAND_KEY);
if (wandNode == null) return null;
Object value = InventoryUtils.getMetaObject(wandNode, key);
if (value == null) {
WandTemplate template = getWandTemplate(InventoryUtils.getMetaString(wandNode, "template"));
if (template != null) {
value = template.getProperty(key);
}
}
return value;
}
@Override
public <T> T getWandProperty(ItemStack item, String key, T defaultValue) {
Preconditions.checkNotNull(key, "key");
Preconditions.checkNotNull(defaultValue, "defaultValue");
if (InventoryUtils.isEmpty(item)) {
return defaultValue;
}
Object wandNode = InventoryUtils.getNode(item, Wand.WAND_KEY);
if (wandNode == null) {
return defaultValue;
}
// Obtain the type via the default value.
// (This is unchecked because of type erasure)
@SuppressWarnings("unchecked")
Class<? extends T> clazz = (Class<? extends T>) defaultValue.getClass();
// Value directly stored on wand
Object value = InventoryUtils.getMetaObject(wandNode, key);
if (value != null) {
if (clazz.isInstance(value)) {
return clazz.cast(value);
}
return defaultValue;
}
String tplName = InventoryUtils.getMetaString(wandNode, "template");
WandTemplate template = getWandTemplate(tplName);
if (template != null) {
return template.getProperty(key, defaultValue);
}
return defaultValue;
}
public boolean useHeroesMana() {
return useHeroesMana;
}
public boolean useSkillAPIMana() {
return useSkillAPIMana;
}
public @Nonnull
MageIdentifier getMageIdentifier() {
return mageIdentifier;
}
public void setMageIdentifier(@Nonnull MageIdentifier mageIdentifier) {
Preconditions.checkNotNull(mageIdentifier, "mageIdentifier");
this.mageIdentifier = mageIdentifier;
}
@Override
public String getHeroesSkillPrefix() {
return heroesSkillPrefix;
}
public List<AttributeProvider> getAttributeProviders() {
return attributeProviders;
}
@Override
@Nullable
public MagicAttribute getAttribute(String attributeKey) {
return attributes.get(attributeKey);
}
@Override
public boolean createLight(Location location, int lightLevel, boolean async) {
if (lightAPIManager == null) return false;
long blockId = BlockData.getBlockId(location);
String chunkId = getChunkKey(location);
Integer chunkRefs = lightChunks.get(chunkId);
if (chunkRefs == null) {
lightChunks.put(chunkId, 1);
} else {
lightChunks.put(chunkId, chunkRefs + 1);
}
Integer refCount = lightBlocks.get(blockId);
if (refCount != null) {
lightBlocks.put(blockId, refCount + 1);
return false;
}
lightBlocks.put(blockId, 1);
return lightAPIManager.createLight(location, lightLevel, async);
}
@Override
public boolean deleteLight(Location location, boolean async) {
if (lightAPIManager == null) return false;
long blockId = BlockData.getBlockId(location);
Integer refCount = lightBlocks.get(blockId);
String chunkId = getChunkKey(location);
Integer chunkRefs = lightChunks.get(chunkId);
if (chunkRefs != null) {
if (chunkRefs <= 1) {
lightChunks.remove(chunkId);
} else {
lightChunks.put(chunkId, chunkRefs - 1);
}
}
if (refCount != null) {
if (refCount <= 1) {
lightBlocks.remove(blockId);
} else {
lightBlocks.put(blockId, refCount - 1);
return false;
}
}
return lightAPIManager.deleteLight(location, async);
}
@Override
public boolean updateLight(Location location) {
return updateLight(location, true);
}
@Override
public boolean updateLight(Location location, boolean force) {
if (lightAPIManager == null) return false;
if (!force) {
String chunkId = getChunkKey(location);
Integer chunkRefs = lightChunks.get(chunkId);
if (chunkRefs != null) return false;
}
return lightAPIManager.updateChunks(location);
}
@Override
public int getLightCount() {
return lightBlocks.size();
}
@Override
public boolean isLightingAvailable() {
return lightAPIManager != null;
}
@Override
public @Nullable
String checkRequirements(@Nonnull MageContext context, @Nullable Collection<Requirement> requirements) {
if (requirements == null) return null;
for (Requirement requirement : requirements) {
String type = requirement.getType();
RequirementsProcessor processor = requirementProcessors.get(type);
if (processor != null) {
if (!processor.checkRequirement(context, requirement)) {
String message = processor.getRequirementDescription(context, requirement);
if (message == null || message.isEmpty()) {
message = messages.get("requirements.unknown");
}
return message;
}
}
}
return null;
}
@Override
public @Nonnull
Collection<String> getLoadedExamples() {
List<String> examples = new ArrayList<>();
if (exampleDefaults != null && !exampleDefaults.isEmpty()) examples.add(exampleDefaults);
if (addExamples != null) examples.addAll(addExamples);
return examples;
}
@Nullable
@Override
public String getExample() {
return exampleDefaults != null && exampleDefaults.isEmpty() ? null : exampleDefaults;
}
@Nonnull
@Override
public Collection<String> getExamples() {
List<String> examples = new ArrayList<>();
try {
CodeSource src = MagicController.class.getProtectionDomain().getCodeSource();
if (src != null) {
URL jar = src.getLocation();
try (InputStream is = jar.openStream();
ZipInputStream zip = new ZipInputStream(is)) {
while (true) {
ZipEntry e = zip.getNextEntry();
if (e == null)
break;
String name = e.getName();
if (!name.equals("examples/")
&& !name.equals("examples/localizations/")
&& name.startsWith("examples/")
&& name.endsWith("/") && !name.contains(".")) {
examples.add(name.replace("examples/", "").replace("/", ""));
}
}
}
}
} catch (IOException ex) {
plugin.getLogger().log(Level.WARNING, "Error scanning example files", ex);
}
examples.addAll(getDownloadedExternalExamples());
return examples;
}
@Nonnull
@Override
public Collection<String> getLocalizations() {
List<String> examples = new ArrayList<>();
try {
CodeSource src = MagicController.class.getProtectionDomain().getCodeSource();
if (src != null) {
URL jar = src.getLocation();
try (InputStream is = jar.openStream();
ZipInputStream zip = new ZipInputStream(is)) {
while (true) {
ZipEntry e = zip.getNextEntry();
if (e == null)
break;
String name = e.getName();
if (!name.equals("examples/")
&& !name.equals("examples/localizations/")
&& name.startsWith("examples/localizations/messages.")
&& name.endsWith(".yml")) {
examples.add(name.replace("examples/localizations/messages.", "").replace(".yml", ""));
}
}
}
}
} catch (IOException ex) {
plugin.getLogger().log(Level.WARNING, "Error scanning example files", ex);
}
return examples;
}
@Nonnull
@Override
public Collection<String> getExternalExamples() {
Set<String> examples = getDownloadedExternalExamples();
examples.addAll(builtinExternalExamples.keySet());
return examples;
}
public Set<String> getDownloadedExternalExamples() {
Set<String> examples = new HashSet<>();
File examplesFolder = new File(getPlugin().getDataFolder(), "examples");
if (examplesFolder.exists()) {
for (File file : examplesFolder.listFiles()) {
if (!file.isDirectory() || file.getName().contains(".")) continue;
examples.add(file.getName());
}
}
return examples;
}
public void updateExternalExamples(CommandSender sender) {
Collection<String> examples = getDownloadedExternalExamples();
if (examples.isEmpty()) {
loadConfiguration(sender);
return;
}
Set<String> loadedExamples = new HashSet<>(getLoadedExamples());
sender.sendMessage(getMessages().get("commands.mconfig.example.fetch.wait_all").replace("$count", Integer.toString(examples.size())));
UpdateAllExamplesCallback callback = new UpdateAllExamplesCallback(sender, this);
for (String exampleKey : examples) {
if (!loadedExamples.contains(exampleKey)) {
sender.sendMessage(getMessages().get("commands.mconfig.example.fetch.skip").replace("$example", exampleKey));
continue;
}
String url = getExternalExampleURL(exampleKey);
if (url == null || url.isEmpty()) {
continue;
}
callback.loading();
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new FetchExampleRunnable(this, sender, exampleKey, url, callback, true));
}
callback.check();
}
@Nullable
@Override
public String getExternalExampleURL(String exampleKey) {
String url = null;
File exampleFolder = new File(getPlugin().getDataFolder(), "examples");
exampleFolder = new File(exampleFolder, exampleKey);
File urlFile = new File(exampleFolder, "url.txt");
if (urlFile.exists()) {
try {
url = new String(Files.readAllBytes(Paths.get(urlFile.getAbsolutePath())), StandardCharsets.UTF_8);
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error loading example url from file: " + urlFile.getAbsolutePath(), ex);
}
}
if (url == null) {
url = builtinExternalExamples.get(exampleKey);
}
return url;
}
@Override
public double getBlockDurability(@Nonnull Block block) {
double durability = CompatibilityUtils.getDurability(block.getType());
if (citadelManager != null) {
Integer reinforcement = citadelManager.getDurability(block.getLocation());
if (reinforcement != null) {
durability += reinforcement;
}
}
return durability;
}
@Override
@Nonnull
public String getSkillsSpell() {
return skillsSpell;
}
@Override
@Nonnull
public Collection<EffectPlayer> getEffects(@Nonnull String effectKey) {
Collection<EffectPlayer> effectList = effects.get(effectKey);
if (effectList == null) {
effectList = new ArrayList<>();
}
return effectList;
}
@Override
public void playEffects(@Nonnull String effectKey, @Nonnull Location sourceLocation, @Nonnull Location targetLocation) {
Collection<EffectPlayer> effectPlayers = effects.get(effectKey);
if (effectPlayers == null) return;
for (EffectPlayer player : effectPlayers) {
player.start(sourceLocation, targetLocation);
}
}
@Override
public void playEffects(@Nonnull String effectKey, @Nonnull EffectContext context) {
Collection<EffectPlayer> effectPlayers = effects.get(effectKey);
if (effectPlayers == null) return;
for (EffectPlayer player : effectPlayers) {
player.start(context);
}
}
@Override
@Nonnull
public Collection<String> getEffectKeys() {
return effects.keySet();
}
@Override
public Collection<String> getRecipeKeys() {
return crafting.getRecipeKeys();
}
@Override
public Collection<String> getAutoDiscoverRecipeKeys() {
return crafting.getAutoDiscoverRecipeKeys();
}
public void checkVanished(Player player) {
for (Mage mage : mages.values()) {
if (mage.isVanished()) {
DeprecatedUtils.hidePlayer(plugin, player, mage.getPlayer());
}
}
}
@Override
public void logBlockChange(@Nonnull Mage mage, @Nonnull BlockState priorState, @Nonnull BlockState newState) {
if (logBlockManager != null) {
Entity entity = mage.getEntity();
if (entity != null) {
logBlockManager.logBlockChange(entity, priorState, newState);
}
}
}
@Override
public boolean isFileLockingEnabled() {
return isFileLockingEnabled;
}
/**
* @return The supplier set that is used.
*/
public NPCSupplierSet getNPCSuppliers() {
return npcSuppliers;
}
@Override
public Collection<com.elmakers.mine.bukkit.api.npc.MagicNPC> getNPCs() {
return new ArrayList<>(npcs.values());
}
@Override
public void removeNPC(com.elmakers.mine.bukkit.api.npc.MagicNPC npc) {
unregisterNPC(npc);
npc.remove();
npcs.remove(npc.getId());
npcsByEntity.remove(npc.getEntityId());
}
public void unregisterNPC(com.elmakers.mine.bukkit.api.npc.MagicNPC npc) {
String chunkId = getChunkKey(npc.getLocation());
if (chunkId == null) return;
List<MagicNPC> chunkNPCs = npcsByChunk.get(chunkId);
if (chunkNPCs == null) {
return;
}
Iterator<MagicNPC> it = chunkNPCs.iterator();
while (it.hasNext()) {
if (it.next().getId().equals(npc.getId())) {
it.remove();
break;
}
}
}
@Override
@Nullable
public MagicNPC addNPC(com.elmakers.mine.bukkit.api.magic.Mage creator, String name) {
EntityData template = mobs.get(name);
MagicNPC npc;
if (template != null && template instanceof com.elmakers.mine.bukkit.entity.EntityData) {
npc = new MagicNPC(this, creator, creator.getLocation(), (com.elmakers.mine.bukkit.entity.EntityData) template);
} else {
npc = new MagicNPC(this, creator, creator.getLocation(), name);
}
if (!registerNPC(npc)) {
return null;
}
return npc;
}
public boolean registerNPC(MagicNPC npc) {
Location location = npc.getLocation();
String chunkId = getChunkKey(location);
if (chunkId == null) {
return false;
}
List<MagicNPC> chunkNPCs = npcsByChunk.get(chunkId);
if (chunkNPCs == null) {
chunkNPCs = new ArrayList<>();
npcsByChunk.put(chunkId, chunkNPCs);
}
chunkNPCs.add(npc);
npcs.put(npc.getId(), npc);
activateNPC(npc);
return true;
}
@Override
@Nullable
public MagicNPC getNPC(@Nullable Entity entity) {
return npcsByEntity.get(entity.getUniqueId());
}
@Override
@Nullable
public MagicNPC getNPC(UUID id) {
return npcs.get(id);
}
public void restoreNPCs(final Chunk chunk) {
String chunkKey = getChunkKey(chunk);
List<MagicNPC> chunkData = npcsByChunk.get(chunkKey);
if (chunkData != null) {
for (MagicNPC npc : chunkData) {
npc.restore();
activateNPC(npc);
}
}
}
public void activateNPC(MagicNPC npc) {
npcsByEntity.put(npc.getEntityId(), npc);
}
@Override
@Nullable
public String getPlaceholder(Player player, String namespace, String placeholder) {
return placeholderAPIManager == null ? null : placeholderAPIManager.getPlaceholder(player, namespace, placeholder);
}
@Override
@Nonnull
public String setPlaceholders(Player player, String message) {
return placeholderAPIManager == null ? message : placeholderAPIManager.setPlaceholders(player, message);
}
@Override
public void registerMob(@Nonnull Entity entity, @Nonnull EntityData entityData) {
mobs.register(entity, (com.elmakers.mine.bukkit.entity.EntityData) entityData);
}
public CitizensController getCitizensController() {
return citizens;
}
@Override
public void lockChunk(Chunk chunk) {
Integer locked = lockedChunks.get(chunk);
if (locked == null) {
lockedChunks.put(chunk, 1);
CompatibilityUtils.lockChunk(chunk, plugin);
} else {
lockedChunks.put(chunk, locked + 1);
}
}
@Override
public void unlockChunk(Chunk chunk) {
Integer locked = lockedChunks.get(chunk);
if (locked == null || locked <= 1) {
lockedChunks.remove(chunk);
CompatibilityUtils.unlockChunk(chunk, plugin);
} else {
lockedChunks.put(chunk, locked - 1);
}
}
@Override
@Nonnull
public Collection<Chunk> getLockedChunks() {
return lockedChunks.keySet();
}
@Override
@Nullable
public String getResourcePackURL() {
return resourcePacks.getDefaultResourcePackURL();
}
@Override
@Nullable
public String getResourcePackURL(CommandSender sender) {
return resourcePacks.getResourcePackURL(sender);
}
@Override
public boolean isUrlIconsEnabled() {
return urlIconsEnabled;
}
@Override
public boolean isLegacyIconsEnabled() {
return legacyIconsEnabled;
}
public boolean resourcePackUsesSkulls(String pack) {
Boolean packOverride = resourcePacks.resourcePackUsesSkulls(pack);
return packOverride == null ? urlIconsEnabled : packOverride;
}
@Override
public Collection<String> getAlternateResourcePacks() {
return resourcePacks.getAlternateResourcePacks();
}
@Override
public boolean isResourcePackEnabledByDefault() {
return resourcePacks.isResourcePackEnabledByDefault();
}
@Override
public boolean showConsoleCastFeedback() {
return castConsoleFeedback;
}
public String getEditorURL() {
return editorURL;
}
public void setReloadingMage(Mage mage) {
this.reloadingMage = mage;
}
public boolean useAnimationEvents(Player player) {
if (swingType == SwingType.ANIMATE) return true;
if (swingType == SwingType.INTERACT) return false;
return player.getGameMode() == GameMode.ADVENTURE;
}
@Override
@Nullable
public List<DeathLocation> getDeathLocations(Player player) {
List<DeathLocation> locations = null;
if (deadSoulsController != null) {
locations = new ArrayList<>();
deadSoulsController.getSoulLocations(player, locations);
}
return locations;
}
public boolean isDespawnMagicMobs() {
return despawnMagicMobs;
}
public void checkLogs(CommandSender sender) {
logger.notify(messages, sender);
}
public MagicWorld getMagicWorld(String name) {
return worldController.getWorld(name);
}
public WorldController getWorlds() {
return worldController;
}
@Override
public int getMaxHeight(World world) {
MagicWorld magicWorld = getMagicWorld(world.getName());
int maxHeight = CompatibilityUtils.getMaxHeight(world);
if (magicWorld != null) {
maxHeight = magicWorld.getMaxHeight(maxHeight);
}
return maxHeight;
}
@Override
public int getMinHeight(World world) {
MagicWorld magicWorld = getMagicWorld(world.getName());
int minHeight = CompatibilityUtils.getMinHeight(world);
if (magicWorld != null) {
minHeight = magicWorld.getMinHeight(minHeight);
}
return minHeight;
}
public boolean isDisableSpawnReplacement() {
return disableSpawnReplacement > 0;
}
@Override
public void setDisableSpawnReplacement(boolean disable) {
if (disable) {
disableSpawnReplacement++;
} else {
disableSpawnReplacement--;
}
}
@Override
@Nullable
public MagicWarp getMagicWarp(String warpKey) {
return warpController.getMagicWarp(warpKey);
}
@Override
@Nonnull
public Collection<? extends MagicWarp> getMagicWarps() {
return warpController.getMagicWarps();
}
public void finalizeIntegration() {
final PluginManager pluginManager = plugin.getServer().getPluginManager();
blockController.finalizeIntegration();
// Check for SkillAPI
Plugin skillAPIPlugin = pluginManager.getPlugin("SkillAPI");
if (skillAPIPlugin != null && skillAPIEnabled && skillAPIPlugin.isEnabled()) {
skillAPIManager = new SkillAPIManager(this, skillAPIPlugin);
if (skillAPIManager.initialize()) {
getLogger().info("SkillAPI found, attributes can be used in spell parameters. Classes and skills can be used in requirements.");
if (useSkillAPIAllies) {
getLogger().info("SKillAPI allies will be respected in friendly fire checks");
}
if (useSkillAPIMana) {
getLogger().info("SkillAPI mana will be used by spells and wands");
}
} else {
skillAPIManager = null;
getLogger().warning("SkillAPI integration failed");
}
} else if (!skillAPIEnabled) {
skillAPIManager = null;
getLogger().info("SkillAPI integration disabled");
}
// Check for BattleArenas
Plugin battleArenaPlugin = pluginManager.getPlugin("BattleArena");
if (battleArenaPlugin != null) {
if (useBattleArenaTeams) {
try {
battleArenaManager = new BattleArenaManager();
} catch (Throwable ex) {
getLogger().log(Level.SEVERE, "Error integrating with BattleArena", ex);
}
getLogger().info("BattleArena found, teams will be respected in friendly fire checks");
} else {
battleArenaManager = null;
getLogger().info("BattleArena integration disabled");
}
}
// Check for WildStacker
if (pluginManager.isPluginEnabled("WildStacker")) {
if (useWildStacker) {
getLogger().info("Wild Stacker integration enabled");
pluginManager.registerEvents(new WildStackerListener(), plugin);
} else {
getLogger().info("Wild Stacker found, but integration disabled");
}
}
// Try to link to Heroes:
try {
Plugin heroesPlugin = pluginManager.getPlugin("Heroes");
if (heroesPlugin != null) {
heroesManager = new HeroesManager(plugin, heroesPlugin);
} else {
heroesManager = null;
}
} catch (Throwable ex) {
getLogger().warning(ex.getMessage());
}
// Vault integration
if (!vaultEnabled) {
getLogger().info("Vault integration disabled");
} else {
Plugin vaultPlugin = pluginManager.getPlugin("Vault");
if (vaultPlugin == null || !vaultPlugin.isEnabled()) {
getLogger().info("Vault not found, 'currency' cost types unavailable");
} else {
if (!VaultController.initialize(plugin, vaultPlugin)) {
getLogger().warning("Vault integration failed");
}
}
}
// Check for Minigames
Plugin minigamesPlugin = pluginManager.getPlugin("Minigames");
if (minigamesPlugin != null && minigamesPlugin.isEnabled()) {
pluginManager.registerEvents(new MinigamesListener(this), plugin);
getLogger().info("Minigames found, wands will deactivate before joining a minigame");
}
// Check for LibsDisguise
Plugin libsDisguisePlugin = pluginManager.getPlugin("LibsDisguises");
if (libsDisguisePlugin == null || !libsDisguisePlugin.isEnabled()) {
getLogger().info("LibsDisguises not found, magic mob disguises will not be available");
} else if (libsDisguiseEnabled) {
if (!LibsDisguiseManager.isCurrentVersion()) {
getLogger().info("Using legacy LibsDisguise integration, please update");
libsDisguiseManager = new LegacyLibsDisguiseManager(getPlugin(), libsDisguisePlugin);
} else {
libsDisguiseManager = new ModernLibsDisguiseManager(this, libsDisguisePlugin);
}
if (libsDisguiseManager.initialize()) {
getLogger().info("LibsDisguises found, mob disguises and disguise_restricted features enabled");
} else {
getLogger().warning("LibsDisguises integration failed");
}
} else {
libsDisguiseManager = null;
getLogger().info("LibsDisguises integration disabled");
}
// Check for MobArena
Plugin mobArenaPlugin = pluginManager.getPlugin("MobArena");
if (mobArenaPlugin == null) {
getLogger().info("MobArena not found");
} else if (mobArenaConfiguration.getBoolean("enabled", true)) {
try {
mobArenaManager = new MobArenaManager(this, mobArenaPlugin, mobArenaConfiguration);
getLogger().info("Integrated with MobArena, use \"magic:<itemkey>\" in arena configs for Magic items, magic mobs can be used in monster configurations");
} catch (Throwable ex) {
getLogger().warning("MobArena integration failed, you may need to update the MobArena plugin to use Magic items");
}
} else {
getLogger().info("MobArena integration disabled");
}
// Check for LogBlock
Plugin logBlockPlugin = pluginManager.getPlugin("LogBlock");
if (logBlockPlugin == null || !logBlockPlugin.isEnabled()) {
getLogger().info("LogBlock not found");
} else if (logBlockEnabled) {
try {
logBlockManager = new LogBlockManager(plugin, logBlockPlugin);
getLogger().info("Integrated with LogBlock, engineering magic will be logged");
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "LogBlock integration failed", ex);
}
} else {
getLogger().info("LogBlock integration disabled");
}
// Try to link to Essentials:
Plugin essentials = pluginManager.getPlugin("Essentials");
essentialsController = null;
hasEssentials = essentials != null && essentials.isEnabled();
if (hasEssentials) {
essentialsController = EssentialsController.initialize(essentials);
if (essentialsController == null) {
getLogger().warning("Error integrating with Essentials");
} else {
getLogger().info("Integrating with Essentials for vanish detection");
}
if (warpController.setEssentials(essentials)) {
getLogger().info("Integrating with Essentials for Recall warps");
}
try {
mailer = new Mailer(essentials);
} catch (Exception ex) {
getLogger().warning("Essentials found, but failed to hook up to Mailer");
mailer = null;
}
}
if (essentialsSignsEnabled) {
try {
if (essentials != null) {
Class<?> essentialsClass = essentials.getClass();
essentialsClass.getMethod("getItemDb");
if (MagicItemDb.register(this, essentials)) {
getLogger().info("Essentials found, hooked up custom item handler");
} else {
getLogger().warning("Essentials found, but something went wrong hooking up the custom item handler");
}
}
} catch (Throwable ex) {
getLogger().warning("Essentials found, but is not up to date. Magic item integration will not work with this version of Magic. Please upgrade EssentialsX or downgrade Magic to 7.6.19");
}
}
// Try to link to CommandBook
hasCommandBook = false;
try {
Plugin commandBookPlugin = plugin.getServer().getPluginManager().getPlugin("CommandBook");
if (commandBookPlugin != null && commandBookPlugin.isEnabled()) {
if (warpController.setCommandBook(commandBookPlugin)) {
getLogger().info("CommandBook found, integrating for Recall warps");
hasCommandBook = true;
} else {
getLogger().warning("CommandBook integration failed");
}
}
} catch (Throwable ignored) {
}
// Link to factions
factionsManager.initialize(plugin);
// Try to (dynamically) link to WorldGuard:
worldGuardManager.initialize(plugin);
// Link to PvpManager
pvpManager.initialize(plugin);
// Link to Multiverse
multiverseManager.initialize(plugin);
// Link to DeadSouls
Plugin deadSoulsPlugin = plugin.getServer().getPluginManager().getPlugin("DeadSouls");
if (deadSoulsPlugin != null) {
try {
deadSoulsController = new DeadSoulsManager(this);
} catch (Exception ex) {
getLogger().log(Level.WARNING, "Error integrating with DeadSouls, is it up to date? Version 1.6 or higher required.", ex);
}
}
// Link to PreciousStones
preciousStonesManager.initialize(plugin);
// Link to Towny
townyManager.initialize(plugin);
// Link to Lockette
locketteManager.initialize(plugin);
// Link to GriefPrevention
griefPreventionManager.initialize(plugin);
// Link to NoCheatPlus
ncpManager.initialize(plugin);
// Try to link to dynmap:
try {
Plugin dynmapPlugin = plugin.getServer().getPluginManager().getPlugin("dynmap");
if (dynmapPlugin != null && dynmapPlugin.isEnabled()) {
dynmap = new DynmapController(plugin, dynmapPlugin, messages);
} else {
dynmap = null;
}
} catch (Throwable ex) {
getLogger().warning(ex.getMessage());
}
if (dynmap == null) {
getLogger().info("dynmap not found, not integrating.");
} else {
getLogger().info("dynmap found, integrating.");
}
// Try to link to Elementals:
try {
Plugin elementalsPlugin = plugin.getServer().getPluginManager().getPlugin("Splateds_Elementals");
if (elementalsPlugin != null && elementalsPlugin.isEnabled()) {
elementals = new ElementalsController(elementalsPlugin);
} else {
elementals = null;
}
} catch (Throwable ex) {
getLogger().warning(ex.getMessage());
}
if (elementals != null) {
getLogger().info("Elementals found, integrating.");
}
// Check for Shopkeepers, this is an optimization to avoid scanning for metadata if the plugin is not
// present
hasShopkeepers = pluginManager.isPluginEnabled("Shopkeepers");
if (hasShopkeepers) {
npcSuppliers.register(new GenericMetadataNPCSupplier("shopkeeper"));
}
// Try to link to Citizens
try {
Plugin citizensPlugin = plugin.getServer().getPluginManager().getPlugin("Citizens");
if (citizensPlugin != null && citizensPlugin.isEnabled()) {
citizens = new CitizensController(citizensPlugin, this, citizensEnabled);
new MagicTraitCommandExecutor(MagicPlugin.getAPI(), citizens).register(plugin);
} else {
citizens = null;
getLogger().info("Citizens not found, Magic trait unavailable.");
}
} catch (Throwable ex) {
citizens = null;
getLogger().warning("Error integrating with Citizens");
getLogger().warning(ex.getMessage());
}
if (citizens != null) {
npcSuppliers.register(citizens);
}
// Placeholder API
if (placeholdersEnabled) {
if (pluginManager.isPluginEnabled("PlaceholderAPI")) {
try {
// Can only register this once
if (placeholderAPIManager == null) {
placeholderAPIManager = new PlaceholderAPIManager(this);
}
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with PlaceholderAPI", ex);
}
}
} else {
getLogger().info("PlaceholderAPI integration disabled.");
}
// Light API
if (lightAPIEnabled) {
if (pluginManager.isPluginEnabled("LightAPI")) {
try {
lightAPIManager = new LightAPIManager(plugin);
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with LightAPI", ex);
}
} else {
getLogger().info("LightAPI not found, Light action will not work");
}
} else {
lightAPIManager = null;
getLogger().info("LightAPI integration disabled.");
}
// Geyser
if (pluginManager.isPluginEnabled("Geyser-Spigot")) {
try {
geyserManager = new GeyserManager(this);
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with Geyser", ex);
}
}
// Skript
if (skriptEnabled) {
if (pluginManager.isPluginEnabled("Skript")) {
try {
new SkriptManager(this);
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with Skript", ex);
}
}
} else {
getLogger().info("Skript integration disabled.");
}
// ajParkour
if (ajParkourConfiguration.getBoolean("enabled")) {
if (pluginManager.isPluginEnabled("ajParkour")) {
try {
ajParkourManager = new AJParkourManager(this);
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with ajParkour", ex);
}
}
} else {
getLogger().info("ajParkour integration disabled.");
}
// Citadel
if (citadelConfiguration.getBoolean("enabled")) {
if (pluginManager.isPluginEnabled("Citadel")) {
try {
citadelManager = new CitadelManager(this, citadelConfiguration);
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with Citadel", ex);
}
}
} else {
getLogger().info("Citadel integration disabled.");
}
// Residence
if (residenceConfiguration.getBoolean("enabled")) {
if (pluginManager.isPluginEnabled("Residence")) {
try {
residenceManager = new ResidenceManager(pluginManager.getPlugin("Residence"), this, residenceConfiguration);
getLogger().info("Integrated with residence for build/break/pvp/target checks");
getLogger().info("Disable warping to residences in recall config with allow_residence: false");
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with Residence", ex);
}
}
} else {
getLogger().info("Residence integration disabled.");
}
// RedProtect
if (redProtectConfiguration.getBoolean("enabled")) {
if (pluginManager.isPluginEnabled("RedProtect")) {
try {
redProtectManager = new RedProtectManager(pluginManager.getPlugin("RedProtect"), this, redProtectConfiguration);
getLogger().info("Integrated with RedProtect for build/break/pvp/target checks");
getLogger().info("Disable warping to fields in recall config with allow_redprotect: false");
if (redProtectManager.isFlagsEnabled()) {
getLogger().info("Added custom flags: " + StringUtils.join(RedProtectManager.flags, ','));
}
} catch (Throwable ex) {
getLogger().log(Level.WARNING, "Error integrating with RedProtect", ex);
}
}
} else {
getLogger().info("RedProtect integration disabled.");
}
// Set up the Mage update timer
final MageUpdateTask mageTask = new MageUpdateTask(this);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, mageTask, 0, mageUpdateFrequency);
// Set up the Block update timer
final BatchUpdateTask blockTask = new BatchUpdateTask(this);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, blockTask, 0, workFrequency);
// Set up the Automata timer
final AutomataUpdateTask automataTaks = new AutomataUpdateTask(this);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, automataTaks, 0, automataUpdateFrequency);
// Set up the Update check timer
final UndoUpdateTask undoTask = new UndoUpdateTask(this);
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, undoTask, 0, undoFrequency);
}
protected void loadProperties(CommandSender sender, ConfigurationSection properties) {
if (properties == null) return;
// Delegate to resource pack handler
resourcePacks.load(properties, sender, !loaded);
logVerbosity = properties.getInt("log_verbosity", 0);
SkinUtils.DEBUG = logVerbosity >= 5;
LOG_WATCHDOG_TIMEOUT = properties.getInt("load_watchdog_timeout", 30000);
logger.setColorize(properties.getBoolean("colored_logs", true));
// Cancel any pending save tasks
if (autoSaveTaskId > 0) {
Bukkit.getScheduler().cancelTask(autoSaveTaskId);
autoSaveTaskId = 0;
}
if (configCheckTask != null) {
configCheckTask.cancel();
configCheckTask = null;
}
if (logNotifyTask != null) {
logNotifyTask.cancel();
logNotifyTask = null;
}
debugEffectLib = properties.getBoolean("debug_effects", false);
com.elmakers.mine.bukkit.effect.EffectPlayer.debugEffects(debugEffectLib);
boolean effectLibStackTraces = properties.getBoolean("debug_effects_stack_traces", false);
com.elmakers.mine.bukkit.effect.EffectPlayer.showStackTraces(effectLibStackTraces);
CompatibilityUtils.USE_MAGIC_DAMAGE = properties.getBoolean("use_magic_damage", CompatibilityUtils.USE_MAGIC_DAMAGE);
com.elmakers.mine.bukkit.effect.EffectPlayer.setParticleRange(properties.getInt("particle_range", com.elmakers.mine.bukkit.effect.EffectPlayer.PARTICLE_RANGE));
showCastHoloText = properties.getBoolean("show_cast_holotext", showCastHoloText);
showActivateHoloText = properties.getBoolean("show_activate_holotext", showCastHoloText);
castHoloTextRange = properties.getInt("cast_holotext_range", castHoloTextRange);
activateHoloTextRange = properties.getInt("activate_holotext_range", activateHoloTextRange);
urlIconsEnabled = properties.getBoolean("url_icons_enabled", urlIconsEnabled);
legacyIconsEnabled = properties.getBoolean("legacy_icons_enabled", legacyIconsEnabled);
spellProgressionEnabled = properties.getBoolean("enable_spell_progression", spellProgressionEnabled);
autoSpellUpgradesEnabled = properties.getBoolean("enable_automatic_spell_upgrades", autoSpellUpgradesEnabled);
autoPathUpgradesEnabled = properties.getBoolean("enable_automatic_spell_upgrades", autoPathUpgradesEnabled);
undoQueueDepth = properties.getInt("undo_depth", undoQueueDepth);
workPerUpdate = properties.getInt("work_per_update", workPerUpdate);
workFrequency = properties.getInt("work_frequency", workFrequency);
automataUpdateFrequency = properties.getInt("automata_update_frequency", automataUpdateFrequency);
mageUpdateFrequency = properties.getInt("mage_update_frequency", mageUpdateFrequency);
undoFrequency = properties.getInt("undo_frequency", undoFrequency);
pendingQueueDepth = properties.getInt("pending_depth", pendingQueueDepth);
undoMaxPersistSize = properties.getInt("undo_max_persist_size", undoMaxPersistSize);
commitOnQuit = properties.getBoolean("commit_on_quit", commitOnQuit);
saveNonPlayerMages = properties.getBoolean("save_non_player_mages", saveNonPlayerMages);
defaultWandPath = properties.getString("default_wand_path", "");
Wand.DEFAULT_WAND_TEMPLATE = properties.getString("default_wand", "");
defaultWandMode = Wand.parseWandMode(properties.getString("default_wand_mode", ""), defaultWandMode);
defaultBrushMode = Wand.parseWandMode(properties.getString("default_brush_mode", ""), defaultBrushMode);
backupInventories = properties.getBoolean("backup_player_inventory", true);
Wand.brushSelectSpell = properties.getString("brush_select_spell", Wand.brushSelectSpell);
showMessages = properties.getBoolean("show_messages", showMessages);
showCastMessages = properties.getBoolean("show_cast_messages", showCastMessages);
messageThrottle = properties.getInt("message_throttle", 0);
soundsEnabled = properties.getBoolean("sounds", soundsEnabled);
fillingEnabled = properties.getBoolean("fill_wands", fillingEnabled);
Wand.FILL_CREATOR = properties.getBoolean("fill_wand_creator", Wand.FILL_CREATOR);
Wand.CREATIVE_CHEST_MODE = properties.getBoolean("wand_creative_chest_switch", Wand.CREATIVE_CHEST_MODE);
maxFillLevel = properties.getInt("fill_wand_level", maxFillLevel);
welcomeWand = properties.getString("welcome_wand", "");
maxDamagePowerMultiplier = (float) properties.getDouble("max_power_damage_multiplier", maxDamagePowerMultiplier);
maxConstructionPowerMultiplier = (float) properties.getDouble("max_power_construction_multiplier", maxConstructionPowerMultiplier);
maxRangePowerMultiplier = (float) properties.getDouble("max_power_range_multiplier", maxRangePowerMultiplier);
maxRangePowerMultiplierMax = (float) properties.getDouble("max_power_range_multiplier_max", maxRangePowerMultiplierMax);
maxRadiusPowerMultiplier = (float) properties.getDouble("max_power_radius_multiplier", maxRadiusPowerMultiplier);
maxRadiusPowerMultiplierMax = (float) properties.getDouble("max_power_radius_multiplier_max", maxRadiusPowerMultiplierMax);
materialColors = ConfigurationUtils.getNodeList(properties, "material_colors");
materialVariants = ConfigurationUtils.getList(properties, "material_variants");
blockItems = properties.getConfigurationSection("block_items");
loadBlockSkins(properties.getConfigurationSection("block_skins"));
loadMobSkins(properties.getConfigurationSection("mob_skins"));
loadMobEggs(properties.getConfigurationSection("mob_eggs"));
loadSkulls(properties.getConfigurationSection("skulls"));
loadOtherMaterials(properties);
WandCommandExecutor.CONSOLE_BYPASS_LOCKED = properties.getBoolean("console_bypass_locked_wands", true);
maxPower = (float) properties.getDouble("max_power", maxPower);
ConfigurationSection damageTypes = properties.getConfigurationSection("damage_types");
if (damageTypes != null) {
Set<String> typeKeys = damageTypes.getKeys(false);
for (String typeKey : typeKeys) {
ConfigurationSection damageType = damageTypes.getConfigurationSection(typeKey);
this.damageTypes.put(typeKey, new DamageType(damageType));
}
}
maxCostReduction = (float) properties.getDouble("max_cost_reduction", maxCostReduction);
maxCooldownReduction = (float) properties.getDouble("max_cooldown_reduction", maxCooldownReduction);
maxMana = properties.getInt("max_mana", maxMana);
maxManaRegeneration = properties.getInt("max_mana_regeneration", maxManaRegeneration);
worthBase = properties.getDouble("worth_base", 1);
com.elmakers.mine.bukkit.item.ItemData.EARN_SCALE = properties.getDouble("default_earn_scale", 0.5);
SafetyUtils.MAX_VELOCITY = properties.getDouble("max_velocity", 10);
HitboxUtils.setHitboxScale(properties.getDouble("hitbox_scale", 1.0));
HitboxUtils.setHitboxScaleY(properties.getDouble("hitbox_scale_y", 1.0));
HitboxUtils.setHitboxSneakScaleY(properties.getDouble("hitbox_sneaking_scale_y", 0.75));
if (properties.contains("hitboxes")) {
HitboxUtils.configureHitboxes(properties.getConfigurationSection("hitboxes"));
}
if (properties.contains("head_sizes")) {
HitboxUtils.configureHeadSizes(properties.getConfigurationSection("head_sizes"));
}
if (properties.contains("max_height")) {
HitboxUtils.configureMaxHeights(properties.getConfigurationSection("max_height"));
}
// These were changed from set values to multipliers, we're going to translate for backwards compatibility.
// The default configs used to have these set to either 0 or 100, where 100 indicated that we should be
// turning off the costs/cooldowns.
if (properties.contains("cast_command_cost_reduction")) {
castCommandCostFree = (properties.getDouble("cast_command_cost_reduction") > 0);
} else {
castCommandCostFree = properties.getBoolean("cast_command_cost_free", castCommandCostFree);
}
if (properties.contains("cast_command_cooldown_reduction")) {
castCommandCooldownFree = (properties.getDouble("cast_command_cooldown_reduction") > 0);
} else {
castCommandCooldownFree = properties.getBoolean("cast_command_cooldown_free", castCommandCooldownFree);
}
if (properties.contains("cast_console_cost_reduction")) {
castConsoleCostFree = (properties.getDouble("cast_console_cost_reduction") > 0);
} else {
castConsoleCostFree = properties.getBoolean("cast_console_cost_free", castConsoleCostFree);
}
if (properties.contains("cast_console_cooldown_reduction")) {
castConsoleCooldownFree = (properties.getDouble("cast_console_cooldown_reduction") > 0);
} else {
castConsoleCooldownFree = properties.getBoolean("cast_console_cooldown_free", castConsoleCooldownFree);
}
castConsoleFeedback = properties.getBoolean("cast_console_feedback", false);
editorURL = properties.getString("editor_url");
castCommandPowerMultiplier = (float) properties.getDouble("cast_command_power_multiplier", castCommandPowerMultiplier);
castConsolePowerMultiplier = (float) properties.getDouble("cast_console_power_multiplier", castConsolePowerMultiplier);
maps.setAnimationAllowed(properties.getBoolean("enable_map_animations", true));
costReduction = (float) properties.getDouble("cost_reduction", costReduction);
cooldownReduction = (float) properties.getDouble("cooldown_reduction", cooldownReduction);
autoUndo = properties.getInt("auto_undo", autoUndo);
spellDroppingEnabled = properties.getBoolean("allow_spell_dropping", spellDroppingEnabled);
essentialsSignsEnabled = properties.getBoolean("enable_essentials_signs", essentialsSignsEnabled);
logBlockEnabled = properties.getBoolean("logblock_enabled", logBlockEnabled);
citizensEnabled = properties.getBoolean("enable_citizens", citizensEnabled);
dynmapShowWands = properties.getBoolean("dynmap_show_wands", dynmapShowWands);
dynmapShowSpells = properties.getBoolean("dynmap_show_spells", dynmapShowSpells);
dynmapOnlyPlayerSpells = properties.getBoolean("dynmap_only_player_spells", dynmapOnlyPlayerSpells);
dynmapUpdate = properties.getBoolean("dynmap_update", dynmapUpdate);
protectLocked = properties.getBoolean("protect_locked", protectLocked);
bindOnGive = properties.getBoolean("bind_on_give", bindOnGive);
bypassBuildPermissions = properties.getBoolean("bypass_build", bypassBuildPermissions);
bypassBreakPermissions = properties.getBoolean("bypass_break", bypassBreakPermissions);
bypassPvpPermissions = properties.getBoolean("bypass_pvp", bypassPvpPermissions);
bypassFriendlyFire = properties.getBoolean("bypass_friendly_fire", bypassFriendlyFire);
useScoreboardTeams = properties.getBoolean("use_scoreboard_teams", useScoreboardTeams);
defaultFriendly = properties.getBoolean("default_friendly", defaultFriendly);
extraSchematicFilePath = properties.getString("schematic_files", extraSchematicFilePath);
createWorldsEnabled = properties.getBoolean("enable_world_creation", createWorldsEnabled);
defaultSkillIcon = properties.getString("default_skill_icon", defaultSkillIcon);
skillInventoryRows = properties.getInt("skill_inventory_max_rows", skillInventoryRows);
skillsSpell = properties.getString("mskills_spell", skillsSpell);
InventoryUtils.MAX_LORE_LENGTH = properties.getInt("lore_wrap_limit", InventoryUtils.MAX_LORE_LENGTH);
libsDisguiseEnabled = properties.getBoolean("enable_libsdisguises", libsDisguiseEnabled);
skillAPIEnabled = properties.getBoolean("skillapi_enabled", skillAPIEnabled);
useSkillAPIMana = properties.getBoolean("use_skillapi_mana", useSkillAPIMana);
placeholdersEnabled = properties.getBoolean("placeholder_api_enabled", placeholdersEnabled);
lightAPIEnabled = properties.getBoolean("light_api_enabled", lightAPIEnabled);
skriptEnabled = properties.getBoolean("skript_enabled", skriptEnabled);
vaultEnabled = properties.getConfigurationSection("vault").getBoolean("enabled");
citadelConfiguration = properties.getConfigurationSection("citadel");
mobArenaConfiguration = properties.getConfigurationSection("mobarena");
residenceConfiguration = properties.getConfigurationSection("residence");
redProtectConfiguration = properties.getConfigurationSection("redprotect");
ajParkourConfiguration = properties.getConfigurationSection("ajparkour");
if (mobArenaManager != null) {
mobArenaManager.configure(mobArenaConfiguration);
}
String swingTypeString = properties.getString("left_click_type");
try {
swingType = SwingType.valueOf(swingTypeString.toUpperCase());
} catch (Exception ex) {
getLogger().warning("Invalid left_click_type: " + swingTypeString);
}
List<? extends Object> permissionTeams = properties.getList("permission_teams");
if (permissionTeams != null) {
this.permissionTeams = new ArrayList<>();
for (Object o : permissionTeams) {
if (o instanceof List) {
@SuppressWarnings("unchecked")
List<String> stringList = (List<String>) o;
this.permissionTeams.add(stringList);
} else if (o instanceof String) {
List<String> newList = new ArrayList<>();
newList.add((String) o);
this.permissionTeams.add(newList);
}
}
}
String defaultSpellIcon = properties.getString("default_spell_icon");
try {
BaseSpell.DEFAULT_SPELL_ICON = Material.valueOf(defaultSpellIcon.toUpperCase());
} catch (Exception ex) {
getLogger().warning("Invalid default_spell_icon: " + defaultSpellIcon);
}
skillsUseHeroes = properties.getBoolean("skills_use_heroes", skillsUseHeroes);
useHeroesParties = properties.getBoolean("use_heroes_parties", useHeroesParties);
useSkillAPIAllies = properties.getBoolean("use_skillapi_allies", useSkillAPIAllies);
useBattleArenaTeams = properties.getBoolean("use_battlearena_teams", useBattleArenaTeams);
useHeroesMana = properties.getBoolean("use_heroes_mana", useHeroesMana);
heroesSkillPrefix = properties.getString("heroes_skill_prefix", heroesSkillPrefix);
skillsUsePermissions = properties.getBoolean("skills_use_permissions", skillsUsePermissions);
messagePrefix = properties.getString("message_prefix", messagePrefix);
castMessagePrefix = properties.getString("cast_message_prefix", castMessagePrefix);
Messages.RANGE_FORMATTER = new DecimalFormat(properties.getString("range_formatter"));
Messages.MOMENT_SECONDS_FORMATTER = new DecimalFormat(properties.getString("moment_seconds_formatter"));
Messages.MOMENT_MILLISECONDS_FORMATTER = new DecimalFormat(properties.getString("moment_milliseconds_formatter"));
Messages.SECONDS_FORMATTER = new DecimalFormat(properties.getString("seconds_formatter"));
Messages.MINUTES_FORMATTER = new DecimalFormat(properties.getString("minutes_formatter"));
Messages.HOURS_FORMATTER = new DecimalFormat(properties.getString("hours_formatter"));
redstoneReplacement = ConfigurationUtils.getMaterialAndData(properties, "redstone_replacement", redstoneReplacement);
messagePrefix = ChatColor.translateAlternateColorCodes('&', messagePrefix);
castMessagePrefix = ChatColor.translateAlternateColorCodes('&', castMessagePrefix);
worldGuardManager.setEnabled(properties.getBoolean("region_manager_enabled", worldGuardManager.isEnabled()));
factionsManager.setEnabled(properties.getBoolean("factions_enabled", factionsManager.isEnabled()));
pvpManager.setEnabled(properties.getBoolean("pvp_manager_enabled", pvpManager.isEnabled()));
multiverseManager.setEnabled(properties.getBoolean("multiverse_enabled", multiverseManager.isEnabled()));
preciousStonesManager.setEnabled(properties.getBoolean("precious_stones_enabled", preciousStonesManager.isEnabled()));
preciousStonesManager.setOverride(properties.getBoolean("precious_stones_override", true));
townyManager.setEnabled(properties.getBoolean("towny_enabled", townyManager.isEnabled()));
townyManager.setWildernessBypass(properties.getBoolean("towny_wilderness_bypass", true));
locketteManager.setEnabled(properties.getBoolean("lockette_enabled", locketteManager.isEnabled()));
griefPreventionManager.setEnabled(properties.getBoolean("grief_prevention_enabled", griefPreventionManager.isEnabled()));
ncpManager.setEnabled(properties.getBoolean("ncp_enabled", false));
useWildStacker = properties.getBoolean("wildstacker.enabled", true);
com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CLASS = properties.getString("default_mage_class", "");
metricsLevel = properties.getInt("metrics_level", metricsLevel);
ConfigurationSection autoWandsConfig = properties.getConfigurationSection("auto_wands");
Set<String> autoWandsKeys = autoWandsConfig.getKeys(false);
autoWands.clear();
for (String autoWandKey : autoWandsKeys) {
try {
Material autoWandMaterial = Material.valueOf(autoWandKey.toUpperCase());
autoWands.put(autoWandMaterial, autoWandsConfig.getString(autoWandKey));
} catch (Exception ex) {
getLogger().warning("Invalid material in auto_wands config: " + autoWandKey);
}
}
ConfigurationSection builtinExampleConfigs = properties.getConfigurationSection("external_examples");
Set<String> exampleKeys = builtinExampleConfigs.getKeys(false);
builtinExternalExamples.clear();
for (String exampleKey : exampleKeys) {
builtinExternalExamples.put(exampleKey, builtinExampleConfigs.getString(exampleKey));
}
Wand.regenWhileInactive = properties.getBoolean("regenerate_while_inactive", Wand.regenWhileInactive);
if (properties.contains("mana_display")) {
String manaDisplay = properties.getString("mana_display");
if (manaDisplay.equalsIgnoreCase("bar") || manaDisplay.equalsIgnoreCase("hybrid")) {
Wand.manaMode = WandManaMode.BAR;
} else if (manaDisplay.equalsIgnoreCase("number")) {
Wand.manaMode = WandManaMode.NUMBER;
} else if (manaDisplay.equalsIgnoreCase("durability")) {
Wand.manaMode = WandManaMode.DURABILITY;
} else if (manaDisplay.equalsIgnoreCase("glow")) {
Wand.manaMode = WandManaMode.GLOW;
} else if (manaDisplay.equalsIgnoreCase("none")) {
Wand.manaMode = WandManaMode.NONE;
}
}
if (properties.contains("sp_display")) {
String spDisplay = properties.getString("sp_display");
if (spDisplay.equalsIgnoreCase("number")) {
Wand.currencyMode = WandManaMode.NUMBER;
} else {
Wand.currencyMode = WandManaMode.NONE;
}
}
spEnabled = properties.getBoolean("sp_enabled", true);
spEarnEnabled = properties.getBoolean("sp_earn_enabled", true);
populateEntityTypes(undoEntityTypes, properties, "entity_undo_types");
populateEntityTypes(friendlyEntityTypes, properties, "friendly_entity_types");
ActionHandler.setRestrictedActions(properties.getStringList("restricted_spell_actions"));
String defaultLocationString = properties.getString("default_cast_location");
try {
com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_LOCATION = CastSourceLocation.valueOf(defaultLocationString.toUpperCase());
} catch (Exception ex) {
com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_LOCATION = CastSourceLocation.MAINHAND;
getLogger().warning("Invalid default_cast_location: " + defaultLocationString);
}
com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_OFFSET.setZ(properties.getDouble("default_cast_location_offset", com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_OFFSET.getZ()));
com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_OFFSET.setY(properties.getDouble("default_cast_location_offset_vertical", com.elmakers.mine.bukkit.magic.Mage.DEFAULT_CAST_OFFSET.getY()));
com.elmakers.mine.bukkit.magic.Mage.OFFHAND_CAST_COOLDOWN = properties.getInt("offhand_cast_cooldown", com.elmakers.mine.bukkit.magic.Mage.OFFHAND_CAST_COOLDOWN);
com.elmakers.mine.bukkit.magic.Mage.SNEAKING_CAST_OFFSET = properties.getDouble("sneaking_cast_location_offset_vertical", com.elmakers.mine.bukkit.magic.Mage.SNEAKING_CAST_OFFSET);
com.elmakers.mine.bukkit.magic.Mage.CURRENCY_MESSAGE_DELAY = properties.getInt("currency_message_delay", com.elmakers.mine.bukkit.magic.Mage.CURRENCY_MESSAGE_DELAY);
// Parse wand settings
Wand.DefaultUpgradeMaterial = ConfigurationUtils.getMaterial(properties, "wand_upgrade_item", Wand.DefaultUpgradeMaterial);
Wand.SpellGlow = properties.getBoolean("spell_glow", Wand.SpellGlow);
Wand.LiveHotbarSkills = properties.getBoolean("live_hotbar_skills", Wand.LiveHotbarSkills);
Wand.LiveHotbar = properties.getBoolean("live_hotbar", Wand.LiveHotbar);
Wand.LiveHotbarCooldown = properties.getBoolean("live_hotbar_cooldown", Wand.LiveHotbarCooldown);
Wand.LiveHotbarMana = properties.getBoolean("live_hotbar_mana", Wand.LiveHotbarMana);
Wand.BrushGlow = properties.getBoolean("brush_glow", Wand.BrushGlow);
Wand.BrushItemGlow = properties.getBoolean("brush_item_glow", Wand.BrushItemGlow);
Wand.WAND_KEY = properties.getString("wand_key", "wand");
Wand.UPGRADE_KEY = properties.getString("wand_upgrade_key", "wand");
Wand.WAND_SELF_DESTRUCT_KEY = properties.getString("wand_self_destruct_key", "");
if (Wand.WAND_SELF_DESTRUCT_KEY.isEmpty()) {
Wand.WAND_SELF_DESTRUCT_KEY = null;
}
Wand.HIDE_FLAGS = (byte) properties.getInt("wand_hide_flags", Wand.HIDE_FLAGS);
Wand.Unbreakable = properties.getBoolean("wand_unbreakable", Wand.Unbreakable);
Wand.Unstashable = properties.getBoolean("wand_undroppable", properties.getBoolean("wand_unstashable", Wand.Unstashable));
MaterialBrush.CopyMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "copy_item", legacyIconsEnabled, MaterialBrush.CopyMaterial);
MaterialBrush.EraseMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "erase_item", legacyIconsEnabled, MaterialBrush.EraseMaterial);
MaterialBrush.CloneMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "clone_item", legacyIconsEnabled, MaterialBrush.CloneMaterial);
MaterialBrush.ReplicateMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "replicate_item", legacyIconsEnabled, MaterialBrush.ReplicateMaterial);
MaterialBrush.SchematicMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "schematic_item", legacyIconsEnabled, MaterialBrush.SchematicMaterial);
MaterialBrush.MapMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "map_item", legacyIconsEnabled, MaterialBrush.MapMaterial);
MaterialBrush.DefaultBrushMaterial = ConfigurationUtils.getIconMaterialAndData(properties, "default_brush_item", legacyIconsEnabled, MaterialBrush.DefaultBrushMaterial);
MaterialBrush.configureReplacements(properties.getConfigurationSection("brush_replacements"));
MaterialBrush.CopyCustomIcon = properties.getString("copy_icon_url", MaterialBrush.CopyCustomIcon);
MaterialBrush.EraseCustomIcon = properties.getString("erase_icon_url", MaterialBrush.EraseCustomIcon);
MaterialBrush.CloneCustomIcon = properties.getString("clone_icon_url", MaterialBrush.CloneCustomIcon);
MaterialBrush.ReplicateCustomIcon = properties.getString("replicate_icon_url", MaterialBrush.ReplicateCustomIcon);
MaterialBrush.SchematicCustomIcon = properties.getString("schematic_icon_url", MaterialBrush.SchematicCustomIcon);
MaterialBrush.MapCustomIcon = properties.getString("map_icon_url", MaterialBrush.MapCustomIcon);
MaterialBrush.DefaultBrushCustomIcon = properties.getString("default_brush_icon_url", MaterialBrush.DefaultBrushCustomIcon);
BaseSpell.DEFAULT_DISABLED_ICON_URL = properties.getString("disabled_icon_url", BaseSpell.DEFAULT_DISABLED_ICON_URL);
Wand.DEFAULT_CAST_OFFSET.setZ(properties.getDouble("wand_location_offset", Wand.DEFAULT_CAST_OFFSET.getZ()));
Wand.DEFAULT_CAST_OFFSET.setY(properties.getDouble("wand_location_offset_vertical", Wand.DEFAULT_CAST_OFFSET.getY()));
com.elmakers.mine.bukkit.magic.Mage.JUMP_EFFECT_FLIGHT_EXEMPTION_DURATION = properties.getInt("jump_exemption", 0);
com.elmakers.mine.bukkit.magic.Mage.CHANGE_WORLD_EQUIP_COOLDOWN = properties.getInt("change_world_equip_cooldown", 0);
com.elmakers.mine.bukkit.magic.Mage.DEACTIVATE_WAND_ON_WORLD_CHANGE = properties.getBoolean("close_wand_on_world_change", false);
Wand.inventoryOpenSound = ConfigurationUtils.toSoundEffect(properties.getString("wand_inventory_open_sound"));
Wand.inventoryCloseSound = ConfigurationUtils.toSoundEffect(properties.getString("wand_inventory_close_sound"));
Wand.inventoryCycleSound = ConfigurationUtils.toSoundEffect(properties.getString("wand_inventory_cycle_sound"));
Wand.noActionSound = ConfigurationUtils.toSoundEffect(properties.getString("wand_no_action_sound"));
Wand.itemPickupSound = ConfigurationUtils.toSoundEffect(properties.getString("wand_pickup_item_sound"));
// Configure sub-controllers
explosionController.loadProperties(properties);
inventoryController.loadProperties(properties);
entityController.loadProperties(properties);
playerController.loadProperties(properties);
blockController.loadProperties(properties);
// Set up other systems
com.elmakers.mine.bukkit.effect.EffectPlayer.SOUNDS_ENABLED = soundsEnabled;
// Set up auto-save timer
int autoSaveIntervalTicks = properties.getInt("auto_save", 0) * 20 / 1000;
if (autoSaveIntervalTicks > 1) {
final AutoSaveTask autoSave = new AutoSaveTask(this);
autoSaveTaskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, autoSave,
autoSaveIntervalTicks, autoSaveIntervalTicks);
}
savePlayerData = properties.getBoolean("save_player_data", true);
externalPlayerData = properties.getBoolean("external_player_data", false);
if (externalPlayerData) {
getLogger().info("Magic is expecting player data to be loaded from an external source");
} else if (!savePlayerData) {
getLogger().info("Magic player data saving is disabled");
}
asynchronousSaving = properties.getBoolean("save_player_data_asynchronously", true);
isFileLockingEnabled = properties.getBoolean("use_file_locking", false);
fileLoadDelay = properties.getInt("file_load_delay", 0);
despawnMagicMobs = properties.getBoolean("despawn_magic_mobs", false);
MobController.REMOVE_INVULNERABLE = properties.getBoolean("remove_invulnerable_mobs", false);
com.elmakers.mine.bukkit.effect.EffectPlayer.ENABLE_VANILLA_SOUNDS = properties.getBoolean("enable_vanilla_sounds", true);
ConfigurationSection blockExchange = properties.getConfigurationSection("block_exchange");
if (blockExchange != null) {
if (blockExchange.getBoolean("enabled", true)) {
blockExchangeCurrency = blockExchange.getString("currency");
if (blockExchangeCurrency != null && blockExchangeCurrency.isEmpty()) {
blockExchangeCurrency = null;
}
} else {
blockExchangeCurrency = null;
}
} else {
blockExchangeCurrency = null;
}
// Set up mage data store
if (mageDataStore != null) {
mageDataStore.close();
}
ConfigurationSection mageDataStoreConfiguration = properties.getConfigurationSection("player_data_store");
if (mageDataStoreConfiguration != null) {
mageDataStore = loadMageDataStore(mageDataStoreConfiguration);
if (mageDataStore == null) {
getLogger().log(Level.WARNING, "Failed to load player_data_store configuration, player data saving disabled!");
}
} else {
getLogger().log(Level.WARNING, "Missing player_data_store configuration, player data saving disabled!");
mageDataStore = null;
}
ConfigurationSection migrateDataStoreConfiguration = properties.getConfigurationSection("migrate_data_store");
if (migrateDataStoreConfiguration != null) {
migrateDataStore = loadMageDataStore(migrateDataStoreConfiguration);
if (migrateDataStore == null) {
getLogger().log(Level.WARNING, "Failed to load migrate_data_store configuration, migration will not work");
}
} else {
migrateDataStore = null;
}
if (migrateDataStore != null) {
migrateDataStore.close();
}
// Semi-deprecated Wand defaults
Wand.DefaultWandMaterial = ConfigurationUtils.getMaterial(properties, "wand_item", Wand.DefaultWandMaterial);
Wand.EnchantableWandMaterial = ConfigurationUtils.getMaterial(properties, "wand_item_enchantable", Wand.EnchantableWandMaterial);
// Load sub-controllers
enchanting.setEnabled(properties.getBoolean("enable_enchanting", enchanting.isEnabled()));
if (enchanting.isEnabled()) {
log("Wand enchanting is enabled");
}
crafting.loadMainConfiguration(properties);
if (crafting.isEnabled()) {
log("Wand crafting is enabled");
}
anvil.load(properties);
if (anvil.isCombiningEnabled()) {
log("Wand anvil combining is enabled");
}
if (anvil.isOrganizingEnabled()) {
log("Wand anvil organizing is enabled");
}
if (isUrlIconsEnabled()) {
log("Skin-based spell icons enabled");
} else {
log("Skin-based spell icons disabled");
}
// Set up sandbox config update timer
int configUpdateInterval = properties.getInt("config_update_interval");
if (configUpdateInterval > 0) {
log("Sandbox enabled, will check for updates from the web UI");
final ConfigCheckTask configCheck = new ConfigCheckTask(this);
configCheckTask = Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, configCheck,
configUpdateInterval * 20 / 1000, configUpdateInterval * 20 / 1000);
}
// Set up log notify timer
logger.clearNotify();
int logNotifyInterval = properties.getInt("log_notify_interval");
if (logNotifyInterval > 0) {
final LogNotifyTask logNotify = new LogNotifyTask(this);
logNotifyTask = Bukkit.getScheduler().runTaskTimer(plugin, logNotify,
logNotifyInterval * 20 / 1000, logNotifyInterval * 20 / 1000);
}
// Configure world generation and spawn replacement
worldController.load(properties.getConfigurationSection("world_modification"));
// Link to generic protection plugins
protectionManager.initialize(plugin, ConfigurationUtils.getStringList(properties, "generic_protection"));
}
protected void loadMaterials(ConfigurationSection materialNode) {
if (materialNode == null)
return;
materialSetManager.loadMaterials(materialNode);
DefaultMaterials defaultMaterials = DefaultMaterials.getInstance();
defaultMaterials.initialize(materialSetManager);
defaultMaterials.loadColors(materialColors);
defaultMaterials.loadVariants(materialVariants);
defaultMaterials.loadBlockItems(blockItems);
defaultMaterials.setPlayerSkullItem(skullItems.get(EntityType.PLAYER));
defaultMaterials.setPlayerSkullWallBlock(skullWallBlocks.get(EntityType.PLAYER));
defaultMaterials.setSkeletonSkullItem(skullItems.get(EntityType.SKELETON));
buildingMaterials = materialSetManager.getMaterialSetEmpty("building");
indestructibleMaterials = materialSetManager
.getMaterialSetEmpty("indestructible");
restrictedMaterials = materialSetManager
.getMaterialSetEmpty("restricted");
destructibleMaterials = materialSetManager
.getMaterialSetEmpty("destructible");
interactibleMaterials = materialSetManager
.getMaterialSetEmpty("interactible");
containerMaterials = materialSetManager
.getMaterialSetEmpty("containers");
climbableMaterials = materialSetManager.getMaterialSetEmpty("climbable");
undoableMaterials = materialSetManager.getMaterialSetEmpty("undoable");
wearableMaterials = materialSetManager.getMaterialSetEmpty("wearable");
meleeMaterials = materialSetManager.getMaterialSetEmpty("melee");
offhandMaterials = materialSetManager.getMaterialSetEmpty("offhand");
com.elmakers.mine.bukkit.block.UndoList.attachables = materialSetManager
.getMaterialSetEmpty("attachable");
com.elmakers.mine.bukkit.block.UndoList.attachablesWall = materialSetManager
.getMaterialSetEmpty("attachable_wall");
com.elmakers.mine.bukkit.block.UndoList.attachablesDouble = materialSetManager
.getMaterialSetEmpty("attachable_double");
}
@Override
@Nullable
public Currency getBlockExchangeCurrency() {
return blockExchangeCurrency == null ? null : getCurrency(blockExchangeCurrency);
}
public int getMaxLevel(String spellName) {
Integer maxLevel = maxSpellLevels.get(spellName);
return maxLevel == null ? 1 : maxLevel;
}
@Nullable
public Double getBuiltinAttribute(String attributeKey) {
switch (attributeKey) {
case "weeks":
return (double) 604800000;
case "days":
return (double) 86400000;
case "hours":
return (double) 3600000;
case "minutes":
return (double) 60000;
case "seconds":
return (double) 1000;
case "epoch":
return (double) System.currentTimeMillis();
case "pi":
return Math.PI;
default:
return null;
}
}
@Nullable
@Override
public ItemStack createBrushItem(String materialKey, com.elmakers.mine.bukkit.api.wand.Wand wand, boolean isItem) {
return Wand.createBrushItem(materialKey, this, (Wand) wand, isItem);
}
public ClientPlatform getClientPlatform(Player player) {
return geyserManager != null && geyserManager.isBedrock(player.getUniqueId()) ? ClientPlatform.BEDROCk : ClientPlatform.JAVA;
}
}
| I do not know why this didn't give an error before, nor why IntelliJ didn't put these two methods together when I reformatted :\
| Magic/src/main/java/com/elmakers/mine/bukkit/magic/MagicController.java | I do not know why this didn't give an error before, nor why IntelliJ didn't put these two methods together when I reformatted :\ | <ide><path>agic/src/main/java/com/elmakers/mine/bukkit/magic/MagicController.java
<ide> return Wand.createBrushItem(brushKey, this, null, true);
<ide> }
<ide>
<add> @Nullable
<add> @Override
<add> public ItemStack createBrushItem(String materialKey, com.elmakers.mine.bukkit.api.wand.Wand wand, boolean isItem) {
<add> return Wand.createBrushItem(materialKey, this, (Wand) wand, isItem);
<add> }
<add>
<ide> public boolean isSameItem(ItemStack first, ItemStack second) {
<ide> if (first.getType() != second.getType()) return false;
<ide> if (first.getDurability() != second.getDurability()) return false;
<ide> }
<ide> }
<ide>
<del> @Nullable
<del> @Override
<del> public ItemStack createBrushItem(String materialKey, com.elmakers.mine.bukkit.api.wand.Wand wand, boolean isItem) {
<del> return Wand.createBrushItem(materialKey, this, (Wand) wand, isItem);
<del> }
<del>
<ide> public ClientPlatform getClientPlatform(Player player) {
<ide> return geyserManager != null && geyserManager.isBedrock(player.getUniqueId()) ? ClientPlatform.BEDROCk : ClientPlatform.JAVA;
<ide> } |
|
Java | apache-2.0 | f8eb7d36fc5e5389ab10f8fda25c1ddd25b078d2 | 0 | Bananeweizen/cgeo,kumy/cgeo,tobiasge/cgeo,cgeo/cgeo,pstorch/cgeo,pstorch/cgeo,rsudev/c-geo-opensource,matej116/cgeo,kumy/cgeo,tobiasge/cgeo,auricgoldfinger/cgeo,rsudev/c-geo-opensource,tobiasge/cgeo,matej116/cgeo,S-Bartfast/cgeo,auricgoldfinger/cgeo,cgeo/cgeo,S-Bartfast/cgeo,cgeo/cgeo,S-Bartfast/cgeo,rsudev/c-geo-opensource,kumy/cgeo,matej116/cgeo,Bananeweizen/cgeo,auricgoldfinger/cgeo,cgeo/cgeo,pstorch/cgeo,Bananeweizen/cgeo | package cgeo.geocaching.connector.trackable;
import org.xml.sax.InputSource;
import java.util.List;
import cgeo.geocaching.models.Trackable;
import cgeo.geocaching.test.AbstractResourceInstrumentationTestCase;
import cgeo.geocaching.test.R;
import static org.assertj.core.api.Java6Assertions.assertThat;
/**
* test for {@link GeokretyConnector}
*/
public class GeokretyConnectorTest extends AbstractResourceInstrumentationTestCase {
public static void testCanHandleTrackable() {
assertThat(getConnector().canHandleTrackable("GK82A2")).isTrue();
assertThat(getConnector().canHandleTrackable("TB1234")).isFalse();
assertThat(getConnector().canHandleTrackable("UNKNOWN")).isFalse();
assertThat(getConnector().canHandleTrackable("GKXYZ1")).isFalse(); // non hex
assertThat(getConnector().canHandleTrackable("GKXYZ1", TrackableBrand.GEOKRETY)).isTrue(); // non hex, but match secret codes pattern
assertThat(getConnector().canHandleTrackable("123456", TrackableBrand.GEOKRETY)).isTrue(); // Secret code
assertThat(getConnector().canHandleTrackable("012345", TrackableBrand.GEOKRETY)).isFalse(); // blacklisted 0/O
assertThat(getConnector().canHandleTrackable("ABCDEF", TrackableBrand.GEOKRETY)).isTrue(); // Secret code
assertThat(getConnector().canHandleTrackable("LMNOPQ", TrackableBrand.GEOKRETY)).isFalse(); // blacklisted 0/O
assertThat(getConnector().canHandleTrackable("GC1234")).isFalse();
assertThat(getConnector().canHandleTrackable("GC1234", TrackableBrand.UNKNOWN)).isFalse();
assertThat(getConnector().canHandleTrackable("GC1234", TrackableBrand.TRAVELBUG)).isFalse();
assertThat(getConnector().canHandleTrackable("GC1234", TrackableBrand.GEOKRETY)).isTrue();
}
public static void testGetTrackableCodeFromUrl() throws Exception {
assertThat(getConnector().getTrackableCodeFromUrl("http://www.geokrety.org/konkret.php?id=46464")).isEqualTo("GKB580");
assertThat(getConnector().getTrackableCodeFromUrl("https://www.geokrety.org/konkret.php?id=46464")).isEqualTo("GKB580");
assertThat(getConnector().getTrackableCodeFromUrl("http://geokrety.org/konkret.php?id=46465")).isEqualTo("GKB581");
assertThat(getConnector().getTrackableCodeFromUrl("https://geokrety.org/konkret.php?id=46465")).isEqualTo("GKB581");
}
public static void testGeocode() throws Exception {
assertThat(GeokretyConnector.geocode(46464)).isEqualTo("GKB580");
}
public static void testGetId() throws Exception {
assertThat(GeokretyConnector.getId("GKB581")).isEqualTo(46465);
}
public void testGetUrl() throws Exception {
final List<Trackable> trackables = GeokretyParser.parse(new InputSource(getResourceStream(R.raw.geokret141_xml)));
assertThat(trackables).hasSize(2);
assertThat(trackables.get(0).getUrl()).isEqualTo("https://geokrety.org/konkret.php?id=46464");
assertThat(trackables.get(1).getUrl()).isEqualTo("https://geokrety.org/konkret.php?id=46465");
}
public void testSearchTrackable() throws Exception {
final Trackable geokret = GeokretyConnector.searchTrackable("GKB580");
assertThat(geokret).isNotNull();
assert geokret != null;
assertThat(geokret.getBrand()).isEqualTo(TrackableBrand.GEOKRETY);
assertThat(geokret.getName()).isEqualTo("c:geo One");
assertThat(geokret.getDetails()).isEqualTo("GeoKret for the c:geo project :)<br />DO NOT MOVE");
assertThat(geokret.getOwner()).isEqualTo("kumy");
assertThat(geokret.isMissing()).isTrue();
assertThat(geokret.isLoggable()).isTrue();
assertThat(geokret.getSpottedName()).isEqualTo("OX5BRQK");
assertThat(geokret.getSpottedType()).isEqualTo(Trackable.SPOTTED_CACHE);
}
public void testSearchTrackables() throws Exception {
// here it is assumed that:
// * cache OX5BRQK contains these 2 objects only...
// * objects never been moved
// * GK website always return list in the same order
final List<Trackable> trackables = new GeokretyConnector().searchTrackables("OX5BRQK");
assertThat(trackables).hasSize(2);
assertThat(trackables.get(0).getName()).isEqualTo("c:geo One");
assertThat(trackables.get(1).getName()).isEqualTo("c:geo Two");
}
public void testGetIconBrand() throws Exception {
final List<Trackable> trackables = GeokretyParser.parse(new InputSource(getResourceStream(R.raw.geokret141_xml)));
assertThat(trackables).hasSize(2);
assertThat(trackables.get(0).getIconBrand()).isEqualTo(TrackableBrand.GEOKRETY.getIconResource());
assertThat(trackables.get(1).getIconBrand()).isEqualTo(TrackableBrand.GEOKRETY.getIconResource());
}
private static GeokretyConnector getConnector() {
return new GeokretyConnector();
}
public static void testRecommendGeocode() throws Exception {
assertThat(getConnector().recommendLogWithGeocode()).isTrue();
}
}
| tests/src-android/cgeo/geocaching/connector/trackable/GeokretyConnectorTest.java | package cgeo.geocaching.connector.trackable;
import org.xml.sax.InputSource;
import java.util.List;
import cgeo.geocaching.models.Trackable;
import cgeo.geocaching.test.AbstractResourceInstrumentationTestCase;
import cgeo.geocaching.test.R;
import static org.assertj.core.api.Java6Assertions.assertThat;
/**
* test for {@link GeokretyConnector}
*/
public class GeokretyConnectorTest extends AbstractResourceInstrumentationTestCase {
public static void testCanHandleTrackable() {
assertThat(getConnector().canHandleTrackable("GK82A2")).isTrue();
assertThat(getConnector().canHandleTrackable("TB1234")).isFalse();
assertThat(getConnector().canHandleTrackable("UNKNOWN")).isFalse();
assertThat(getConnector().canHandleTrackable("GKXYZ1")).isFalse(); // non hex
assertThat(getConnector().canHandleTrackable("GKXYZ1", TrackableBrand.GEOKRETY)).isTrue(); // non hex, but match secret codes pattern
assertThat(getConnector().canHandleTrackable("123456", TrackableBrand.GEOKRETY)).isTrue(); // Secret code
assertThat(getConnector().canHandleTrackable("012345", TrackableBrand.GEOKRETY)).isFalse(); // blacklisted 0/O
assertThat(getConnector().canHandleTrackable("ABCDEF", TrackableBrand.GEOKRETY)).isTrue(); // Secret code
assertThat(getConnector().canHandleTrackable("LMNOPQ", TrackableBrand.GEOKRETY)).isFalse(); // blacklisted 0/O
assertThat(getConnector().canHandleTrackable("GC1234")).isFalse();
assertThat(getConnector().canHandleTrackable("GC1234", TrackableBrand.UNKNOWN)).isFalse();
assertThat(getConnector().canHandleTrackable("GC1234", TrackableBrand.TRAVELBUG)).isFalse();
assertThat(getConnector().canHandleTrackable("GC1234", TrackableBrand.GEOKRETY)).isTrue();
}
public static void testGetTrackableCodeFromUrl() throws Exception {
assertThat(getConnector().getTrackableCodeFromUrl("http://www.geokrety.org/konkret.php?id=46464")).isEqualTo("GKB580");
assertThat(getConnector().getTrackableCodeFromUrl("https://www.geokrety.org/konkret.php?id=46464")).isEqualTo("GKB580");
assertThat(getConnector().getTrackableCodeFromUrl("http://geokrety.org/konkret.php?id=46465")).isEqualTo("GKB581");
assertThat(getConnector().getTrackableCodeFromUrl("https://geokrety.org/konkret.php?id=46465")).isEqualTo("GKB581");
}
public static void testGeocode() throws Exception {
assertThat(GeokretyConnector.geocode(46464)).isEqualTo("GKB580");
}
public static void testGetId() throws Exception {
assertThat(GeokretyConnector.getId("GKB581")).isEqualTo(46465);
}
public void testGetUrl() throws Exception {
final List<Trackable> trackables = GeokretyParser.parse(new InputSource(getResourceStream(R.raw.geokret141_xml)));
assertThat(trackables).hasSize(2);
assertThat(trackables.get(0).getUrl()).isEqualTo("https://geokrety.org/konkret.php?id=46464");
assertThat(trackables.get(1).getUrl()).isEqualTo("https://geokrety.org/konkret.php?id=46465");
}
public void testSearchTrackable() throws Exception {
final Trackable geokret = GeokretyConnector.searchTrackable("GKB580");
assertThat(geokret).isNotNull();
assert geokret != null;
assertThat(geokret.getBrand()).isEqualTo(TrackableBrand.GEOKRETY);
assertThat(geokret.getName()).isEqualTo("c:geo One");
assertThat(geokret.getDetails()).isEqualTo("GeoKret for the c:geo project :)<br />DO NOT MOVE");
assertThat(geokret.getOwner()).isEqualTo("kumy");
assertThat(geokret.isMissing()).isTrue();
assertThat(geokret.isLoggable()).isTrue();
assertThat(geokret.getSpottedName()).isEqualTo("OX5BRQK");
assertThat(geokret.getSpottedType()).isEqualTo(Trackable.SPOTTED_CACHE);
}
public void testSearchTrackables() throws Exception {
// here it is assumed that:
// * cache OX5BRQK contains these 2 objects only...
// * objects never been moved
// * GK website always return list in the same order
final List<Trackable> trackables = new GeokretyConnector().searchTrackables("OX5BRQK");
assertThat(trackables).hasSize(2);
assertThat(trackables.get(0).getName()).isEqualTo("c:geo Two");
assertThat(trackables.get(1).getName()).isEqualTo("c:geo One");
}
public void testGetIconBrand() throws Exception {
final List<Trackable> trackables = GeokretyParser.parse(new InputSource(getResourceStream(R.raw.geokret141_xml)));
assertThat(trackables).hasSize(2);
assertThat(trackables.get(0).getIconBrand()).isEqualTo(TrackableBrand.GEOKRETY.getIconResource());
assertThat(trackables.get(1).getIconBrand()).isEqualTo(TrackableBrand.GEOKRETY.getIconResource());
}
private static GeokretyConnector getConnector() {
return new GeokretyConnector();
}
public static void testRecommendGeocode() throws Exception {
assertThat(getConnector().recommendLogWithGeocode()).isTrue();
}
}
| Reorder GeoKrety tests
Since GK website upgrade, GK are received in another order
| tests/src-android/cgeo/geocaching/connector/trackable/GeokretyConnectorTest.java | Reorder GeoKrety tests | <ide><path>ests/src-android/cgeo/geocaching/connector/trackable/GeokretyConnectorTest.java
<ide> // * GK website always return list in the same order
<ide> final List<Trackable> trackables = new GeokretyConnector().searchTrackables("OX5BRQK");
<ide> assertThat(trackables).hasSize(2);
<del> assertThat(trackables.get(0).getName()).isEqualTo("c:geo Two");
<del> assertThat(trackables.get(1).getName()).isEqualTo("c:geo One");
<add> assertThat(trackables.get(0).getName()).isEqualTo("c:geo One");
<add> assertThat(trackables.get(1).getName()).isEqualTo("c:geo Two");
<ide> }
<ide>
<ide> public void testGetIconBrand() throws Exception { |
|
Java | mit | 45eba2b989308aead4e5957f2c0c77b31d8b5a67 | 0 | EvilMcJerkface/jessy,EvilMcJerkface/jessy,EvilMcJerkface/jessy,EvilMcJerkface/jessy,EvilMcJerkface/jessy,EvilMcJerkface/jessy | package fr.inria.jessy.transaction.termination;
import static fr.inria.jessy.transaction.ExecutionHistory.TransactionType.BLIND_WRITE;
import static fr.inria.jessy.transaction.TransactionState.COMMITTED;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import net.sourceforge.fractal.FractalManager;
import net.sourceforge.fractal.Learner;
import net.sourceforge.fractal.Stream;
import net.sourceforge.fractal.membership.Group;
import net.sourceforge.fractal.membership.Membership;
import net.sourceforge.fractal.multicast.MulticastMessage;
import net.sourceforge.fractal.multicast.MulticastStream;
import net.sourceforge.fractal.wanamcast.WanAMCastStream;
import org.apache.log4j.Logger;
import fr.inria.jessy.ConstantPool;
import fr.inria.jessy.DistributedJessy;
import fr.inria.jessy.consistency.ConsistencyFactory;
import fr.inria.jessy.store.JessyEntity;
import fr.inria.jessy.transaction.ExecutionHistory;
import fr.inria.jessy.transaction.TransactionHandler;
import fr.inria.jessy.transaction.TransactionState;
import fr.inria.jessy.transaction.termination.message.TerminateTransactionReplyMessage;
import fr.inria.jessy.transaction.termination.message.TerminateTransactionRequestMessage;
import fr.inria.jessy.transaction.termination.message.VoteMessage;
import fr.inria.jessy.utils.ExecutorPool;
//TODO COMMENT ME
//TODO Clean these ConcurrentMaps
public class DistributedTermination implements Learner, Runnable {
private static Logger logger = Logger
.getLogger(DistributedTermination.class);
private DistributedJessy jessy;
private ExecutorPool pool = ExecutorPool.getInstance();
private WanAMCastStream atomicMulticastStream;
private MulticastStream voteStream;
private MulticastStream terminationNotificationStream;
private Membership membership;
private Group group;
private Map<UUID, TransactionHandler> terminationRequests;
private Map<UUID, TerminationResult> terminationResults;
private Map<TransactionHandler, VotingQuorum> votingQuorums;
private Map<TransactionHandler, String> coordinatorGroups;
private LinkedBlockingQueue<TerminateTransactionRequestMessage> atomicDeliveredMessages;
private Map<TransactionHandler, TerminateTransactionRequestMessage> processingMessages;
private List<TransactionHandler> terminated;
private Thread thread;
public DistributedTermination(DistributedJessy j, Group g) {
jessy = j;
membership = j.membership;
group = g;
terminationNotificationStream = FractalManager.getInstance()
.getOrCreateMulticastStream(ConstantPool.JESSY_ALL_GROUP,
ConstantPool.JESSY_ALL_GROUP);
terminationNotificationStream.registerLearner(
"TerminateTransactionReplyMessage", this);
voteStream = FractalManager.getInstance().getOrCreateMulticastStream(
group.name(), group.name());
voteStream.registerLearner("VoteMessage", this);
atomicMulticastStream = FractalManager.getInstance()
.getOrCreateWanAMCastStream(group.name(), group.name());
atomicMulticastStream.registerLearner(
"TerminateTransactionRequestMessage", this);
terminationNotificationStream.start();
voteStream.start();
atomicMulticastStream.start();
terminationRequests = new ConcurrentHashMap<UUID, TransactionHandler>();
terminationResults = new ConcurrentHashMap<UUID, TerminationResult>();
atomicDeliveredMessages = new LinkedBlockingQueue<TerminateTransactionRequestMessage>();
processingMessages = new ConcurrentHashMap<TransactionHandler, TerminateTransactionRequestMessage>();
votingQuorums = new ConcurrentHashMap<TransactionHandler, VotingQuorum>();
coordinatorGroups = new ConcurrentHashMap<TransactionHandler, String>();
terminated = new CopyOnWriteArrayList<TransactionHandler>();
thread = new Thread(this);
thread.start();
}
public Future<TerminationResult> terminateTransaction(ExecutionHistory ex) {
logger.debug("terminate transaction "
+ ex.getTransactionHandler().getId());
ex.changeState(TransactionState.COMMITTING);
terminationRequests.put(ex.getTransactionHandler().getId(),
ex.getTransactionHandler());
Future<TerminationResult> reply = pool.submit(new AtomicMulticastTask(
ex));
return reply;
}
@Deprecated
public void learn(Stream s, Serializable v) {
if (v instanceof TerminateTransactionRequestMessage) {
TerminateTransactionRequestMessage requestMessage = (TerminateTransactionRequestMessage) v;
atomicDeliveredMessages.add(requestMessage);
coordinatorGroups.put(requestMessage.getExecutionHistory()
.getTransactionHandler(), requestMessage.gSource);
} else if (v instanceof TerminateTransactionReplyMessage) {
TerminateTransactionReplyMessage replyMessage = (TerminateTransactionReplyMessage) v;
TransactionHandler th = replyMessage.getTerminationResult()
.getTransactionHandler();
logger.debug("got a terminateTransactionReplyMesssage for "
+ th.getId());
if (terminated.contains(th))
return;
/*
* This node is the coordinator, and it is not in the replica set.
*/
assert terminationRequests.containsKey(th.getId());
assert replyMessage.getTerminationResult()
.isSendBackToCoordinator();
handleTerminationResult(null, replyMessage.getTerminationResult());
} else { // VoteMessage
Vote vote = ((VoteMessage) v).getVote();
if (terminated.contains(vote.getTransactionHandler()))
return;
addVote(vote);
}
}
/**
* Continuesly, checks {@code atomicDeliveredMessages} queue, and if the
* message in the head of the queue does not conflict with already
* committing transactions, creates a new {@code CertifyAndVoteTask} for
* processing it. Otherwise, waits until one message in processingMessages
* list finishes its execution.
*
*/
@Override
public void run() {
TerminateTransactionRequestMessage msg;
while (true) {
/*
* When a new certify and vote task is submitted, it is first check
* whether is a concurrent conflicting transaction already
* committing or not. If not, the message is put in {@code
* processingMessages} map, otherwise, it should wait until one
* transaction finishes its termination.
*/
try {
msg = atomicDeliveredMessages.take();
Iterator<TerminateTransactionRequestMessage> itr = processingMessages
.values().iterator();
while (itr.hasNext()) {
if (ConsistencyFactory.getConsistency().hasConflict(
msg.getExecutionHistory(),
itr.next().getExecutionHistory())) {
try {
synchronized (processingMessages) {
processingMessages.wait();
}
itr = processingMessages.values().iterator();
continue;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
processingMessages.put(msg.getExecutionHistory()
.getTransactionHandler(), msg);
/*
* There is no conflict with already processing messages in
* {@code processingMessages}, thus a new {@code
* CertifyAndVoteTask} is created for handling this messages.
*/
pool.submit(new CertifyAndVoteTask(msg));
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
/**
* Upon receiving a new certification vote, it is added to the
* votingQuorums.
*
* @param vote
*/
private void addVote(Vote vote) {
if (votingQuorums.containsKey(vote.getTransactionHandler())) {
votingQuorums.get(vote.getTransactionHandler()).addVote(vote);
} else {
VotingQuorum vq = new VotingQuorum(vote.getTransactionHandler(),
vote.getAllVoterGroups());
vq.addVote(vote);
votingQuorums.put(vote.getTransactionHandler(), vq);
}
}
/**
* If this method is called at the transaction's coordinator, we should
* notify the pending future of the coordinator. Otherwise, the method is
* called at a remote replica. If the transaction is not going to be
* certified at the coordinator (coordinator does not replicate an object
* concerned by the transaction), the {@code terminationCode} should be send
* to the coordinator.
*
* PIERRE null for executionHistory indicates that we are at the coordinator
* and the coordinator is not in the replica set
*
* FIXME change this
*
* TODO should it be synchronized?
*/
private void handleTerminationResult(
ExecutionHistory executionHistory,
TerminationResult terminationResult) {
logger.debug("handling termination result for "
+ terminationResult.getTransactionHandler().getId());
HashSet<String> cordinatorGroup = new HashSet<String>();
cordinatorGroup.add(coordinatorGroups.get(terminationResult
.getTransactionHandler()));
/*
* Apply the transaction if (i) it is committed and (ii) we hold a
* modified entity. Observe that if executionHistory==null, then we are
* the coord. and we own no modified entity.
*/
if (terminationResult.getTransactionState() == COMMITTED
&& executionHistory != null) {
boolean hasLocal = false;
for (JessyEntity e : executionHistory.getWriteSet().getEntities()) {
if (jessy.partitioner.isLocal(e.getSecondaryKey())) {
try {
hasLocal = true;
jessy.performNonTransactionalLocalWrite(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
for (JessyEntity e : executionHistory.getCreateSet().getEntities()) {
if (jessy.partitioner.isLocal(e.getSecondaryKey())) {
try {
hasLocal = true;
jessy.performNonTransactionalLocalWrite(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
assert hasLocal;
}
/*
* if the future is not null, it means that this process is the
* coordinator, and it has received the outcome of a transaction
* termination phase. It puts the result in the terminationResults Map,
* and call the notify the future to finishes its task.
*
* Otherwise, a non-cordinator has received the required votes, and has
* decided the outcome of the transaction. So, if the coordinator does
* not receive the outcome, this process unicasts the result to the
* coordinator.
*/
if (terminationRequests.containsKey(terminationResult
.getTransactionHandler().getId())) {
TransactionHandler transactionHandler = terminationRequests
.get(terminationResult.getTransactionHandler().getId());
synchronized (transactionHandler) {
terminationResults.put(terminationResult
.getTransactionHandler().getId(), terminationResult);
transactionHandler.notify();
}
} else if (terminationResult.isSendBackToCoordinator()) {
MulticastMessage replyMessage = new TerminateTransactionReplyMessage(
terminationResult, cordinatorGroup, group.name(),
membership.myId());
logger.debug("send a terminateTransactionReplyMesssage for "
+ executionHistory.getTransactionHandler().getId());
terminationNotificationStream.unicast(replyMessage,
executionHistory.getCoordinator());
}
garbageCollect(terminationResult.getTransactionHandler());
}
/**
* Garbage collect all concurrent hash maps entries for the given
* {@code transactionHandler}
*
* TODO is it necessary to be synchronized?
*
* @param transactionHandler
* The transactionHandler to be garbage collected.
*/
private void garbageCollect(TransactionHandler transactionHandler) {
/*
* Upon removing the transaction from {@code processingMessages}, it
* notifies the main thread to process waiting messages again.
*/
processingMessages.remove(transactionHandler);
synchronized (processingMessages) {
processingMessages.notify();
}
terminated.add(transactionHandler);
if (terminationRequests.containsKey(transactionHandler.getId())) {
logger.debug("garbage-collect for " + transactionHandler.getId());
terminationRequests.remove(transactionHandler);
votingQuorums.remove(transactionHandler);
coordinatorGroups.remove(transactionHandler);
}
}
private class AtomicMulticastTask implements Callable<TerminationResult> {
private ExecutionHistory executionHistory;
private AtomicMulticastTask(ExecutionHistory eh) {
this.executionHistory = eh;
}
public TerminationResult call() throws Exception {
HashSet<String> destGroups = new HashSet<String>();
Set<String> concernedKeys = ConsistencyFactory
.getConcerningKeys(executionHistory);
/*
* If there is no concerning key, it means that the transaction can
* commit right away. e.g. read-only transaction with NMSI
* consistency.
*/
if (concernedKeys.size() == 0) {
executionHistory.changeState(TransactionState.COMMITTED);
return new TerminationResult(
executionHistory.getTransactionHandler(),
TransactionState.COMMITTED, null);
}
destGroups.addAll(jessy.partitioner
.resolveToGroupNames(concernedKeys));
/*
* if this process will receive this transaction through atomic
* multicast then certifyAtCoordinator is set to true, otherwise, it
* is set to false.
*/
executionHistory.setCoordinator(membership.myId());
if (destGroups.contains(group.name())) {
executionHistory.setCertifyAtCoordinator(true);
} else {
executionHistory.setCertifyAtCoordinator(false);
}
/*
* Atomic multicast the transaction.
*/
atomicMulticastStream
.atomicMulticast(new TerminateTransactionRequestMessage(
executionHistory, destGroups, group.name(),
membership.myId()));
/*
* Wait here until the result of the transaction is known. While is
* for preventing <i>spurious wakeup</i>
*/
synchronized (executionHistory.getTransactionHandler()) {
while (!terminationResults.containsKey(executionHistory
.getTransactionHandler().getId())) {
executionHistory.getTransactionHandler().wait();
}
}
TerminationResult result = terminationResults.get(executionHistory
.getTransactionHandler().getId());
/*
* garbage collect he result. We do not need it anymore. Note, you
* cannot garbage collect {@code terminationResults} in {@code
* garbageCollect}.
*/
terminationResults.remove(executionHistory.getTransactionHandler()
.getId());
return result;
}
}
private class CertifyAndVoteTask implements Callable<Boolean> {
private TerminateTransactionRequestMessage msg;
private CertifyAndVoteTask(TerminateTransactionRequestMessage msg) {
this.msg = msg;
}
public Boolean call() throws Exception {
try {
/*
* First, it needs to run the certification test on the received
* execution history. A blind write always succeeds.
*/
boolean certified = msg.getExecutionHistory()
.getTransactionType() == BLIND_WRITE
|| ConsistencyFactory.getConsistency().certify(
jessy.getLastCommittedEntities(),
msg.getExecutionHistory());
/*
* If it holds all keys, it can decide <i>locally</i> according
* to the value of <@code certified>.
*
* Otherwise, it should vote and wait to get a voting quorums;
*/
if (msg.gDest.size() == 1 && msg.gDest.contains(group.name())) {
msg.getExecutionHistory()
.changeState(
(certified) ? TransactionState.COMMITTED
: TransactionState.ABORTED_BY_CERTIFICATION);
} else {
/*
* Compute a set of destinations for the votes, and sends
* out the votes to all replicas <i>that replicate objects
* modified inside the transaction</i>.
*/
Set<String> dest = jessy.partitioner
.resolveToGroupNames(msg.getExecutionHistory()
.getWriteSet().getKeys());
voteStream.multicast(new VoteMessage(new Vote(msg
.getExecutionHistory().getTransactionHandler(),
certified, group.name(), msg.gDest), dest, group
.name(), membership.myId()));
TransactionState state = votingQuorums.get(
msg.getExecutionHistory().getTransactionHandler())
.getTerminationResult();
msg.getExecutionHistory().changeState(state);
}
/*
* The transaction is decided. creates a termination result, and
* passes it to the {@code handleTerminationResult}, and returns
* true.
*/
TerminationResult terminationResult = new TerminationResult(msg
.getExecutionHistory().getTransactionHandler(), msg
.getExecutionHistory().getTransactionState(), !msg
.getExecutionHistory().isCertifyAtCoordinator());
handleTerminationResult(msg.getExecutionHistory(),
terminationResult);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
}
| src/fr/inria/jessy/transaction/termination/DistributedTermination.java | package fr.inria.jessy.transaction.termination;
import static fr.inria.jessy.transaction.ExecutionHistory.TransactionType.BLIND_WRITE;
import static fr.inria.jessy.transaction.ExecutionHistory.TransactionType.READONLY_TRANSACTION;
import static fr.inria.jessy.transaction.TransactionState.COMMITTED;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.hadoop.fs.Trash;
import org.apache.log4j.Logger;
import net.sourceforge.fractal.FractalManager;
import net.sourceforge.fractal.Learner;
import net.sourceforge.fractal.Stream;
import net.sourceforge.fractal.membership.Group;
import net.sourceforge.fractal.membership.Membership;
import net.sourceforge.fractal.multicast.MulticastMessage;
import net.sourceforge.fractal.multicast.MulticastStream;
import net.sourceforge.fractal.wanamcast.WanAMCastStream;
import fr.inria.jessy.ConstantPool;
import fr.inria.jessy.DistributedJessy;
import fr.inria.jessy.consistency.ConsistencyFactory;
import fr.inria.jessy.store.JessyEntity;
import fr.inria.jessy.transaction.ExecutionHistory;
import fr.inria.jessy.transaction.TransactionHandler;
import fr.inria.jessy.transaction.TransactionState;
import fr.inria.jessy.transaction.termination.message.TerminateTransactionReplyMessage;
import fr.inria.jessy.transaction.termination.message.TerminateTransactionRequestMessage;
import fr.inria.jessy.transaction.termination.message.VoteMessage;
import fr.inria.jessy.utils.ExecutorPool;
//TODO COMMENT ME
//TODO Clean these ConcurrentMaps
public class DistributedTermination implements Learner, Runnable {
private static Logger logger = Logger
.getLogger(DistributedTermination.class);
private DistributedJessy jessy;
private ExecutorPool pool = ExecutorPool.getInstance();
private WanAMCastStream atomicMulticastStream;
private MulticastStream voteStream;
private MulticastStream terminationNotificationStream;
private Membership membership;
private Group group;
private Map<UUID, TransactionHandler> terminationRequests;
private Map<UUID, TerminationResult> terminationResults;
private Map<TransactionHandler, VotingQuorum> votingQuorums;
private Map<TransactionHandler, String> coordinatorGroups;
private LinkedBlockingQueue<TerminateTransactionRequestMessage> atomicDeliveredMessages;
private Map<TransactionHandler, TerminateTransactionRequestMessage> processingMessages;
private List<TransactionHandler> terminated;
private Thread thread;
public DistributedTermination(DistributedJessy j, Group g) {
jessy = j;
membership = j.membership;
group = g;
terminationNotificationStream = FractalManager.getInstance()
.getOrCreateMulticastStream(ConstantPool.JESSY_ALL_GROUP,
ConstantPool.JESSY_ALL_GROUP);
terminationNotificationStream.registerLearner(
"TerminateTransactionReplyMessage", this);
voteStream = FractalManager.getInstance().getOrCreateMulticastStream(
group.name(), group.name());
voteStream.registerLearner("VoteMessage", this);
atomicMulticastStream = FractalManager.getInstance()
.getOrCreateWanAMCastStream(group.name(), group.name());
atomicMulticastStream.registerLearner(
"TerminateTransactionRequestMessage", this);
terminationNotificationStream.start();
voteStream.start();
atomicMulticastStream.start();
terminationRequests = new ConcurrentHashMap<UUID, TransactionHandler>();
terminationResults = new ConcurrentHashMap<UUID, TerminationResult>();
atomicDeliveredMessages = new LinkedBlockingQueue<TerminateTransactionRequestMessage>();
processingMessages = new ConcurrentHashMap<TransactionHandler, TerminateTransactionRequestMessage>();
votingQuorums = new ConcurrentHashMap<TransactionHandler, VotingQuorum>();
coordinatorGroups = new ConcurrentHashMap<TransactionHandler, String>();
terminated = new ArrayList<TransactionHandler>();
thread = new Thread(this);
thread.start();
}
public Future<TerminationResult> terminateTransaction(ExecutionHistory ex) {
logger.debug("terminate transaction "
+ ex.getTransactionHandler().getId());
ex.changeState(TransactionState.COMMITTING);
terminationRequests.put(ex.getTransactionHandler().getId(),
ex.getTransactionHandler());
Future<TerminationResult> reply = pool.submit(new AtomicMulticastTask(
ex));
return reply;
}
@Deprecated
public void learn(Stream s, Serializable v) {
if (v instanceof TerminateTransactionRequestMessage) {
TerminateTransactionRequestMessage requestMessage = (TerminateTransactionRequestMessage) v;
atomicDeliveredMessages.add(requestMessage);
coordinatorGroups.put(requestMessage.getExecutionHistory()
.getTransactionHandler(), requestMessage.gSource);
} else if (v instanceof TerminateTransactionReplyMessage) {
TerminateTransactionReplyMessage replyMessage = (TerminateTransactionReplyMessage) v;
TransactionHandler th = replyMessage.getTerminationResult()
.getTransactionHandler();
logger.debug("got a terminateTransactionReplyMesssage for "
+ th.getId());
if (terminated.contains(th))
return;
/*
* This node is the coordinator, and it is not in the replica set.
*/
assert terminationRequests.containsKey(th.getId());
assert replyMessage.getTerminationResult()
.isSendBackToCoordinator();
handleTerminationResult(null, replyMessage.getTerminationResult());
} else { // VoteMessage
Vote vote = ((VoteMessage) v).getVote();
if (terminated.contains(vote.getTransactionHandler()))
return;
addVote(vote);
}
}
/**
* Continuesly, checks {@code atomicDeliveredMessages} queue, and if the
* message in the head of the queue does not conflict with already
* committing transactions, creates a new {@code CertifyAndVoteTask} for
* processing it. Otherwise, waits until one message in processingMessages
* list finishes its execution.
*
* FIXME
*/
@Override
public void run() {
TerminateTransactionRequestMessage msg;
while (true) {
// FIXME
// msg = atomicDeliveredMessages.peek();
// if (msg == null)
// continue;
//
// /*
// * if there is a conflict, it cannot proceed to handle the head
// * message, thus waits until one of a messages in {@link
// *
// * @processingMessgaes} finishes and notify this queue.
// */
// for (TerminateTransactionRequestMessage committing :
// processingMessages
// .values()) {
// if (ConsistencyFactory.getConsistency().hasConflict(
// msg.getExecutionHistory(),
// committing.getExecutionHistory())) {
// try {
// wait();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
/*
* There is no conflict with already processing messages in {@code
* processingMessages}, thus a new {@code CertifyAndVoteTask} is
* created for handling this messages.
*/
try {
msg = atomicDeliveredMessages.take();
pool.submit(new CertifyAndVoteTask(msg));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* Upon receiving a new certification vote, it is added to the
* votingQuorums.
*
* @param vote
*/
private void addVote(Vote vote) {
if (votingQuorums.containsKey(vote.getTransactionHandler())) {
votingQuorums.get(vote.getTransactionHandler()).addVote(vote);
} else {
VotingQuorum vq = new VotingQuorum(vote.getTransactionHandler(),
vote.getAllVoterGroups());
vq.addVote(vote);
votingQuorums.put(vote.getTransactionHandler(), vq);
}
}
/**
* If this method is called at the transaction's coordinator, we should
* notify the pending future of the coordinator. Otherwise, the method is
* called at a remote replica. If the transaction is not going to be
* certified at the coordinator (coordinator does not replicate an object
* concerned by the transaction), the {@code terminationCode} should be send
* to the coordinator.
*
* PIERRE null for executionHistory indicates that we are at the coordinator
* and the coordinator is not in the replica set FIXME change this TODO
* should it be synchronized?
*/
private synchronized void handleTerminationResult(
ExecutionHistory executionHistory,
TerminationResult terminationResult) {
logger.debug("handling termination result for "
+ terminationResult.getTransactionHandler().getId());
HashSet<String> cordinatorGroup = new HashSet<String>();
cordinatorGroup.add(coordinatorGroups.get(terminationResult
.getTransactionHandler()));
/*
* Apply the transaction if (i) it is committed and (ii) we hold a
* modified entity. Observe that if executionHistory==null, then we are
* the coord. and we own no modified entity.
*/
if (terminationResult.getTransactionState() == COMMITTED
&& executionHistory != null) {
boolean hasLocal = false;
for (JessyEntity e : executionHistory.getWriteSet().getEntities()) {
if (jessy.partitioner.isLocal(e.getSecondaryKey())) {
try {
hasLocal = true;
jessy.performNonTransactionalLocalWrite(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
for (JessyEntity e : executionHistory.getCreateSet().getEntities()) {
if (jessy.partitioner.isLocal(e.getSecondaryKey())) {
try {
hasLocal = true;
jessy.performNonTransactionalLocalWrite(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
assert hasLocal;
}
/*
* if the future is not null, it means that this process is the
* coordinator, and it has received the outcome of a transaction
* termination phase. It puts the result in the terminationResults Map,
* and call the notify the future to finishes its task.
*
* Otherwise, a non-cordinator has received the required votes, and has
* decided the outcome of the transaction. So, if the coordinator does
* not receive the outcome, this process unicasts the result to the
* coordinator.
*/
if (terminationRequests.containsKey(terminationResult
.getTransactionHandler().getId())) {
TransactionHandler transactionHandler = terminationRequests
.get(terminationResult.getTransactionHandler().getId());
synchronized (transactionHandler) {
terminationResults.put(terminationResult
.getTransactionHandler().getId(), terminationResult);
transactionHandler.notify();
}
} else if (terminationResult.isSendBackToCoordinator()) {
MulticastMessage replyMessage = new TerminateTransactionReplyMessage(
terminationResult, cordinatorGroup, group.name(),
membership.myId());
logger.debug("send a terminateTransactionReplyMesssage for "
+ executionHistory.getTransactionHandler().getId());
terminationNotificationStream.unicast(replyMessage,
executionHistory.getCoordinator());
}
garbageCollect(terminationResult.getTransactionHandler());
}
/**
* Garbage collect all concurrent hash maps entries for the given
* {@code transactionHandler} TODO is it necessary to be synchronized?
*
* @param transactionHandler
* The transactionHandler to be garbage collected.
*/
private synchronized void garbageCollect(
TransactionHandler transactionHandler) {
processingMessages.remove(transactionHandler);
synchronized (processingMessages) {
processingMessages.notifyAll();
}
terminated.add(transactionHandler);
if (terminationRequests.containsKey(transactionHandler.getId())) {
logger.debug("garbage-collect for " + transactionHandler.getId());
terminationRequests.remove(transactionHandler);
// terminationResults.remove(transactionHandler);
votingQuorums.remove(transactionHandler);
coordinatorGroups.remove(transactionHandler);
}
}
private class AtomicMulticastTask implements Callable<TerminationResult> {
private ExecutionHistory executionHistory;
private AtomicMulticastTask(ExecutionHistory eh) {
this.executionHistory = eh;
}
public TerminationResult call() throws Exception {
HashSet<String> destGroups = new HashSet<String>();
Set<String> concernedKeys = ConsistencyFactory
.getConcerningKeys(executionHistory);
/*
* If there is no concerning key, it means that the transaction can
* commit right away. e.g. read-only transaction with NMSI
* consistency.
*/
if (concernedKeys.size() == 0) {
executionHistory.changeState(TransactionState.COMMITTED);
return new TerminationResult(
executionHistory.getTransactionHandler(),
TransactionState.COMMITTED, null);
}
destGroups.addAll(jessy.partitioner
.resolveToGroupNames(concernedKeys));
/*
* if this process will receive this transaction through atomic
* multicast then certifyAtCoordinator is set to true, otherwise, it
* is set to false.
*/
executionHistory.setCoordinator(membership.myId());
if (destGroups.contains(group.name())) {
executionHistory.setCertifyAtCoordinator(true);
} else {
executionHistory.setCertifyAtCoordinator(false);
}
/*
* Atomic multicast the transaction.
*/
atomicMulticastStream
.atomicMulticast(new TerminateTransactionRequestMessage(
executionHistory, destGroups, group.name(),
membership.myId()));
/*
* Wait here until the result of the transaction is known. While is
* for preventing <i>spurious wakeup</i>
*/
synchronized (executionHistory.getTransactionHandler()) {
while (!terminationResults.containsKey(executionHistory
.getTransactionHandler().getId())) {
executionHistory.getTransactionHandler().wait();
}
}
TerminationResult result = terminationResults.get(executionHistory
.getTransactionHandler().getId());
/*
* garbage collect he result. We do not need it anymore. Note, you
* cannot garbage collect {@code terminationResults} in {@code
* garbageCollect}.
*/
terminationResults.remove(executionHistory.getTransactionHandler()
.getId());
return result;
}
}
private class CertifyAndVoteTask implements Callable<Boolean> {
private TerminateTransactionRequestMessage msg;
private CertifyAndVoteTask(TerminateTransactionRequestMessage msg) {
this.msg = msg;
}
public Boolean call() throws Exception {
/*
* When a new certify and vote task is submitted, it is first check
* whether is a concurrent conflicting transaction already
* committing or not. If not, the message is put in {@code
* processingMessages} map, otherwise, it should wait until one
* transaction finishes its termination.
*/
Iterator<TerminateTransactionRequestMessage> itr = processingMessages
.values().iterator();
while (itr.hasNext()) {
if (ConsistencyFactory.getConsistency().hasConflict(
msg.getExecutionHistory(),
itr.next().getExecutionHistory())) {
try {
synchronized (processingMessages) {
processingMessages.wait();
}
itr = processingMessages.values().iterator();
continue;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
processingMessages.put(msg.getExecutionHistory()
.getTransactionHandler(), msg);
try {
/*
* First, it needs to run the certification test on the received
* execution history. A blind write always succeeds.
*/
boolean certified = msg.getExecutionHistory()
.getTransactionType() == BLIND_WRITE
|| ConsistencyFactory.getConsistency().certify(
jessy.getLastCommittedEntities(),
msg.getExecutionHistory());
/*
* If it holds all keys, it can decide <i>locally</i> according
* to the value of <@code certified>.
*
* Otherwise, it should vote and wait to get a voting quorums;
*/
if (msg.gDest.size() == 1 && msg.gDest.contains(group.name())) {
msg.getExecutionHistory()
.changeState(
(certified) ? TransactionState.COMMITTED
: TransactionState.ABORTED_BY_CERTIFICATION);
} else {
/*
* Compute a set of destinations for the votes, and sends
* out the votes to all replicas <i>that replicate objects
* modified inside the transaction</i>.
*/
Set<String> dest = jessy.partitioner
.resolveToGroupNames(msg.getExecutionHistory()
.getWriteSet().getKeys());
voteStream.multicast(new VoteMessage(new Vote(msg
.getExecutionHistory().getTransactionHandler(),
certified, group.name(), msg.gDest), dest, group
.name(), membership.myId()));
TransactionState state = votingQuorums.get(
msg.getExecutionHistory().getTransactionHandler())
.getTerminationResult();
msg.getExecutionHistory().changeState(state);
}
/*
* The transaction is decided. creates a termination result, and
* passes it to the {@code handleTerminationResult}, and returns
* true.
*/
TerminationResult terminationResult = new TerminationResult(msg
.getExecutionHistory().getTransactionHandler(), msg
.getExecutionHistory().getTransactionState(), !msg
.getExecutionHistory().isCertifyAtCoordinator());
handleTerminationResult(msg.getExecutionHistory(),
terminationResult);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
}
|
git-svn-id: svn+ssh://scm.gforge.inria.fr/svn/regal/trunk/src/jessy@1025 334080fa-30e0-4884-a663-39494f8d70c4
| src/fr/inria/jessy/transaction/termination/DistributedTermination.java | <ide><path>rc/fr/inria/jessy/transaction/termination/DistributedTermination.java
<ide> package fr.inria.jessy.transaction.termination;
<ide>
<ide> import static fr.inria.jessy.transaction.ExecutionHistory.TransactionType.BLIND_WRITE;
<del>import static fr.inria.jessy.transaction.ExecutionHistory.TransactionType.READONLY_TRANSACTION;
<ide> import static fr.inria.jessy.transaction.TransactionState.COMMITTED;
<ide>
<ide> import java.io.Serializable;
<del>import java.util.ArrayList;
<ide> import java.util.HashSet;
<ide> import java.util.Iterator;
<ide> import java.util.List;
<ide> import java.util.Map;
<del>import java.util.Queue;
<ide> import java.util.Set;
<ide> import java.util.UUID;
<ide> import java.util.concurrent.Callable;
<ide> import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.concurrent.CopyOnWriteArrayList;
<ide> import java.util.concurrent.Future;
<ide> import java.util.concurrent.LinkedBlockingQueue;
<del>
<del>import org.apache.hadoop.fs.Trash;
<del>import org.apache.log4j.Logger;
<ide>
<ide> import net.sourceforge.fractal.FractalManager;
<ide> import net.sourceforge.fractal.Learner;
<ide> import net.sourceforge.fractal.multicast.MulticastMessage;
<ide> import net.sourceforge.fractal.multicast.MulticastStream;
<ide> import net.sourceforge.fractal.wanamcast.WanAMCastStream;
<add>
<add>import org.apache.log4j.Logger;
<add>
<ide> import fr.inria.jessy.ConstantPool;
<ide> import fr.inria.jessy.DistributedJessy;
<ide> import fr.inria.jessy.consistency.ConsistencyFactory;
<ide> votingQuorums = new ConcurrentHashMap<TransactionHandler, VotingQuorum>();
<ide> coordinatorGroups = new ConcurrentHashMap<TransactionHandler, String>();
<ide>
<del> terminated = new ArrayList<TransactionHandler>();
<add> terminated = new CopyOnWriteArrayList<TransactionHandler>();
<ide>
<ide> thread = new Thread(this);
<ide> thread.start();
<ide> * processing it. Otherwise, waits until one message in processingMessages
<ide> * list finishes its execution.
<ide> *
<del> * FIXME
<ide> */
<ide> @Override
<ide> public void run() {
<ide>
<ide> while (true) {
<ide>
<del> // FIXME
<del> // msg = atomicDeliveredMessages.peek();
<del> // if (msg == null)
<del> // continue;
<del> //
<del> // /*
<del> // * if there is a conflict, it cannot proceed to handle the head
<del> // * message, thus waits until one of a messages in {@link
<del> // *
<del> // * @processingMessgaes} finishes and notify this queue.
<del> // */
<del> // for (TerminateTransactionRequestMessage committing :
<del> // processingMessages
<del> // .values()) {
<del> // if (ConsistencyFactory.getConsistency().hasConflict(
<del> // msg.getExecutionHistory(),
<del> // committing.getExecutionHistory())) {
<del> // try {
<del> // wait();
<del> // } catch (InterruptedException e) {
<del> // e.printStackTrace();
<del> // }
<del> // }
<del> // }
<del>
<del> /*
<del> * There is no conflict with already processing messages in {@code
<del> * processingMessages}, thus a new {@code CertifyAndVoteTask} is
<del> * created for handling this messages.
<add> /*
<add> * When a new certify and vote task is submitted, it is first check
<add> * whether is a concurrent conflicting transaction already
<add> * committing or not. If not, the message is put in {@code
<add> * processingMessages} map, otherwise, it should wait until one
<add> * transaction finishes its termination.
<ide> */
<ide> try {
<ide> msg = atomicDeliveredMessages.take();
<add> Iterator<TerminateTransactionRequestMessage> itr = processingMessages
<add> .values().iterator();
<add> while (itr.hasNext()) {
<add> if (ConsistencyFactory.getConsistency().hasConflict(
<add> msg.getExecutionHistory(),
<add> itr.next().getExecutionHistory())) {
<add> try {
<add> synchronized (processingMessages) {
<add> processingMessages.wait();
<add> }
<add> itr = processingMessages.values().iterator();
<add> continue;
<add> } catch (InterruptedException e) {
<add> e.printStackTrace();
<add> }
<add> }
<add> }
<add> processingMessages.put(msg.getExecutionHistory()
<add> .getTransactionHandler(), msg);
<add>
<add> /*
<add> * There is no conflict with already processing messages in
<add> * {@code processingMessages}, thus a new {@code
<add> * CertifyAndVoteTask} is created for handling this messages.
<add> */
<ide> pool.submit(new CertifyAndVoteTask(msg));
<del> } catch (InterruptedException e) {
<del> // TODO Auto-generated catch block
<del> e.printStackTrace();
<add> } catch (InterruptedException e1) {
<add> e1.printStackTrace();
<ide> }
<ide>
<ide> }
<ide> * to the coordinator.
<ide> *
<ide> * PIERRE null for executionHistory indicates that we are at the coordinator
<del> * and the coordinator is not in the replica set FIXME change this TODO
<del> * should it be synchronized?
<add> * and the coordinator is not in the replica set
<add> *
<add> * FIXME change this
<add> *
<add> * TODO should it be synchronized?
<ide> */
<del> private synchronized void handleTerminationResult(
<add> private void handleTerminationResult(
<ide> ExecutionHistory executionHistory,
<ide> TerminationResult terminationResult) {
<ide>
<ide>
<ide> /**
<ide> * Garbage collect all concurrent hash maps entries for the given
<del> * {@code transactionHandler} TODO is it necessary to be synchronized?
<add> * {@code transactionHandler}
<add> *
<add> * TODO is it necessary to be synchronized?
<ide> *
<ide> * @param transactionHandler
<ide> * The transactionHandler to be garbage collected.
<ide> */
<del> private synchronized void garbageCollect(
<del> TransactionHandler transactionHandler) {
<add> private void garbageCollect(TransactionHandler transactionHandler) {
<add> /*
<add> * Upon removing the transaction from {@code processingMessages}, it
<add> * notifies the main thread to process waiting messages again.
<add> */
<ide> processingMessages.remove(transactionHandler);
<ide> synchronized (processingMessages) {
<del> processingMessages.notifyAll();
<add> processingMessages.notify();
<ide> }
<ide>
<ide> terminated.add(transactionHandler);
<ide> if (terminationRequests.containsKey(transactionHandler.getId())) {
<ide> logger.debug("garbage-collect for " + transactionHandler.getId());
<ide> terminationRequests.remove(transactionHandler);
<del> // terminationResults.remove(transactionHandler);
<ide> votingQuorums.remove(transactionHandler);
<ide> coordinatorGroups.remove(transactionHandler);
<ide> }
<ide> }
<ide>
<ide> public Boolean call() throws Exception {
<del>
<del> /*
<del> * When a new certify and vote task is submitted, it is first check
<del> * whether is a concurrent conflicting transaction already
<del> * committing or not. If not, the message is put in {@code
<del> * processingMessages} map, otherwise, it should wait until one
<del> * transaction finishes its termination.
<del> */
<del> Iterator<TerminateTransactionRequestMessage> itr = processingMessages
<del> .values().iterator();
<del> while (itr.hasNext()) {
<del> if (ConsistencyFactory.getConsistency().hasConflict(
<del> msg.getExecutionHistory(),
<del> itr.next().getExecutionHistory())) {
<del> try {
<del> synchronized (processingMessages) {
<del> processingMessages.wait();
<del> }
<del> itr = processingMessages.values().iterator();
<del> continue;
<del> } catch (InterruptedException e) {
<del> e.printStackTrace();
<del> }
<del> }
<del> }
<del> processingMessages.put(msg.getExecutionHistory()
<del> .getTransactionHandler(), msg);
<ide>
<ide> try {
<ide> |
||
Java | apache-2.0 | 11f06c8189d9f694c15b51c2cf753ca2aad78fa3 | 0 | burris/dwr,burris/dwr | /*
* Copyright 2005 Joe Walker
*
* 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.getahead.dwrdemo.clock;
import java.util.Collection;
import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContext;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.proxy.dwr.Util;
import org.directwebremoting.util.SharedObjects;
/**
* A server-side clock that broadcasts the server time to any browsers that will
* listen.
* This is an example of how to control clients using server side threads
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class Clock
{
/**
* Create a schedule to update the clock every second.
*/
public Clock()
{
ScheduledThreadPoolExecutor executor = SharedObjects.getScheduledThreadPoolExecutor();
executor.scheduleAtFixedRate(new Runnable()
{
public void run()
{
if (active)
{
setClockDisplay(new Date().toString());
}
}
}, 120, 120, TimeUnit.SECONDS);
}
/**
* Called from the client to turn the clock on/off
*/
public synchronized void toggle()
{
active = !active;
if (active)
{
setClockDisplay("Started");
}
else
{
setClockDisplay("Stopped");
}
}
/**
* Actually alter the clients.
* In DWR 2.x you had to know the ServletContext in order to be able to get
* a ServerContext. With DWR 3.0 this restriction has been removed.
* This method is public so you can call this from the dwr auto-generated
* pages to demo altering one page from another
* @param output The string to display.
*/
public void setClockDisplay(String output)
{
ServerContext sctx = ServerContextFactory.get();
Collection<ScriptSession> sessions = sctx.getScriptSessionsByPage(sctx.getContextPath() + "/clock/index.html");
Util pages = new Util(sessions);
pages.setValue("clockDisplay", output);
}
/**
* Are we updating the clocks on all the pages?
*/
protected transient boolean active = false;
}
| demo/org/getahead/dwrdemo/clock/Clock.java | /*
* Copyright 2005 Joe Walker
*
* 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.getahead.dwrdemo.clock;
import java.util.Collection;
import java.util.Date;
import javax.servlet.ServletContext;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContext;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.dwr.Util;
/**
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class Clock implements Runnable
{
/**
*
*/
public Clock()
{
ServletContext servletContext = WebContextFactory.get().getServletContext();
sctx = ServerContextFactory.get(servletContext);
}
/**
*
*/
public synchronized void toggle()
{
active = !active;
if (active)
{
new Thread(this).start();
}
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run()
{
try
{
log.debug("CLOCK: Starting server-side thread");
while (active)
{
Collection<ScriptSession> sessions = sctx.getScriptSessionsByPage(sctx.getContextPath() + "/clock/index.html");
Util pages = new Util(sessions);
pages.setValue("clockDisplay", new Date().toString());
Thread.sleep(1000);
}
Collection<ScriptSession> sessions = sctx.getScriptSessionsByPage(sctx.getContextPath() + "/clock/index.html");
Util pages = new Util(sessions);
pages.setValue("clockDisplay", "");
log.debug("CLOCK: Stopping server-side thread");
}
catch (InterruptedException ex)
{
log.warn("Interrupted", ex);
}
}
/**
* Our key to get hold of ServerContexts
*/
private ServerContext sctx;
/**
* Are we updating the clocks on all the pages?
*/
private transient boolean active = false;
/**
* The log stream
*/
private static final Log log = LogFactory.getLog(Clock.class);
}
| Use a scheduler rather than a special thread for the clock
git-svn-id: ba1d8d5a2a2c535e023d6080c1e5c29aa0f5364e@1608 3a8262b2-faa5-11dc-8610-ff947880b6b2
| demo/org/getahead/dwrdemo/clock/Clock.java | Use a scheduler rather than a special thread for the clock | <ide><path>emo/org/getahead/dwrdemo/clock/Clock.java
<ide>
<ide> import java.util.Collection;
<ide> import java.util.Date;
<add>import java.util.concurrent.ScheduledThreadPoolExecutor;
<add>import java.util.concurrent.TimeUnit;
<ide>
<del>import javax.servlet.ServletContext;
<del>
<del>import org.apache.commons.logging.LogFactory;
<del>import org.apache.commons.logging.Log;
<ide> import org.directwebremoting.ScriptSession;
<ide> import org.directwebremoting.ServerContext;
<ide> import org.directwebremoting.ServerContextFactory;
<del>import org.directwebremoting.WebContextFactory;
<ide> import org.directwebremoting.proxy.dwr.Util;
<add>import org.directwebremoting.util.SharedObjects;
<ide>
<ide> /**
<add> * A server-side clock that broadcasts the server time to any browsers that will
<add> * listen.
<add> * This is an example of how to control clients using server side threads
<ide> * @author Joe Walker [joe at getahead dot ltd dot uk]
<ide> */
<del>public class Clock implements Runnable
<add>public class Clock
<ide> {
<ide> /**
<del> *
<add> * Create a schedule to update the clock every second.
<ide> */
<ide> public Clock()
<ide> {
<del> ServletContext servletContext = WebContextFactory.get().getServletContext();
<del> sctx = ServerContextFactory.get(servletContext);
<add> ScheduledThreadPoolExecutor executor = SharedObjects.getScheduledThreadPoolExecutor();
<add> executor.scheduleAtFixedRate(new Runnable()
<add> {
<add> public void run()
<add> {
<add> if (active)
<add> {
<add> setClockDisplay(new Date().toString());
<add> }
<add> }
<add> }, 120, 120, TimeUnit.SECONDS);
<ide> }
<ide>
<ide> /**
<del> *
<add> * Called from the client to turn the clock on/off
<ide> */
<ide> public synchronized void toggle()
<ide> {
<ide>
<ide> if (active)
<ide> {
<del> new Thread(this).start();
<add> setClockDisplay("Started");
<ide> }
<del> }
<del>
<del> /* (non-Javadoc)
<del> * @see java.lang.Runnable#run()
<del> */
<del> public void run()
<del> {
<del> try
<add> else
<ide> {
<del> log.debug("CLOCK: Starting server-side thread");
<del>
<del> while (active)
<del> {
<del> Collection<ScriptSession> sessions = sctx.getScriptSessionsByPage(sctx.getContextPath() + "/clock/index.html");
<del> Util pages = new Util(sessions);
<del> pages.setValue("clockDisplay", new Date().toString());
<del>
<del> Thread.sleep(1000);
<del> }
<del>
<del> Collection<ScriptSession> sessions = sctx.getScriptSessionsByPage(sctx.getContextPath() + "/clock/index.html");
<del> Util pages = new Util(sessions);
<del> pages.setValue("clockDisplay", "");
<del>
<del> log.debug("CLOCK: Stopping server-side thread");
<del> }
<del> catch (InterruptedException ex)
<del> {
<del> log.warn("Interrupted", ex);
<add> setClockDisplay("Stopped");
<ide> }
<ide> }
<ide>
<ide> /**
<del> * Our key to get hold of ServerContexts
<add> * Actually alter the clients.
<add> * In DWR 2.x you had to know the ServletContext in order to be able to get
<add> * a ServerContext. With DWR 3.0 this restriction has been removed.
<add> * This method is public so you can call this from the dwr auto-generated
<add> * pages to demo altering one page from another
<add> * @param output The string to display.
<ide> */
<del> private ServerContext sctx;
<add> public void setClockDisplay(String output)
<add> {
<add> ServerContext sctx = ServerContextFactory.get();
<add> Collection<ScriptSession> sessions = sctx.getScriptSessionsByPage(sctx.getContextPath() + "/clock/index.html");
<add> Util pages = new Util(sessions);
<add> pages.setValue("clockDisplay", output);
<add> }
<ide>
<ide> /**
<ide> * Are we updating the clocks on all the pages?
<ide> */
<del> private transient boolean active = false;
<del>
<del> /**
<del> * The log stream
<del> */
<del> private static final Log log = LogFactory.getLog(Clock.class);
<add> protected transient boolean active = false;
<ide> } |
|
Java | apache-2.0 | 6a5a46783fcc40c6dd8a9957a89d29b7f41ced72 | 0 | Hipparchus-Math/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,sdinot/hipparchus,sdinot/hipparchus,apache/commons-math,sdinot/hipparchus,apache/commons-math,sdinot/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,Hipparchus-Math/hipparchus | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.fraction;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.apache.commons.math.MathRuntimeException;
/**
* Representation of a rational number without any overflow. This class is
* immutable.
*
* @version $Revision$ $Date$
* @since 2.0
*/
public class BigFraction extends Number implements Comparable<BigFraction> {
/** A fraction representing "1". */
public static final BigFraction ONE = new BigFraction(1, 1);
/** A fraction representing "0". */
public static final BigFraction ZERO = new BigFraction(0, 1);
/** A fraction representing "4/5". */
public static final BigFraction FOUR_FIFTHS = new BigFraction(4, 5);
/** A fraction representing "1/5". */
public static final BigFraction ONE_FIFTH = new BigFraction(1, 5);
/** A fraction representing "1/2". */
public static final BigFraction ONE_HALF = new BigFraction(1, 2);
/** A fraction representing "1/4". */
public static final BigFraction ONE_QUARTER = new BigFraction(1, 4);
/** A fraction representing "1/3". */
public static final BigFraction ONE_THIRD = new BigFraction(1, 3);
/** A fraction representing "3/5". */
public static final BigFraction THREE_FIFTHS = new BigFraction(3, 5);
/** A fraction representing "3/4". */
public static final BigFraction THREE_QUARTERS = new BigFraction(3, 4);
/** A fraction representing "4/5". */
public static final BigFraction TWO_FIFTHS = new BigFraction(4, 5);
/** A fraction representing "2/4". */
public static final BigFraction TWO_QUARTERS = new BigFraction(2, 4);
/** A fraction representing "2/3". */
public static final BigFraction TWO_THIRDS = new BigFraction(2, 3);
/** A fraction representing "-1 / 1". */
public static final BigFraction MINUS_ONE = new BigFraction(-1, 1);
/** Serializable version identifier. */
private static final long serialVersionUID = -5984892138972589598L;
/** <code>BigInteger</code> representation of 100. */
private static final BigInteger ONE_HUNDRED_DOUBLE = BigInteger.valueOf(100);
/** The numerator. */
private final BigInteger numerator;
/** The denominator. */
private final BigInteger denominator;
/**
* <p>
* Creates a <code>BigFraction</code> instance with the 2 parts of a fraction
* Y/Z.
* </p>
*
* <p>
* Any negative signs are resolved to be on the numerator.
* </p>
*
* @param numerator
* the numerator, for example the three in 'three sevenths'.
* @param denominator
* the denominator, for example the seven in 'three sevenths'.
* @return a new fraction instance, with the numerator and denominator
* reduced.
* @throws ArithmeticException
* if the denominator is <code>zero</code>.
*/
public static BigFraction getReducedFraction(final int numerator,
final int denominator) {
if (numerator == 0) {
return ZERO; // normalize zero.
}
return new BigFraction(numerator, denominator);
}
/**
* <p>
* Create a {@link BigFraction} equivalent to the passed <tt>BigInteger</tt>, ie
* "num / 1".
* </p>
*
* @param num
* the numerator.
*/
public BigFraction(final BigInteger num) {
this(num, BigInteger.ONE);
}
/**
* <p>
* Create a {@link BigFraction} given the numerator and denominator as
* <code>BigInteger</code>. The {@link BigFraction} is reduced to lowest terms.
* </p>
*
* @param num
* the numerator, must not be <code>null</code>.
* @param den
* the denominator, must not be <code>null</code>.
* @throws ArithmeticException
* if the denominator is <code>zero</code>.
* @throws NullPointerException
* if the numerator or the denominator is <code>zero</code>.
*/
public BigFraction(BigInteger num, BigInteger den) {
if (num == null) {
throw MathRuntimeException.createNullPointerException("numerator is null");
}
if (den == null) {
throw MathRuntimeException.createNullPointerException("denominator is null");
}
if (BigInteger.ZERO.equals(den)) {
throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
}
if (BigInteger.ZERO.equals(num)) {
numerator = BigInteger.ZERO;
denominator = BigInteger.ONE;
} else {
// reduce numerator and denominator by greatest common denominator
final BigInteger gcd = num.gcd(den);
if (BigInteger.ONE.compareTo(gcd) < 0) {
num = num.divide(gcd);
den = den.divide(gcd);
}
// move sign to numerator
if (BigInteger.ZERO.compareTo(den) > 0) {
num = num.negate();
den = den.negate();
}
// store the values in the final fields
numerator = num;
denominator = den;
}
}
/**
* Create a fraction given the double value.
* <p>
* This constructor behaves <em>differently</em> from
* {@link #BigFraction(double, double, int)}. It converts the
* double value exactly, considering its internal bits representation.
* This does work for all values except NaN and infinities and does
* not requires any loop or convergence threshold.
* </p>
* <p>
* Since this conversion is exact and since double numbers are sometimes
* approximated, the fraction created may seem strange in some cases. For example
* calling <code>new BigFraction(1.0 / 3.0)</code> does <em>not</em> create
* the fraction 1/3 but the fraction 6004799503160661 / 18014398509481984
* because the double number passed to the constructor is not exactly 1/3
* (this number cannot be stored exactly in IEEE754).
* </p>
* @see #BigFraction(double, double, int)
* @param value the double value to convert to a fraction.
* @exception IllegalArgumentException if value is NaN or infinite
*/
public BigFraction(final double value) throws IllegalArgumentException {
if (Double.isNaN(value)) {
throw MathRuntimeException.createIllegalArgumentException("cannot convert NaN value");
}
if (Double.isInfinite(value)) {
throw MathRuntimeException.createIllegalArgumentException("cannot convert infinite value");
}
// compute m and k such that value = m * 2^k
final long bits = Double.doubleToLongBits(value);
final long sign = bits & 0x8000000000000000L;
final long exponent = bits & 0x7ff0000000000000L;
long m = bits & 0x000fffffffffffffL;
if (exponent != 0) {
// this was a normalized number, add the implicit most significant bit
m |= 0x0010000000000000L;
}
if (sign != 0) {
m = -m;
}
int k = ((int) (exponent >> 52)) - 1075;
while (((m & 0x001ffffffffffffeL) != 0) && ((m & 0x1) == 0)) {
m = m >> 1;
++k;
}
if (k < 0) {
numerator = BigInteger.valueOf(m);
denominator = BigInteger.ZERO.flipBit(-k);
} else {
numerator = BigInteger.valueOf(m).multiply(BigInteger.ZERO.flipBit(k));
denominator = BigInteger.ONE;
}
}
/**
* Create a fraction given the double value and maximum error allowed.
* <p>
* References:
* <ul>
* <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html">
* Continued Fraction</a> equations (11) and (22)-(26)</li>
* </ul>
* </p>
*
* @param value
* the double value to convert to a fraction.
* @param epsilon
* maximum error allowed. The resulting fraction is within
* <code>epsilon</code> of <code>value</code>, in absolute terms.
* @param maxIterations
* maximum number of convergents.
* @throws FractionConversionException
* if the continued fraction failed to converge.
* @see #BigFraction(double)
*/
public BigFraction(final double value, final double epsilon,
final int maxIterations)
throws FractionConversionException {
this(value, epsilon, Integer.MAX_VALUE, maxIterations);
}
/**
* Create a fraction given the double value and either the maximum error
* allowed or the maximum number of denominator digits.
* <p>
*
* NOTE: This constructor is called with EITHER - a valid epsilon value and
* the maxDenominator set to Integer.MAX_VALUE (that way the maxDenominator
* has no effect). OR - a valid maxDenominator value and the epsilon value
* set to zero (that way epsilon only has effect if there is an exact match
* before the maxDenominator value is reached).
* </p>
* <p>
*
* It has been done this way so that the same code can be (re)used for both
* scenarios. However this could be confusing to users if it were part of
* the public API and this constructor should therefore remain PRIVATE.
* </p>
*
* See JIRA issue ticket MATH-181 for more details:
*
* https://issues.apache.org/jira/browse/MATH-181
*
* @param value
* the double value to convert to a fraction.
* @param epsilon
* maximum error allowed. The resulting fraction is within
* <code>epsilon</code> of <code>value</code>, in absolute terms.
* @param maxDenominator
* maximum denominator value allowed.
* @param maxIterations
* maximum number of convergents.
* @throws FractionConversionException
* if the continued fraction failed to converge.
*/
private BigFraction(final double value, final double epsilon,
final int maxDenominator, int maxIterations)
throws FractionConversionException {
long overflow = Integer.MAX_VALUE;
double r0 = value;
long a0 = (long) Math.floor(r0);
if (a0 > overflow) {
throw new FractionConversionException(value, a0, 1l);
}
// check for (almost) integer arguments, which should not go
// to iterations.
if (Math.abs(a0 - value) < epsilon) {
numerator = BigInteger.valueOf(a0);
denominator = BigInteger.ONE;
return;
}
long p0 = 1;
long q0 = 0;
long p1 = a0;
long q1 = 1;
long p2 = 0;
long q2 = 1;
int n = 0;
boolean stop = false;
do {
++n;
final double r1 = 1.0 / (r0 - a0);
final long a1 = (long) Math.floor(r1);
p2 = (a1 * p1) + p0;
q2 = (a1 * q1) + q0;
if ((p2 > overflow) || (q2 > overflow)) {
throw new FractionConversionException(value, p2, q2);
}
final double convergent = (double) p2 / (double) q2;
if ((n < maxIterations) &&
(Math.abs(convergent - value) > epsilon) &&
(q2 < maxDenominator)) {
p0 = p1;
p1 = p2;
q0 = q1;
q1 = q2;
a0 = a1;
r0 = r1;
} else {
stop = true;
}
} while (!stop);
if (n >= maxIterations) {
throw new FractionConversionException(value, maxIterations);
}
if (q2 < maxDenominator) {
numerator = BigInteger.valueOf(p2);
denominator = BigInteger.valueOf(q2);
} else {
numerator = BigInteger.valueOf(p1);
denominator = BigInteger.valueOf(q1);
}
}
/**
* Create a fraction given the double value and maximum denominator.
* <p>
* References:
* <ul>
* <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html">
* Continued Fraction</a> equations (11) and (22)-(26)</li>
* </ul>
* </p>
*
* @param value
* the double value to convert to a fraction.
* @param maxDenominator
* The maximum allowed value for denominator.
* @throws FractionConversionException
* if the continued fraction failed to converge.
*/
public BigFraction(final double value, final int maxDenominator)
throws FractionConversionException {
this(value, 0, maxDenominator, 100);
}
/**
* <p>
* Create a {@link BigFraction} equivalent to the passed <tt>int</tt>, ie
* "num / 1".
* </p>
*
* @param num
* the numerator.
*/
public BigFraction(final int num) {
this(BigInteger.valueOf(num), BigInteger.ONE);
}
/**
* <p>
* Create a {@link BigFraction} given the numerator and denominator as simple
* <tt>int</tt>. The {@link BigFraction} is reduced to lowest terms.
* </p>
*
* @param num
* the numerator.
* @param den
* the denominator.
*/
public BigFraction(final int num, final int den) {
this(BigInteger.valueOf(num), BigInteger.valueOf(den));
}
/**
* <p>
* Create a {@link BigFraction} equivalent to the passed long, ie "num / 1".
* </p>
*
* @param num
* the numerator.
*/
public BigFraction(final long num) {
this(BigInteger.valueOf(num), BigInteger.ONE);
}
/**
* <p>
* Create a {@link BigFraction} given the numerator and denominator as simple
* <tt>long</tt>. The {@link BigFraction} is reduced to lowest terms.
* </p>
*
* @param num
* the numerator.
* @param den
* the denominator.
*/
public BigFraction(final long num, final long den) {
this(BigInteger.valueOf(num), BigInteger.valueOf(den));
}
/**
* <p>
* Returns the absolute value of this {@link BigFraction}.
* </p>
*
* @return the absolute value as a {@link BigFraction}.
*/
public BigFraction abs() {
return (BigInteger.ZERO.compareTo(numerator) <= 0) ? this : negate();
}
/**
* <p>
* Adds the value of this fraction to the passed {@link BigInteger},
* returning the result in reduced form.
* </p>
*
* @param bg
* the {@link BigInteger} to add, must'nt be <code>null</code>.
* @return a <code>BigFraction</code> instance with the resulting values.
* @throws NullPointerException
* if the {@link BigInteger} is <code>null</code>.
*/
public BigFraction add(final BigInteger bg) {
return add(new BigFraction(bg, BigInteger.ONE));
}
/**
* <p>
* Adds the value of this fraction to another, returning the result in
* reduced form.
* </p>
*
* @param fraction
* the {@link BigFraction} to add, must not be <code>null</code>.
* @return a {@link BigFraction} instance with the resulting values.
* @throws NullPointerException
* if the {@link BigFraction} is <code>null</code>.
*/
public BigFraction add(final BigFraction fraction) {
if (ZERO.equals(fraction)) {
return this;
}
BigInteger num = null;
BigInteger den = null;
if (denominator.equals(fraction.denominator)) {
num = numerator.add(fraction.numerator);
den = denominator;
} else {
num = (numerator.multiply(fraction.denominator)).add((fraction.numerator).multiply(denominator));
den = denominator.multiply(fraction.denominator);
}
return new BigFraction(num, den);
}
/**
* <p>
* Adds the value of this fraction to the passed <tt>integer</tt>, returning
* the result in reduced form.
* </p>
*
* @param i
* the <tt>integer</tt> to add.
* @return a <code>BigFraction</code> instance with the resulting values.
*/
public BigFraction add(final int i) {
return add(new BigFraction(i, 1));
}
/**
* <p>
* Adds the value of this fraction to the passed <tt>long</tt>, returning
* the result in reduced form.
* </p>
*
* @param l
* the <tt>long</tt> to add.
* @return a <code>BigFraction</code> instance with the resulting values.
*/
public BigFraction add(final long l) {
return add(new BigFraction(l, 1L));
}
/**
* <p>
* Gets the fraction as a <code>BigDecimal</code>. This calculates the
* fraction as the numerator divided by denominator.
* </p>
*
* @return the fraction as a <code>BigDecimal</code>.
* @throws ArithmeticException
* if the exact quotient does not have a terminating decimal
* expansion.
* @see BigDecimal
*/
public BigDecimal bigDecimalValue() {
return new BigDecimal(numerator).divide(new BigDecimal(denominator));
}
/**
* <p>
* Gets the fraction as a <code>BigDecimal</code> following the passed
* rounding mode. This calculates the fraction as the numerator divided by
* denominator.
* </p>
*
* @param roundingMode
* rounding mode to apply. see {@link BigDecimal} constants.
* @return the fraction as a <code>BigDecimal</code>.
* @throws IllegalArgumentException
* if <tt>roundingMode</tt> does not represent a valid rounding
* mode.
* @see BigDecimal
*/
public BigDecimal bigDecimalValue(final int roundingMode) {
return new BigDecimal(numerator).divide(new BigDecimal(denominator), roundingMode);
}
/**
* <p>
* Gets the fraction as a <code>BigDecimal</code> following the passed scale
* and rounding mode. This calculates the fraction as the numerator divided
* by denominator.
* </p>
*
* @param scale
* scale of the <code>BigDecimal</code> quotient to be returned.
* see {@link BigDecimal} for more information.
* @param roundingMode
* rounding mode to apply. see {@link BigDecimal} constants.
* @return the fraction as a <code>BigDecimal</code>.
* @see BigDecimal
*/
public BigDecimal bigDecimalValue(final int scale, final int roundingMode) {
return new BigDecimal(numerator).divide(new BigDecimal(denominator), scale, roundingMode);
}
/**
* <p>
* Compares this object to another based on size.
* </p>
*
* @param object
* the object to compare to, must not be <code>null</code>.
* @return -1 if this is less than <tt>object</tt>, +1 if this is greater
* than <tt>object</tt>, 0 if they are equal.
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(final BigFraction object) {
BigInteger nOd = numerator.multiply(object.denominator);
BigInteger dOn = denominator.multiply(object.numerator);
return nOd.compareTo(dOn);
}
/**
* <p>
* Divide the value of this fraction by the passed <code>BigInteger</code>,
* ie "this * 1 / bg", returning the result in reduced form.
* </p>
*
* @param bg
* the <code>BigInteger</code> to divide by, must not be
* <code>null</code>.
* @return a {@link BigFraction} instance with the resulting values.
* @throws NullPointerException
* if the <code>BigInteger</code> is <code>null</code>.
*/
public BigFraction divide(final BigInteger bg) {
return divide(new BigFraction(bg, BigInteger.ONE));
}
/**
* <p>
* Divide the value of this fraction by another, returning the result in
* reduced form.
* </p>
*
* @param fraction
* the fraction to divide by, must not be <code>null</code>.
* @return a {@link BigFraction} instance with the resulting values.
* @throws NullPointerException
* if the fraction is <code>null</code>.
* @throws ArithmeticException
* if the fraction to divide by is zero.
*/
public BigFraction divide(final BigFraction fraction) {
if (BigInteger.ZERO.equals(fraction.numerator)) {
throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
}
return multiply(fraction.reciprocal());
}
/**
* <p>
* Divide the value of this fraction by the passed <tt>int</tt>, ie
* "this * 1 / i", returning the result in reduced form.
* </p>
*
* @param i
* the <tt>int</tt> to divide by.
* @return a {@link BigFraction} instance with the resulting values.
*/
public BigFraction divide(final int i) {
return divide(new BigFraction(i, 1));
}
/**
* <p>
* Divide the value of this fraction by the passed <tt>long</tt>, ie
* "this * 1 / l", returning the result in reduced form.
* </p>
*
* @param l
* the <tt>long</tt> to divide by.
* @return a {@link BigFraction} instance with the resulting values.
*/
public BigFraction divide(final long l) {
return divide(new BigFraction(l, 1L));
}
/**
* <p>
* Gets the fraction as a <tt>double</tt>. This calculates the fraction as
* the numerator divided by denominator.
* </p>
*
* @return the fraction as a <tt>double</tt>
* @see java.lang.Number#doubleValue()
*/
@Override
public double doubleValue() {
return numerator.doubleValue() / denominator.doubleValue();
}
/**
* <p>
* Test for the equality of two fractions. If the lowest term numerator and
* denominators are the same for both fractions, the two fractions are
* considered to be equal.
* </p>
*
* @param other
* fraction to test for equality to this fraction, can be
* <code>null</code>.
* @return true if two fractions are equal, false if object is
* <code>null</code>, not an instance of {@link BigFraction}, or not
* equal to this fraction instance.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object other) {
boolean ret = false;
if (this == other) {
ret = true;
} else if (other instanceof BigFraction) {
BigFraction rhs = ((BigFraction) other).reduce();
BigFraction thisOne = this.reduce();
ret = thisOne.numerator.equals(rhs.numerator) && thisOne.denominator.equals(rhs.denominator);
}
return ret;
}
/**
* <p>
* Gets the fraction as a <tt>float</tt>. This calculates the fraction as
* the numerator divided by denominator.
* </p>
*
* @return the fraction as a <tt>float</tt>.
* @see java.lang.Number#floatValue()
*/
@Override
public float floatValue() {
return numerator.floatValue() / denominator.floatValue();
}
/**
* <p>
* Access the denominator as a <code>BigInteger</code>.
* </p>
*
* @return the denominator as a <code>BigInteger</code>.
*/
public BigInteger getDenominator() {
return denominator;
}
/**
* <p>
* Access the denominator as a <tt>int</tt>.
* </p>
*
* @return the denominator as a <tt>int</tt>.
*/
public int getDenominatorAsInt() {
return denominator.intValue();
}
/**
* <p>
* Access the denominator as a <tt>long</tt>.
* </p>
*
* @return the denominator as a <tt>long</tt>.
*/
public long getDenominatorAsLong() {
return denominator.longValue();
}
/**
* <p>
* Access the numerator as a <code>BigInteger</code>.
* </p>
*
* @return the numerator as a <code>BigInteger</code>.
*/
public BigInteger getNumerator() {
return numerator;
}
/**
* <p>
* Access the numerator as a <tt>int</tt>.
* </p>
*
* @return the numerator as a <tt>int</tt>.
*/
public int getNumeratorAsInt() {
return numerator.intValue();
}
/**
* <p>
* Access the numerator as a <tt>long</tt>.
* </p>
*
* @return the numerator as a <tt>long</tt>.
*/
public long getNumeratorAsLong() {
return numerator.longValue();
}
/**
* <p>
* Gets a hashCode for the fraction.
* </p>
*
* @return a hash code value for this object.
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 37 * (37 * 17 + numerator.hashCode()) + denominator.hashCode();
}
/**
* <p>
* Gets the fraction as an <tt>int</tt>. This returns the whole number part
* of the fraction.
* </p>
*
* @return the whole number fraction part.
* @see java.lang.Number#intValue()
*/
@Override
public int intValue() {
return numerator.divide(denominator).intValue();
}
/**
* <p>
* Gets the fraction as a <tt>long</tt>. This returns the whole number part
* of the fraction.
* </p>
*
* @return the whole number fraction part.
* @see java.lang.Number#longValue()
*/
@Override
public long longValue() {
return numerator.divide(denominator).longValue();
}
/**
* <p>
* Multiplies the value of this fraction by the passed
* <code>BigInteger</code>, returning the result in reduced form.
* </p>
*
* @param bg
* the <code>BigInteger</code> to multiply by.
* @return a <code>BigFraction</code> instance with the resulting values.
* @throws NullPointerException
* if the bg is <code>null</code>.
*/
public BigFraction multiply(final BigInteger bg) {
return new BigFraction(bg.multiply(numerator), denominator);
}
/**
* <p>
* Multiplies the value of this fraction by another, returning the result in
* reduced form.
* </p>
*
* @param fraction
* the fraction to multiply by, must not be <code>null</code>.
* @return a {@link BigFraction} instance with the resulting values.
* @throws NullPointerException
* if the fraction is <code>null</code>.
*/
public BigFraction multiply(final BigFraction fraction) {
BigFraction ret = ZERO;
if (getNumeratorAsInt() != 0 && fraction.getNumeratorAsInt() != 0) {
ret = new BigFraction(numerator.multiply(fraction.numerator), denominator.multiply(fraction.denominator));
}
return ret;
}
/**
* <p>
* Multiply the value of this fraction by the passed <tt>int</tt>, returning
* the result in reduced form.
* </p>
*
* @param i
* the <tt>int</tt> to multiply by.
* @return a {@link BigFraction} instance with the resulting values.
*/
public BigFraction multiply(final int i) {
return multiply(new BigFraction(i, 1));
}
/**
* <p>
* Multiply the value of this fraction by the passed <tt>long</tt>,
* returning the result in reduced form.
* </p>
*
* @param l
* the <tt>long</tt> to multiply by.
* @return a {@link BigFraction} instance with the resulting values.
*/
public BigFraction multiply(final long l) {
return multiply(new BigFraction(l, 1L));
}
/**
* <p>
* Return the additive inverse of this fraction, returning the result in
* reduced form.
* </p>
*
* @return the negation of this fraction.
*/
public BigFraction negate() {
return new BigFraction(numerator.negate(), denominator);
}
/**
* <p>
* Gets the fraction percentage as a <tt>double</tt>. This calculates the
* fraction as the numerator divided by denominator multiplied by 100.
* </p>
*
* @return the fraction percentage as a <tt>double</tt>.
*/
public double percentageValue() {
return (numerator.divide(denominator)).multiply(ONE_HUNDRED_DOUBLE).doubleValue();
}
/**
* <p>
* Returns a <code>BigFraction</code> whose value is
* <tt>(this<sup>exponent</sup>)</tt>, returning the result in reduced form.
* </p>
*
* @param exponent
* exponent to which this <code>BigFraction</code> is to be raised.
* @return <tt>this<sup>exponent</sup></tt> as a <code>BigFraction</code>.
*/
public BigFraction pow(final BigInteger exponent) {
BigFraction ret = this;
if (!BigInteger.ONE.equals(exponent)) {
ret = ONE;
if (!BigInteger.ZERO.equals(exponent)) {
for (BigInteger bg = BigInteger.ONE; bg.compareTo(exponent) < 0; bg = bg.add(BigInteger.ONE)) {
ret = ret.multiply(this);
}
}
}
return ret;
}
/**
* <p>
* Returns a <code>BigFraction</code> whose value is
* <tt>(this<sup>exponent</sup>)</tt>, returning the result in reduced form.
* </p>
*
* @param exponent
* exponent to which this <code>BigFraction</code> is to be raised.
* @return <tt>this<sup>exponent</sup></tt>.
*/
public double pow(final BigFraction exponent) {
return Math.pow(numerator.doubleValue(), exponent.doubleValue()) / Math.pow(denominator.doubleValue(), exponent.doubleValue());
}
/**
* <p>
* Returns a <tt>integer</tt> whose value is
* <tt>(this<sup>exponent</sup>)</tt>, returning the result in reduced form.
* </p>
*
* @param exponent
* exponent to which this <code>BigInteger</code> is to be
* raised.
* @return <tt>this<sup>exponent</sup></tt>.
*/
public BigFraction pow(final int exponent) {
return pow(BigInteger.valueOf(exponent));
}
/**
* <p>
* Returns a <code>BigFraction</code> whose value is
* <tt>(this<sup>exponent</sup>)</tt>, returning the result in reduced form.
* </p>
*
* @param exponent
* exponent to which this <code>BigFraction</code> is to be raised.
* @return <tt>this<sup>exponent</sup></tt> as a <code>BigFraction</code>.
*/
public BigFraction pow(final long exponent) {
return pow(BigInteger.valueOf(exponent));
}
/**
* <p>
* Return the multiplicative inverse of this fraction.
* </p>
*
* @return the reciprocal fraction.
*/
public BigFraction reciprocal() {
return new BigFraction(denominator, numerator);
}
/**
* <p>
* Reduce this <code>BigFraction</code> to its lowest terms.
* </p>
*
* @return the reduced <code>BigFraction</code>. It doesn't change anything if
* the fraction can be reduced.
*/
public BigFraction reduce() {
final BigInteger gcd = numerator.gcd(denominator);
return new BigFraction(numerator.divide(gcd), denominator.divide(gcd));
}
/**
* <p>
* Subtracts the value of an {@link BigInteger} from the value of this one,
* returning the result in reduced form.
* </p>
*
* @param bg
* the {@link BigInteger} to subtract, must'nt be
* <code>null</code>.
* @return a <code>BigFraction</code> instance with the resulting values.
* @throws NullPointerException
* if the {@link BigInteger} is <code>null</code>.
*/
public BigFraction subtract(final BigInteger bg) {
return subtract(new BigFraction(bg, BigInteger.valueOf(1)));
}
/**
* <p>
* Subtracts the value of another fraction from the value of this one,
* returning the result in reduced form.
* </p>
*
* @param fraction
* the {@link BigFraction} to subtract, must not be
* <code>null</code>.
* @return a {@link BigFraction} instance with the resulting values
* @throws NullPointerException
* if the fraction is <code>null</code>.
*/
public BigFraction subtract(final BigFraction fraction) {
if (ZERO.equals(fraction)) {
return this;
}
BigInteger num = null;
BigInteger den = null;
if (denominator.equals(fraction.denominator)) {
num = numerator.subtract(fraction.numerator);
den = denominator;
} else {
num = (numerator.multiply(fraction.denominator)).subtract((fraction.numerator).multiply(denominator));
den = denominator.multiply(fraction.denominator);
}
return new BigFraction(num, den);
}
/**
* <p>
* Subtracts the value of an <tt>integer</tt> from the value of this one,
* returning the result in reduced form.
* </p>
*
* @param i
* the <tt>integer</tt> to subtract.
* @return a <code>BigFraction</code> instance with the resulting values.
*/
public BigFraction subtract(final int i) {
return subtract(new BigFraction(i, 1));
}
/**
* <p>
* Subtracts the value of an <tt>integer</tt> from the value of this one,
* returning the result in reduced form.
* </p>
*
* @param l
* the <tt>long</tt> to subtract.
* @return a <code>BigFraction</code> instance with the resulting values, or
* this object if the <tt>long</tt> is zero.
*/
public BigFraction subtract(final long l) {
return subtract(new BigFraction(l, 1L));
}
/**
* <p>
* Returns the <code>String</code> representing this fraction, ie
* "num / dem" or just "num" if the denominator is one.
* </p>
*
* @return a string representation of the fraction.
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String str = null;
if (BigInteger.ONE.equals(denominator)) {
str = numerator.toString();
} else if (BigInteger.ZERO.equals(numerator)) {
str = "0";
} else {
str = numerator + " / " + denominator;
}
return str;
}
}
| src/java/org/apache/commons/math/fraction/BigFraction.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.commons.math.fraction;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.apache.commons.math.MathRuntimeException;
/**
* Representation of a rational number without any overflow. This class is
* immutable.
*
* @version $Revision$ $Date$
* @since 2.0
*/
public class BigFraction extends Number implements Comparable<BigFraction> {
/** A fraction representing "1". */
public static final BigFraction ONE = new BigFraction(1, 1);
/** A fraction representing "0". */
public static final BigFraction ZERO = new BigFraction(0, 1);
/** A fraction representing "4/5". */
public static final BigFraction FOUR_FIFTHS = new BigFraction(4, 5);
/** A fraction representing "1/5". */
public static final BigFraction ONE_FIFTH = new BigFraction(1, 5);
/** A fraction representing "1/2". */
public static final BigFraction ONE_HALF = new BigFraction(1, 2);
/** A fraction representing "1/4". */
public static final BigFraction ONE_QUARTER = new BigFraction(1, 4);
/** A fraction representing "1/3". */
public static final BigFraction ONE_THIRD = new BigFraction(1, 3);
/** A fraction representing "3/5". */
public static final BigFraction THREE_FIFTHS = new BigFraction(3, 5);
/** A fraction representing "3/4". */
public static final BigFraction THREE_QUARTERS = new BigFraction(3, 4);
/** A fraction representing "4/5". */
public static final BigFraction TWO_FIFTHS = new BigFraction(4, 5);
/** A fraction representing "2/4". */
public static final BigFraction TWO_QUARTERS = new BigFraction(2, 4);
/** A fraction representing "2/3". */
public static final BigFraction TWO_THIRDS = new BigFraction(2, 3);
/** A fraction representing "-1 / 1". */
public static final BigFraction MINUS_ONE = new BigFraction(-1, 1);
/** Serializable version identifier. */
private static final long serialVersionUID = -5984892138972589598L;
/** <code>BigInteger</code> representation of 100. */
private static final BigInteger ONE_HUNDRED_DOUBLE = BigInteger.valueOf(100);
/** The numerator. */
private final BigInteger numerator;
/** The denominator. */
private final BigInteger denominator;
/**
* <p>
* Creates a <code>BigFraction</code> instance with the 2 parts of a fraction
* Y/Z.
* </p>
*
* <p>
* Any negative signs are resolved to be on the numerator.
* </p>
*
* @param numerator
* the numerator, for example the three in 'three sevenths'.
* @param denominator
* the denominator, for example the seven in 'three sevenths'.
* @return a new fraction instance, with the numerator and denominator
* reduced.
* @throws ArithmeticException
* if the denominator is <code>zero</code>.
*/
public static BigFraction getReducedFraction(final int numerator,
final int denominator) {
if (numerator == 0) {
return ZERO; // normalize zero.
}
return new BigFraction(numerator, denominator).reduce();
}
/**
* <p>
* Create a {@link BigFraction} equivalent to the passed <tt>BigInteger</tt>, ie
* "num / 1".
* </p>
*
* @param num
* the numerator.
*/
public BigFraction(final BigInteger num) {
this(num, BigInteger.ONE);
}
/**
* <p>
* Create a {@link BigFraction} given the numerator and denominator as
* <code>BigInteger</code>. The {@link BigFraction} is reduced to lowest terms.
* </p>
*
* @param num
* the numerator, must not be <code>null</code>.
* @param den
* the denominator, must not be <code>null</code>.
* @throws ArithmeticException
* if the denominator is <code>zero</code>.
* @throws NullPointerException
* if the numerator or the denominator is <code>zero</code>.
*/
public BigFraction(BigInteger num, BigInteger den) {
if (num == null) {
throw MathRuntimeException.createNullPointerException("numerator is null");
}
if (den == null) {
throw MathRuntimeException.createNullPointerException("denominator is null");
}
if (BigInteger.ZERO.equals(den)) {
throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
}
if (BigInteger.ZERO.equals(num)) {
numerator = BigInteger.ZERO;
denominator = BigInteger.ONE;
} else {
// reduce numerator and denominator by greatest common denominator
final BigInteger gcd = num.gcd(den);
if (BigInteger.ONE.compareTo(gcd) < 0) {
num = num.divide(gcd);
den = den.divide(gcd);
}
// move sign to numerator
if (BigInteger.ZERO.compareTo(den) > 0) {
num = num.negate();
den = den.negate();
}
// store the values in the final fields
numerator = num;
denominator = den;
}
}
/**
* Create a fraction given the double value.
* <p>
* This constructor behaves <em>differently</em> from
* {@link #BigFraction(double, double, int)}. It converts the
* double value exactly, considering its internal bits representation.
* This does work for all values except NaN and infinities and does
* not requires any loop or convergence threshold.
* </p>
* <p>
* Since this conversion is exact and since double numbers are sometimes
* approximated, the fraction created may seem strange in some cases. For example
* calling <code>new BigFraction(1.0 / 3.0)</code> does <em>not</em> create
* the fraction 1/3 but the fraction 6004799503160661 / 18014398509481984
* because the double number passed to the constructor is not exactly 1/3
* (this number cannot be stored exactly in IEEE754).
* </p>
* @see #BigFraction(double, double, int)
* @param value the double value to convert to a fraction.
* @exception IllegalArgumentException if value is NaN or infinite
*/
public BigFraction(final double value) throws IllegalArgumentException {
if (Double.isNaN(value)) {
throw MathRuntimeException.createIllegalArgumentException("cannot convert NaN value");
}
if (Double.isInfinite(value)) {
throw MathRuntimeException.createIllegalArgumentException("cannot convert infinite value");
}
// compute m and k such that value = m * 2^k
final long bits = Double.doubleToLongBits(value);
final long sign = bits & 0x8000000000000000L;
final long exponent = bits & 0x7ff0000000000000L;
long m = bits & 0x000fffffffffffffL;
if (exponent != 0) {
// this was a normalized number, add the implicit most significant bit
m |= 0x0010000000000000L;
}
if (sign != 0) {
m = -m;
}
int k = ((int) (exponent >> 52)) - 1075;
while (((m & 0x001ffffffffffffeL) != 0) && ((m & 0x1) == 0)) {
m = m >> 1;
++k;
}
if (k < 0) {
numerator = BigInteger.valueOf(m);
denominator = BigInteger.ZERO.flipBit(-k);
} else {
numerator = BigInteger.valueOf(m).multiply(BigInteger.ZERO.flipBit(k));
denominator = BigInteger.ONE;
}
}
/**
* Create a fraction given the double value and maximum error allowed.
* <p>
* References:
* <ul>
* <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html">
* Continued Fraction</a> equations (11) and (22)-(26)</li>
* </ul>
* </p>
*
* @param value
* the double value to convert to a fraction.
* @param epsilon
* maximum error allowed. The resulting fraction is within
* <code>epsilon</code> of <code>value</code>, in absolute terms.
* @param maxIterations
* maximum number of convergents.
* @throws FractionConversionException
* if the continued fraction failed to converge.
* @see #BigFraction(double)
*/
public BigFraction(final double value, final double epsilon,
final int maxIterations)
throws FractionConversionException {
this(value, epsilon, Integer.MAX_VALUE, maxIterations);
}
/**
* Create a fraction given the double value and either the maximum error
* allowed or the maximum number of denominator digits.
* <p>
*
* NOTE: This constructor is called with EITHER - a valid epsilon value and
* the maxDenominator set to Integer.MAX_VALUE (that way the maxDenominator
* has no effect). OR - a valid maxDenominator value and the epsilon value
* set to zero (that way epsilon only has effect if there is an exact match
* before the maxDenominator value is reached).
* </p>
* <p>
*
* It has been done this way so that the same code can be (re)used for both
* scenarios. However this could be confusing to users if it were part of
* the public API and this constructor should therefore remain PRIVATE.
* </p>
*
* See JIRA issue ticket MATH-181 for more details:
*
* https://issues.apache.org/jira/browse/MATH-181
*
* @param value
* the double value to convert to a fraction.
* @param epsilon
* maximum error allowed. The resulting fraction is within
* <code>epsilon</code> of <code>value</code>, in absolute terms.
* @param maxDenominator
* maximum denominator value allowed.
* @param maxIterations
* maximum number of convergents.
* @throws FractionConversionException
* if the continued fraction failed to converge.
*/
private BigFraction(final double value, final double epsilon,
final int maxDenominator, int maxIterations)
throws FractionConversionException {
long overflow = Integer.MAX_VALUE;
double r0 = value;
long a0 = (long) Math.floor(r0);
if (a0 > overflow) {
throw new FractionConversionException(value, a0, 1l);
}
// check for (almost) integer arguments, which should not go
// to iterations.
if (Math.abs(a0 - value) < epsilon) {
numerator = BigInteger.valueOf(a0);
denominator = BigInteger.ONE;
return;
}
long p0 = 1;
long q0 = 0;
long p1 = a0;
long q1 = 1;
long p2 = 0;
long q2 = 1;
int n = 0;
boolean stop = false;
do {
++n;
final double r1 = 1.0 / (r0 - a0);
final long a1 = (long) Math.floor(r1);
p2 = (a1 * p1) + p0;
q2 = (a1 * q1) + q0;
if ((p2 > overflow) || (q2 > overflow)) {
throw new FractionConversionException(value, p2, q2);
}
final double convergent = (double) p2 / (double) q2;
if ((n < maxIterations) &&
(Math.abs(convergent - value) > epsilon) &&
(q2 < maxDenominator)) {
p0 = p1;
p1 = p2;
q0 = q1;
q1 = q2;
a0 = a1;
r0 = r1;
} else {
stop = true;
}
} while (!stop);
if (n >= maxIterations) {
throw new FractionConversionException(value, maxIterations);
}
if (q2 < maxDenominator) {
numerator = BigInteger.valueOf(p2);
denominator = BigInteger.valueOf(q2);
} else {
numerator = BigInteger.valueOf(p1);
denominator = BigInteger.valueOf(q1);
}
}
/**
* Create a fraction given the double value and maximum denominator.
* <p>
* References:
* <ul>
* <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html">
* Continued Fraction</a> equations (11) and (22)-(26)</li>
* </ul>
* </p>
*
* @param value
* the double value to convert to a fraction.
* @param maxDenominator
* The maximum allowed value for denominator.
* @throws FractionConversionException
* if the continued fraction failed to converge.
*/
public BigFraction(final double value, final int maxDenominator)
throws FractionConversionException {
this(value, 0, maxDenominator, 100);
}
/**
* <p>
* Create a {@link BigFraction} equivalent to the passed <tt>int</tt>, ie
* "num / 1".
* </p>
*
* @param num
* the numerator.
*/
public BigFraction(final int num) {
this(BigInteger.valueOf(num), BigInteger.ONE);
}
/**
* <p>
* Create a {@link BigFraction} given the numerator and denominator as simple
* <tt>int</tt>. The {@link BigFraction} is reduced to lowest terms.
* </p>
*
* @param num
* the numerator.
* @param den
* the denominator.
*/
public BigFraction(final int num, final int den) {
this(BigInteger.valueOf(num), BigInteger.valueOf(den));
}
/**
* <p>
* Create a {@link BigFraction} equivalent to the passed long, ie "num / 1".
* </p>
*
* @param num
* the numerator.
*/
public BigFraction(final long num) {
this(BigInteger.valueOf(num), BigInteger.ONE);
}
/**
* <p>
* Create a {@link BigFraction} given the numerator and denominator as simple
* <tt>long</tt>. The {@link BigFraction} is reduced to lowest terms.
* </p>
*
* @param num
* the numerator.
* @param den
* the denominator.
*/
public BigFraction(final long num, final long den) {
this(BigInteger.valueOf(num), BigInteger.valueOf(den));
}
/**
* <p>
* Returns the absolute value of this {@link BigFraction}.
* </p>
*
* @return the absolute value as a {@link BigFraction}.
*/
public BigFraction abs() {
return (BigInteger.ZERO.compareTo(numerator) <= 0) ? this : negate();
}
/**
* <p>
* Adds the value of this fraction to the passed {@link BigInteger},
* returning the result in reduced form.
* </p>
*
* @param bg
* the {@link BigInteger} to add, must'nt be <code>null</code>.
* @return a <code>BigFraction</code> instance with the resulting values.
* @throws NullPointerException
* if the {@link BigInteger} is <code>null</code>.
*/
public BigFraction add(final BigInteger bg) {
return add(new BigFraction(bg, BigInteger.ONE));
}
/**
* <p>
* Adds the value of this fraction to another, returning the result in
* reduced form.
* </p>
*
* @param fraction
* the {@link BigFraction} to add, must not be <code>null</code>.
* @return a {@link BigFraction} instance with the resulting values.
* @throws NullPointerException
* if the {@link BigFraction} is <code>null</code>.
*/
public BigFraction add(final BigFraction fraction) {
if (ZERO.equals(fraction)) {
return this;
}
BigInteger num = null;
BigInteger den = null;
if (denominator.equals(fraction.denominator)) {
num = numerator.add(fraction.numerator);
den = denominator;
} else {
num = (numerator.multiply(fraction.denominator)).add((fraction.numerator).multiply(denominator));
den = denominator.multiply(fraction.denominator);
}
return new BigFraction(num, den);
}
/**
* <p>
* Adds the value of this fraction to the passed <tt>integer</tt>, returning
* the result in reduced form.
* </p>
*
* @param i
* the <tt>integer</tt> to add.
* @return a <code>BigFraction</code> instance with the resulting values.
*/
public BigFraction add(final int i) {
return add(new BigFraction(i, 1));
}
/**
* <p>
* Adds the value of this fraction to the passed <tt>long</tt>, returning
* the result in reduced form.
* </p>
*
* @param l
* the <tt>long</tt> to add.
* @return a <code>BigFraction</code> instance with the resulting values.
*/
public BigFraction add(final long l) {
return add(new BigFraction(l, 1L));
}
/**
* <p>
* Gets the fraction as a <code>BigDecimal</code>. This calculates the
* fraction as the numerator divided by denominator.
* </p>
*
* @return the fraction as a <code>BigDecimal</code>.
* @throws ArithmeticException
* if the exact quotient does not have a terminating decimal
* expansion.
* @see BigDecimal
*/
public BigDecimal bigDecimalValue() {
return new BigDecimal(numerator).divide(new BigDecimal(denominator));
}
/**
* <p>
* Gets the fraction as a <code>BigDecimal</code> following the passed
* rounding mode. This calculates the fraction as the numerator divided by
* denominator.
* </p>
*
* @param roundingMode
* rounding mode to apply. see {@link BigDecimal} constants.
* @return the fraction as a <code>BigDecimal</code>.
* @throws IllegalArgumentException
* if <tt>roundingMode</tt> does not represent a valid rounding
* mode.
* @see BigDecimal
*/
public BigDecimal bigDecimalValue(final int roundingMode) {
return new BigDecimal(numerator).divide(new BigDecimal(denominator), roundingMode);
}
/**
* <p>
* Gets the fraction as a <code>BigDecimal</code> following the passed scale
* and rounding mode. This calculates the fraction as the numerator divided
* by denominator.
* </p>
*
* @param scale
* scale of the <code>BigDecimal</code> quotient to be returned.
* see {@link BigDecimal} for more information.
* @param roundingMode
* rounding mode to apply. see {@link BigDecimal} constants.
* @return the fraction as a <code>BigDecimal</code>.
* @see BigDecimal
*/
public BigDecimal bigDecimalValue(final int scale, final int roundingMode) {
return new BigDecimal(numerator).divide(new BigDecimal(denominator), scale, roundingMode);
}
/**
* <p>
* Compares this object to another based on size.
* </p>
*
* @param object
* the object to compare to, must not be <code>null</code>.
* @return -1 if this is less than <tt>object</tt>, +1 if this is greater
* than <tt>object</tt>, 0 if they are equal.
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(final BigFraction object) {
BigInteger nOd = numerator.multiply(object.denominator);
BigInteger dOn = denominator.multiply(object.numerator);
return nOd.compareTo(dOn);
}
/**
* <p>
* Divide the value of this fraction by the passed <code>BigInteger</code>,
* ie "this * 1 / bg", returning the result in reduced form.
* </p>
*
* @param bg
* the <code>BigInteger</code> to divide by, must not be
* <code>null</code>.
* @return a {@link BigFraction} instance with the resulting values.
* @throws NullPointerException
* if the <code>BigInteger</code> is <code>null</code>.
*/
public BigFraction divide(final BigInteger bg) {
return divide(new BigFraction(bg, BigInteger.ONE));
}
/**
* <p>
* Divide the value of this fraction by another, returning the result in
* reduced form.
* </p>
*
* @param fraction
* the fraction to divide by, must not be <code>null</code>.
* @return a {@link BigFraction} instance with the resulting values.
* @throws NullPointerException
* if the fraction is <code>null</code>.
* @throws ArithmeticException
* if the fraction to divide by is zero.
*/
public BigFraction divide(final BigFraction fraction) {
if (BigInteger.ZERO.equals(fraction.numerator)) {
throw MathRuntimeException.createArithmeticException("denominator must be different from 0");
}
return multiply(fraction.reciprocal());
}
/**
* <p>
* Divide the value of this fraction by the passed <tt>int</tt>, ie
* "this * 1 / i", returning the result in reduced form.
* </p>
*
* @param i
* the <tt>int</tt> to divide by.
* @return a {@link BigFraction} instance with the resulting values.
*/
public BigFraction divide(final int i) {
return divide(new BigFraction(i, 1));
}
/**
* <p>
* Divide the value of this fraction by the passed <tt>long</tt>, ie
* "this * 1 / l", returning the result in reduced form.
* </p>
*
* @param l
* the <tt>long</tt> to divide by.
* @return a {@link BigFraction} instance with the resulting values.
*/
public BigFraction divide(final long l) {
return divide(new BigFraction(l, 1L));
}
/**
* <p>
* Gets the fraction as a <tt>double</tt>. This calculates the fraction as
* the numerator divided by denominator.
* </p>
*
* @return the fraction as a <tt>double</tt>
* @see java.lang.Number#doubleValue()
*/
@Override
public double doubleValue() {
return numerator.doubleValue() / denominator.doubleValue();
}
/**
* <p>
* Test for the equality of two fractions. If the lowest term numerator and
* denominators are the same for both fractions, the two fractions are
* considered to be equal.
* </p>
*
* @param other
* fraction to test for equality to this fraction, can be
* <code>null</code>.
* @return true if two fractions are equal, false if object is
* <code>null</code>, not an instance of {@link BigFraction}, or not
* equal to this fraction instance.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object other) {
boolean ret = false;
if (this == other) {
ret = true;
} else if (other instanceof BigFraction) {
BigFraction rhs = ((BigFraction) other).reduce();
BigFraction thisOne = this.reduce();
ret = thisOne.numerator.equals(rhs.numerator) && thisOne.denominator.equals(rhs.denominator);
}
return ret;
}
/**
* <p>
* Gets the fraction as a <tt>float</tt>. This calculates the fraction as
* the numerator divided by denominator.
* </p>
*
* @return the fraction as a <tt>float</tt>.
* @see java.lang.Number#floatValue()
*/
@Override
public float floatValue() {
return numerator.floatValue() / denominator.floatValue();
}
/**
* <p>
* Access the denominator as a <code>BigInteger</code>.
* </p>
*
* @return the denominator as a <code>BigInteger</code>.
*/
public BigInteger getDenominator() {
return denominator;
}
/**
* <p>
* Access the denominator as a <tt>int</tt>.
* </p>
*
* @return the denominator as a <tt>int</tt>.
*/
public int getDenominatorAsInt() {
return denominator.intValue();
}
/**
* <p>
* Access the denominator as a <tt>long</tt>.
* </p>
*
* @return the denominator as a <tt>long</tt>.
*/
public long getDenominatorAsLong() {
return denominator.longValue();
}
/**
* <p>
* Access the numerator as a <code>BigInteger</code>.
* </p>
*
* @return the numerator as a <code>BigInteger</code>.
*/
public BigInteger getNumerator() {
return numerator;
}
/**
* <p>
* Access the numerator as a <tt>int</tt>.
* </p>
*
* @return the numerator as a <tt>int</tt>.
*/
public int getNumeratorAsInt() {
return numerator.intValue();
}
/**
* <p>
* Access the numerator as a <tt>long</tt>.
* </p>
*
* @return the numerator as a <tt>long</tt>.
*/
public long getNumeratorAsLong() {
return numerator.longValue();
}
/**
* <p>
* Gets a hashCode for the fraction.
* </p>
*
* @return a hash code value for this object.
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 37 * (37 * 17 + numerator.hashCode()) + denominator.hashCode();
}
/**
* <p>
* Gets the fraction as an <tt>int</tt>. This returns the whole number part
* of the fraction.
* </p>
*
* @return the whole number fraction part.
* @see java.lang.Number#intValue()
*/
@Override
public int intValue() {
return numerator.divide(denominator).intValue();
}
/**
* <p>
* Gets the fraction as a <tt>long</tt>. This returns the whole number part
* of the fraction.
* </p>
*
* @return the whole number fraction part.
* @see java.lang.Number#longValue()
*/
@Override
public long longValue() {
return numerator.divide(denominator).longValue();
}
/**
* <p>
* Multiplies the value of this fraction by the passed
* <code>BigInteger</code>, returning the result in reduced form.
* </p>
*
* @param bg
* the <code>BigInteger</code> to multiply by.
* @return a <code>BigFraction</code> instance with the resulting values.
* @throws NullPointerException
* if the bg is <code>null</code>.
*/
public BigFraction multiply(final BigInteger bg) {
return new BigFraction(bg.multiply(numerator), denominator);
}
/**
* <p>
* Multiplies the value of this fraction by another, returning the result in
* reduced form.
* </p>
*
* @param fraction
* the fraction to multiply by, must not be <code>null</code>.
* @return a {@link BigFraction} instance with the resulting values.
* @throws NullPointerException
* if the fraction is <code>null</code>.
*/
public BigFraction multiply(final BigFraction fraction) {
BigFraction ret = ZERO;
if (getNumeratorAsInt() != 0 && fraction.getNumeratorAsInt() != 0) {
ret = new BigFraction(numerator.multiply(fraction.numerator), denominator.multiply(fraction.denominator));
}
return ret;
}
/**
* <p>
* Multiply the value of this fraction by the passed <tt>int</tt>, returning
* the result in reduced form.
* </p>
*
* @param i
* the <tt>int</tt> to multiply by.
* @return a {@link BigFraction} instance with the resulting values.
*/
public BigFraction multiply(final int i) {
return multiply(new BigFraction(i, 1));
}
/**
* <p>
* Multiply the value of this fraction by the passed <tt>long</tt>,
* returning the result in reduced form.
* </p>
*
* @param l
* the <tt>long</tt> to multiply by.
* @return a {@link BigFraction} instance with the resulting values.
*/
public BigFraction multiply(final long l) {
return multiply(new BigFraction(l, 1L));
}
/**
* <p>
* Return the additive inverse of this fraction, returning the result in
* reduced form.
* </p>
*
* @return the negation of this fraction.
*/
public BigFraction negate() {
return new BigFraction(numerator.negate(), denominator);
}
/**
* <p>
* Gets the fraction percentage as a <tt>double</tt>. This calculates the
* fraction as the numerator divided by denominator multiplied by 100.
* </p>
*
* @return the fraction percentage as a <tt>double</tt>.
*/
public double percentageValue() {
return (numerator.divide(denominator)).multiply(ONE_HUNDRED_DOUBLE).doubleValue();
}
/**
* <p>
* Returns a <code>BigFraction</code> whose value is
* <tt>(this<sup>exponent</sup>)</tt>, returning the result in reduced form.
* </p>
*
* @param exponent
* exponent to which this <code>BigFraction</code> is to be raised.
* @return <tt>this<sup>exponent</sup></tt> as a <code>BigFraction</code>.
*/
public BigFraction pow(final BigInteger exponent) {
BigFraction ret = this;
if (!BigInteger.ONE.equals(exponent)) {
ret = ONE;
if (!BigInteger.ZERO.equals(exponent)) {
for (BigInteger bg = BigInteger.ONE; bg.compareTo(exponent) < 0; bg = bg.add(BigInteger.ONE)) {
ret = ret.multiply(this);
}
}
}
return ret;
}
/**
* <p>
* Returns a <code>BigFraction</code> whose value is
* <tt>(this<sup>exponent</sup>)</tt>, returning the result in reduced form.
* </p>
*
* @param exponent
* exponent to which this <code>BigFraction</code> is to be raised.
* @return <tt>this<sup>exponent</sup></tt>.
*/
public double pow(final BigFraction exponent) {
return Math.pow(numerator.doubleValue(), exponent.doubleValue()) / Math.pow(denominator.doubleValue(), exponent.doubleValue());
}
/**
* <p>
* Returns a <tt>integer</tt> whose value is
* <tt>(this<sup>exponent</sup>)</tt>, returning the result in reduced form.
* </p>
*
* @param exponent
* exponent to which this <code>BigInteger</code> is to be
* raised.
* @return <tt>this<sup>exponent</sup></tt>.
*/
public BigFraction pow(final int exponent) {
return pow(BigInteger.valueOf(exponent));
}
/**
* <p>
* Returns a <code>BigFraction</code> whose value is
* <tt>(this<sup>exponent</sup>)</tt>, returning the result in reduced form.
* </p>
*
* @param exponent
* exponent to which this <code>BigFraction</code> is to be raised.
* @return <tt>this<sup>exponent</sup></tt> as a <code>BigFraction</code>.
*/
public BigFraction pow(final long exponent) {
return pow(BigInteger.valueOf(exponent));
}
/**
* <p>
* Return the multiplicative inverse of this fraction.
* </p>
*
* @return the reciprocal fraction.
*/
public BigFraction reciprocal() {
return new BigFraction(denominator, numerator);
}
/**
* <p>
* Reduce this <code>BigFraction</code> to its lowest terms.
* </p>
*
* @return the reduced <code>BigFraction</code>. It doesn't change anything if
* the fraction can be reduced.
*/
public BigFraction reduce() {
final BigInteger gcd = numerator.gcd(denominator);
return new BigFraction(numerator.divide(gcd), denominator.divide(gcd));
}
/**
* <p>
* Subtracts the value of an {@link BigInteger} from the value of this one,
* returning the result in reduced form.
* </p>
*
* @param bg
* the {@link BigInteger} to subtract, must'nt be
* <code>null</code>.
* @return a <code>BigFraction</code> instance with the resulting values.
* @throws NullPointerException
* if the {@link BigInteger} is <code>null</code>.
*/
public BigFraction subtract(final BigInteger bg) {
return subtract(new BigFraction(bg, BigInteger.valueOf(1)));
}
/**
* <p>
* Subtracts the value of another fraction from the value of this one,
* returning the result in reduced form.
* </p>
*
* @param fraction
* the {@link BigFraction} to subtract, must not be
* <code>null</code>.
* @return a {@link BigFraction} instance with the resulting values
* @throws NullPointerException
* if the fraction is <code>null</code>.
*/
public BigFraction subtract(final BigFraction fraction) {
if (ZERO.equals(fraction)) {
return this;
}
BigInteger num = null;
BigInteger den = null;
if (denominator.equals(fraction.denominator)) {
num = numerator.subtract(fraction.numerator);
den = denominator;
} else {
num = (numerator.multiply(fraction.denominator)).subtract((fraction.numerator).multiply(denominator));
den = denominator.multiply(fraction.denominator);
}
return new BigFraction(num, den);
}
/**
* <p>
* Subtracts the value of an <tt>integer</tt> from the value of this one,
* returning the result in reduced form.
* </p>
*
* @param i
* the <tt>integer</tt> to subtract.
* @return a <code>BigFraction</code> instance with the resulting values.
*/
public BigFraction subtract(final int i) {
return subtract(new BigFraction(i, 1));
}
/**
* <p>
* Subtracts the value of an <tt>integer</tt> from the value of this one,
* returning the result in reduced form.
* </p>
*
* @param l
* the <tt>long</tt> to subtract.
* @return a <code>BigFraction</code> instance with the resulting values, or
* this object if the <tt>long</tt> is zero.
*/
public BigFraction subtract(final long l) {
return subtract(new BigFraction(l, 1L));
}
/**
* <p>
* Returns the <code>String</code> representing this fraction, ie
* "num / dem" or just "num" if the denominator is one.
* </p>
*
* @return a string representation of the fraction.
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String str = null;
if (BigInteger.ONE.equals(denominator)) {
str = numerator.toString();
} else if (BigInteger.ZERO.equals(numerator)) {
str = "0";
} else {
str = numerator + " / " + denominator;
}
return str;
}
}
| removed an unneeded call to reduce()
(the constructor already reduces the fraction)
git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@759678 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/commons/math/fraction/BigFraction.java | removed an unneeded call to reduce() (the constructor already reduces the fraction) | <ide><path>rc/java/org/apache/commons/math/fraction/BigFraction.java
<ide> return ZERO; // normalize zero.
<ide> }
<ide>
<del> return new BigFraction(numerator, denominator).reduce();
<add> return new BigFraction(numerator, denominator);
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 60dfa34f20b5471ef5acc0880e52a78274dcb5da | 0 | ctripcorp/zeus,sdgdsffdsfff/zeus,sdgdsffdsfff/zeus,sdgdsffdsfff/zeus,ctripcorp/zeus,ctripcorp/zeus,sdgdsffdsfff/zeus,sdgdsffdsfff/zeus,ctripcorp/zeus | package com.ctrip.zeus.service.aop;
import com.ctrip.zeus.model.entity.Group;
import com.ctrip.zeus.model.entity.GroupServer;
import com.ctrip.zeus.model.entity.Slb;
import com.ctrip.zeus.model.entity.VirtualServer;
import com.ctrip.zeus.model.transform.DefaultJsonParser;
import com.ctrip.zeus.model.transform.DefaultSaxParser;
import com.ctrip.zeus.service.aop.OperationLog.OperationLogConfig;
import com.ctrip.zeus.service.aop.OperationLog.OperationLogType;
import com.ctrip.zeus.service.model.GroupRepository;
import com.ctrip.zeus.service.model.SlbRepository;
import com.ctrip.zeus.service.model.VirtualServerRepository;
import com.ctrip.zeus.service.operationLog.OperationLogService;
import com.ctrip.zeus.service.query.GroupCriteriaQuery;
import com.ctrip.zeus.service.query.SlbCriteriaQuery;
import com.ctrip.zeus.support.ObjectJsonParser;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicPropertyFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Created by fanqq on 2015/7/15.
*/
@Aspect
@Component
public class OperationLogAspect implements Ordered {
@Resource
private GroupRepository groupRepository;
@Resource
private SlbRepository slbRepository;
@Resource
private VirtualServerRepository virtualServerRepository;
@Resource
private SlbCriteriaQuery slbCriteriaQuery;
@Resource
private GroupCriteriaQuery groupCriteriaQuery;
@Resource
private OperationLogService operationLogService;
private final static String QUERY_NAME_SLB_ID = "slbId";
private final static String QUERY_NAME_SLB_NAME = "slbName";
private final static String QUERY_NAME_GROUP_ID = "groupId";
private final static String QUERY_NAME_VS_ID = "vsId";
private final static String QUERY_NAME_GROUP_NAME = "groupName";
private final static String ID_NEW = "New";
private final static String ID_UNKNOW = "Unknow";
private final static String ID_BATCH = "Batch";
private Logger logger = LoggerFactory.getLogger(this.getClass());
private DynamicBooleanProperty enableAccess = DynamicPropertyFactory.getInstance().getBooleanProperty("log.access.enable", true);
@Around("execution(* com.ctrip.zeus.restful.resource.*Resource.*(..))")
public Object operationLog(ProceedingJoinPoint point) throws Throwable {
if (!enableAccess.get()) {
return point.proceed();
}
String type = null;
String id = null;
String op = null;
String userName = null;
String remoteAddr = null;
HashMap<String, String> data = new HashMap<>();
Object response = null;
String errMsg = null;
boolean success = false;
HttpServletRequest request = findRequestArg(point);
if (request == null) {
return point.proceed();
}
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
String key = point.getTarget().getClass().getSimpleName() + "." + method.getName();
if (!OperationLogConfig.getInstance().contain(key)) {
return point.proceed();
}
try {
Object[] args = point.getArgs();
Annotation[][] annotations = method.getParameterAnnotations();
HttpHeaders hh = findHttpHeaders(point);
type = OperationLogConfig.getInstance().getType(key).value();
id = findId(key, request, args, point, hh);
op = method.getName();
userName = request.getRemoteUser();
remoteAddr = request.getRemoteAddr();
data = findData(key, request, args, hh, method);
} catch (Exception e) {
logger.warn("Operation Log Aspect Exception!" + e.getMessage());
}
try {
response = point.proceed();
} catch (Throwable throwable) {
errMsg = throwable.getMessage();
throw throwable;
} finally {
if (response != null) {
success = true;
}
if (userName == null) {
userName = "Unknown";
}
operationLogService.insert(type, id, op, data.toString(), userName, remoteAddr, success, errMsg, new Date());
}
return response;
}
@Override
public int getOrder() {
return AspectOrder.Access;
}
private HttpServletRequest findRequestArg(JoinPoint point) {
Object[] args = point.getArgs();
for (Object arg : args) {
if (arg instanceof HttpServletRequest) {
return (HttpServletRequest) arg;
}
}
return null;
}
private HttpHeaders findHttpHeaders(JoinPoint point) {
Object[] args = point.getArgs();
for (Object arg : args) {
if (arg instanceof HttpHeaders) {
return (HttpHeaders) arg;
}
}
return null;
}
private String findId(String key, HttpServletRequest request, Object[] args, JoinPoint point, HttpHeaders hh) throws Exception {
//1. Batch is true, return "Batch"
if (OperationLogConfig.getInstance().getBatch(key)) {
return ID_BATCH;
}
// find by config ids
int[] ids = OperationLogConfig.getInstance().getIds(key);
for (int i : ids) {
//2. if id is out of range , return New
if (i < 0 || i >= args.length) {
return ID_NEW;
}
//3. if request Method is Post , Parse post data to get id
if (request.getMethod().equals("POST") && null != args[i]) {
// 3.1 httpHeaders is null , Can not parse post data;
if (null == hh) {
return ID_UNKNOW;
}
// 3.2 type is AccessType.SLB , parse data to Slb object.
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.SLB) {
Slb slb = parseSlb(hh.getMediaType(), (String) args[i]);
if (slb == null) {
return ID_UNKNOW;//"Slb Parse Fail";
}
return slb.getId() != null ? String.valueOf(slb.getId()) : slb.getName();
}
// 3.3 type is AccessType.GROUP , parse data to Group object.
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP) {
Group group = parseGroup((String) args[i]);
if (group == null) {
return ID_UNKNOW;//"Group Parse Fail";
}
return group.getId() != null ? String.valueOf(group.getId()) : group.getName();
}
// 3.3 type is AccessType.VS , parse data to Group object.
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.VS) {
VirtualServer vs = parseVS(hh.getMediaType(), (String) args[i]);
if (vs == null) {
return ID_UNKNOW;//"Group Parse Fail";
}
return vs.getId() != null ? String.valueOf(vs.getId()) : vs.getName();
}
return ID_UNKNOW;
}
// 4. if method is GET , find id from args. Type Long comes first.
if (null != args[i]) {
String name = null;
if (args[i] instanceof String) {
name = (String) args[i];
}
if (args[i] instanceof Long) {
return String.valueOf((Long) args[i]);
}
if (args[i] instanceof List<?>) {
List tmp = (List) args[i];
if (tmp.size() > 1) {
return ID_BATCH;
} else if (tmp.size() == 1) {
if (tmp.get(0) instanceof String) {
name = (String) tmp.get(0);
} else {
return tmp.get(0).toString();
}
}
}
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP && name != null) {
Long groupId = groupCriteriaQuery.queryByName(name);
return groupId == null ? name : String.valueOf(groupId);
} else if (OperationLogConfig.getInstance().getType(key) == OperationLogType.SLB && name != null) {
Long slbId = slbCriteriaQuery.queryByName(name);
return slbId == null ? name : String.valueOf(slbId);
} else if (name != null) {
return name;
}
}
}
return ID_UNKNOW;
}
private HashMap<String, String> findData(String key, HttpServletRequest request, Object[] args, HttpHeaders hh, Method method) throws Exception {
HashMap<String, String> data = new HashMap<>();
int[] ids = OperationLogConfig.getInstance().getIds(key);
Annotation[][] annotations = method.getParameterAnnotations();
//1. request Method is Post, data should be Name and Version
if (request.getMethod().equals("POST")) {
if (ids == null || ids.length <= 0) {
return data;
}
//1.1 in case of New
if (ids.length > 0 && (ids[0] < 0 || ids[0] >= args.length)) {
data.put("Version", "1");
if (ids.length >= 2 && args[ids[1]] instanceof String) {
String postData = (String) args[ids[1]];
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.SLB && hh != null) {
Slb slb = parseSlb(hh.getMediaType(), postData);
if (slb == null) {
data.put("Slb", "Slb Parse Fail!");
} else {
data.put("SlbName", String.valueOf(slb.getName()));
}
} else if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP && hh != null) {
Group group = parseGroup(postData);
if (group == null) {
data.put("Group", "Group Parse Fail!");
} else {
data.put("GroupName", String.valueOf(group.getName()));
}
}
}
return data;
}
//1.2 in case of update
Object obj = args[ids[0]];
String tmp;
if (obj instanceof String) {
tmp = (String) obj;
} else {
data.put("errMsg", ids[0] + "'st argument is not String");
return data;
}
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.SLB && hh != null) {
Slb slb = parseSlb(hh.getMediaType(), tmp);
if (slb == null) {
data.put("Slb", "Slb Parse Fail!");
} else {
data.put("SlbName", String.valueOf(slb.getName()));
data.put("Version", String.valueOf(slb.getVersion()));
}
} else if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP && hh != null) {
Group group = parseGroup(tmp);
if (group == null) {
data.put("Group", "Group Parse Fail!");
} else {
data.put("GroupName", String.valueOf(group.getName()));
data.put("Version", String.valueOf(group.getVersion()));
}
} else if (OperationLogConfig.getInstance().getType(key) == OperationLogType.VS && hh != null) {
VirtualServer vs = parseVS(hh.getMediaType(), tmp);
if (vs == null) {
data.put("VS", "Group Parse Fail!");
} else {
data.put("VSName", String.valueOf(vs.getName()));
data.put("VsVersion", String.valueOf(vs.getVersion()));
}
}
return data;
} else {
//2. request method is GET, get data from QueryString
String tmpKey = null;
for (int i = 0; i < args.length; i++) {
if (annotations[i][0] instanceof QueryParam) {
//1. get queryParam Names
tmpKey = ((QueryParam) annotations[i][0]).value();
//2. queryParam Names equals QUERY_NAME_GROUP_ID , must be groupId.
if (tmpKey.equalsIgnoreCase(QUERY_NAME_GROUP_ID) && args[i] != null) {
if (args[i] instanceof Long) {
Group group = groupRepository.getById((Long) args[i]);
data.put(OperationLogType.GROUP.value(), group != null ? group.getName() : args[i].toString() + "[id not found]");
}
if (args[i] instanceof List) {
List list = (List) args[i];
List<String> groupNames = new ArrayList<>();
for (Object groupId : list) {
Group group = groupRepository.getById((Long) groupId);
groupNames.add(group != null ? group.getName() : groupId.toString() + "[id not found]");
}
if (groupNames.size() > 0) {
data.put(OperationLogType.GROUP.value(), groupNames.toString());
}
}
} else if (tmpKey.equalsIgnoreCase(QUERY_NAME_SLB_ID) && args[i] != null) {
if (args[i] instanceof Long) {
Slb slb = slbRepository.getById((Long) args[i]);
data.put(OperationLogType.SLB.value(), slb != null ? slb.getName() : args[i].toString() + "[id not found]");
}
if (args[i] instanceof List) {
List list = (List) args[i];
List<String> slbNames = new ArrayList<>();
for (Object slbId : list) {
Slb slb = slbRepository.getById((Long) slbId);
slbNames.add(slb != null ? slb.getName() : slbId.toString() + "[id not found]");
}
if (slbNames.size() > 0) {
data.put(OperationLogType.SLB.value(), slbNames.toString());
}
}
} else if (tmpKey.equalsIgnoreCase(QUERY_NAME_VS_ID) && args[i] != null) {
if (args[i] instanceof Long) {
VirtualServer vs = virtualServerRepository.getById((Long) args[i]);
data.put(OperationLogType.VS.value(), vs != null ? vs.getName() : args[i].toString() + "[id not found]");
}
if (args[i] instanceof List) {
List list = (List) args[i];
List<String> vsNames = new ArrayList<>();
for (Object slbId : list) {
VirtualServer vs = virtualServerRepository.getById((Long) slbId);
vsNames.add(vs != null ? vs.getName() : slbId.toString() + "[id not found]");
}
if (vsNames.size() > 0) {
data.put(OperationLogType.VS.value(), vsNames.toString());
}
}
} else if (args[i] != null) {
if (args[i] instanceof List && ((List) args[i]).size() > 0 || !(args[i] instanceof List)) {
data.put(tmpKey, args[i].toString());
}
}
}
}
return data;
}
}
private Group parseGroup(String group) {
Group g = ObjectJsonParser.parse(group, Group.class);
trim(g);
return g;
}
private Slb parseSlb(MediaType mediaType, String slb) {
Slb s;
try {
if (mediaType.equals(MediaType.APPLICATION_XML_TYPE)) {
s = DefaultSaxParser.parseEntity(Slb.class, slb);
} else {
s = DefaultJsonParser.parse(Slb.class, slb);
}
} catch (Exception e) {
logger.warn("Slb Parse Fail!");
return null;
}
return s;
}
private VirtualServer parseVS(MediaType mediaType, String vs) {
VirtualServer s;
try {
if (mediaType.equals(MediaType.APPLICATION_XML_TYPE)) {
s = DefaultSaxParser.parseEntity(VirtualServer.class, vs);
} else {
s = DefaultJsonParser.parse(VirtualServer.class, vs);
}
} catch (Exception e) {
logger.warn("VirtualServer Parse Fail!");
return null;
}
return s;
}
private void trim(Group g) {
g.setAppId(trimIfNotNull(g.getAppId()));
g.setName(trimIfNotNull(g.getName()));
if (g.getHealthCheck() != null)
g.getHealthCheck().setUri(trimIfNotNull(g.getHealthCheck().getUri()));
for (GroupServer groupServer : g.getGroupServers()) {
groupServer.setIp(trimIfNotNull(groupServer.getIp()));
groupServer.setHostName(trimIfNotNull(groupServer.getHostName()));
}
if (g.getLoadBalancingMethod() != null)
g.getLoadBalancingMethod().setValue(trimIfNotNull(g.getLoadBalancingMethod().getValue()));
}
private String trimIfNotNull(String value) {
return value != null ? value.trim() : value;
}
}
| src/main/java/com/ctrip/zeus/service/aop/OperationLogAspect.java | package com.ctrip.zeus.service.aop;
import com.ctrip.zeus.model.entity.Group;
import com.ctrip.zeus.model.entity.Slb;
import com.ctrip.zeus.model.entity.VirtualServer;
import com.ctrip.zeus.model.transform.DefaultJsonParser;
import com.ctrip.zeus.model.transform.DefaultSaxParser;
import com.ctrip.zeus.service.aop.OperationLog.OperationLogConfig;
import com.ctrip.zeus.service.aop.OperationLog.OperationLogType;
import com.ctrip.zeus.service.model.GroupRepository;
import com.ctrip.zeus.service.model.SlbRepository;
import com.ctrip.zeus.service.model.VirtualServerRepository;
import com.ctrip.zeus.service.operationLog.OperationLogService;
import com.ctrip.zeus.service.query.GroupCriteriaQuery;
import com.ctrip.zeus.service.query.SlbCriteriaQuery;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicPropertyFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* Created by fanqq on 2015/7/15.
*/
@Aspect
@Component
public class OperationLogAspect implements Ordered {
@Resource
private GroupRepository groupRepository;
@Resource
private SlbRepository slbRepository;
@Resource
private VirtualServerRepository virtualServerRepository;
@Resource
private SlbCriteriaQuery slbCriteriaQuery;
@Resource
private GroupCriteriaQuery groupCriteriaQuery;
@Resource
private OperationLogService operationLogService;
private final static String QUERY_NAME_SLB_ID = "slbId";
private final static String QUERY_NAME_SLB_NAME = "slbName";
private final static String QUERY_NAME_GROUP_ID = "groupId";
private final static String QUERY_NAME_VS_ID = "vsId";
private final static String QUERY_NAME_GROUP_NAME = "groupName";
private final static String ID_NEW = "New";
private final static String ID_UNKNOW = "Unknow";
private final static String ID_BATCH = "Batch";
private Logger logger = LoggerFactory.getLogger(this.getClass());
private DynamicBooleanProperty enableAccess = DynamicPropertyFactory.getInstance().getBooleanProperty("log.access.enable", true);
@Around("execution(* com.ctrip.zeus.restful.resource.*Resource.*(..))")
public Object operationLog(ProceedingJoinPoint point) throws Throwable {
if (!enableAccess.get()) {
return point.proceed();
}
String type = null;
String id = null;
String op = null;
String userName = null;
String remoteAddr = null;
HashMap<String, String> data = new HashMap<>();
Object response = null;
String errMsg = null;
boolean success = false;
HttpServletRequest request = findRequestArg(point);
if (request == null) {
return point.proceed();
}
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
String key = point.getTarget().getClass().getSimpleName() + "." + method.getName();
if (!OperationLogConfig.getInstance().contain(key)) {
return point.proceed();
}
try {
Object[] args = point.getArgs();
Annotation[][] annotations = method.getParameterAnnotations();
HttpHeaders hh = findHttpHeaders(point);
type = OperationLogConfig.getInstance().getType(key).value();
id = findId(key, request, args, point, hh);
op = method.getName();
userName = request.getRemoteUser();
remoteAddr = request.getRemoteAddr();
data = findData(key, request, args, hh, method);
} catch (Exception e) {
logger.warn("Operation Log Aspect Exception!" + e.getMessage());
}
try {
response = point.proceed();
} catch (Throwable throwable) {
errMsg = throwable.getMessage();
throw throwable;
} finally {
if (response != null) {
success = true;
}
if (userName == null) {
userName = "Unknown";
}
operationLogService.insert(type, id, op, data.toString(), userName, remoteAddr, success, errMsg, new Date());
}
return response;
}
@Override
public int getOrder() {
return AspectOrder.Access;
}
private HttpServletRequest findRequestArg(JoinPoint point) {
Object[] args = point.getArgs();
for (Object arg : args) {
if (arg instanceof HttpServletRequest) {
return (HttpServletRequest) arg;
}
}
return null;
}
private HttpHeaders findHttpHeaders(JoinPoint point) {
Object[] args = point.getArgs();
for (Object arg : args) {
if (arg instanceof HttpHeaders) {
return (HttpHeaders) arg;
}
}
return null;
}
private String findId(String key, HttpServletRequest request, Object[] args, JoinPoint point, HttpHeaders hh) throws Exception {
//1. Batch is true, return "Batch"
if (OperationLogConfig.getInstance().getBatch(key)) {
return ID_BATCH;
}
// find by config ids
int[] ids = OperationLogConfig.getInstance().getIds(key);
for (int i : ids) {
//2. if id is out of range , return New
if (i < 0 || i >= args.length) {
return ID_NEW;
}
//3. if request Method is Post , Parse post data to get id
if (request.getMethod().equals("POST") && null != args[i]) {
// 3.1 httpHeaders is null , Can not parse post data;
if (null == hh) {
return ID_UNKNOW;
}
// 3.2 type is AccessType.SLB , parse data to Slb object.
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.SLB) {
Slb slb = parseSlb(hh.getMediaType(), (String) args[i]);
if (slb == null) {
return ID_UNKNOW;//"Slb Parse Fail";
}
return slb.getId() != null ? String.valueOf(slb.getId()) : slb.getName();
}
// 3.3 type is AccessType.GROUP , parse data to Group object.
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP) {
Group group = parseGroup(hh.getMediaType(), (String) args[i]);
if (group == null) {
return ID_UNKNOW;//"Group Parse Fail";
}
return group.getId() != null ? String.valueOf(group.getId()) : group.getName();
}
// 3.3 type is AccessType.VS , parse data to Group object.
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.VS) {
VirtualServer vs = parseVS(hh.getMediaType(), (String) args[i]);
if (vs == null) {
return ID_UNKNOW;//"Group Parse Fail";
}
return vs.getId() != null ? String.valueOf(vs.getId()) : vs.getName();
}
return ID_UNKNOW;
}
// 4. if method is GET , find id from args. Type Long comes first.
if (null != args[i]) {
String name = null;
if (args[i] instanceof String) {
name = (String) args[i];
}
if (args[i] instanceof Long) {
return String.valueOf((Long) args[i]);
}
if (args[i] instanceof List<?>) {
List tmp = (List) args[i];
if (tmp.size() > 1) {
return ID_BATCH;
} else if (tmp.size() == 1) {
if (tmp.get(0) instanceof String) {
name = (String) tmp.get(0);
} else {
return tmp.get(0).toString();
}
}
}
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP && name != null) {
Long groupId = groupCriteriaQuery.queryByName(name);
return groupId == null ? name : String.valueOf(groupId);
} else if (OperationLogConfig.getInstance().getType(key) == OperationLogType.SLB && name != null) {
Long slbId = slbCriteriaQuery.queryByName(name);
return slbId == null ? name : String.valueOf(slbId);
} else if (name != null) {
return name;
}
}
}
return ID_UNKNOW;
}
private HashMap<String, String> findData(String key, HttpServletRequest request, Object[] args, HttpHeaders hh, Method method) throws Exception {
HashMap<String, String> data = new HashMap<>();
int[] ids = OperationLogConfig.getInstance().getIds(key);
Annotation[][] annotations = method.getParameterAnnotations();
//1. request Method is Post, data should be Name and Version
if (request.getMethod().equals("POST")) {
if (ids == null || ids.length <= 0) {
return data;
}
//1.1 in case of New
if (ids.length > 0 && (ids[0] < 0 || ids[0] >= args.length)) {
data.put("Version", "1");
if (ids.length >= 2 && args[ids[1]] instanceof String) {
String postData = (String) args[ids[1]];
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.SLB && hh != null) {
Slb slb = parseSlb(hh.getMediaType(), postData);
if (slb == null) {
data.put("Slb", "Slb Parse Fail!");
} else {
data.put("SlbName", String.valueOf(slb.getName()));
}
} else if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP && hh != null) {
Group group = parseGroup(hh.getMediaType(), postData);
if (group == null) {
data.put("Group", "Group Parse Fail!");
} else {
data.put("GroupName", String.valueOf(group.getName()));
}
}
}
return data;
}
//1.2 in case of update
Object obj = args[ids[0]];
String tmp = null;
if (obj instanceof String) {
tmp = (String) obj;
} else {
data.put("errMsg", ids[0] + "'st argument is not String");
return data;
}
if (OperationLogConfig.getInstance().getType(key) == OperationLogType.SLB && hh != null) {
Slb slb = parseSlb(hh.getMediaType(), tmp);
if (slb == null) {
data.put("Slb", "Slb Parse Fail!");
} else {
data.put("SlbName", String.valueOf(slb.getName()));
data.put("Version", String.valueOf(slb.getVersion()));
}
} else if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP && hh != null) {
Group group = parseGroup(hh.getMediaType(), tmp);
if (group == null) {
data.put("Group", "Group Parse Fail!");
} else {
data.put("GroupName", String.valueOf(group.getName()));
data.put("Version", String.valueOf(group.getVersion()));
}
} else if (OperationLogConfig.getInstance().getType(key) == OperationLogType.VS && hh != null) {
VirtualServer vs = parseVS(hh.getMediaType(), tmp);
if (vs == null) {
data.put("VS", "Group Parse Fail!");
} else {
data.put("VSName", String.valueOf(vs.getName()));
data.put("VsVersion", String.valueOf(vs.getVersion()));
}
}
return data;
} else {
//2. request method is GET, get data from QueryString
String tmpKey = null;
for (int i = 0; i < args.length; i++) {
if (annotations[i][0] instanceof QueryParam) {
//1. get queryParam Names
tmpKey = ((QueryParam) annotations[i][0]).value();
//2. queryParam Names equals QUERY_NAME_GROUP_ID , must be groupId.
if (tmpKey.equalsIgnoreCase(QUERY_NAME_GROUP_ID) && args[i] != null) {
if (args[i] instanceof Long) {
Group group = groupRepository.getById((Long) args[i]);
data.put(OperationLogType.GROUP.value(), group != null ? group.getName() : args[i].toString() + "[id not found]");
}
if (args[i] instanceof List) {
List list = (List) args[i];
List<String> groupNames = new ArrayList<>();
for (Object groupId : list) {
Group group = groupRepository.getById((Long) groupId);
groupNames.add(group != null ? group.getName() : groupId.toString() + "[id not found]");
}
if (groupNames.size() > 0) {
data.put(OperationLogType.GROUP.value(), groupNames.toString());
}
}
} else if (tmpKey.equalsIgnoreCase(QUERY_NAME_SLB_ID) && args[i] != null) {
if (args[i] instanceof Long) {
Slb slb = slbRepository.getById((Long) args[i]);
data.put(OperationLogType.SLB.value(), slb != null ? slb.getName() : args[i].toString() + "[id not found]");
}
if (args[i] instanceof List) {
List list = (List) args[i];
List<String> slbNames = new ArrayList<>();
for (Object slbId : list) {
Slb slb = slbRepository.getById((Long) slbId);
slbNames.add(slb != null ? slb.getName() : slbId.toString() + "[id not found]");
}
if (slbNames.size() > 0) {
data.put(OperationLogType.SLB.value(), slbNames.toString());
}
}
} else if (tmpKey.equalsIgnoreCase(QUERY_NAME_VS_ID) && args[i] != null) {
if (args[i] instanceof Long) {
VirtualServer vs = virtualServerRepository.getById((Long) args[i]);
data.put(OperationLogType.VS.value(), vs != null ? vs.getName() : args[i].toString() + "[id not found]");
}
if (args[i] instanceof List) {
List list = (List) args[i];
List<String> vsNames = new ArrayList<>();
for (Object slbId : list) {
VirtualServer vs = virtualServerRepository.getById((Long) slbId);
vsNames.add(vs != null ? vs.getName() : slbId.toString() + "[id not found]");
}
if (vsNames.size() > 0) {
data.put(OperationLogType.VS.value(), vsNames.toString());
}
}
} else if (args[i] != null) {
if (args[i] instanceof List && ((List) args[i]).size() > 0 || !(args[i] instanceof List)) {
data.put(tmpKey, args[i].toString());
}
}
}
}
return data;
}
}
private Group parseGroup(MediaType mediaType, String group) {
Group g;
try {
if (mediaType.equals(MediaType.APPLICATION_XML_TYPE)) {
g = DefaultSaxParser.parseEntity(Group.class, group);
} else {
g = DefaultJsonParser.parse(Group.class, group);
}
} catch (Exception e) {
logger.warn("Group Parse Fail!");
return null;
}
return g;
}
private Slb parseSlb(MediaType mediaType, String slb) {
Slb s;
try {
if (mediaType.equals(MediaType.APPLICATION_XML_TYPE)) {
s = DefaultSaxParser.parseEntity(Slb.class, slb);
} else {
s = DefaultJsonParser.parse(Slb.class, slb);
}
} catch (Exception e) {
logger.warn("Slb Parse Fail!");
return null;
}
return s;
}
private VirtualServer parseVS(MediaType mediaType, String vs) {
VirtualServer s;
try {
if (mediaType.equals(MediaType.APPLICATION_XML_TYPE)) {
s = DefaultSaxParser.parseEntity(VirtualServer.class, vs);
} else {
s = DefaultJsonParser.parse(VirtualServer.class, vs);
}
} catch (Exception e) {
logger.warn("VirtualServer Parse Fail!");
return null;
}
return s;
}
}
| update parseGroup in OperationLogAspect
| src/main/java/com/ctrip/zeus/service/aop/OperationLogAspect.java | update parseGroup in OperationLogAspect | <ide><path>rc/main/java/com/ctrip/zeus/service/aop/OperationLogAspect.java
<ide> package com.ctrip.zeus.service.aop;
<ide>
<ide> import com.ctrip.zeus.model.entity.Group;
<add>import com.ctrip.zeus.model.entity.GroupServer;
<ide> import com.ctrip.zeus.model.entity.Slb;
<ide> import com.ctrip.zeus.model.entity.VirtualServer;
<ide> import com.ctrip.zeus.model.transform.DefaultJsonParser;
<ide> import com.ctrip.zeus.service.operationLog.OperationLogService;
<ide> import com.ctrip.zeus.service.query.GroupCriteriaQuery;
<ide> import com.ctrip.zeus.service.query.SlbCriteriaQuery;
<add>import com.ctrip.zeus.support.ObjectJsonParser;
<ide> import com.netflix.config.DynamicBooleanProperty;
<ide> import com.netflix.config.DynamicPropertyFactory;
<ide> import org.aspectj.lang.JoinPoint;
<ide> }
<ide> // 3.3 type is AccessType.GROUP , parse data to Group object.
<ide> if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP) {
<del> Group group = parseGroup(hh.getMediaType(), (String) args[i]);
<add> Group group = parseGroup((String) args[i]);
<ide> if (group == null) {
<ide> return ID_UNKNOW;//"Group Parse Fail";
<ide> }
<ide> }
<ide>
<ide> } else if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP && hh != null) {
<del> Group group = parseGroup(hh.getMediaType(), postData);
<add> Group group = parseGroup(postData);
<ide> if (group == null) {
<ide> data.put("Group", "Group Parse Fail!");
<ide> } else {
<ide> }
<ide> //1.2 in case of update
<ide> Object obj = args[ids[0]];
<del> String tmp = null;
<add> String tmp;
<ide> if (obj instanceof String) {
<ide> tmp = (String) obj;
<ide> } else {
<ide> }
<ide>
<ide> } else if (OperationLogConfig.getInstance().getType(key) == OperationLogType.GROUP && hh != null) {
<del> Group group = parseGroup(hh.getMediaType(), tmp);
<add> Group group = parseGroup(tmp);
<ide> if (group == null) {
<ide> data.put("Group", "Group Parse Fail!");
<ide> } else {
<ide> }
<ide> }
<ide>
<del> private Group parseGroup(MediaType mediaType, String group) {
<del> Group g;
<del> try {
<del> if (mediaType.equals(MediaType.APPLICATION_XML_TYPE)) {
<del> g = DefaultSaxParser.parseEntity(Group.class, group);
<del> } else {
<del> g = DefaultJsonParser.parse(Group.class, group);
<del> }
<del> } catch (Exception e) {
<del> logger.warn("Group Parse Fail!");
<del> return null;
<del> }
<add> private Group parseGroup(String group) {
<add> Group g = ObjectJsonParser.parse(group, Group.class);
<add> trim(g);
<ide> return g;
<ide> }
<ide>
<ide> }
<ide> return s;
<ide> }
<add>
<add> private void trim(Group g) {
<add> g.setAppId(trimIfNotNull(g.getAppId()));
<add> g.setName(trimIfNotNull(g.getName()));
<add> if (g.getHealthCheck() != null)
<add> g.getHealthCheck().setUri(trimIfNotNull(g.getHealthCheck().getUri()));
<add> for (GroupServer groupServer : g.getGroupServers()) {
<add> groupServer.setIp(trimIfNotNull(groupServer.getIp()));
<add> groupServer.setHostName(trimIfNotNull(groupServer.getHostName()));
<add> }
<add> if (g.getLoadBalancingMethod() != null)
<add> g.getLoadBalancingMethod().setValue(trimIfNotNull(g.getLoadBalancingMethod().getValue()));
<add> }
<add>
<add> private String trimIfNotNull(String value) {
<add> return value != null ? value.trim() : value;
<add> }
<ide> } |
|
Java | apache-2.0 | d318e7c3307d5bbd2d0067d95f70e87cf7f2000b | 0 | gianpaj/mongo-java-driver,kay-kim/mongo-java-driver,rozza/mongo-java-driver,rozza/mongo-java-driver,jsonking/mongo-java-driver,jyemin/mongo-java-driver,jsonking/mongo-java-driver,PSCGroup/mongo-java-driver,jyemin/mongo-java-driver | /*
* Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.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.mongodb;
import org.mongodb.MongoConnector;
import org.mongodb.annotations.NotThreadSafe;
import org.mongodb.operation.GetMore;
import org.mongodb.operation.MongoFind;
import org.mongodb.operation.MongoKillCursor;
import org.mongodb.result.QueryResult;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import static com.mongodb.DBObjects.toDocument;
/**
* An iterator over database results. Doing a <code>find()</code> query on a collection returns a <code>DBCursor</code>
* thus
* <p/>
* <blockquote><pre>
* DBCursor cursor = collection.find( query );
* if( cursor.hasNext() )
* DBObject obj = cursor.next();
* </pre></blockquote>
* <p/>
* <p><b>Warning:</b> Calling <code>toArray</code> or <code>length</code> on a DBCursor will irrevocably turn it into an
* array. This means that, if the cursor was iterating over ten million results (which it was lazily fetching from the
* database), suddenly there will be a ten-million element array in memory. Before converting to an array, make sure
* that there are a reasonable number of results using <code>skip()</code> and <code>limit()</code>. <p>For example, to
* get an array of the 1000-1100th elements of a cursor, use
* <p/>
* <blockquote><pre>
* List<DBObject> obj = collection.find( query ).skip( 1000 ).limit( 100 ).toArray();
* </pre></blockquote>
*
* @dochub cursors
*/
@NotThreadSafe
public class DBCursor implements Iterator<DBObject>, Iterable<DBObject>, Closeable {
private final DBCollection collection;
private final MongoFind find;
private CursorType cursorType;
private QueryResult<DBObject> currentResult;
private Iterator<DBObject> currentIterator;
private DBObject currentObject;
private int numSeen;
private boolean closed;
private final List<DBObject> all = new ArrayList<DBObject>();
/**
* Initializes a new database cursor
*
* @param collection collection to use
* @param query query to perform
* @param fields keys to return from the query
* @param readPreference the read preference for this query
*/
public DBCursor(final DBCollection collection, final DBObject query, final DBObject fields, final ReadPreference readPreference) {
if (collection == null) {
throw new IllegalArgumentException("Collection can't be null");
}
this.collection = collection;
find = new MongoFind();
find.where(toDocument(query))
.select(DBObjects.toFieldSelectorDocument(fields))
.readPreference(readPreference.toNew());
}
/**
* Creates a copy of an existing database cursor. The new cursor is an iterator, even if the original was an array.
*
* @return the new cursor
*/
public DBCursor copy() {
return new DBCursor(collection, find);
}
public boolean hasNext() {
if (closed) {
throw new IllegalStateException("Cursor has been closed");
}
if (currentResult == null && currentIterator == null) {
query();
}
if (currentIterator.hasNext()) {
return true;
}
if (find.getLimit() > 0 && find.getLimit() <= numSeen) {
return false;
}
if (currentResult.getCursor() == null) {
return false;
}
getMore();
return currentIterator.hasNext();
}
public DBObject next() {
checkCursorType(CursorType.ITERATOR);
if (!hasNext()) {
throw new NoSuchElementException();
}
return nextInternal();
}
/**
* Returns the element the cursor is at.
*
* @return the next element
*/
public DBObject curr() {
return currentObject;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
/**
* adds a query option - see Bytes.QUERYOPTION_* for list
*
* @param option
* @return
*/
public DBCursor addOption(final int option) {
throw new UnsupportedOperationException(); // TODO
}
/**
* sets the query option - see Bytes.QUERYOPTION_* for list
*
* @param options
*/
public DBCursor setOptions(final int options) {
throw new UnsupportedOperationException(); // TODO
}
/**
* resets the query options
*/
public DBCursor resetOptions() {
throw new UnsupportedOperationException(); // TODO
}
/**
* gets the query options
*
* @return
*/
public int getOptions() {
throw new UnsupportedOperationException(); // TODO
}
/**
* adds a special operator like $maxScan or $returnKey e.g. addSpecial( "$returnKey" , 1 ) e.g. addSpecial(
* "$maxScan" , 100 )
*
* @param name the name of the special query operator
* @param o the value of the special query operator
* @return this
* @dochub specialOperators
*/
public DBCursor addSpecial(final String name, final Object o) {
throw new UnsupportedOperationException(); // TODO
}
/**
* Informs the database of indexed fields of the collection in order to improve performance.
*
* @param indexKeys a <code>DBObject</code> with fields and direction
* @return same DBCursor for chaining operations
*/
public DBCursor hint(final DBObject indexKeys) {
throw new UnsupportedOperationException(); // TODO
}
/**
* Informs the database of an indexed field of the collection in order to improve performance.
*
* @param indexName the name of an index
* @return same DBCursort for chaining operations
*/
public DBCursor hint(final String indexName) {
throw new UnsupportedOperationException(); // TODO
}
/**
* Use snapshot mode for the query. Snapshot mode assures no duplicates are returned, or objects missed, which were
* present at both the start and end of the query's execution (if an object is new during the query, or deleted
* during the query, it may or may not be returned, even with snapshot mode). Note that short query responses (less
* than 1MB) are always effectively snapshot. Currently, snapshot mode may not be used with sorting or explicit
* hints.
*
* @return this
*/
public DBCursor snapshot() {
find.snapshot();
return this;
}
/**
* Returns an object containing basic information about the execution of the query that created this cursor This
* creates a <code>DBObject</code> with the key/value pairs: "cursor" : cursor type "nScanned" : number of records
* examined by the database for this query "n" : the number of records that the database returned "millis" : how
* long it took the database to execute the query
*
* @return a <code>DBObject</code>
* @throws MongoException
* @dochub explain
*/
public DBObject explain() {
throw new UnsupportedOperationException(); // TODO
}
/**
* Sorts this cursor's elements. This method must be called before getting any object from the cursor.
*
* @param orderBy the fields by which to sort
* @return a cursor pointing to the first element of the sorted results
*/
public DBCursor sort(final DBObject orderBy) {
find.order(toDocument(orderBy));
return this;
}
/**
* Limits the number of elements returned. Note: parameter <tt>n</tt> should be positive, although a negative value
* is supported for legacy reason. Passing a negative value will call {@link DBCursor#batchSize(int)} which is the
* preferred method.
*
* @param n the number of elements to return
* @return a cursor to iterate the results
* @dochub limit
*/
public DBCursor limit(final int n) {
find.limit(n);
return this;
}
/**
* Limits the number of elements returned in one batch. A cursor typically fetches a batch of result objects and
* store them locally.
* <p/>
* If <tt>batchSize</tt> is positive, it represents the size of each batch of objects retrieved. It can be adjusted
* to optimize performance and limit data transfer.
* <p/>
* If <tt>batchSize</tt> is negative, it will limit of number objects returned, that fit within the max batch size
* limit (usually 4MB), and cursor will be closed. For example if <tt>batchSize</tt> is -10, then the server will
* return a maximum of 10 documents and as many as can fit in 4MB, then close the cursor. Note that this feature is
* different from limit() in that documents must fit within a maximum size, and it removes the need to send a
* request to close the cursor server-side.
* <p/>
* The batch size can be changed even after a cursor is iterated, in which case the setting will apply on the next
* batch retrieval.
*
* @param n the number of elements to return in a batch
* @return
*/
public DBCursor batchSize(final int n) {
find.batchSize(n);
return this;
}
/**
* Discards a given number of elements at the beginning of the cursor.
*
* @param n the number of elements to skip
* @return a cursor pointing to the new first element of the results
* @throws IllegalStateException if the cursor has started to be iterated through
*/
public DBCursor skip(final int n) {
find.skip(n);
return this;
}
/**
* gets the cursor id.
*
* @return the cursor id, or 0 if there is no active cursor.
*/
public long getCursorId() {
if (currentResult != null && currentResult.getCursor() != null) {
return currentResult.getCursor().getId();
} else {
return 0;
}
}
/**
* gets the number of times, so far, that the cursor retrieved a batch from the database
*
* @return
*/
public int numGetMores() {
throw new UnsupportedOperationException(); // TODO
}
/**
* gets a list containing the number of items received in each batch
*
* @return
*/
public List<Integer> getSizes() {
throw new UnsupportedOperationException(); // TODO
}
/**
* Returns the number of objects through which the cursor has iterated.
*
* @return the number of objects seen
*/
public int numSeen() {
return numSeen;
}
/**
* kills the current cursor on the server.
*/
@Override
public void close() {
closed = true;
if (currentResult != null && currentResult.getCursor() != null) {
getConnector().killCursors(new MongoKillCursor(currentResult.getCursor()));
}
currentResult = null;
currentIterator = null;
currentObject = null;
}
/**
* makes this query ok to run on a slave node
*
* @return a copy of the same cursor (for chaining)
* @see ReadPreference#secondaryPreferred()
* @deprecated Replaced with {@code ReadPreference.secondaryPreferred()}
*/
@Deprecated
public DBCursor slaveOk() {
return addOption(Bytes.QUERYOPTION_SLAVEOK);
}
/**
* creates a copy of this cursor object that can be iterated. Note: - you can iterate the DBCursor itself without
* calling this method - no actual data is getting copied.
*
* @return an iterator
*/
// TODO: document the dangerousness of this method, regarding close...
public Iterator<DBObject> iterator() {
return this.copy();
}
/**
* Converts this cursor to an array.
*
* @return an array of elements
* @throws MongoException
*/
public List<DBObject> toArray() {
return toArray(Integer.MAX_VALUE);
}
/**
* Converts this cursor to an array.
*
* @param max the maximum number of objects to return
* @return an array of objects
* @throws MongoException
*/
public List<DBObject> toArray(final int max) {
checkCursorType(CursorType.ARRAY);
fillArray(max - 1);
return all;
}
/**
* Counts the number of objects matching the query This does not take limit/skip into consideration
*
* @return the number of objects
* @throws MongoException
* @see DBCursor#size
*/
public int count() {
return (int) collection.count(getQuery(), getReadPreference());
// TODO: dangerous cast. Throw exception instead?
}
/**
* pulls back all items into an array and returns the number of objects. Note: this can be resource intensive
*
* @return the number of elements in the array
* @throws MongoException
* @see #count()
* @see #size()
*/
public int length() {
checkCursorType(CursorType.ARRAY);
fillArray(Integer.MAX_VALUE);
return all.size();
}
/**
* for testing only! Iterates cursor and counts objects
*
* @return num objects
* @throws MongoException
* @see #count()
*/
public int itcount() {
int n = 0;
while (this.hasNext()) {
this.next();
n++;
}
return n;
}
/**
* Counts the number of objects matching the query this does take limit/skip into consideration
*
* @return the number of objects
* @throws MongoException
* @see #count()
*/
public int size() {
throw new UnsupportedOperationException(); // TODO
}
/**
* gets the fields to be returned
*
* @return
*/
public DBObject getKeysWanted() {
if (find.getFields() == null) {
return null;
}
return DBObjects.toDBObject(find.getFields());
}
/**
* gets the query
*
* @return
*/
public DBObject getQuery() {
return DBObjects.toDBObject(find.getFilter());
}
/**
* gets the collection
*
* @return
*/
public DBCollection getCollection() {
return collection;
}
/**
* Gets the Server Address of the server that data is pulled from. Note that this information may not be available
* until hasNext() or next() is called.
*
* @return
*/
public ServerAddress getServerAddress() {
if (currentResult == null || currentResult.getCursor() == null) {
return null;
} else {
return new ServerAddress(currentResult.getCursor().getAddress());
}
}
/**
* Sets the read preference for this cursor. See the * documentation for {@link ReadPreference} for more
* information.
*
* @param readPreference read preference to use
*/
public DBCursor setReadPreference(final ReadPreference readPreference) {
find.readPreference(readPreference.toNew());
return this;
}
/**
* Gets the default read preference
*
* @return
*/
public ReadPreference getReadPreference() {
return ReadPreference.fromNew(find.getReadPreference());
}
@Override
public String toString() {
return "DBCursor{" +
"collection=" + collection +
", find=" + find +
(currentResult != null ? (", cursor=" + currentResult.getCursor()) : "") +
'}';
}
private DBCursor(final DBCollection collection, final MongoFind find) {
this.collection = collection;
this.find = new MongoFind(find);
}
/**
* Types of cursors: iterator or array.
*/
static enum CursorType {
ITERATOR,
ARRAY
}
void checkCursorType(final CursorType type) {
if (cursorType == null) {
cursorType = type;
return;
}
if (type == cursorType) {
return;
}
throw new IllegalArgumentException("Can't switch cursor access methods");
}
void fillArray(final int n) {
checkCursorType(CursorType.ARRAY);
while (n >= all.size() && hasNext()) {
all.add(nextInternal());
}
}
private DBObject nextInternal() {
if (cursorType == null) {
checkCursorType(CursorType.ITERATOR);
}
currentObject = currentIterator.next();
numSeen++;
if (find.getFields() != null && !find.getFields().isEmpty()) {
currentObject.markAsPartialObject();
}
return currentObject;
}
private void getMore() {
currentResult = getConnector().getMore(
collection.getNamespace(),
new GetMore(currentResult.getCursor(), find.getBatchSize()),
collection.getObjectSerializer());
currentIterator = currentResult.getResults().iterator();
}
private void query() {
currentResult = getConnector().query(
collection.getNamespace(),
find,
collection.getDocumentSerializer(),
collection.getObjectSerializer());
currentIterator = currentResult.getResults().iterator();
}
private MongoConnector getConnector() {
return getCollection().getConnector();
}
} | driver-compat/src/main/com/mongodb/DBCursor.java | /*
* Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.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.mongodb;
import org.mongodb.MongoConnector;
import org.mongodb.annotations.NotThreadSafe;
import org.mongodb.operation.GetMore;
import org.mongodb.operation.MongoFind;
import org.mongodb.operation.MongoKillCursor;
import org.mongodb.result.QueryResult;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import static com.mongodb.DBObjects.toDocument;
/**
* An iterator over database results. Doing a <code>find()</code> query on a collection returns a <code>DBCursor</code>
* thus
* <p/>
* <blockquote><pre>
* DBCursor cursor = collection.find( query );
* if( cursor.hasNext() )
* DBObject obj = cursor.next();
* </pre></blockquote>
* <p/>
* <p><b>Warning:</b> Calling <code>toArray</code> or <code>length</code> on a DBCursor will irrevocably turn it into an
* array. This means that, if the cursor was iterating over ten million results (which it was lazily fetching from the
* database), suddenly there will be a ten-million element array in memory. Before converting to an array, make sure
* that there are a reasonable number of results using <code>skip()</code> and <code>limit()</code>. <p>For example, to
* get an array of the 1000-1100th elements of a cursor, use
* <p/>
* <blockquote><pre>
* List<DBObject> obj = collection.find( query ).skip( 1000 ).limit( 100 ).toArray();
* </pre></blockquote>
*
* @dochub cursors
*/
@NotThreadSafe
public class DBCursor implements Iterator<DBObject>, Iterable<DBObject>, Closeable {
private final DBCollection collection;
private final MongoFind find;
private CursorType cursorType;
private QueryResult<DBObject> currentResult;
private Iterator<DBObject> currentIterator;
private DBObject currentObject;
private int numSeen;
private boolean closed;
private final List<DBObject> all = new ArrayList<DBObject>();
/**
* Initializes a new database cursor
*
* @param collection collection to use
* @param query query to perform
* @param fields keys to return from the query
* @param readPreference the read preference for this query
*/
public DBCursor(final DBCollection collection, final DBObject query, final DBObject fields, final ReadPreference readPreference) {
if (collection == null) {
throw new IllegalArgumentException("Collection can't be null");
}
this.collection = collection;
find = new MongoFind();
find.where(toDocument(query))
.select(DBObjects.toFieldSelectorDocument(fields))
.readPreference(readPreference.toNew());
}
/**
* Creates a copy of an existing database cursor. The new cursor is an iterator, even if the original was an array.
*
* @return the new cursor
*/
public DBCursor copy() {
return new DBCursor(collection, find);
}
public boolean hasNext() {
if (closed) {
throw new IllegalStateException("Cursor has been closed");
}
if (currentResult == null && currentIterator == null) {
query();
}
if (currentIterator.hasNext()) {
return true;
}
if (find.getLimit() > 0 && find.getLimit() <= numSeen) {
return false;
}
if (currentResult.getCursor() == null) {
return false;
}
getMore();
return currentIterator.hasNext();
}
public DBObject next() {
checkCursorType(CursorType.ITERATOR);
if (!hasNext()) {
throw new NoSuchElementException();
}
return nextInternal();
}
/**
* Returns the element the cursor is at.
*
* @return the next element
*/
public DBObject curr() {
return currentObject;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
/**
* adds a query option - see Bytes.QUERYOPTION_* for list
*
* @param option
* @return
*/
public DBCursor addOption(final int option) {
throw new UnsupportedOperationException(); // TODO
}
/**
* sets the query option - see Bytes.QUERYOPTION_* for list
*
* @param options
*/
public DBCursor setOptions(final int options) {
throw new UnsupportedOperationException(); // TODO
}
/**
* resets the query options
*/
public DBCursor resetOptions() {
throw new UnsupportedOperationException(); // TODO
}
/**
* gets the query options
*
* @return
*/
public int getOptions() {
throw new UnsupportedOperationException(); // TODO
}
/**
* adds a special operator like $maxScan or $returnKey e.g. addSpecial( "$returnKey" , 1 ) e.g. addSpecial(
* "$maxScan" , 100 )
*
* @param name the name of the special query operator
* @param o the value of the special query operator
* @return this
* @dochub specialOperators
*/
public DBCursor addSpecial(final String name, final Object o) {
throw new UnsupportedOperationException(); // TODO
}
/**
* Informs the database of indexed fields of the collection in order to improve performance.
*
* @param indexKeys a <code>DBObject</code> with fields and direction
* @return same DBCursor for chaining operations
*/
public DBCursor hint(final DBObject indexKeys) {
throw new UnsupportedOperationException(); // TODO
}
/**
* Informs the database of an indexed field of the collection in order to improve performance.
*
* @param indexName the name of an index
* @return same DBCursort for chaining operations
*/
public DBCursor hint(final String indexName) {
throw new UnsupportedOperationException(); // TODO
}
/**
* Use snapshot mode for the query. Snapshot mode assures no duplicates are returned, or objects missed, which were
* present at both the start and end of the query's execution (if an object is new during the query, or deleted
* during the query, it may or may not be returned, even with snapshot mode). Note that short query responses (less
* than 1MB) are always effectively snapshot. Currently, snapshot mode may not be used with sorting or explicit
* hints.
*
* @return this
*/
public DBCursor snapshot() {
find.snapshot();
return this;
}
/**
* Returns an object containing basic information about the execution of the query that created this cursor This
* creates a <code>DBObject</code> with the key/value pairs: "cursor" : cursor type "nScanned" : number of records
* examined by the database for this query "n" : the number of records that the database returned "millis" : how
* long it took the database to execute the query
*
* @return a <code>DBObject</code>
* @throws MongoException
* @dochub explain
*/
public DBObject explain() {
throw new UnsupportedOperationException(); // TODO
}
/**
* Sorts this cursor's elements. This method must be called before getting any object from the cursor.
*
* @param orderBy the fields by which to sort
* @return a cursor pointing to the first element of the sorted results
*/
public DBCursor sort(final DBObject orderBy) {
find.order(toDocument(orderBy));
return this;
}
/**
* Limits the number of elements returned. Note: parameter <tt>n</tt> should be positive, although a negative value
* is supported for legacy reason. Passing a negative value will call {@link DBCursor#batchSize(int)} which is the
* preferred method.
*
* @param n the number of elements to return
* @return a cursor to iterate the results
* @dochub limit
*/
public DBCursor limit(final int n) {
find.limit(n);
return this;
}
/**
* Limits the number of elements returned in one batch. A cursor typically fetches a batch of result objects and
* store them locally.
* <p/>
* If <tt>batchSize</tt> is positive, it represents the size of each batch of objects retrieved. It can be adjusted
* to optimize performance and limit data transfer.
* <p/>
* If <tt>batchSize</tt> is negative, it will limit of number objects returned, that fit within the max batch size
* limit (usually 4MB), and cursor will be closed. For example if <tt>batchSize</tt> is -10, then the server will
* return a maximum of 10 documents and as many as can fit in 4MB, then close the cursor. Note that this feature is
* different from limit() in that documents must fit within a maximum size, and it removes the need to send a
* request to close the cursor server-side.
* <p/>
* The batch size can be changed even after a cursor is iterated, in which case the setting will apply on the next
* batch retrieval.
*
* @param n the number of elements to return in a batch
* @return
*/
public DBCursor batchSize(final int n) {
find.batchSize(n);
return this;
}
/**
* Discards a given number of elements at the beginning of the cursor.
*
* @param n the number of elements to skip
* @return a cursor pointing to the new first element of the results
* @throws IllegalStateException if the cursor has started to be iterated through
*/
public DBCursor skip(final int n) {
find.skip(n);
return this;
}
/**
* gets the cursor id.
*
* @return the cursor id, or 0 if there is no active cursor.
*/
public long getCursorId() {
if (currentResult != null && currentResult.getCursor() != null) {
return currentResult.getCursor().getId();
} else {
return 0;
}
}
/**
* gets the number of times, so far, that the cursor retrieved a batch from the database
*
* @return
*/
public int numGetMores() {
throw new UnsupportedOperationException(); // TODO
}
/**
* gets a list containing the number of items received in each batch
*
* @return
*/
public List<Integer> getSizes() {
throw new UnsupportedOperationException(); // TODO
}
/**
* Returns the number of objects through which the cursor has iterated.
*
* @return the number of objects seen
*/
public int numSeen() {
return numSeen;
}
/**
* kills the current cursor on the server.
*/
@Override
public void close() {
closed = true;
if (currentResult != null && currentResult.getCursor() != null) {
getConnector().killCursors(new MongoKillCursor(currentResult.getCursor()));
}
currentResult = null;
currentIterator = null;
currentObject = null;
}
/**
* makes this query ok to run on a slave node
*
* @return a copy of the same cursor (for chaining)
* @see ReadPreference#secondaryPreferred()
* @deprecated Replaced with {@code ReadPreference.secondaryPreferred()}
*/
@Deprecated
public DBCursor slaveOk() {
return addOption(Bytes.QUERYOPTION_SLAVEOK);
}
/**
* creates a copy of this cursor object that can be iterated. Note: - you can iterate the DBCursor itself without
* calling this method - no actual data is getting copied.
*
* @return an iterator
*/
// TODO: document the dangerousness of this method, regarding close...
public Iterator<DBObject> iterator() {
return this.copy();
}
/**
* Converts this cursor to an array.
*
* @return an array of elements
* @throws MongoException
*/
public List<DBObject> toArray() {
return toArray(Integer.MAX_VALUE);
}
/**
* Converts this cursor to an array.
*
* @param max the maximum number of objects to return
* @return an array of objects
* @throws MongoException
*/
public List<DBObject> toArray(final int max) {
checkCursorType(CursorType.ARRAY);
fillArray(max - 1);
return all;
}
/**
* Counts the number of objects matching the query This does not take limit/skip into consideration
*
* @return the number of objects
* @throws MongoException
* @see DBCursor#size
*/
public int count() {
return (int) collection.count(getQuery(), getReadPreference());
// TODO: dangerous cast. Throw exception instead?
}
/**
* pulls back all items into an array and returns the number of objects. Note: this can be resource intensive
*
* @return the number of elements in the array
* @throws MongoException
* @see #count()
* @see #size()
*/
public int length() {
checkCursorType(CursorType.ARRAY);
fillArray(Integer.MAX_VALUE);
return all.size();
}
/**
* for testing only! Iterates cursor and counts objects
*
* @return num objects
* @throws MongoException
* @see #count()
*/
public int itcount() {
int n = 0;
while (this.hasNext()) {
this.next();
n++;
}
return n;
}
/**
* Counts the number of objects matching the query this does take limit/skip into consideration
*
* @return the number of objects
* @throws MongoException
* @see #count()
*/
public int size() {
throw new UnsupportedOperationException(); // TODO
}
/**
* gets the fields to be returned
*
* @return
*/
public DBObject getKeysWanted() {
if (find.getFields() == null) {
return null;
}
return DBObjects.toDBObject(find.getFields());
}
/**
* gets the query
*
* @return
*/
public DBObject getQuery() {
return DBObjects.toDBObject(find.getFilter());
}
/**
* gets the collection
*
* @return
*/
public DBCollection getCollection() {
return collection;
}
/**
* Gets the Server Address of the server that data is pulled from. Note that this information may not be available
* until hasNext() or next() is called.
*
* @return
*/
public ServerAddress getServerAddress() {
if (currentResult == null || currentResult.getCursor() == null) {
return null;
} else {
return new ServerAddress(currentResult.getCursor().getAddress());
}
}
/**
* Sets the read preference for this cursor. See the * documentation for {@link ReadPreference} for more
* information.
*
* @param readPreference read preference to use
*/
public DBCursor setReadPreference(final ReadPreference readPreference) {
find.readPreference(readPreference.toNew());
return this;
}
/**
* Gets the default read preference
*
* @return
*/
public ReadPreference getReadPreference() {
return ReadPreference.fromNew(find.getReadPreference());
}
@Override
public String toString() {
return "DBCursor{" +
"collection=" + collection +
", find=" + find +
(currentResult != null ? (", cursor=" + currentResult.getCursor()) : "") +
'}';
}
private DBCursor(final DBCollection collection, final MongoFind find) {
this.collection = collection;
this.find = new MongoFind(find);
}
/**
* Types of cursors: iterator or array.
*/
static enum CursorType {
ITERATOR,
ARRAY
}
void checkCursorType(final CursorType type) {
if (cursorType == null) {
cursorType = type;
return;
}
if (type == cursorType) {
return;
}
throw new IllegalArgumentException("Can't switch cursor access methods");
}
void fillArray(final int n) {
checkCursorType(CursorType.ARRAY);
while (n >= all.size() && hasNext()) {
all.add(nextInternal());
}
}
private DBObject nextInternal() {
if (cursorType == null) {
checkCursorType(CursorType.ITERATOR);
}
currentObject = currentIterator.next();
numSeen++;
if (find.getFields() != null && !find.getFields().isEmpty()) {
currentObject.markAsPartialObject();
}
return currentObject;
}
private void getMore() {
currentResult = getConnector().getMore(
collection.getNamespace(),
new GetMore(currentResult.getCursor(), find.getBatchSize()),
collection.getObjectSerializer());
currentIterator = currentResult.getResults().iterator();
}
private void query() {
currentResult = getConnector().query(
collection.getNamespace(),
find,
collection.getDocumentSerializer(),
collection.getObjectSerializer());
currentIterator = currentResult.getResults().iterator();
}
protected MongoConnector getConnector() {
return getCollection().getConnector();
}
} | Changed visibility of getConnector method to private
| driver-compat/src/main/com/mongodb/DBCursor.java | Changed visibility of getConnector method to private | <ide><path>river-compat/src/main/com/mongodb/DBCursor.java
<ide> currentIterator = currentResult.getResults().iterator();
<ide> }
<ide>
<del> protected MongoConnector getConnector() {
<add> private MongoConnector getConnector() {
<ide> return getCollection().getConnector();
<ide> }
<del>
<ide> } |
|
Java | mit | 80a570e26bf479af0fbe4c106480440ac332637f | 0 | j0ergo/react-native-maps,wannyk/react-native-maps,zigbang/react-native-maps,pjamrozowicz/react-native-maps,wannyk/react-native-maps,wannyk/react-native-maps,pjamrozowicz/react-native-maps,parkling/react-native-maps,j0ergo/react-native-maps,lelandrichardson/react-native-maps,lelandrichardson/react-native-maps,pjamrozowicz/react-native-maps,parkling/react-native-maps,lelandrichardson/react-native-maps,wannyk/react-native-maps,j0ergo/react-native-maps,zigbang/react-native-maps,zigbang/react-native-maps,parkling/react-native-maps | package com.airbnb.android.react.maps;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Handler;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.VisibleRegion;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.support.v4.content.PermissionChecker.checkSelfPermission;
public class AirMapView extends MapView implements GoogleMap.InfoWindowAdapter,
GoogleMap.OnMarkerDragListener, OnMapReadyCallback {
public GoogleMap map;
private ProgressBar mapLoadingProgressBar;
private RelativeLayout mapLoadingLayout;
private ImageView cacheImageView;
private Boolean isMapLoaded = false;
private Integer loadingBackgroundColor = null;
private Integer loadingIndicatorColor = null;
private final int baseMapPadding = 50;
private LatLngBounds boundsToMove;
private boolean showUserLocation = false;
private boolean isMonitoringRegion = false;
private boolean isTouchDown = false;
private boolean handlePanDrag = false;
private boolean moveOnMarkerPress = true;
private boolean cacheEnabled = false;
private static final String[] PERMISSIONS = new String[]{
"android.permission.ACCESS_FINE_LOCATION", "android.permission.ACCESS_COARSE_LOCATION"};
private final List<AirMapFeature> features = new ArrayList<>();
private final Map<Marker, AirMapMarker> markerMap = new HashMap<>();
private final Map<Polyline, AirMapPolyline> polylineMap = new HashMap<>();
private final Map<Polygon, AirMapPolygon> polygonMap = new HashMap<>();
private final ScaleGestureDetector scaleDetector;
private final GestureDetectorCompat gestureDetector;
private final AirMapManager manager;
private LifecycleEventListener lifecycleListener;
private boolean paused = false;
private boolean destroyed = false;
private final ThemedReactContext context;
private final EventDispatcher eventDispatcher;
private static boolean contextHasBug(Context context) {
return context == null ||
context.getResources() == null ||
context.getResources().getConfiguration() == null;
}
// We do this to fix this bug:
// https://github.com/airbnb/react-native-maps/issues/271
//
// which conflicts with another bug regarding the passed in context:
// https://github.com/airbnb/react-native-maps/issues/1147
//
// Doing this allows us to avoid both bugs.
private static Context getNonBuggyContext(ThemedReactContext reactContext,
ReactApplicationContext appContext) {
Context superContext = reactContext;
if (!contextHasBug(appContext.getCurrentActivity())) {
superContext = appContext.getCurrentActivity();
} else if (contextHasBug(superContext)) {
// we have the bug! let's try to find a better context to use
if (!contextHasBug(reactContext.getCurrentActivity())) {
superContext = reactContext.getCurrentActivity();
} else if (!contextHasBug(reactContext.getApplicationContext())) {
superContext = reactContext.getApplicationContext();
} else {
// ยฏ\_(ใ)_/ยฏ
}
}
return superContext;
}
public AirMapView(ThemedReactContext reactContext, ReactApplicationContext appContext,
AirMapManager manager,
GoogleMapOptions googleMapOptions) {
super(getNonBuggyContext(reactContext, appContext), googleMapOptions);
this.manager = manager;
this.context = reactContext;
super.onCreate(null);
// TODO(lmr): what about onStart????
super.onResume();
super.getMapAsync(this);
final AirMapView view = this;
scaleDetector =
new ScaleGestureDetector(reactContext,
new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
view.startMonitoringRegion();
return true; // stop recording this gesture. let mapview handle it.
}
});
gestureDetector =
new GestureDetectorCompat(reactContext, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
view.startMonitoringRegion();
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
if (handlePanDrag) {
onPanDrag(e2);
}
view.startMonitoringRegion();
return false;
}
});
this.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (!paused) {
AirMapView.this.cacheView();
}
}
});
eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
}
@Override
public void onMapReady(final GoogleMap map) {
if (destroyed) {
return;
}
this.map = map;
this.map.setInfoWindowAdapter(this);
this.map.setOnMarkerDragListener(this);
manager.pushEvent(context, this, "onMapReady", new WritableNativeMap());
final AirMapView view = this;
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
WritableMap event;
AirMapMarker airMapMarker = markerMap.get(marker);
event = makeClickEventData(marker.getPosition());
event.putString("action", "marker-press");
event.putString("id", airMapMarker.getIdentifier());
manager.pushEvent(context, view, "onMarkerPress", event);
event = makeClickEventData(marker.getPosition());
event.putString("action", "marker-press");
event.putString("id", airMapMarker.getIdentifier());
manager.pushEvent(context, markerMap.get(marker), "onPress", event);
// Return false to open the callout info window and center on the marker
// https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap
// .OnMarkerClickListener
if (view.moveOnMarkerPress) {
return false;
} else {
marker.showInfoWindow();
return true;
}
}
});
map.setOnPolygonClickListener(new GoogleMap.OnPolygonClickListener() {
@Override
public void onPolygonClick(Polygon polygon) {
WritableMap event = makeClickEventData(polygon.getPoints().get(0));
event.putString("action", "polygon-press");
manager.pushEvent(context, polygonMap.get(polygon), "onPress", event);
}
});
map.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
@Override
public void onPolylineClick(Polyline polyline) {
WritableMap event = makeClickEventData(polyline.getPoints().get(0));
event.putString("action", "polyline-press");
manager.pushEvent(context, polylineMap.get(polyline), "onPress", event);
}
});
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
WritableMap event;
event = makeClickEventData(marker.getPosition());
event.putString("action", "callout-press");
manager.pushEvent(context, view, "onCalloutPress", event);
event = makeClickEventData(marker.getPosition());
event.putString("action", "callout-press");
AirMapMarker markerView = markerMap.get(marker);
manager.pushEvent(context, markerView, "onCalloutPress", event);
event = makeClickEventData(marker.getPosition());
event.putString("action", "callout-press");
AirMapCallout infoWindow = markerView.getCalloutView();
if (infoWindow != null) manager.pushEvent(context, infoWindow, "onPress", event);
}
});
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
WritableMap event = makeClickEventData(point);
event.putString("action", "press");
manager.pushEvent(context, view, "onPress", event);
}
});
map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng point) {
WritableMap event = makeClickEventData(point);
event.putString("action", "long-press");
manager.pushEvent(context, view, "onLongPress", makeClickEventData(point));
}
});
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
LatLngBounds bounds = map.getProjection().getVisibleRegion().latLngBounds;
LatLng center = position.target;
lastBoundsEmitted = bounds;
eventDispatcher.dispatchEvent(new RegionChangeEvent(getId(), bounds, center, isTouchDown));
view.stopMonitoringRegion();
}
});
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override public void onMapLoaded() {
isMapLoaded = true;
AirMapView.this.cacheView();
}
});
// We need to be sure to disable location-tracking when app enters background, in-case some
// other module
// has acquired a wake-lock and is controlling location-updates, otherwise, location-manager
// will be left
// updating location constantly, killing the battery, even though some other location-mgmt
// module may
// desire to shut-down location-services.
lifecycleListener = new LifecycleEventListener() {
@Override
public void onHostResume() {
if (hasPermissions()) {
//noinspection MissingPermission
map.setMyLocationEnabled(showUserLocation);
}
synchronized (AirMapView.this) {
if (!destroyed) {
AirMapView.this.onResume();
}
paused = false;
}
}
@Override
public void onHostPause() {
if (hasPermissions()) {
//noinspection MissingPermission
map.setMyLocationEnabled(false);
}
synchronized (AirMapView.this) {
if (!destroyed) {
AirMapView.this.onPause();
}
paused = true;
}
}
@Override
public void onHostDestroy() {
AirMapView.this.doDestroy();
}
};
context.addLifecycleEventListener(lifecycleListener);
}
private boolean hasPermissions() {
return checkSelfPermission(getContext(), PERMISSIONS[0]) == PackageManager.PERMISSION_GRANTED ||
checkSelfPermission(getContext(), PERMISSIONS[1]) == PackageManager.PERMISSION_GRANTED;
}
/*
onDestroy is final method so I can't override it.
*/
public synchronized void doDestroy() {
if (destroyed) {
return;
}
destroyed = true;
if (lifecycleListener != null && context != null) {
context.removeLifecycleEventListener(lifecycleListener);
lifecycleListener = null;
}
if (!paused) {
onPause();
paused = true;
}
onDestroy();
}
public void setRegion(ReadableMap region) {
if (region == null) return;
Double lng = region.getDouble("longitude");
Double lat = region.getDouble("latitude");
Double lngDelta = region.getDouble("longitudeDelta");
Double latDelta = region.getDouble("latitudeDelta");
LatLngBounds bounds = new LatLngBounds(
new LatLng(lat - latDelta / 2, lng - lngDelta / 2), // southwest
new LatLng(lat + latDelta / 2, lng + lngDelta / 2) // northeast
);
if (super.getHeight() <= 0 || super.getWidth() <= 0) {
// in this case, our map has not been laid out yet, so we save the bounds in a local
// variable, and make a guess of zoomLevel 10. Not to worry, though: as soon as layout
// occurs, we will move the camera to the saved bounds. Note that if we tried to move
// to the bounds now, it would trigger an exception.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
boundsToMove = bounds;
} else {
map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 0));
boundsToMove = null;
}
}
public void setShowsUserLocation(boolean showUserLocation) {
this.showUserLocation = showUserLocation; // hold onto this for lifecycle handling
if (hasPermissions()) {
//noinspection MissingPermission
map.setMyLocationEnabled(showUserLocation);
}
}
public void setShowsMyLocationButton(boolean showMyLocationButton) {
if (hasPermissions()) {
map.getUiSettings().setMyLocationButtonEnabled(showMyLocationButton);
}
}
public void setToolbarEnabled(boolean toolbarEnabled) {
if (hasPermissions()) {
map.getUiSettings().setMapToolbarEnabled(toolbarEnabled);
}
}
public void setCacheEnabled(boolean cacheEnabled) {
this.cacheEnabled = cacheEnabled;
this.cacheView();
}
public void enableMapLoading(boolean loadingEnabled) {
if (loadingEnabled && !this.isMapLoaded) {
this.getMapLoadingLayoutView().setVisibility(View.VISIBLE);
}
}
public void setMoveOnMarkerPress(boolean moveOnPress) {
this.moveOnMarkerPress = moveOnPress;
}
public void setLoadingBackgroundColor(Integer loadingBackgroundColor) {
this.loadingBackgroundColor = loadingBackgroundColor;
if (this.mapLoadingLayout != null) {
if (loadingBackgroundColor == null) {
this.mapLoadingLayout.setBackgroundColor(Color.WHITE);
} else {
this.mapLoadingLayout.setBackgroundColor(this.loadingBackgroundColor);
}
}
}
public void setLoadingIndicatorColor(Integer loadingIndicatorColor) {
this.loadingIndicatorColor = loadingIndicatorColor;
if (this.mapLoadingProgressBar != null) {
Integer color = loadingIndicatorColor;
if (color == null) {
color = Color.parseColor("#606060");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ColorStateList progressTintList = ColorStateList.valueOf(loadingIndicatorColor);
ColorStateList secondaryProgressTintList = ColorStateList.valueOf(loadingIndicatorColor);
ColorStateList indeterminateTintList = ColorStateList.valueOf(loadingIndicatorColor);
this.mapLoadingProgressBar.setProgressTintList(progressTintList);
this.mapLoadingProgressBar.setSecondaryProgressTintList(secondaryProgressTintList);
this.mapLoadingProgressBar.setIndeterminateTintList(indeterminateTintList);
} else {
PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
mode = PorterDuff.Mode.MULTIPLY;
}
if (this.mapLoadingProgressBar.getIndeterminateDrawable() != null)
this.mapLoadingProgressBar.getIndeterminateDrawable().setColorFilter(color, mode);
if (this.mapLoadingProgressBar.getProgressDrawable() != null)
this.mapLoadingProgressBar.getProgressDrawable().setColorFilter(color, mode);
}
}
}
public void setHandlePanDrag(boolean handlePanDrag) {
this.handlePanDrag = handlePanDrag;
}
public void addFeature(View child, int index) {
// Our desired API is to pass up annotations/overlays as children to the mapview component.
// This is where we intercept them and do the appropriate underlying mapview action.
if (child instanceof AirMapMarker) {
AirMapMarker annotation = (AirMapMarker) child;
annotation.addToMap(map);
features.add(index, annotation);
Marker marker = (Marker) annotation.getFeature();
markerMap.put(marker, annotation);
} else if (child instanceof AirMapPolyline) {
AirMapPolyline polylineView = (AirMapPolyline) child;
polylineView.addToMap(map);
features.add(index, polylineView);
Polyline polyline = (Polyline) polylineView.getFeature();
polylineMap.put(polyline, polylineView);
} else if (child instanceof AirMapPolygon) {
AirMapPolygon polygonView = (AirMapPolygon) child;
polygonView.addToMap(map);
features.add(index, polygonView);
Polygon polygon = (Polygon) polygonView.getFeature();
polygonMap.put(polygon, polygonView);
} else if (child instanceof AirMapCircle) {
AirMapCircle circleView = (AirMapCircle) child;
circleView.addToMap(map);
features.add(index, circleView);
} else if (child instanceof AirMapUrlTile) {
AirMapUrlTile urlTileView = (AirMapUrlTile) child;
urlTileView.addToMap(map);
features.add(index, urlTileView);
} else {
ViewGroup children = (ViewGroup) child;
for (int i = 0; i < children.getChildCount(); i++) {
addFeature(children.getChildAt(i), index);
}
}
}
public int getFeatureCount() {
return features.size();
}
public View getFeatureAt(int index) {
return features.get(index);
}
public void removeFeatureAt(int index) {
AirMapFeature feature = features.remove(index);
if (feature instanceof AirMapMarker) {
markerMap.remove(feature.getFeature());
}
feature.removeFromMap(map);
}
public WritableMap makeClickEventData(LatLng point) {
WritableMap event = new WritableNativeMap();
WritableMap coordinate = new WritableNativeMap();
coordinate.putDouble("latitude", point.latitude);
coordinate.putDouble("longitude", point.longitude);
event.putMap("coordinate", coordinate);
Projection projection = map.getProjection();
Point screenPoint = projection.toScreenLocation(point);
WritableMap position = new WritableNativeMap();
position.putDouble("x", screenPoint.x);
position.putDouble("y", screenPoint.y);
event.putMap("position", position);
return event;
}
public void updateExtraData(Object extraData) {
// if boundsToMove is not null, we now have the MapView's width/height, so we can apply
// a proper camera move
if (boundsToMove != null) {
HashMap<String, Float> data = (HashMap<String, Float>) extraData;
int width = data.get("width") == null ? 0 : data.get("width").intValue();
int height = data.get("height") == null ? 0 : data.get("height").intValue();
//fix for https://github.com/airbnb/react-native-maps/issues/245,
//it's not guaranteed the passed-in height and width would be greater than 0.
if (width <= 0 || height <= 0) {
map.moveCamera(CameraUpdateFactory.newLatLngBounds(boundsToMove, 0));
} else {
map.moveCamera(CameraUpdateFactory.newLatLngBounds(boundsToMove, width, height, 0));
}
boundsToMove = null;
}
}
public void animateToRegion(LatLngBounds bounds, int duration) {
if (map != null) {
startMonitoringRegion();
map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 0), duration, null);
}
}
public void animateToCoordinate(LatLng coordinate, int duration) {
if (map != null) {
startMonitoringRegion();
map.animateCamera(CameraUpdateFactory.newLatLng(coordinate), duration, null);
}
}
public void fitToElements(boolean animated) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
boolean addedPosition = false;
for (AirMapFeature feature : features) {
if (feature instanceof AirMapMarker) {
Marker marker = (Marker) feature.getFeature();
builder.include(marker.getPosition());
addedPosition = true;
}
// TODO(lmr): may want to include shapes / etc.
}
if (addedPosition) {
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, baseMapPadding);
if (animated) {
startMonitoringRegion();
map.animateCamera(cu);
} else {
map.moveCamera(cu);
}
}
}
public void fitToSuppliedMarkers(ReadableArray markerIDsArray, boolean animated) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
String[] markerIDs = new String[markerIDsArray.size()];
for (int i = 0; i < markerIDsArray.size(); i++) {
markerIDs[i] = markerIDsArray.getString(i);
}
boolean addedPosition = false;
List<String> markerIDList = Arrays.asList(markerIDs);
for (AirMapFeature feature : features) {
if (feature instanceof AirMapMarker) {
String identifier = ((AirMapMarker) feature).getIdentifier();
Marker marker = (Marker) feature.getFeature();
if (markerIDList.contains(identifier)) {
builder.include(marker.getPosition());
addedPosition = true;
}
}
}
if (addedPosition) {
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, baseMapPadding);
if (animated) {
startMonitoringRegion();
map.animateCamera(cu);
} else {
map.moveCamera(cu);
}
}
}
public void fitToCoordinates(ReadableArray coordinatesArray, ReadableMap edgePadding,
boolean animated) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (int i = 0; i < coordinatesArray.size(); i++) {
ReadableMap latLng = coordinatesArray.getMap(i);
Double lat = latLng.getDouble("latitude");
Double lng = latLng.getDouble("longitude");
builder.include(new LatLng(lat, lng));
}
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, baseMapPadding);
if (edgePadding != null) {
map.setPadding(edgePadding.getInt("left"), edgePadding.getInt("top"),
edgePadding.getInt("right"), edgePadding.getInt("bottom"));
}
if (animated) {
startMonitoringRegion();
map.animateCamera(cu);
} else {
map.moveCamera(cu);
}
map.setPadding(0, 0, 0,
0); // Without this, the Google logo is moved up by the value of edgePadding.bottom
}
// InfoWindowAdapter interface
@Override
public View getInfoWindow(Marker marker) {
AirMapMarker markerView = markerMap.get(marker);
return markerView.getCallout();
}
@Override
public View getInfoContents(Marker marker) {
AirMapMarker markerView = markerMap.get(marker);
return markerView.getInfoContents();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
scaleDetector.onTouchEvent(ev);
gestureDetector.onTouchEvent(ev);
int action = MotionEventCompat.getActionMasked(ev);
switch (action) {
case (MotionEvent.ACTION_DOWN):
this.getParent().requestDisallowInterceptTouchEvent(
map != null && map.getUiSettings().isScrollGesturesEnabled());
isTouchDown = true;
break;
case (MotionEvent.ACTION_MOVE):
startMonitoringRegion();
break;
case (MotionEvent.ACTION_UP):
// Clear this regardless, since isScrollGesturesEnabled() may have been updated
this.getParent().requestDisallowInterceptTouchEvent(false);
isTouchDown = false;
break;
}
super.dispatchTouchEvent(ev);
return true;
}
// Timer Implementation
public void startMonitoringRegion() {
if (map == null || isMonitoringRegion) return;
timerHandler.postDelayed(timerRunnable, 100);
isMonitoringRegion = true;
}
public void stopMonitoringRegion() {
if (map == null || !isMonitoringRegion) return;
timerHandler.removeCallbacks(timerRunnable);
isMonitoringRegion = false;
}
private LatLngBounds lastBoundsEmitted;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
if (map != null) {
Projection projection = map.getProjection();
VisibleRegion region = (projection != null) ? projection.getVisibleRegion() : null;
LatLngBounds bounds = (region != null) ? region.latLngBounds : null;
if ((bounds != null) &&
(lastBoundsEmitted == null ||
LatLngBoundsUtils.BoundsAreDifferent(bounds, lastBoundsEmitted))) {
LatLng center = map.getCameraPosition().target;
lastBoundsEmitted = bounds;
eventDispatcher.dispatchEvent(new RegionChangeEvent(getId(), bounds, center, true));
}
}
timerHandler.postDelayed(this, 100);
}
};
@Override
public void onMarkerDragStart(Marker marker) {
WritableMap event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, this, "onMarkerDragStart", event);
AirMapMarker markerView = markerMap.get(marker);
event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, markerView, "onDragStart", event);
}
@Override
public void onMarkerDrag(Marker marker) {
WritableMap event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, this, "onMarkerDrag", event);
AirMapMarker markerView = markerMap.get(marker);
event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, markerView, "onDrag", event);
}
@Override
public void onMarkerDragEnd(Marker marker) {
WritableMap event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, this, "onMarkerDragEnd", event);
AirMapMarker markerView = markerMap.get(marker);
event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, markerView, "onDragEnd", event);
}
private ProgressBar getMapLoadingProgressBar() {
if (this.mapLoadingProgressBar == null) {
this.mapLoadingProgressBar = new ProgressBar(getContext());
this.mapLoadingProgressBar.setIndeterminate(true);
}
if (this.loadingIndicatorColor != null) {
this.setLoadingIndicatorColor(this.loadingIndicatorColor);
}
return this.mapLoadingProgressBar;
}
private RelativeLayout getMapLoadingLayoutView() {
if (this.mapLoadingLayout == null) {
this.mapLoadingLayout = new RelativeLayout(getContext());
this.mapLoadingLayout.setBackgroundColor(Color.LTGRAY);
this.addView(this.mapLoadingLayout,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
this.mapLoadingLayout.addView(this.getMapLoadingProgressBar(), params);
this.mapLoadingLayout.setVisibility(View.INVISIBLE);
}
this.setLoadingBackgroundColor(this.loadingBackgroundColor);
return this.mapLoadingLayout;
}
private ImageView getCacheImageView() {
if (this.cacheImageView == null) {
this.cacheImageView = new ImageView(getContext());
this.addView(this.cacheImageView,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
this.cacheImageView.setVisibility(View.INVISIBLE);
}
return this.cacheImageView;
}
private void removeCacheImageView() {
if (this.cacheImageView != null) {
((ViewGroup) this.cacheImageView.getParent()).removeView(this.cacheImageView);
this.cacheImageView = null;
}
}
private void removeMapLoadingProgressBar() {
if (this.mapLoadingProgressBar != null) {
((ViewGroup) this.mapLoadingProgressBar.getParent()).removeView(this.mapLoadingProgressBar);
this.mapLoadingProgressBar = null;
}
}
private void removeMapLoadingLayoutView() {
this.removeMapLoadingProgressBar();
if (this.mapLoadingLayout != null) {
((ViewGroup) this.mapLoadingLayout.getParent()).removeView(this.mapLoadingLayout);
this.mapLoadingLayout = null;
}
}
private void cacheView() {
if (this.cacheEnabled) {
final ImageView cacheImageView = this.getCacheImageView();
final RelativeLayout mapLoadingLayout = this.getMapLoadingLayoutView();
cacheImageView.setVisibility(View.INVISIBLE);
mapLoadingLayout.setVisibility(View.VISIBLE);
if (this.isMapLoaded) {
this.map.snapshot(new GoogleMap.SnapshotReadyCallback() {
@Override public void onSnapshotReady(Bitmap bitmap) {
cacheImageView.setImageBitmap(bitmap);
cacheImageView.setVisibility(View.VISIBLE);
mapLoadingLayout.setVisibility(View.INVISIBLE);
}
});
}
} else {
this.removeCacheImageView();
if (this.isMapLoaded) {
this.removeMapLoadingLayoutView();
}
}
}
public void onPanDrag(MotionEvent ev) {
Point point = new Point((int) ev.getX(), (int) ev.getY());
LatLng coords = this.map.getProjection().fromScreenLocation(point);
WritableMap event = makeClickEventData(coords);
manager.pushEvent(context, this, "onPanDrag", event);
}
}
| lib/android/src/main/java/com/airbnb/android/react/maps/AirMapView.java | package com.airbnb.android.react.maps;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Handler;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.VisibleRegion;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.support.v4.content.PermissionChecker.checkSelfPermission;
public class AirMapView extends MapView implements GoogleMap.InfoWindowAdapter,
GoogleMap.OnMarkerDragListener, OnMapReadyCallback {
public GoogleMap map;
private ProgressBar mapLoadingProgressBar;
private RelativeLayout mapLoadingLayout;
private ImageView cacheImageView;
private Boolean isMapLoaded = false;
private Integer loadingBackgroundColor = null;
private Integer loadingIndicatorColor = null;
private final int baseMapPadding = 50;
private LatLngBounds boundsToMove;
private boolean showUserLocation = false;
private boolean isMonitoringRegion = false;
private boolean isTouchDown = false;
private boolean handlePanDrag = false;
private boolean moveOnMarkerPress = true;
private boolean cacheEnabled = false;
private static final String[] PERMISSIONS = new String[]{
"android.permission.ACCESS_FINE_LOCATION", "android.permission.ACCESS_COARSE_LOCATION"};
private final List<AirMapFeature> features = new ArrayList<>();
private final Map<Marker, AirMapMarker> markerMap = new HashMap<>();
private final Map<Polyline, AirMapPolyline> polylineMap = new HashMap<>();
private final Map<Polygon, AirMapPolygon> polygonMap = new HashMap<>();
private final ScaleGestureDetector scaleDetector;
private final GestureDetectorCompat gestureDetector;
private final AirMapManager manager;
private LifecycleEventListener lifecycleListener;
private boolean paused = false;
private boolean destroyed = false;
private final ThemedReactContext context;
private final EventDispatcher eventDispatcher;
private static boolean contextHasBug(Context context) {
return context == null ||
context.getResources() == null ||
context.getResources().getConfiguration() == null;
}
// We do this to fix this bug:
// https://github.com/airbnb/react-native-maps/issues/271
//
// which conflicts with another bug regarding the passed in context:
// https://github.com/airbnb/react-native-maps/issues/1147
//
// Doing this allows us to avoid both bugs.
private static Context getNonBuggyContext(ThemedReactContext reactContext,
ReactApplicationContext appContext) {
Context superContext = reactContext;
if (!contextHasBug(appContext.getCurrentActivity())) {
superContext = appContext.getCurrentActivity();
} else if (contextHasBug(superContext)) {
// we have the bug! let's try to find a better context to use
if (!contextHasBug(reactContext.getCurrentActivity())) {
superContext = reactContext.getCurrentActivity();
} else if (!contextHasBug(reactContext.getApplicationContext())) {
superContext = reactContext.getApplicationContext();
} else {
// ยฏ\_(ใ)_/ยฏ
}
}
return superContext;
}
public AirMapView(ThemedReactContext reactContext, ReactApplicationContext appContext,
AirMapManager manager,
GoogleMapOptions googleMapOptions) {
super(getNonBuggyContext(reactContext, appContext), googleMapOptions);
this.manager = manager;
this.context = reactContext;
super.onCreate(null);
// TODO(lmr): what about onStart????
super.onResume();
super.getMapAsync(this);
final AirMapView view = this;
scaleDetector =
new ScaleGestureDetector(reactContext,
new ScaleGestureDetector.SimpleOnScaleGestureListener() {
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
view.startMonitoringRegion();
return true; // stop recording this gesture. let mapview handle it.
}
});
gestureDetector =
new GestureDetectorCompat(reactContext, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
view.startMonitoringRegion();
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
if (handlePanDrag) {
onPanDrag(e2);
}
view.startMonitoringRegion();
return false;
}
});
this.addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (!paused) {
AirMapView.this.cacheView();
}
}
});
eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
}
@Override
public void onMapReady(final GoogleMap map) {
if (destroyed) {
return;
}
this.map = map;
this.map.setInfoWindowAdapter(this);
this.map.setOnMarkerDragListener(this);
manager.pushEvent(context, this, "onMapReady", new WritableNativeMap());
final AirMapView view = this;
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
WritableMap event;
AirMapMarker airMapMarker = markerMap.get(marker);
event = makeClickEventData(marker.getPosition());
event.putString("action", "marker-press");
event.putString("id", airMapMarker.getIdentifier());
manager.pushEvent(context, view, "onMarkerPress", event);
event = makeClickEventData(marker.getPosition());
event.putString("action", "marker-press");
event.putString("id", airMapMarker.getIdentifier());
manager.pushEvent(context, markerMap.get(marker), "onPress", event);
// Return false to open the callout info window and center on the marker
// https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap
// .OnMarkerClickListener
if (view.moveOnMarkerPress) {
return false;
} else {
marker.showInfoWindow();
return true;
}
}
});
map.setOnPolygonClickListener(new GoogleMap.OnPolygonClickListener() {
@Override
public void onPolygonClick(Polygon polygon) {
WritableMap event = makeClickEventData(polygon.getPoints().get(0));
event.putString("action", "polygon-press");
manager.pushEvent(context, polygonMap.get(polygon), "onPress", event);
}
});
map.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
@Override
public void onPolylineClick(Polyline polyline) {
WritableMap event = makeClickEventData(polyline.getPoints().get(0));
event.putString("action", "polyline-press");
manager.pushEvent(context, polylineMap.get(polyline), "onPress", event);
}
});
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
WritableMap event;
event = makeClickEventData(marker.getPosition());
event.putString("action", "callout-press");
manager.pushEvent(context, view, "onCalloutPress", event);
event = makeClickEventData(marker.getPosition());
event.putString("action", "callout-press");
AirMapMarker markerView = markerMap.get(marker);
manager.pushEvent(context, markerView, "onCalloutPress", event);
event = makeClickEventData(marker.getPosition());
event.putString("action", "callout-press");
AirMapCallout infoWindow = markerView.getCalloutView();
if (infoWindow != null) manager.pushEvent(context, infoWindow, "onPress", event);
}
});
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
WritableMap event = makeClickEventData(point);
event.putString("action", "press");
manager.pushEvent(context, view, "onPress", event);
}
});
map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng point) {
WritableMap event = makeClickEventData(point);
event.putString("action", "long-press");
manager.pushEvent(context, view, "onLongPress", makeClickEventData(point));
}
});
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
LatLngBounds bounds = map.getProjection().getVisibleRegion().latLngBounds;
LatLng center = position.target;
lastBoundsEmitted = bounds;
eventDispatcher.dispatchEvent(new RegionChangeEvent(getId(), bounds, center, isTouchDown));
view.stopMonitoringRegion();
}
});
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override public void onMapLoaded() {
isMapLoaded = true;
AirMapView.this.cacheView();
}
});
// We need to be sure to disable location-tracking when app enters background, in-case some
// other module
// has acquired a wake-lock and is controlling location-updates, otherwise, location-manager
// will be left
// updating location constantly, killing the battery, even though some other location-mgmt
// module may
// desire to shut-down location-services.
lifecycleListener = new LifecycleEventListener() {
@Override
public void onHostResume() {
if (hasPermissions()) {
//noinspection MissingPermission
map.setMyLocationEnabled(showUserLocation);
}
synchronized (AirMapView.this) {
if (!destroyed) {
AirMapView.this.onResume();
}
paused = false;
}
}
@Override
public void onHostPause() {
if (hasPermissions()) {
//noinspection MissingPermission
map.setMyLocationEnabled(false);
}
synchronized (AirMapView.this) {
if (!destroyed) {
AirMapView.this.onPause();
}
paused = true;
}
}
@Override
public void onHostDestroy() {
AirMapView.this.doDestroy();
}
};
context.addLifecycleEventListener(lifecycleListener);
}
private boolean hasPermissions() {
return checkSelfPermission(getContext(), PERMISSIONS[0]) == PackageManager.PERMISSION_GRANTED ||
checkSelfPermission(getContext(), PERMISSIONS[1]) == PackageManager.PERMISSION_GRANTED;
}
/*
onDestroy is final method so I can't override it.
*/
public synchronized void doDestroy() {
if (destroyed) {
return;
}
destroyed = true;
if (lifecycleListener != null && context != null) {
context.removeLifecycleEventListener(lifecycleListener);
lifecycleListener = null;
}
if (!paused) {
onPause();
paused = true;
}
onDestroy();
}
public void setRegion(ReadableMap region) {
if (region == null) return;
Double lng = region.getDouble("longitude");
Double lat = region.getDouble("latitude");
Double lngDelta = region.getDouble("longitudeDelta");
Double latDelta = region.getDouble("latitudeDelta");
LatLngBounds bounds = new LatLngBounds(
new LatLng(lat - latDelta / 2, lng - lngDelta / 2), // southwest
new LatLng(lat + latDelta / 2, lng + lngDelta / 2) // northeast
);
if (super.getHeight() <= 0 || super.getWidth() <= 0) {
// in this case, our map has not been laid out yet, so we save the bounds in a local
// variable, and make a guess of zoomLevel 10. Not to worry, though: as soon as layout
// occurs, we will move the camera to the saved bounds. Note that if we tried to move
// to the bounds now, it would trigger an exception.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
boundsToMove = bounds;
} else {
map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 0));
boundsToMove = null;
}
}
public void setShowsUserLocation(boolean showUserLocation) {
this.showUserLocation = showUserLocation; // hold onto this for lifecycle handling
if (hasPermissions()) {
//noinspection MissingPermission
map.setMyLocationEnabled(showUserLocation);
}
}
public void setShowsMyLocationButton(boolean showMyLocationButton) {
if (hasPermissions()) {
map.getUiSettings().setMyLocationButtonEnabled(showMyLocationButton);
}
}
public void setToolbarEnabled(boolean toolbarEnabled) {
if (hasPermissions()) {
map.getUiSettings().setMapToolbarEnabled(toolbarEnabled);
}
}
public void setCacheEnabled(boolean cacheEnabled) {
this.cacheEnabled = cacheEnabled;
this.cacheView();
}
public void enableMapLoading(boolean loadingEnabled) {
if (loadingEnabled && !this.isMapLoaded) {
this.getMapLoadingLayoutView().setVisibility(View.VISIBLE);
}
}
public void setMoveOnMarkerPress(boolean moveOnPress) {
this.moveOnMarkerPress = moveOnPress;
}
public void setLoadingBackgroundColor(Integer loadingBackgroundColor) {
this.loadingBackgroundColor = loadingBackgroundColor;
if (this.mapLoadingLayout != null) {
if (loadingBackgroundColor == null) {
this.mapLoadingLayout.setBackgroundColor(Color.WHITE);
} else {
this.mapLoadingLayout.setBackgroundColor(this.loadingBackgroundColor);
}
}
}
public void setLoadingIndicatorColor(Integer loadingIndicatorColor) {
this.loadingIndicatorColor = loadingIndicatorColor;
if (this.mapLoadingProgressBar != null) {
Integer color = loadingIndicatorColor;
if (color == null) {
color = Color.parseColor("#606060");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ColorStateList progressTintList = ColorStateList.valueOf(loadingIndicatorColor);
ColorStateList secondaryProgressTintList = ColorStateList.valueOf(loadingIndicatorColor);
ColorStateList indeterminateTintList = ColorStateList.valueOf(loadingIndicatorColor);
this.mapLoadingProgressBar.setProgressTintList(progressTintList);
this.mapLoadingProgressBar.setSecondaryProgressTintList(secondaryProgressTintList);
this.mapLoadingProgressBar.setIndeterminateTintList(indeterminateTintList);
} else {
PorterDuff.Mode mode = PorterDuff.Mode.SRC_IN;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
mode = PorterDuff.Mode.MULTIPLY;
}
if (this.mapLoadingProgressBar.getIndeterminateDrawable() != null)
this.mapLoadingProgressBar.getIndeterminateDrawable().setColorFilter(color, mode);
if (this.mapLoadingProgressBar.getProgressDrawable() != null)
this.mapLoadingProgressBar.getProgressDrawable().setColorFilter(color, mode);
}
}
}
public void setHandlePanDrag(boolean handlePanDrag) {
this.handlePanDrag = handlePanDrag;
}
public void addFeature(View child, int index) {
// Our desired API is to pass up annotations/overlays as children to the mapview component.
// This is where we intercept them and do the appropriate underlying mapview action.
if (child instanceof AirMapMarker) {
AirMapMarker annotation = (AirMapMarker) child;
annotation.addToMap(map);
features.add(index, annotation);
Marker marker = (Marker) annotation.getFeature();
markerMap.put(marker, annotation);
} else if (child instanceof AirMapPolyline) {
AirMapPolyline polylineView = (AirMapPolyline) child;
polylineView.addToMap(map);
features.add(index, polylineView);
Polyline polyline = (Polyline) polylineView.getFeature();
polylineMap.put(polyline, polylineView);
} else if (child instanceof AirMapPolygon) {
AirMapPolygon polygonView = (AirMapPolygon) child;
polygonView.addToMap(map);
features.add(index, polygonView);
Polygon polygon = (Polygon) polygonView.getFeature();
polygonMap.put(polygon, polygonView);
} else if (child instanceof AirMapCircle) {
AirMapCircle circleView = (AirMapCircle) child;
circleView.addToMap(map);
features.add(index, circleView);
} else if (child instanceof AirMapUrlTile) {
AirMapUrlTile urlTileView = (AirMapUrlTile) child;
urlTileView.addToMap(map);
features.add(index, urlTileView);
} else {
ViewGroup children = (ViewGroup) child;
for (int i = 0; i < children.getChildCount(); i++) {
addFeature(children.getChildAt(i), index);
}
}
}
public int getFeatureCount() {
return features.size();
}
public View getFeatureAt(int index) {
return features.get(index);
}
public void removeFeatureAt(int index) {
AirMapFeature feature = features.remove(index);
if (feature instanceof AirMapMarker) {
markerMap.remove(feature.getFeature());
}
feature.removeFromMap(map);
}
public WritableMap makeClickEventData(LatLng point) {
WritableMap event = new WritableNativeMap();
WritableMap coordinate = new WritableNativeMap();
coordinate.putDouble("latitude", point.latitude);
coordinate.putDouble("longitude", point.longitude);
event.putMap("coordinate", coordinate);
Projection projection = map.getProjection();
Point screenPoint = projection.toScreenLocation(point);
WritableMap position = new WritableNativeMap();
position.putDouble("x", screenPoint.x);
position.putDouble("y", screenPoint.y);
event.putMap("position", position);
return event;
}
public void updateExtraData(Object extraData) {
// if boundsToMove is not null, we now have the MapView's width/height, so we can apply
// a proper camera move
if (boundsToMove != null) {
HashMap<String, Float> data = (HashMap<String, Float>) extraData;
float width = data.get("width");
float height = data.get("height");
map.moveCamera(
CameraUpdateFactory.newLatLngBounds(
boundsToMove,
(int) width,
(int) height,
0
)
);
boundsToMove = null;
}
}
public void animateToRegion(LatLngBounds bounds, int duration) {
if (map != null) {
startMonitoringRegion();
map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 0), duration, null);
}
}
public void animateToCoordinate(LatLng coordinate, int duration) {
if (map != null) {
startMonitoringRegion();
map.animateCamera(CameraUpdateFactory.newLatLng(coordinate), duration, null);
}
}
public void fitToElements(boolean animated) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
boolean addedPosition = false;
for (AirMapFeature feature : features) {
if (feature instanceof AirMapMarker) {
Marker marker = (Marker) feature.getFeature();
builder.include(marker.getPosition());
addedPosition = true;
}
// TODO(lmr): may want to include shapes / etc.
}
if (addedPosition) {
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, baseMapPadding);
if (animated) {
startMonitoringRegion();
map.animateCamera(cu);
} else {
map.moveCamera(cu);
}
}
}
public void fitToSuppliedMarkers(ReadableArray markerIDsArray, boolean animated) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
String[] markerIDs = new String[markerIDsArray.size()];
for (int i = 0; i < markerIDsArray.size(); i++) {
markerIDs[i] = markerIDsArray.getString(i);
}
boolean addedPosition = false;
List<String> markerIDList = Arrays.asList(markerIDs);
for (AirMapFeature feature : features) {
if (feature instanceof AirMapMarker) {
String identifier = ((AirMapMarker) feature).getIdentifier();
Marker marker = (Marker) feature.getFeature();
if (markerIDList.contains(identifier)) {
builder.include(marker.getPosition());
addedPosition = true;
}
}
}
if (addedPosition) {
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, baseMapPadding);
if (animated) {
startMonitoringRegion();
map.animateCamera(cu);
} else {
map.moveCamera(cu);
}
}
}
public void fitToCoordinates(ReadableArray coordinatesArray, ReadableMap edgePadding,
boolean animated) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (int i = 0; i < coordinatesArray.size(); i++) {
ReadableMap latLng = coordinatesArray.getMap(i);
Double lat = latLng.getDouble("latitude");
Double lng = latLng.getDouble("longitude");
builder.include(new LatLng(lat, lng));
}
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, baseMapPadding);
if (edgePadding != null) {
map.setPadding(edgePadding.getInt("left"), edgePadding.getInt("top"),
edgePadding.getInt("right"), edgePadding.getInt("bottom"));
}
if (animated) {
startMonitoringRegion();
map.animateCamera(cu);
} else {
map.moveCamera(cu);
}
map.setPadding(0, 0, 0,
0); // Without this, the Google logo is moved up by the value of edgePadding.bottom
}
// InfoWindowAdapter interface
@Override
public View getInfoWindow(Marker marker) {
AirMapMarker markerView = markerMap.get(marker);
return markerView.getCallout();
}
@Override
public View getInfoContents(Marker marker) {
AirMapMarker markerView = markerMap.get(marker);
return markerView.getInfoContents();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
scaleDetector.onTouchEvent(ev);
gestureDetector.onTouchEvent(ev);
int action = MotionEventCompat.getActionMasked(ev);
switch (action) {
case (MotionEvent.ACTION_DOWN):
this.getParent().requestDisallowInterceptTouchEvent(
map != null && map.getUiSettings().isScrollGesturesEnabled());
isTouchDown = true;
break;
case (MotionEvent.ACTION_MOVE):
startMonitoringRegion();
break;
case (MotionEvent.ACTION_UP):
// Clear this regardless, since isScrollGesturesEnabled() may have been updated
this.getParent().requestDisallowInterceptTouchEvent(false);
isTouchDown = false;
break;
}
super.dispatchTouchEvent(ev);
return true;
}
// Timer Implementation
public void startMonitoringRegion() {
if (map == null || isMonitoringRegion) return;
timerHandler.postDelayed(timerRunnable, 100);
isMonitoringRegion = true;
}
public void stopMonitoringRegion() {
if (map == null || !isMonitoringRegion) return;
timerHandler.removeCallbacks(timerRunnable);
isMonitoringRegion = false;
}
private LatLngBounds lastBoundsEmitted;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
if (map != null) {
Projection projection = map.getProjection();
VisibleRegion region = (projection != null) ? projection.getVisibleRegion() : null;
LatLngBounds bounds = (region != null) ? region.latLngBounds : null;
if ((bounds != null) &&
(lastBoundsEmitted == null ||
LatLngBoundsUtils.BoundsAreDifferent(bounds, lastBoundsEmitted))) {
LatLng center = map.getCameraPosition().target;
lastBoundsEmitted = bounds;
eventDispatcher.dispatchEvent(new RegionChangeEvent(getId(), bounds, center, true));
}
}
timerHandler.postDelayed(this, 100);
}
};
@Override
public void onMarkerDragStart(Marker marker) {
WritableMap event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, this, "onMarkerDragStart", event);
AirMapMarker markerView = markerMap.get(marker);
event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, markerView, "onDragStart", event);
}
@Override
public void onMarkerDrag(Marker marker) {
WritableMap event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, this, "onMarkerDrag", event);
AirMapMarker markerView = markerMap.get(marker);
event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, markerView, "onDrag", event);
}
@Override
public void onMarkerDragEnd(Marker marker) {
WritableMap event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, this, "onMarkerDragEnd", event);
AirMapMarker markerView = markerMap.get(marker);
event = makeClickEventData(marker.getPosition());
manager.pushEvent(context, markerView, "onDragEnd", event);
}
private ProgressBar getMapLoadingProgressBar() {
if (this.mapLoadingProgressBar == null) {
this.mapLoadingProgressBar = new ProgressBar(getContext());
this.mapLoadingProgressBar.setIndeterminate(true);
}
if (this.loadingIndicatorColor != null) {
this.setLoadingIndicatorColor(this.loadingIndicatorColor);
}
return this.mapLoadingProgressBar;
}
private RelativeLayout getMapLoadingLayoutView() {
if (this.mapLoadingLayout == null) {
this.mapLoadingLayout = new RelativeLayout(getContext());
this.mapLoadingLayout.setBackgroundColor(Color.LTGRAY);
this.addView(this.mapLoadingLayout,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
this.mapLoadingLayout.addView(this.getMapLoadingProgressBar(), params);
this.mapLoadingLayout.setVisibility(View.INVISIBLE);
}
this.setLoadingBackgroundColor(this.loadingBackgroundColor);
return this.mapLoadingLayout;
}
private ImageView getCacheImageView() {
if (this.cacheImageView == null) {
this.cacheImageView = new ImageView(getContext());
this.addView(this.cacheImageView,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
this.cacheImageView.setVisibility(View.INVISIBLE);
}
return this.cacheImageView;
}
private void removeCacheImageView() {
if (this.cacheImageView != null) {
((ViewGroup) this.cacheImageView.getParent()).removeView(this.cacheImageView);
this.cacheImageView = null;
}
}
private void removeMapLoadingProgressBar() {
if (this.mapLoadingProgressBar != null) {
((ViewGroup) this.mapLoadingProgressBar.getParent()).removeView(this.mapLoadingProgressBar);
this.mapLoadingProgressBar = null;
}
}
private void removeMapLoadingLayoutView() {
this.removeMapLoadingProgressBar();
if (this.mapLoadingLayout != null) {
((ViewGroup) this.mapLoadingLayout.getParent()).removeView(this.mapLoadingLayout);
this.mapLoadingLayout = null;
}
}
private void cacheView() {
if (this.cacheEnabled) {
final ImageView cacheImageView = this.getCacheImageView();
final RelativeLayout mapLoadingLayout = this.getMapLoadingLayoutView();
cacheImageView.setVisibility(View.INVISIBLE);
mapLoadingLayout.setVisibility(View.VISIBLE);
if (this.isMapLoaded) {
this.map.snapshot(new GoogleMap.SnapshotReadyCallback() {
@Override public void onSnapshotReady(Bitmap bitmap) {
cacheImageView.setImageBitmap(bitmap);
cacheImageView.setVisibility(View.VISIBLE);
mapLoadingLayout.setVisibility(View.INVISIBLE);
}
});
}
} else {
this.removeCacheImageView();
if (this.isMapLoaded) {
this.removeMapLoadingLayoutView();
}
}
}
public void onPanDrag(MotionEvent ev) {
Point point = new Point((int) ev.getX(), (int) ev.getY());
LatLng coords = this.map.getProjection().fromScreenLocation(point);
WritableMap event = makeClickEventData(coords);
manager.pushEvent(context, this, "onPanDrag", event);
}
}
| fix rare android crashes when map size is 0
| lib/android/src/main/java/com/airbnb/android/react/maps/AirMapView.java | fix rare android crashes when map size is 0 | <ide><path>ib/android/src/main/java/com/airbnb/android/react/maps/AirMapView.java
<ide> // a proper camera move
<ide> if (boundsToMove != null) {
<ide> HashMap<String, Float> data = (HashMap<String, Float>) extraData;
<del> float width = data.get("width");
<del> float height = data.get("height");
<del> map.moveCamera(
<del> CameraUpdateFactory.newLatLngBounds(
<del> boundsToMove,
<del> (int) width,
<del> (int) height,
<del> 0
<del> )
<del> );
<add> int width = data.get("width") == null ? 0 : data.get("width").intValue();
<add> int height = data.get("height") == null ? 0 : data.get("height").intValue();
<add>
<add> //fix for https://github.com/airbnb/react-native-maps/issues/245,
<add> //it's not guaranteed the passed-in height and width would be greater than 0.
<add> if (width <= 0 || height <= 0) {
<add> map.moveCamera(CameraUpdateFactory.newLatLngBounds(boundsToMove, 0));
<add> } else {
<add> map.moveCamera(CameraUpdateFactory.newLatLngBounds(boundsToMove, width, height, 0));
<add> }
<add>
<ide> boundsToMove = null;
<ide> }
<ide> } |
|
JavaScript | mit | 10f0f9a7fd773d6ebd1b7b65c9d2c264c5715cf6 | 0 | ochakov/SpeechRecognitionPlugin,ochakov/SpeechRecognitionPlugin | var exec = require("cordova/exec");
/**
attribute SpeechGrammarList grammars;
attribute DOMString lang;
attribute boolean continuous;
attribute boolean interimResults;
attribute unsigned long maxAlternatives;
attribute DOMString serviceURI;
*/
var SpeechRecognition = function () {
this.grammars = null;
this.lang = "en";
this.continuous = false;
this.interimResults = false;
this.maxAlternatives = 1;
this.serviceURI = "";
// event methods
this.onaudiostart = null;
this.onsoundstart = null;
this.onspeechstart = null;
this.onspeechend = null;
this.onsoundend = null;
this.onaudioend = null;
this.onresult = null;
this.onnomatch = null;
this.onerror = null;
this.onstart = null;
this.onend = null;
this.onready = null;
this.onrms = null;
exec(function() {
console.log("initialized");
}, function(e) {
console.log("error: " + e);
}, "SpeechRecognition", "init", []);
};
SpeechRecognition.prototype.start = function() {
var that = this;
var successCallback = function(event) {
if (event.type === "audiostart" && typeof that.onaudiostart === "function") {
that.onaudiostart(event);
} else if (event.type === "soundstart" && typeof that.onsoundstart === "function") {
that.onsoundstart(event);
} else if (event.type === "speechstart" && typeof that.onspeechstart === "function") {
that.onspeechstart(event);
} else if (event.type === "speechend" && typeof that.onspeechend === "function") {
that.onspeechend(event);
} else if (event.type === "soundend" && typeof that.onsoundend === "function") {
that.onsoundend(event);
} else if (event.type === "audioend" && typeof that.onaudioend === "function") {
that.onaudioend(event);
} else if (event.type === "result" && typeof that.onresult === "function") {
that.onresult(event);
} else if (event.type === "nomatch" && typeof that.onnomatch === "function") {
that.onnomatch(event);
} else if (event.type === "start" && typeof that.onstart === "function") {
that.onstart(event);
} else if (event.type === "end" && typeof that.onend === "function") {
that.onend(event);
} else if (event.type === "readyforspeech" && typeof that.onready === "function") {
that.onready(event);
} else if (event.type === "rms" && typeof that.onrms === "function") {
that.onrms(event);
}
};
var errorCallback = function(err) {
if (typeof that.onerror === "function") {
that.onerror(err);
}
};
exec(successCallback, errorCallback, "SpeechRecognition", "start", [this.lang,this.interimResults,this.maxAlternatives,this.continuous]);
};
SpeechRecognition.prototype.stop = function() {
exec(null, null, "SpeechRecognition", "stop", []);
};
SpeechRecognition.prototype.abort = function() {
exec(null, null, "SpeechRecognition", "abort", []);
};
module.exports = SpeechRecognition;
| www/SpeechRecognition.js | var exec = require("cordova/exec");
/**
attribute SpeechGrammarList grammars;
attribute DOMString lang;
attribute boolean continuous;
attribute boolean interimResults;
attribute unsigned long maxAlternatives;
attribute DOMString serviceURI;
*/
var SpeechRecognition = function () {
this.grammars = null;
this.lang = "en";
this.continuous = false;
this.interimResults = false;
this.maxAlternatives = 1;
this.serviceURI = "";
// event methods
this.onaudiostart = null;
this.onsoundstart = null;
this.onspeechstart = null;
this.onspeechend = null;
this.onsoundend = null;
this.onaudioend = null;
this.onresult = null;
this.onnomatch = null;
this.onerror = null;
this.onstart = null;
this.onend = null;
exec(function() {
console.log("initialized");
}, function(e) {
console.log("error: " + e);
}, "SpeechRecognition", "init", []);
};
SpeechRecognition.prototype.start = function() {
var that = this;
var successCallback = function(event) {
if (event.type === "audiostart" && typeof that.onaudiostart === "function") {
that.onaudiostart(event);
} else if (event.type === "soundstart" && typeof that.onsoundstart === "function") {
that.onsoundstart(event);
} else if (event.type === "speechstart" && typeof that.onspeechstart === "function") {
that.onspeechstart(event);
} else if (event.type === "speechend" && typeof that.onspeechend === "function") {
that.onspeechend(event);
} else if (event.type === "soundend" && typeof that.onsoundend === "function") {
that.onsoundend(event);
} else if (event.type === "audioend" && typeof that.onaudioend === "function") {
that.onaudioend(event);
} else if (event.type === "result" && typeof that.onresult === "function") {
that.onresult(event);
} else if (event.type === "nomatch" && typeof that.onnomatch === "function") {
that.onnomatch(event);
} else if (event.type === "start" && typeof that.onstart === "function") {
that.onstart(event);
} else if (event.type === "end" && typeof that.onend === "function") {
that.onend(event);
}
};
var errorCallback = function(err) {
if (typeof that.onerror === "function") {
that.onerror(err);
}
};
exec(successCallback, errorCallback, "SpeechRecognition", "start", [this.lang,this.interimResults]);
};
SpeechRecognition.prototype.stop = function() {
exec(null, null, "SpeechRecognition", "stop", []);
};
SpeechRecognition.prototype.abort = function() {
exec(null, null, "SpeechRecognition", "abort", []);
};
module.exports = SpeechRecognition;
| readyforspeech and rms events, maxAlternatives
Support readyforspeech and rms events, send maxAlternatives | www/SpeechRecognition.js | readyforspeech and rms events, maxAlternatives | <ide><path>ww/SpeechRecognition.js
<ide> this.onerror = null;
<ide> this.onstart = null;
<ide> this.onend = null;
<add> this.onready = null;
<add> this.onrms = null;
<ide>
<ide> exec(function() {
<ide> console.log("initialized");
<ide> that.onstart(event);
<ide> } else if (event.type === "end" && typeof that.onend === "function") {
<ide> that.onend(event);
<add> } else if (event.type === "readyforspeech" && typeof that.onready === "function") {
<add> that.onready(event);
<add> } else if (event.type === "rms" && typeof that.onrms === "function") {
<add> that.onrms(event);
<ide> }
<ide> };
<ide> var errorCallback = function(err) {
<ide> }
<ide> };
<ide>
<del> exec(successCallback, errorCallback, "SpeechRecognition", "start", [this.lang,this.interimResults]);
<add> exec(successCallback, errorCallback, "SpeechRecognition", "start", [this.lang,this.interimResults,this.maxAlternatives,this.continuous]);
<ide> };
<ide>
<ide> SpeechRecognition.prototype.stop = function() { |
|
JavaScript | mit | dd696f6de8a9ac3354eb7be20475f5224dac2a4c | 0 | kilroy23/brackets,siddharta1337/brackets,Cartman0/brackets,chrisle/brackets,wakermahmud/brackets,ForkedRepos/brackets,chrismoulton/brackets,andrewnc/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,iamchathu/brackets,gcommetti/brackets,Wikunia/brackets,RamirezWillow/brackets,netlams/brackets,alicoding/nimble,cdot-brackets-extensions/nimble-htmlLint,resir014/brackets,netlams/brackets,lunode/brackets,L0g1k/brackets,fabricadeaplicativos/brackets,fronzec/brackets,netlams/brackets,malinkie/brackets,rlugojr/brackets,zLeonjo/brackets,humphd/brackets,fashionsun/brackets,Andrey-Pavlov/brackets,2youyouo2/cocoslite,richmondgozarin/brackets,sprintr/brackets,mozilla/brackets,ralic/brackets,eric-stanley/brackets,andrewnc/brackets,MahadevanSrinivasan/brackets,massimiliano76/brackets,jacobnash/brackets,raygervais/brackets,rlugojr/brackets,IAmAnubhavSaini/brackets,GHackAnonymous/brackets,Th30/brackets,keir-rex/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,shiyamkumar/brackets,baig/brackets,adobe/brackets,NickersF/brackets,youprofit/brackets,youprofit/brackets,NKcentinel/brackets,treejames/brackets,eric-stanley/brackets,RobertJGabriel/brackets,michaeljayt/brackets,brianjking/brackets,cdot-brackets-extensions/nimble-htmlLint,fastrde/brackets,Lojsan123/brackets,youprofit/brackets,Pomax/brackets,cdot-brackets-extensions/nimble-htmlLint,Live4Code/brackets,pkdevbox/brackets,StephanieMak/brackets,zcbenz/brackets,robertkarlsson/brackets,MantisWare/brackets,JordanTheriault/brackets,CapeSepias/brackets,goldcase/brackets,chrismoulton/brackets,sgupta7857/brackets,alexkid64/brackets,gcommetti/brackets,andrewnc/brackets,sedge/nimble,srinivashappy/brackets,gwynndesign/brackets,wesleifreitas/brackets,y12uc231/brackets,gupta-tarun/brackets,L0g1k/quickfire-old,IAmAnubhavSaini/brackets,alicoding/nimble,Lojsan123/brackets,Cartman0/brackets,jiimaho/brackets,ryanackley/tailor,L0g1k/quickfire-old,Mosoc/brackets,dtcom/MyPSDBracket,abhisekp/brackets,gwynndesign/brackets,ricciozhang/brackets,ryanackley/tailor,shal1y/brackets,ralic/brackets,fvntr/brackets,macdg/brackets,MantisWare/brackets,xantage/brackets,mjurczyk/brackets,IAmAnubhavSaini/brackets,MarcelGerber/brackets,GHackAnonymous/brackets,raygervais/brackets,karevn/brackets,Free-Technology-Guild/brackets,Jonavin/brackets,michaeljayt/brackets,ropik/brackets,m66n/brackets,Real-Currents/brackets,MahadevanSrinivasan/brackets,fabricadeaplicativos/brackets,Lojsan123/brackets,jacobnash/brackets,petetnt/brackets,RamirezWillow/brackets,thr0w/brackets,uwsd/brackets,Rynaro/brackets,jiimaho/brackets,massimiliano76/brackets,wangjun/brackets,2youyouo2/cocoslite,NickersF/brackets,raygervais/brackets,fastrde/brackets,Real-Currents/brackets,MarcelGerber/brackets,chinnyannieb/brackets,chambej/brackets,Rynaro/brackets,Pomax/brackets,ForkedRepos/brackets,JordanTheriault/brackets,jmarkina/brackets,Denisov21/brackets,treejames/brackets,jiawenbo/brackets,gupta-tarun/brackets,dtcom/MyPSDBracket,zcbenz/brackets,ChaofengZhou/brackets,NickersF/brackets,L0g1k/brackets,sgupta7857/brackets,sprintr/brackets,macdg/brackets,ScalaInc/brackets,bidle/brackets,ricciozhang/brackets,macdg/brackets,ScalaInc/brackets,wangjun/brackets,keir-rex/brackets,tan9/brackets,IAmAnubhavSaini/brackets,Jonavin/brackets,No9/brackets,NGHGithub/brackets,ggusman/present,udhayam/brackets,zaggino/brackets-electron,zaggino/brackets-electron,zcbenz/brackets,chinnyannieb/brackets,StephanieMak/brackets,ashleygwilliams/brackets,kolipka/brackets,SidBala/brackets,stowball/brackets,FTG-003/brackets,goldcase/brackets,goldcase/brackets,NKcentinel/brackets,busykai/brackets,MantisWare/brackets,TylerL-uxai/brackets,shal1y/brackets,ChaofengZhou/brackets,eric-stanley/brackets,srinivashappy/brackets,ashleygwilliams/brackets,sprintr/brackets,fastrde/brackets,MarcelGerber/brackets,m66n/brackets,Rynaro/brackets,brianjking/brackets,phillipalexander/brackets,adrianhartanto0/brackets,2youyouo2/cocoslite,Real-Currents/brackets,revi/brackets,fvntr/brackets,ryanackley/tailor,veveykocute/brackets,revi/brackets,udhayam/brackets,ChaofengZhou/brackets,TylerL-uxai/brackets,humphd/brackets,bidle/brackets,phillipalexander/brackets,fabricadeaplicativos/brackets,kilroy23/brackets,Rajat-dhyani/brackets,mjurczyk/brackets,NKcentinel/brackets,SidBala/brackets,pomadgw/brackets,mjurczyk/brackets,quasto/ArduinoStudio,lunode/brackets,thr0w/brackets,marcominetti/brackets,iamchathu/brackets,Rajat-dhyani/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,treejames/brackets,JordanTheriault/brackets,albertinad/brackets,massimiliano76/brackets,thehogfather/brackets,mcanthony/brackets,sgupta7857/brackets,ls2uper/brackets,alexkid64/brackets,Rajat-dhyani/brackets,stowball/brackets,flukeout/brackets,Denisov21/brackets,stowball/brackets,srhbinion/brackets,ficristo/brackets,y12uc231/brackets,treejames/brackets,tan9/brackets,abhishekbhalani/brackets,mcanthony/brackets,ashleygwilliams/brackets,quasto/ArduinoStudio,weebygames/brackets,MahadevanSrinivasan/brackets,falcon1812/brackets,ryanackley/tailor,riselabs-ufba/RiPLE-HC-ExperimentalData,amrelnaggar/brackets,marcominetti/brackets,MarcelGerber/brackets,abhishekbhalani/brackets,baig/brackets,show0017/brackets,stowball/brackets,gwynndesign/brackets,albertinad/brackets,raygervais/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,gideonthomas/brackets,gideonthomas/brackets,No9/brackets,Denisov21/brackets,82488059/brackets,abhisekp/brackets,y12uc231/brackets,fashionsun/brackets,kolipka/brackets,TylerL-uxai/brackets,xantage/brackets,ralic/brackets,Denisov21/brackets,sophiacaspar/brackets,MantisWare/brackets,iamchathu/brackets,y12uc231/brackets,chrisle/brackets,agreco/brackets,busykai/brackets,pomadgw/brackets,Wikunia/brackets,albertinad/brackets,Fcmam5/brackets,brianjking/brackets,bidle/brackets,flukeout/brackets,malinkie/brackets,RobertJGabriel/brackets,adrianhartanto0/brackets,Jonavin/brackets,petetnt/brackets,gupta-tarun/brackets,chambej/brackets,adobe/brackets,fastrde/brackets,kolipka/brackets,arduino-org/ArduinoStudio,ecwebservices/brackets,thr0w/brackets,zcbenz/brackets,albertinad/brackets,falcon1812/brackets,thehogfather/brackets,michaeljayt/brackets,emanziano/brackets,alexkid64/brackets,veveykocute/brackets,82488059/brackets,zhukaixy/brackets,mat-mcloughlin/brackets,zaggino/brackets-electron,NKcentinel/brackets,lovewitty/brackets,show0017/brackets,baig/brackets,chrismoulton/brackets,pkdevbox/brackets,youprofit/brackets,weebygames/brackets,m66n/brackets,fronzec/brackets,ScalaInc/brackets,Rynaro/brackets,karevn/brackets,ScalaInc/brackets,adrianhartanto0/brackets,L0g1k/quickfire-old,pomadgw/brackets,emanziano/brackets,falcon1812/brackets,gcommetti/brackets,adrianhartanto0/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,shiyamkumar/brackets,quasto/ArduinoStudio,youprofit/brackets,keir-rex/brackets,abhishekbhalani/brackets,alicoding/nimble,CapeSepias/brackets,RamirezWillow/brackets,ls2uper/brackets,rlugojr/brackets,richmondgozarin/brackets,fcjailybo/brackets,fronzec/brackets,Mosoc/brackets,sedge/nimble,sophiacaspar/brackets,kilroy23/brackets,gcommetti/brackets,lovewitty/brackets,Wikunia/brackets,CoherentLabs/brackets,L0g1k/quickfire-old,brianjking/brackets,Free-Technology-Guild/brackets,sedge/nimble,hanmichael/brackets,robertkarlsson/brackets,gupta-tarun/brackets,dangkhue27/brackets,arduino-org/ArduinoStudio,SebastianBoyd/sebastianboyd.github.io-OLD,simon66/brackets,fastrde/brackets,gideonthomas/brackets,thehogfather/brackets,chrisle/brackets,agreco/brackets,richmondgozarin/brackets,wesleifreitas/brackets,zLeonjo/brackets,alicoding/nimble,zhukaixy/brackets,dangkhue27/brackets,arduino-org/ArduinoStudio,richmondgozarin/brackets,RobertJGabriel/brackets,goldcase/brackets,srhbinion/brackets,lunode/brackets,malinkie/brackets,adobe/brackets,fcjailybo/brackets,siddharta1337/brackets,eric-stanley/brackets,Rajat-dhyani/brackets,weebygames/brackets,arduino-org/ArduinoStudio,Jonavin/brackets,bidle/brackets,mozilla/brackets,resir014/brackets,ricciozhang/brackets,2youyouo2/cocoslite,kilroy23/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,jiawenbo/brackets,chrismoulton/brackets,ricciozhang/brackets,zLeonjo/brackets,uwsd/brackets,Free-Technology-Guild/brackets,RobertJGabriel/brackets,arduino-org/ArduinoStudio,robertkarlsson/brackets,cosmosgenius/brackets,ScalaInc/brackets,ashleygwilliams/brackets,robertkarlsson/brackets,mozilla/brackets,thr0w/brackets,robertkarlsson/brackets,Th30/brackets,chinnyannieb/brackets,rafaelstz/brackets,CapeSepias/brackets,alexkid64/brackets,jacobnash/brackets,Free-Technology-Guild/brackets,FTG-003/brackets,xantage/brackets,jacobnash/brackets,nucliweb/brackets,FTG-003/brackets,jmarkina/brackets,shal1y/brackets,Live4Code/brackets,ForkedRepos/brackets,simon66/brackets,NickersF/brackets,jiawenbo/brackets,baig/brackets,FTG-003/brackets,pratts/brackets,No9/brackets,netlams/brackets,zLeonjo/brackets,Andrey-Pavlov/brackets,hanmichael/brackets,mcanthony/brackets,falcon1812/brackets,uwsd/brackets,sophiacaspar/brackets,busykai/brackets,chambej/brackets,quasto/ArduinoStudio,SidBala/brackets,cdot-brackets-extensions/nimble-htmlLint,dangkhue27/brackets,lovewitty/brackets,udhayam/brackets,sophiacaspar/brackets,Mosoc/brackets,pratts/brackets,zaggino/brackets-electron,adrianhartanto0/brackets,ForkedRepos/brackets,ls2uper/brackets,revi/brackets,abhisekp/brackets,ficristo/brackets,82488059/brackets,macdg/brackets,ls2uper/brackets,amrelnaggar/brackets,petetnt/brackets,xantage/brackets,Live4Code/brackets,thr0w/brackets,jiimaho/brackets,keir-rex/brackets,wesleifreitas/brackets,rafaelstz/brackets,srhbinion/brackets,wakermahmud/brackets,Andrey-Pavlov/brackets,fvntr/brackets,iamchathu/brackets,adobe/brackets,karevn/brackets,Fcmam5/brackets,ficristo/brackets,andrewnc/brackets,fabricadeaplicativos/brackets,Andrey-Pavlov/brackets,sophiacaspar/brackets,RobertJGabriel/brackets,chinnyannieb/brackets,RamirezWillow/brackets,agreco/brackets,pkdevbox/brackets,chrisle/brackets,Pomax/brackets,lunode/brackets,L0g1k/brackets,MahadevanSrinivasan/brackets,tan9/brackets,SidBala/brackets,Cartman0/brackets,jmarkina/brackets,L0g1k/brackets,GHackAnonymous/brackets,uwsd/brackets,sprintr/brackets,stowball/brackets,CoherentLabs/brackets,busykai/brackets,wesleifreitas/brackets,sprintr/brackets,ecwebservices/brackets,flukeout/brackets,ropik/brackets,rafaelstz/brackets,albertinad/brackets,shiyamkumar/brackets,veveykocute/brackets,keir-rex/brackets,Live4Code/brackets,eric-stanley/brackets,jiawenbo/brackets,Mosoc/brackets,falcon1812/brackets,ChaofengZhou/brackets,humphd/brackets,bidle/brackets,petetnt/brackets,flukeout/brackets,fvntr/brackets,wangjun/brackets,siddharta1337/brackets,MantisWare/brackets,tan9/brackets,dtcom/MyPSDBracket,xantage/brackets,siddharta1337/brackets,mjurczyk/brackets,Andrey-Pavlov/brackets,show0017/brackets,fashionsun/brackets,JordanTheriault/brackets,jiimaho/brackets,wangjun/brackets,StephanieMak/brackets,petetnt/brackets,kolipka/brackets,Live4Code/brackets,malinkie/brackets,jmarkina/brackets,resir014/brackets,emanziano/brackets,massimiliano76/brackets,SidBala/brackets,mjurczyk/brackets,richmondgozarin/brackets,ggusman/present,Mosoc/brackets,mat-mcloughlin/brackets,tan9/brackets,zhukaixy/brackets,NGHGithub/brackets,flukeout/brackets,mat-mcloughlin/brackets,gupta-tarun/brackets,Rajat-dhyani/brackets,malinkie/brackets,show0017/brackets,ggusman/present,fcjailybo/brackets,fashionsun/brackets,m66n/brackets,Wikunia/brackets,ropik/brackets,resir014/brackets,Cartman0/brackets,chambej/brackets,dangkhue27/brackets,macdg/brackets,GHackAnonymous/brackets,ashleygwilliams/brackets,Denisov21/brackets,abhisekp/brackets,mozilla/brackets,sgupta7857/brackets,zaggino/brackets-electron,rafaelstz/brackets,alexkid64/brackets,dtcom/MyPSDBracket,fronzec/brackets,zhukaixy/brackets,nucliweb/brackets,Fcmam5/brackets,veveykocute/brackets,wakermahmud/brackets,jmarkina/brackets,srhbinion/brackets,wakermahmud/brackets,gcommetti/brackets,No9/brackets,jiimaho/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,treejames/brackets,mat-mcloughlin/brackets,chrisle/brackets,fcjailybo/brackets,andrewnc/brackets,emanziano/brackets,shal1y/brackets,humphd/brackets,NickersF/brackets,jiawenbo/brackets,ChaofengZhou/brackets,82488059/brackets,fashionsun/brackets,emanziano/brackets,simon66/brackets,TylerL-uxai/brackets,Jonavin/brackets,Th30/brackets,rlugojr/brackets,srinivashappy/brackets,fcjailybo/brackets,ls2uper/brackets,L0g1k/quickfire-old,ralic/brackets,quasto/ArduinoStudio,Wikunia/brackets,michaeljayt/brackets,rafaelstz/brackets,amrelnaggar/brackets,revi/brackets,udhayam/brackets,ficristo/brackets,chinnyannieb/brackets,pomadgw/brackets,phillipalexander/brackets,NGHGithub/brackets,MarcelGerber/brackets,pratts/brackets,nucliweb/brackets,Th30/brackets,lunode/brackets,netlams/brackets,CoherentLabs/brackets,cosmosgenius/brackets,zaggino/brackets-electron,sedge/nimble,lovewitty/brackets,RamirezWillow/brackets,wesleifreitas/brackets,udhayam/brackets,ggusman/present,dangkhue27/brackets,82488059/brackets,iamchathu/brackets,agreco/brackets,revi/brackets,thehogfather/brackets,shiyamkumar/brackets,simon66/brackets,Pomax/brackets,adobe/brackets,kolipka/brackets,No9/brackets,shal1y/brackets,rlugojr/brackets,srinivashappy/brackets,ropik/brackets,michaeljayt/brackets,chambej/brackets,FTG-003/brackets,siddharta1337/brackets,wangjun/brackets,y12uc231/brackets,ecwebservices/brackets,TylerL-uxai/brackets,MahadevanSrinivasan/brackets,GHackAnonymous/brackets,goldcase/brackets,karevn/brackets,CapeSepias/brackets,wakermahmud/brackets,pomadgw/brackets,StephanieMak/brackets,cosmosgenius/brackets,karevn/brackets,lovewitty/brackets,ecwebservices/brackets,pkdevbox/brackets,Free-Technology-Guild/brackets,m66n/brackets,mozilla/brackets,jacobnash/brackets,NGHGithub/brackets,baig/brackets,CoherentLabs/brackets,Fcmam5/brackets,Rynaro/brackets,ForkedRepos/brackets,hanmichael/brackets,weebygames/brackets,StephanieMak/brackets,CapeSepias/brackets,SebastianBoyd/sebastianboyd.github.io-OLD,shiyamkumar/brackets,sgupta7857/brackets,gwynndesign/brackets,hanmichael/brackets,zLeonjo/brackets,uwsd/brackets,mcanthony/brackets,gideonthomas/brackets,simon66/brackets,srhbinion/brackets,pratts/brackets,Real-Currents/brackets,thehogfather/brackets,zhukaixy/brackets,ralic/brackets,sedge/nimble,chrismoulton/brackets,massimiliano76/brackets,NKcentinel/brackets,fabricadeaplicativos/brackets,mcanthony/brackets,amrelnaggar/brackets,fronzec/brackets,Real-Currents/brackets,Th30/brackets,gideonthomas/brackets,pkdevbox/brackets,Pomax/brackets,riselabs-ufba/RiPLE-HC-ExperimentalData,srinivashappy/brackets,NGHGithub/brackets,Lojsan123/brackets,phillipalexander/brackets,hanmichael/brackets,nucliweb/brackets,ficristo/brackets,fvntr/brackets,resir014/brackets,humphd/brackets,amrelnaggar/brackets,weebygames/brackets,veveykocute/brackets,pratts/brackets,nucliweb/brackets,busykai/brackets,raygervais/brackets,ricciozhang/brackets,phillipalexander/brackets,IAmAnubhavSaini/brackets,brianjking/brackets,Fcmam5/brackets,abhisekp/brackets,JordanTheriault/brackets,2youyouo2/cocoslite,Real-Currents/brackets,ecwebservices/brackets,cosmosgenius/brackets,Cartman0/brackets,Lojsan123/brackets,kilroy23/brackets | /*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, describe, it, expect, beforeEach, afterEach, waitsFor, runs, $ */
define(function (require, exports, module) {
'use strict';
var Commands,
Menus,
SpecRunnerUtils = require("./SpecRunnerUtils.js"),
Strings = require("strings");
describe("Menus", function () {
var testWindow;
beforeEach(function () {
SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
testWindow = w;
// Load module instances from brackets.test
Commands = testWindow.brackets.test.Commands;
Menus = testWindow.brackets.test.Menus;
});
});
afterEach(function () {
SpecRunnerUtils.closeTestWindow();
});
describe("Add Menus", function () {
it("should add new menu in last position of list", function () {
runs(function () {
var $listItems = testWindow.$("#main-toolbar > ul.nav").children();
expect($listItems).toBeTruthy(); // non-null and defined
var menuCountOriginal = $listItems.length;
var menu = Menus.addMenu("Custom", "menu-custom");
expect(menu).toBeTruthy();
$listItems = testWindow.$("#main-toolbar > ul.nav").children(); // refresh
expect($listItems.length).toBe(menuCountOriginal + 1);
expect($($listItems[menuCountOriginal]).attr("id")).toBe("menu-custom");
});
});
// it("should add new menu after reference menu", function () {
// runs(function () {
// var $listItems = testWindow.$("#main-toolbar > ul.nav").children();
// expect($listItems).toBeTruthy();
//
// var menuCountOriginal = $listItems.length;
// var menu = Menus.addMenu("Custom", "menu-custom", Menus.AFTER, Menus.AppMenuBar.FILE_MENU);
// expect(menu).toBeTruthy();
//
// $listItems = testWindow.$("#main-toolbar > ul.nav").children();
// expect($listItems.length).toBe(menuCountOriginal + 1);
// expect($($listItems[0]).attr("id")).toBe("Strings.FILE_MENU");
// expect($($listItems[1]).attr("id")).toBe("menu-custom");
// });
// });
// it("should add new menu at end of list when reference menu doesn't exist", function () {
// runs(function () {
// var $listItems = testWindow.$("#main-toolbar > ul.nav").children();
// expect($listItems).toBeTruthy();
//
// var menuCountOriginal = $listItems.length;
// var menu = Menus.addMenu("Custom", "menu-custom", Menus.AFTER, "NONEXISTANT");
// expect(menu).toBeTruthy();
//
// $listItems = testWindow.$("#main-toolbar > ul.nav").children();
// expect($listItems.length).toBe(menuCountOriginal + 1);
// expect($($listItems[menuCountOriginal]).attr("id")).toBe("menu-custom");
// });
// });
it("should not add duplicate menu", function () {
runs(function () {
var $listItems = testWindow.$("#main-toolbar > ul.nav").children();
expect($listItems).toBeTruthy();
var menuCountOriginal = $listItems.length;
var menu = null;
try {
menu = Menus.addMenu(Strings.FILE_MENU, Menus.AppMenuBar.FILE_MENU);
} catch (e) {
// catch exception and do nothing
}
$listItems = testWindow.$("#main-toolbar > ul.nav").children();
expect($listItems.length).toBe(menuCountOriginal);
expect(menu).toBeNull();
});
});
});
describe("Add Menu Items", function () {
it("should add new menu item to empty menu", function () {
runs(function () {
// Adding menus tested above, so minimal validation from this point on
var menu = Menus.addMenu("Custom", "menu-custom");
expect(menu).toBeTruthy();
var $listItems = testWindow.$("#main-toolbar > ul.nav > li#menu-custom > ul").children();
expect($listItems).toBeTruthy();
expect($listItems.length).toBe(0);
// Re-use commands that are already registered
var menuItem = menu.addMenuItem("menuitem-custom-0", Commands.FILE_NEW);
expect(menuItem).toBeTruthy();
$listItems = testWindow.$("#main-toolbar > ul.nav > li#menu-custom > ul").children();
expect($listItems.length).toBe(1);
expect(testWindow.$("#main-toolbar > ul.nav > li#menu-custom > ul > li > a#menuitem-custom-0")).toBeTruthy();
});
});
it("should add new menu item in first position of menu", function () {
runs(function () {
// Add to existing file menu
var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
expect(menu).toBeTruthy();
var listSelector = "#main-toolbar > ul.nav > li#" + Menus.AppMenuBar.FILE_MENU + " > ul";
var $listItems = testWindow.$(listSelector).children();
expect($listItems).toBeTruthy();
var menuItemCountOriginal = $listItems.length;
var menuItem = menu.addMenuItem("menuitem-custom-0", Commands.FILE_NEW, Menus.FIRST);
expect(menuItem).toBeTruthy();
$listItems = testWindow.$(listSelector).children();
expect($listItems.length).toBe(menuItemCountOriginal + 1);
expect(testWindow.$(listSelector + " > li:first-child > a#menuitem-custom-0")).toBeTruthy();
});
});
it("should add new menu item in last position of menu", function () {
runs(function () {
var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
expect(menu).toBeTruthy();
var listSelector = "#main-toolbar > ul.nav > li#" + Menus.AppMenuBar.FILE_MENU + " > ul";
var $listItems = testWindow.$(listSelector).children();
expect($listItems).toBeTruthy();
var menuItemCountOriginal = $listItems.length;
// Use wacky key binding that's hopefully not used
var menuItem = menu.addMenuItem("menuitem-custom-0", Commands.FILE_NEW, "Ctrl-Alt-1", Menus.LAST);
expect(menuItem).toBeTruthy();
$listItems = testWindow.$(listSelector).children();
expect($listItems.length).toBe(menuItemCountOriginal + 1);
expect(testWindow.$(listSelector + " > li:last-child > a#menuitem-custom-0")).toBeTruthy();
});
});
it("should add new menu item in position after reference menu item", function () {
runs(function () {
// Add to existing file menu
var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
expect(menu).toBeTruthy();
var listSelector = "#main-toolbar > ul.nav > li#" + Menus.AppMenuBar.FILE_MENU + " > ul";
var $listItems = testWindow.$(listSelector).children();
expect($listItems).toBeTruthy();
var menuItemCountOriginal = $listItems.length;
menu.addMenuItem("menuitem-custom-0", Commands.FILE_NEW, "Ctrl-Alt-1", Menus.FIRST);
$listItems = testWindow.$(listSelector).children();
expect($listItems.length).toBe(menuItemCountOriginal + 1);
// Insert new item after the one we just added in the first position
var menuItem = menu.addMenuItem("menuitem-custom-1", Commands.FILE_NEW, "Ctrl-Alt-1", Menus.AFTER, "menuitem-custom-0");
expect(testWindow.$(listSelector + " > li:nth-child(2) > a#menuitem-custom-0")).toBeTruthy();
});
});
// it("should add new menu item in position before reference menu item", function () { });
// it("should add new menu item in last position of menu if reference menu item doesn't exist", function () { });
// it("should not add duplicate menu item", function () { });
it("should not add menu item with unregistered command", function () {
runs(function () {
var menu = Menus.addMenu("Custom", "menu-custom");
expect(menu).toBeTruthy();
var $listItems = testWindow.$("#main-toolbar > ul.nav > li#menu-custom > ul").children();
expect($listItems).toBeTruthy();
expect($listItems.length).toBe(0);
var menuItem = null;
try {
menuItem = menu.addMenuItem("menuitem-custom-0", "UNREGISTERED_COMMAND");
} catch (e) {
// catch exception and do nothing
}
$listItems = testWindow.$("#main-toolbar > ul.nav > li#menu-custom > ul").children();
expect($listItems.length).toBe(0);
expect(menuItem).toBeNull();
});
});
// it("should add new menu divider", function () { });
// it("should add duplicate menu divider", function () { });
});
describe("Manipulate Menu Items", function () {
// - verify with jQuery: see WorkingSetView-test.js
// it("should enable a menu item", function () { });
// it("should disable a menu item", function () { });
// it("should check a menu item", function () { });
// it("should uncheck a menu item", function () { });
});
});
});
| test/spec/Menu-test.js | /*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, describe, it, expect, beforeEach, afterEach, waitsFor, runs, $ */
define(function (require, exports, module) {
'use strict';
var Menus,
SpecRunnerUtils = require("./SpecRunnerUtils.js"),
Strings = require("strings");
describe("Menus", function () {
describe("Add Menus", function () {
var testWindow;
beforeEach(function () {
SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
testWindow = w;
// Load module instances from brackets.test
Menus = testWindow.brackets.test.Menus;
});
});
afterEach(function () {
SpecRunnerUtils.closeTestWindow();
});
it("should add new menu in last position of list", function () {
runs(function () {
var $listItems = testWindow.$("#main-toolbar > ul.nav").children();
expect($listItems).toBeTruthy();
var menuCountOriginal = $listItems.length;
var menu = Menus.addMenu("Custom", "menu-custom");
$listItems = testWindow.$("#main-toolbar > ul.nav").children(); // refresh
expect($listItems.length).toBe(menuCountOriginal + 1);
expect($($listItems[menuCountOriginal]).attr("id")).toBe("menu-custom");
});
});
// it("should add new menu after reference menu", function () {
// runs(function () {
// var $listItems = testWindow.$("#main-toolbar > ul.nav").children();
// expect($listItems).toBeTruthy();
//
// var menuCountOriginal = $listItems.length;
// var menu = Menus.addMenu("Custom", "menu-custom", Menus.AFTER, Menus.AppMenuBar.FILE_MENU);
// $listItems = testWindow.$("#main-toolbar > ul.nav").children(); // refresh
//
// expect($listItems.length).toBe(menuCountOriginal + 1);
// expect($($listItems[0]).attr("id")).toBe("Strings.FILE_MENU");
// expect($($listItems[1]).attr("id")).toBe("menu-custom");
// });
// });
// it("should add new menu at end of list when reference menu doesn't exist", function () {
// runs(function () {
// var $listItems = testWindow.$("#main-toolbar > ul.nav").children();
// expect($listItems).toBeTruthy();
//
// var menuCountOriginal = $listItems.length;
// var menu = Menus.addMenu("Custom", "menu-custom", Menus.AFTER, "NONEXISTANT");
// $listItems = testWindow.$("#main-toolbar > ul.nav").children(); // refresh
//
// expect($listItems.length).toBe(menuCountOriginal + 1);
// expect($($listItems[menuCountOriginal]).attr("id")).toBe("menu-custom");
// });
// });
it("should not add duplicate menu", function () {
runs(function () {
var $listItems = testWindow.$("#main-toolbar > ul.nav").children();
expect($listItems).toBeTruthy();
var menuCountOriginal = $listItems.length;
var menu;
try {
menu = Menus.addMenu(Strings.FILE_MENU, Menus.AppMenuBar.FILE_MENU);
} catch (e) {
// catch exception and do nothing
}
$listItems = testWindow.$("#main-toolbar > ul.nav").children(); // refresh
expect($listItems.length).toBe(menuCountOriginal);
});
});
});
describe("Add Menu Items", function () {
// it("should add new menu item to empty menu", function () { });
// it("should add new menu item in first position of menu", function () { });
// it("should add new menu item in last position of menu", function () { });
// it("should add new menu item in position before reference menu item", function () { });
// it("should add new menu item in position after reference menu item", function () { });
// it("should add new menu item in last position of menu if reference menu item doesn't exist", function () { });
// it("should not add duplicate menu item", function () { });
// it("should add new menu divider", function () { });
// it("should add duplicate menu divider", function () { });
});
describe("Manipulate Menu Items", function () {
// - verify with jQuery: see WorkingSetView-test.js
// it("should enable a menu item", function () { });
// it("should disable a menu item", function () { });
// it("should check a menu item", function () { });
// it("should uncheck a menu item", function () { });
});
});
});
| intermediate update
| test/spec/Menu-test.js | intermediate update | <ide><path>est/spec/Menu-test.js
<ide> define(function (require, exports, module) {
<ide> 'use strict';
<ide>
<del> var Menus,
<add> var Commands,
<add> Menus,
<ide> SpecRunnerUtils = require("./SpecRunnerUtils.js"),
<ide> Strings = require("strings");
<ide>
<ide> describe("Menus", function () {
<ide>
<add> var testWindow;
<add>
<add> beforeEach(function () {
<add> SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
<add> testWindow = w;
<add>
<add> // Load module instances from brackets.test
<add> Commands = testWindow.brackets.test.Commands;
<add> Menus = testWindow.brackets.test.Menus;
<add> });
<add> });
<add>
<add> afterEach(function () {
<add> SpecRunnerUtils.closeTestWindow();
<add> });
<add>
<ide> describe("Add Menus", function () {
<ide>
<del> var testWindow;
<del>
<del> beforeEach(function () {
<del> SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
<del> testWindow = w;
<del>
<del> // Load module instances from brackets.test
<del> Menus = testWindow.brackets.test.Menus;
<del> });
<del> });
<del>
<del> afterEach(function () {
<del> SpecRunnerUtils.closeTestWindow();
<del> });
<del>
<ide> it("should add new menu in last position of list", function () {
<ide> runs(function () {
<ide> var $listItems = testWindow.$("#main-toolbar > ul.nav").children();
<del> expect($listItems).toBeTruthy();
<add> expect($listItems).toBeTruthy(); // non-null and defined
<ide>
<ide> var menuCountOriginal = $listItems.length;
<ide> var menu = Menus.addMenu("Custom", "menu-custom");
<add> expect(menu).toBeTruthy();
<add>
<ide> $listItems = testWindow.$("#main-toolbar > ul.nav").children(); // refresh
<del>
<ide> expect($listItems.length).toBe(menuCountOriginal + 1);
<ide> expect($($listItems[menuCountOriginal]).attr("id")).toBe("menu-custom");
<ide> });
<ide> //
<ide> // var menuCountOriginal = $listItems.length;
<ide> // var menu = Menus.addMenu("Custom", "menu-custom", Menus.AFTER, Menus.AppMenuBar.FILE_MENU);
<del>// $listItems = testWindow.$("#main-toolbar > ul.nav").children(); // refresh
<del>//
<add>// expect(menu).toBeTruthy();
<add>//
<add>// $listItems = testWindow.$("#main-toolbar > ul.nav").children();
<ide> // expect($listItems.length).toBe(menuCountOriginal + 1);
<ide> // expect($($listItems[0]).attr("id")).toBe("Strings.FILE_MENU");
<ide> // expect($($listItems[1]).attr("id")).toBe("menu-custom");
<ide> //
<ide> // var menuCountOriginal = $listItems.length;
<ide> // var menu = Menus.addMenu("Custom", "menu-custom", Menus.AFTER, "NONEXISTANT");
<del>// $listItems = testWindow.$("#main-toolbar > ul.nav").children(); // refresh
<del>//
<add>// expect(menu).toBeTruthy();
<add>//
<add>// $listItems = testWindow.$("#main-toolbar > ul.nav").children();
<ide> // expect($listItems.length).toBe(menuCountOriginal + 1);
<ide> // expect($($listItems[menuCountOriginal]).attr("id")).toBe("menu-custom");
<ide> // });
<ide> expect($listItems).toBeTruthy();
<ide>
<ide> var menuCountOriginal = $listItems.length;
<del> var menu;
<add> var menu = null;
<ide>
<ide> try {
<ide> menu = Menus.addMenu(Strings.FILE_MENU, Menus.AppMenuBar.FILE_MENU);
<ide> // catch exception and do nothing
<ide> }
<ide>
<del> $listItems = testWindow.$("#main-toolbar > ul.nav").children(); // refresh
<add> $listItems = testWindow.$("#main-toolbar > ul.nav").children();
<ide> expect($listItems.length).toBe(menuCountOriginal);
<del> });
<del> });
<del>
<del>
<del> });
<add> expect(menu).toBeNull();
<add> });
<add> });
<add> });
<add>
<ide>
<ide> describe("Add Menu Items", function () {
<ide>
<del>// it("should add new menu item to empty menu", function () { });
<del>// it("should add new menu item in first position of menu", function () { });
<del>// it("should add new menu item in last position of menu", function () { });
<add> it("should add new menu item to empty menu", function () {
<add> runs(function () {
<add> // Adding menus tested above, so minimal validation from this point on
<add> var menu = Menus.addMenu("Custom", "menu-custom");
<add> expect(menu).toBeTruthy();
<add>
<add> var $listItems = testWindow.$("#main-toolbar > ul.nav > li#menu-custom > ul").children();
<add> expect($listItems).toBeTruthy();
<add> expect($listItems.length).toBe(0);
<add>
<add> // Re-use commands that are already registered
<add> var menuItem = menu.addMenuItem("menuitem-custom-0", Commands.FILE_NEW);
<add> expect(menuItem).toBeTruthy();
<add>
<add> $listItems = testWindow.$("#main-toolbar > ul.nav > li#menu-custom > ul").children();
<add> expect($listItems.length).toBe(1);
<add> expect(testWindow.$("#main-toolbar > ul.nav > li#menu-custom > ul > li > a#menuitem-custom-0")).toBeTruthy();
<add> });
<add> });
<add>
<add> it("should add new menu item in first position of menu", function () {
<add> runs(function () {
<add> // Add to existing file menu
<add> var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
<add> expect(menu).toBeTruthy();
<add>
<add> var listSelector = "#main-toolbar > ul.nav > li#" + Menus.AppMenuBar.FILE_MENU + " > ul";
<add> var $listItems = testWindow.$(listSelector).children();
<add> expect($listItems).toBeTruthy();
<add> var menuItemCountOriginal = $listItems.length;
<add>
<add> var menuItem = menu.addMenuItem("menuitem-custom-0", Commands.FILE_NEW, Menus.FIRST);
<add> expect(menuItem).toBeTruthy();
<add>
<add> $listItems = testWindow.$(listSelector).children();
<add> expect($listItems.length).toBe(menuItemCountOriginal + 1);
<add> expect(testWindow.$(listSelector + " > li:first-child > a#menuitem-custom-0")).toBeTruthy();
<add> });
<add> });
<add>
<add> it("should add new menu item in last position of menu", function () {
<add> runs(function () {
<add> var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
<add> expect(menu).toBeTruthy();
<add>
<add> var listSelector = "#main-toolbar > ul.nav > li#" + Menus.AppMenuBar.FILE_MENU + " > ul";
<add> var $listItems = testWindow.$(listSelector).children();
<add> expect($listItems).toBeTruthy();
<add> var menuItemCountOriginal = $listItems.length;
<add>
<add> // Use wacky key binding that's hopefully not used
<add> var menuItem = menu.addMenuItem("menuitem-custom-0", Commands.FILE_NEW, "Ctrl-Alt-1", Menus.LAST);
<add> expect(menuItem).toBeTruthy();
<add>
<add> $listItems = testWindow.$(listSelector).children();
<add> expect($listItems.length).toBe(menuItemCountOriginal + 1);
<add> expect(testWindow.$(listSelector + " > li:last-child > a#menuitem-custom-0")).toBeTruthy();
<add> });
<add> });
<add>
<add> it("should add new menu item in position after reference menu item", function () {
<add> runs(function () {
<add> // Add to existing file menu
<add> var menu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
<add> expect(menu).toBeTruthy();
<add>
<add> var listSelector = "#main-toolbar > ul.nav > li#" + Menus.AppMenuBar.FILE_MENU + " > ul";
<add> var $listItems = testWindow.$(listSelector).children();
<add> expect($listItems).toBeTruthy();
<add> var menuItemCountOriginal = $listItems.length;
<add>
<add> menu.addMenuItem("menuitem-custom-0", Commands.FILE_NEW, "Ctrl-Alt-1", Menus.FIRST);
<add> $listItems = testWindow.$(listSelector).children();
<add> expect($listItems.length).toBe(menuItemCountOriginal + 1);
<add>
<add> // Insert new item after the one we just added in the first position
<add> var menuItem = menu.addMenuItem("menuitem-custom-1", Commands.FILE_NEW, "Ctrl-Alt-1", Menus.AFTER, "menuitem-custom-0");
<add> expect(testWindow.$(listSelector + " > li:nth-child(2) > a#menuitem-custom-0")).toBeTruthy();
<add> });
<add> });
<add>
<ide> // it("should add new menu item in position before reference menu item", function () { });
<del>// it("should add new menu item in position after reference menu item", function () { });
<ide> // it("should add new menu item in last position of menu if reference menu item doesn't exist", function () { });
<ide> // it("should not add duplicate menu item", function () { });
<add>
<add> it("should not add menu item with unregistered command", function () {
<add> runs(function () {
<add> var menu = Menus.addMenu("Custom", "menu-custom");
<add> expect(menu).toBeTruthy();
<add>
<add> var $listItems = testWindow.$("#main-toolbar > ul.nav > li#menu-custom > ul").children();
<add> expect($listItems).toBeTruthy();
<add> expect($listItems.length).toBe(0);
<add>
<add> var menuItem = null;
<add>
<add> try {
<add> menuItem = menu.addMenuItem("menuitem-custom-0", "UNREGISTERED_COMMAND");
<add> } catch (e) {
<add> // catch exception and do nothing
<add> }
<add>
<add> $listItems = testWindow.$("#main-toolbar > ul.nav > li#menu-custom > ul").children();
<add>
<add> expect($listItems.length).toBe(0);
<add> expect(menuItem).toBeNull();
<add> });
<add> });
<ide>
<ide> // it("should add new menu divider", function () { });
<ide> // it("should add duplicate menu divider", function () { }); |
|
Java | epl-1.0 | 8b0f7a54808ecd0802c6ddb5d47ac133754f6ce6 | 0 | trajano/openid-connect,trajano/openid-connect | package net.trajano.openidconnect.jaspic.internal;
import static net.trajano.auth.internal.OAuthParameters.CLIENT_ID;
import static net.trajano.auth.internal.OAuthParameters.CODE;
import static net.trajano.auth.internal.OAuthParameters.GRANT_TYPE;
import static net.trajano.auth.internal.OAuthParameters.REDIRECT_URI;
import static net.trajano.auth.internal.OAuthParameters.RESPONSE_TYPE;
import static net.trajano.auth.internal.OAuthParameters.SCOPE;
import static net.trajano.auth.internal.OAuthParameters.STATE;
import static net.trajano.auth.internal.Utils.isGetRequest;
import static net.trajano.auth.internal.Utils.isHeadRequest;
import static net.trajano.auth.internal.Utils.isNullOrEmpty;
import static net.trajano.auth.internal.Utils.isRetrievalRequest;
import static net.trajano.auth.internal.Utils.validateIdToken;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.text.MessageFormat;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.crypto.SecretKey;
import javax.json.Json;
import javax.json.JsonObject;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.MessagePolicy;
import javax.security.auth.message.callback.CallerPrincipalCallback;
import javax.security.auth.message.callback.GroupPrincipalCallback;
import javax.security.auth.message.config.ServerAuthContext;
import javax.security.auth.message.module.ServerAuthModule;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import net.trajano.auth.internal.CipherUtil;
import net.trajano.auth.internal.JsonWebKeySet;
import net.trajano.auth.internal.TokenCookie;
import net.trajano.auth.internal.Utils;
import net.trajano.openidconnect.core.OpenIdProviderConfiguration;
import net.trajano.openidconnect.crypto.Base64Url;
import net.trajano.openidconnect.token.IdTokenResponse;
/**
* OAuth 2.0 server authentication module. This is an implementation of the <a
* href="http://tools.ietf.org/html/rfc6749">OAuth 2.0 authentication
* framework</a>. This assumes no HttpSessions which makes it useful for RESTful
* applications and uses the OAuth token to manage the authentication state. The
* e-mail addresses are not requested.
*
* @author Archimedes Trajano
*/
public abstract class OAuthModule implements ServerAuthModule, ServerAuthContext {
/**
* Access token attribute name.
*/
public static final String ACCESS_TOKEN_KEY = "auth_access";
/**
* Client ID option key and JSON key.
*/
public static final String CLIENT_ID_KEY = "client_id";
/**
* Client secret option key and JSON key.
*/
public static final String CLIENT_SECRET_KEY = "client_secret";
/**
* Cookie context option key. The value is optional.
*/
public static final String COOKIE_CONTEXT_KEY = "cookie_context";
/**
* Disable HTTP certificate checks key. This this is set to true, the auth
* module will disable HTTPS certificate checks for the REST client
* connections. This should only be used in development.
*/
public static final String DISABLE_CERTIFICATE_CHECKS_KEY = "disable_certificate_checks";
/**
* https prefix.
*/
private static final String HTTPS_PREFIX = "https://";
/**
* Open ID token attribute name.
*/
public static final String ID_TOKEN_KEY = "auth_idtoken";
/**
* Logger.
*/
private static final Logger LOG;
/**
* Logger for configuration.
*/
private static final Logger LOGCONFIG;
/**
* URI to go to when the user has logged out relative to the context path.
*/
public static final String LOGOUT_GOTO_URI_KEY = "logout_goto_uri";
public static final String LOGOUT_URI_KEY = "logout_uri";
/**
* Messages resource path.
*/
private static final String MESSAGES = "META-INF/Messages";
/**
* Age cookie name. The value of this cookie is an encrypted version of the
* IP Address and will expire based on the max age of the token.
*/
public static final String NET_TRAJANO_AUTH_AGE = "net.trajano.auth.age";
/**
* ID token cookie name. This one expires when the browser closes.
*/
public static final String NET_TRAJANO_AUTH_ID = "net.trajano.auth.id";
/**
* Nonce cookie name. This one expires when the browser closes.
*/
public static final String NET_TRAJANO_AUTH_NONCE = "net.trajano.auth.nonce";
/**
* Resource bundle.
*/
private static final ResourceBundle R;
/**
* Redirection endpoint URI key. The value is optional and defaults to the
* context root of the application.
*/
public static final String REDIRECTION_ENDPOINT_URI_KEY = "redirection_endpoint"; //$NON-NLS-1$
/**
* Refresh token attribute name.
*/
public static final String REFRESH_TOKEN_KEY = "auth_refresh";
/**
* Scope option key. The value is optional and defaults to "openid"
*/
public static final String SCOPE_KEY = "scope";
/**
* Token URI key. The value is optional and if not specified, the token
* request functionality will not be available.
*/
public static final String TOKEN_URI_KEY = "token_uri";
/**
* User info attribute name.
*/
public static final String USERINFO_KEY = "auth_userinfo";
/**
* User Info URI key. The value is optional and if not specified, the
* userinfo request functionality will not be available.
*/
public static final String USERINFO_URI_KEY = "userinfo_uri";
static {
LOG = Logger.getLogger("net.trajano.auth.oauthsam", MESSAGES);
LOGCONFIG = Logger.getLogger("net.trajano.auth.oauthsam.config", MESSAGES);
R = ResourceBundle.getBundle(MESSAGES);
}
/**
* Client ID. This is set through {@value #CLIENT_ID_KEY} option.
*/
private String clientId;
/**
* Client secret. This is set through {@value #CLIENT_SECRET_KEY} option.
*/
private String clientSecret;
/**
* Cookie context path. Set through through "cookie_context" option. This is
* optional.
*/
private String cookieContext;
/**
* Callback handler.
*/
private CallbackHandler handler;
private String logoutGotoUri;
private String logoutUri;
/**
* Flag to indicate that authentication is mandatory.
*/
private boolean mandatory;
/**
* Options for the module.
*/
private Map<String, String> moduleOptions;
/**
* Randomizer.
*/
private final Random random = new SecureRandom();
/**
* Redirection endpoint URI. This is set through "redirection_endpoint"
* option. This must start with a forward slash. This value is optional.
*/
private String redirectionEndpointUri;
/**
* REST Client. This is not final so a different one can be put in for
* testing.
*/
private Client restClient;
/**
* Scope.
*/
private String scope;
/**
* Secret key used for module level ciphers.
*/
private SecretKey secret;
/**
* Token URI. This is set through "token_uri" option. This must start with a
* forward slash. This value is optional. The calling the token URI will
* return the contents of the JWT token object to the user. Make sure that
* this is intended before setting the value.
*/
private String tokenUri;
/**
* User info URI. This is set through "userinfo_uri" option. This must start
* with a forward slash. This value is optional. The calling the user info
* URI will return the contents of the user info object to the user. Make
* sure that this is intended before setting the value.
*/
private String userInfoUri;
/**
* Builds a REST client that bypasses SSL security checks. Made public so it
* can be used for testing.
*
* @return JAX-RS client.
*/
public Client buildUnsecureRestClient() throws GeneralSecurityException {
final SSLContext context = SSLContext.getInstance("TLSv1");
final TrustManager[] trustManagerArray = { NullX509TrustManager.INSTANCE };
context.init(null, trustManagerArray, null);
return ClientBuilder.newBuilder()
.hostnameVerifier(NullHostnameVerifier.INSTANCE)
.sslContext(context)
.build();
}
/**
* Does nothing.
*
* @param messageInfo
* message info
* @param subject
* subject
*/
@Override
public void cleanSubject(final MessageInfo messageInfo,
final Subject subject) throws AuthException {
// Does nothing.
}
private void deleteAuthCookies(final HttpServletResponse resp) {
for (final String cookieName : new String[] { NET_TRAJANO_AUTH_ID, NET_TRAJANO_AUTH_AGE, NET_TRAJANO_AUTH_NONCE }) {
final Cookie deleteCookie = new Cookie(cookieName, "");
deleteCookie.setMaxAge(0);
deleteCookie.setPath(cookieContext);
resp.addCookie(deleteCookie);
}
}
/**
* Client ID.
*
* @return the client ID.
*/
protected String getClientId() {
return clientId;
}
/**
* Client Secret.
*
* @return the client secret.
*/
protected String getClientSecret() {
return clientSecret;
}
/**
* Gets the ID token. This ensures that both cookies are present, if not
* then this will return <code>null</code>.
*
* @param req
* HTTP servlet request
* @return ID token
* @throws GeneralSecurityException
* @throws IOException
*/
private String getIdToken(final HttpServletRequest req) throws GeneralSecurityException,
IOException {
final Cookie[] cookies = req.getCookies();
if (cookies == null) {
return null;
}
String idToken = null;
boolean foundAge = false;
for (final Cookie cookie : cookies) {
if (NET_TRAJANO_AUTH_ID.equals(cookie.getName()) && !isNullOrEmpty(cookie.getValue())) {
idToken = cookie.getValue();
} else if (NET_TRAJANO_AUTH_AGE.equals(cookie.getName())) {
final String remoteAddr = req.getRemoteAddr();
final String cookieAddr = new String(CipherUtil.decrypt(Base64Url.decode(cookie.getValue()), secret), "US-ASCII");
if (!remoteAddr.equals(cookieAddr)) {
throw new AuthException(MessageFormat.format(R.getString("ipaddressMismatch"), remoteAddr, cookieAddr));
}
foundAge = true;
}
if (idToken != null && foundAge) {
return idToken;
}
}
return null;
}
/**
* Gets the nonce from the cookie.
*
* @param req
* @return
* @throws GeneralSecurityException
* @throws IOException
*/
private String getNonceFromCookie(final HttpServletRequest req) throws GeneralSecurityException,
IOException {
final Cookie[] cookies = req.getCookies();
if (cookies == null) {
return null;
}
for (final Cookie cookie : cookies) {
if (NET_TRAJANO_AUTH_NONCE.equals(cookie.getName())) {
return new String(CipherUtil.decrypt(Base64Url.decode(cookie.getValue()), secret), "US-ASCII");
}
}
return null;
}
/**
* Lets subclasses change the provider configuration.
*
* @param req
* request message
* @param client
* REST client
* @param options
* module options
* @return configuration
* @throws AuthException
* wraps exceptions thrown during processing
*/
protected abstract OpenIdProviderConfiguration getOpenIDProviderConfig(HttpServletRequest req,
Client client,
Map<String, String> options) throws AuthException;
/**
* This gets the redirection endpoint URI. It uses the
* {@link #REDIRECTION_ENDPOINT_URI_KEY} option resolved against the request
* URL to get the host name.
*
* @param req
* request
* @return redirection endpoint URI.
*/
protected URI getRedirectionEndpointUri(final HttpServletRequest req) {
return URI.create(req.getRequestURL()
.toString())
.resolve(redirectionEndpointUri);
}
/**
* Gets an option and ensures it is present.
*
* @param optionKey
* option key
* @return the option value
* @throws AuthException
* missing option exception
*/
private String getRequiredOption(final String optionKey) throws AuthException {
final String optionValue = moduleOptions.get(optionKey);
if (optionValue == null) {
LOG.log(Level.SEVERE, "missingOption", optionKey);
throw new AuthException(MessageFormat.format(R.getString("missingOption"), optionKey));
}
return optionValue;
}
/**
* REST client.
*
* @return REST client
*/
protected Client getRestClient() {
return restClient;
}
/**
* <p>
* Supported message types. For our case we only need to deal with HTTP
* servlet request and responses. On Java EE 7 this will handle WebSockets
* as well.
* </p>
* <p>
* This creates a new array for security at the expense of performance.
* </p>
*
* @return {@link HttpServletRequest} and {@link HttpServletResponse}
* classes.
*/
@SuppressWarnings("rawtypes")
@Override
public Class[] getSupportedMessageTypes() {
return new Class<?>[] { HttpServletRequest.class, HttpServletResponse.class };
}
/**
* Sends a request to the token endpoint to get the token for the code.
*
* @param req
* servlet request
* @param oidProviderConfig
* OpenID provider config
* @return token response
*/
protected IdTokenResponse getToken(final HttpServletRequest req,
final OpenIdProviderConfiguration oidProviderConfig) throws IOException {
final MultivaluedMap<String, String> requestData = new MultivaluedHashMap<>();
requestData.putSingle(CODE, req.getParameter("code"));
requestData.putSingle(GRANT_TYPE, "authorization_code");
requestData.putSingle(REDIRECT_URI, getRedirectionEndpointUri(req).toASCIIString());
try {
final String authorization = "Basic " + Base64Url.encode((clientId + ":" + clientSecret).getBytes("UTF8"));
final IdTokenResponse authorizationTokenResponse = restClient.target(oidProviderConfig.getTokenEndpoint())
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", authorization)
.post(Entity.form(requestData), IdTokenResponse.class);
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("authorization token response = " + authorizationTokenResponse);
}
return authorizationTokenResponse;
} catch (final BadRequestException e) {
// workaround for google that does not support BASIC authentication
// on their endpoint.
requestData.putSingle(CLIENT_ID, clientId);
requestData.putSingle(CLIENT_SECRET_KEY, clientSecret);
final IdTokenResponse authorizationTokenResponse = restClient.target(oidProviderConfig.getTokenEndpoint())
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.form(requestData), IdTokenResponse.class);
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("authorization token response = " + authorizationTokenResponse);
}
return authorizationTokenResponse;
}
}
/**
* Gets the web keys from the options and the OpenID provider configuration.
* This may be overridden by clients.
*
* @param options
* module options
* @param config
* provider configuration
* @return web keys
* @throws GeneralSecurityException
* wraps exceptions thrown during processing
*/
protected JsonWebKeySet getWebKeys(final Map<String, String> options,
final OpenIdProviderConfiguration config) throws GeneralSecurityException {
return new JsonWebKeySet(restClient.target(config.getJwksUri())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(JsonObject.class));
}
/**
* Workaround for the issuer value for Google. This was documented in
* 15.6.2. of the spec. In which case if the issuer does not start with
* https:// it will prepend it.
*
* @param issuer
* issuer
* @return updated issuer
*/
private String googleWorkaround(final String issuer) {
if (issuer.startsWith(HTTPS_PREFIX)) {
return issuer;
}
return HTTPS_PREFIX + issuer;
}
/**
* Handles the callback.
*
* @param req
* servlet request
* @param resp
* servlet response
* @param subject
* user subject
* @return status
* @throws GeneralSecurityException
*/
private AuthStatus handleCallback(final HttpServletRequest req,
final HttpServletResponse resp,
final Subject subject) throws GeneralSecurityException,
IOException {
final OpenIdProviderConfiguration oidProviderConfig = getOpenIDProviderConfig(req, restClient, moduleOptions);
final IdTokenResponse token = getToken(req, oidProviderConfig);
final JsonWebKeySet webKeys = getWebKeys(moduleOptions, oidProviderConfig);
LOG.log(Level.FINEST, "tokenValue", token);
final JsonObject claimsSet = Json.createReader(new ByteArrayInputStream(Utils.getJwsPayload(token.getEncodedIdToken(), webKeys)))
.readObject();
final String nonce = getNonceFromCookie(req);
validateIdToken(clientId, claimsSet, nonce);
final Cookie deleteNonceCookie = new Cookie(NET_TRAJANO_AUTH_NONCE, "");
deleteNonceCookie.setMaxAge(0);
deleteNonceCookie.setPath(cookieContext);
resp.addCookie(deleteNonceCookie);
final String iss = googleWorkaround(claimsSet.getString("iss"));
final String issuer = googleWorkaround(oidProviderConfig.getIssuer());
if (!iss.equals(issuer)) {
LOG.log(Level.SEVERE, "issuerMismatch", new Object[] { iss, issuer });
throw new GeneralSecurityException(MessageFormat.format(R.getString("issuerMismatch"), iss, issuer));
}
updateSubjectPrincipal(subject, claimsSet);
final TokenCookie tokenCookie;
if (oidProviderConfig.getUserinfoEndpoint() != null && Pattern.compile("\\bprofile\\b")
.matcher(scope)
.find()) {
final Response userInfoResponse = restClient.target(oidProviderConfig.getUserinfoEndpoint())
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", token.getTokenType() + " " + token.getAccessToken())
.get();
if (userInfoResponse.getStatus() == 200) {
tokenCookie = new TokenCookie(token.getAccessToken(), token.getRefreshToken(), claimsSet, userInfoResponse.readEntity(JsonObject.class));
} else {
LOG.log(Level.WARNING, "unableToGetProfile");
tokenCookie = new TokenCookie(claimsSet);
}
} else {
tokenCookie = new TokenCookie(claimsSet);
}
final String requestCookieContext;
if (isNullOrEmpty(cookieContext)) {
requestCookieContext = req.getContextPath();
} else {
requestCookieContext = cookieContext;
}
final Cookie idTokenCookie = new Cookie(NET_TRAJANO_AUTH_ID, tokenCookie.toCookieValue(clientId, clientSecret));
idTokenCookie.setMaxAge(-1);
idTokenCookie.setSecure(true);
idTokenCookie.setHttpOnly(true);
idTokenCookie.setPath(requestCookieContext);
resp.addCookie(idTokenCookie);
final Cookie ageCookie = new Cookie(NET_TRAJANO_AUTH_AGE, Base64Url.encode(CipherUtil.encrypt(req.getRemoteAddr()
.getBytes("US-ASCII"), secret)));
if (isNullOrEmpty(req.getParameter("expires_in"))) {
ageCookie.setMaxAge(3600);
} else {
ageCookie.setMaxAge(Integer.parseInt(req.getParameter("expires_in")));
}
ageCookie.setPath(requestCookieContext);
ageCookie.setSecure(true);
ageCookie.setHttpOnly(true);
resp.addCookie(ageCookie);
final String stateEncoded = req.getParameter("state");
final String redirectUri = new String(Base64Url.decode(stateEncoded));
resp.sendRedirect(resp.encodeRedirectURL(req.getContextPath() + redirectUri));
return AuthStatus.SEND_SUCCESS;
}
/**
* {@inheritDoc}
*
* @param requestPolicy
* request policy, ignored
* @param responsePolicy
* response policy, ignored
* @param h
* callback handler
* @param options
* options
*/
@SuppressWarnings("unchecked")
@Override
public void initialize(final MessagePolicy requestPolicy,
final MessagePolicy responsePolicy,
final CallbackHandler h,
@SuppressWarnings("rawtypes") final Map options) throws AuthException {
try {
moduleOptions = options;
clientId = getRequiredOption(CLIENT_ID_KEY);
cookieContext = moduleOptions.get(COOKIE_CONTEXT_KEY);
redirectionEndpointUri = getRequiredOption(REDIRECTION_ENDPOINT_URI_KEY);
tokenUri = moduleOptions.get(TOKEN_URI_KEY);
userInfoUri = moduleOptions.get(USERINFO_URI_KEY);
logoutUri = moduleOptions.get(LOGOUT_URI_KEY);
logoutGotoUri = moduleOptions.get(LOGOUT_GOTO_URI_KEY);
scope = moduleOptions.get(SCOPE_KEY);
if (isNullOrEmpty(scope)) {
scope = "openid";
}
clientSecret = getRequiredOption(CLIENT_SECRET_KEY);
LOGCONFIG.log(Level.CONFIG, "options", moduleOptions);
handler = h;
mandatory = requestPolicy.isMandatory();
secret = CipherUtil.buildSecretKey(clientId, clientSecret);
if (restClient == null) {
if (moduleOptions.get(DISABLE_CERTIFICATE_CHECKS_KEY) != null && Boolean.valueOf(moduleOptions.get(DISABLE_CERTIFICATE_CHECKS_KEY))) {
restClient = buildUnsecureRestClient();
} else {
restClient = ClientBuilder.newClient();
}
}
} catch (final Exception e) {
// Should not happen
LOG.log(Level.SEVERE, "initializeException", e);
throw new AuthException(MessageFormat.format(R.getString("initializeException"), e.getMessage()));
}
}
/**
* Checks to see whether the {@link ServerAuthModule} is called by the
* resource owner. This is indicated by the presence of a <code>code</code>
* and a <code>state</code> on the URL and is an idempotent request (i.e.
* GET or HEAD). The resource owner would be a web browser that got a
* redirect sent by the OAuth 2.0 provider.
*
* @param req
* HTTP servlet request
* @return the module is called by the resource owner.
*/
public boolean isCallback(final HttpServletRequest req) {
return moduleOptions.get(REDIRECTION_ENDPOINT_URI_KEY)
.equals(req.getRequestURI()) && isRetrievalRequest(req) && !isNullOrEmpty(req.getParameter(CODE)) && !isNullOrEmpty(req.getParameter(STATE));
}
/**
* Generate the next nonce.
*
* @return nonce
*/
private String nextNonce() {
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
return Base64Url.encode(bytes);
}
/**
* Builds the token cookie and updates the subject principal and sets the
* token and user info attribute in the request. Any exceptions or
* validation problems during validation will make this return
* <code>null</code> to indicate that there was no valid token.
*
* @param subject
* subject
* @param req
* servlet request
* @return token cookie.
*/
private TokenCookie processTokenCookie(final Subject subject,
final HttpServletRequest req) {
try {
final String idToken = getIdToken(req);
TokenCookie tokenCookie = null;
if (idToken != null) {
tokenCookie = new TokenCookie(idToken, secret);
validateIdToken(clientId, tokenCookie.getIdToken(), null);
updateSubjectPrincipal(subject, tokenCookie.getIdToken());
req.setAttribute(ACCESS_TOKEN_KEY, tokenCookie.getAccessToken());
req.setAttribute(REFRESH_TOKEN_KEY, tokenCookie.getRefreshToken());
req.setAttribute(ID_TOKEN_KEY, tokenCookie.getIdToken());
if (tokenCookie.getUserInfo() != null) {
req.setAttribute(USERINFO_KEY, tokenCookie.getUserInfo());
}
}
return tokenCookie;
} catch (final GeneralSecurityException | IOException e) {
LOG.log(Level.FINE, "invalidToken", e.getMessage());
LOG.throwing(this.getClass()
.getName(), "validateRequest", e);
return null;
}
}
/**
* Sends a redirect to the authorization endpoint. It sends the current
* request URI as the state so that the user can be redirected back to the
* last place. However, this does not work for non-idempotent requests such
* as POST in those cases it will result in a 401 error and
* {@link AuthStatus#SEND_FAILURE}. For idempotent requests, it will build
* the redirect URI and return {@link AuthStatus#SEND_CONTINUE}. It will
* also destroy the cookies used for authorization as part of the response.
* <p>
* It stores an encrypted nonce in the cookies and uses it to verify the
* nonce value later.
* </p>
*
* @param req
* HTTP servlet request
* @param resp
* HTTP servlet response
* @param reason
* reason for redirect (used for logging)
* @return authentication status
* @throws AuthException
*/
private AuthStatus redirectToAuthorizationEndpoint(final HttpServletRequest req,
final HttpServletResponse resp,
final String reason) throws AuthException {
LOG.log(Level.FINE, "redirecting", new Object[] { reason });
URI authorizationEndpointUri = null;
try {
final OpenIdProviderConfiguration oidProviderConfig = getOpenIDProviderConfig(req, restClient, moduleOptions);
final StringBuilder stateBuilder = new StringBuilder(req.getRequestURI()
.substring(req.getContextPath()
.length()));
if (req.getQueryString() != null) {
stateBuilder.append('?');
stateBuilder.append(req.getQueryString());
}
final String state = Base64Url.encode(stateBuilder.toString()
.getBytes("UTF-8"));
final String requestCookieContext;
if (isNullOrEmpty(cookieContext)) {
requestCookieContext = req.getContextPath();
} else {
requestCookieContext = cookieContext;
}
final String nonce = nextNonce();
final Cookie nonceCookie = new Cookie(NET_TRAJANO_AUTH_NONCE, Base64Url.encode(CipherUtil.encrypt(nonce.getBytes(), secret)));
nonceCookie.setMaxAge(-1);
nonceCookie.setPath(requestCookieContext);
nonceCookie.setHttpOnly(true);
nonceCookie.setSecure(true);
resp.addCookie(nonceCookie);
authorizationEndpointUri = UriBuilder.fromUri(oidProviderConfig.getAuthorizationEndpoint())
.queryParam(CLIENT_ID, clientId)
.queryParam(RESPONSE_TYPE, "code")
.queryParam(SCOPE, scope)
.queryParam(REDIRECT_URI, URI.create(req.getRequestURL()
.toString())
.resolve(moduleOptions.get(REDIRECTION_ENDPOINT_URI_KEY)))
.queryParam(STATE, state)
.queryParam("nonce", nonce)
.build();
deleteAuthCookies(resp);
resp.sendRedirect(authorizationEndpointUri.toASCIIString());
return AuthStatus.SEND_CONTINUE;
} catch (final IOException | GeneralSecurityException e) {
// Should not happen
LOG.log(Level.SEVERE, "sendRedirectException", new Object[] { authorizationEndpointUri, e.getMessage() });
LOG.throwing(this.getClass()
.getName(), "redirectToAuthorizationEndpoint", e);
throw new AuthException(MessageFormat.format(R.getString("sendRedirectException"), authorizationEndpointUri, e.getMessage()));
}
}
/**
* Return {@link AuthStatus#SEND_SUCCESS}.
*
* @param messageInfo
* contains the request and response messages. At this point the
* response message is already committed so nothing can be
* changed.
* @param subject
* subject.
* @return {@link AuthStatus#SEND_SUCCESS}
*/
@Override
public AuthStatus secureResponse(final MessageInfo messageInfo,
final Subject subject) throws AuthException {
return AuthStatus.SEND_SUCCESS;
}
/**
* Override REST client for testing.
*
* @param restClient
* REST client. May be mocked.
*/
public void setRestClient(final Client restClient) {
this.restClient = restClient;
}
/**
* Updates the principal for the subject. This is done through the
* callbacks.
*
* @param subject
* subject
* @param jwtPayload
* JWT payload
* @throws AuthException
* @throws GeneralSecurityException
*/
private void updateSubjectPrincipal(final Subject subject,
final JsonObject jwtPayload) throws GeneralSecurityException {
try {
final String iss = googleWorkaround(jwtPayload.getString("iss"));
handler.handle(new Callback[] { new CallerPrincipalCallback(subject, UriBuilder.fromUri(iss)
.userInfo(jwtPayload.getString("sub"))
.build()
.toASCIIString()), new GroupPrincipalCallback(subject, new String[] { iss }) });
} catch (final IOException | UnsupportedCallbackException e) {
// Should not happen
LOG.log(Level.SEVERE, "updatePrincipalException", e.getMessage());
LOG.throwing(this.getClass()
.getName(), "updateSubjectPrincipal", e);
throw new AuthException(MessageFormat.format(R.getString("updatePrincipalException"), e.getMessage()));
}
}
/**
* Validates the request. The request must be secure otherwise it will
* return {@link AuthStatus#FAILURE}. It then tries to build the token
* cookie data if available, if the token is valid, subject is set correctly
* and user info data if present is stored in the request, then call HTTP
* method specific operations.
*
* @param messageInfo
* request and response
* @param clientSubject
* client subject
* @param serviceSubject
* service subject, ignored.
* @return Auth status
*/
@Override
public AuthStatus validateRequest(final MessageInfo messageInfo,
final Subject clientSubject,
final Subject serviceSubject) throws AuthException {
final HttpServletRequest req = (HttpServletRequest) messageInfo.getRequestMessage();
final HttpServletResponse resp = (HttpServletResponse) messageInfo.getResponseMessage();
try {
final TokenCookie tokenCookie = processTokenCookie(clientSubject, req);
if (tokenCookie != null && req.isSecure() && isGetRequest(req) && req.getRequestURI()
.equals(tokenUri)) {
resp.setContentType(MediaType.APPLICATION_JSON);
resp.getWriter()
.print(tokenCookie.getIdToken());
return AuthStatus.SEND_SUCCESS;
}
if (tokenCookie != null && req.isSecure() && isGetRequest(req) && req.getRequestURI()
.equals(userInfoUri)) {
resp.setContentType(MediaType.APPLICATION_JSON);
resp.getWriter()
.print(tokenCookie.getUserInfo());
return AuthStatus.SEND_SUCCESS;
}
if (tokenCookie != null && req.isSecure() && isGetRequest(req) && req.getRequestURI()
.equals(logoutUri)) {
deleteAuthCookies(resp);
if (logoutGotoUri == null) {
resp.sendRedirect(req.getServletContext() + "/");
} else {
resp.sendRedirect(logoutGotoUri);
}
return AuthStatus.SEND_SUCCESS;
}
if (!mandatory && !req.isSecure()) {
// successful if the module is not mandatory and the channel is
// not secure.
return AuthStatus.SUCCESS;
}
if (!req.isSecure() && mandatory) {
// Fail authorization 3.1.2.1
resp.sendError(HttpURLConnection.HTTP_FORBIDDEN, R.getString("SSLReq"));
return AuthStatus.SEND_FAILURE;
}
if (!req.isSecure() && isCallback(req)) {
resp.sendError(HttpURLConnection.HTTP_FORBIDDEN, R.getString("SSLReq"));
return AuthStatus.SEND_FAILURE;
}
if (req.isSecure() && isCallback(req)) {
return handleCallback(req, resp, clientSubject);
}
if (!mandatory || tokenCookie != null && !tokenCookie.isExpired()) {
return AuthStatus.SUCCESS;
}
if (req.isSecure() && isHeadRequest(req) && req.getRequestURI()
.equals(tokenUri)) {
resp.setContentType(MediaType.APPLICATION_JSON);
return AuthStatus.SEND_SUCCESS;
}
if (req.getRequestURI()
.equals(userInfoUri) && isHeadRequest(req)) {
resp.setContentType(MediaType.APPLICATION_JSON);
return AuthStatus.SEND_SUCCESS;
}
if (!isRetrievalRequest(req)) {
resp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "Unable to POST when unauthorized.");
return AuthStatus.SEND_FAILURE;
}
return redirectToAuthorizationEndpoint(req, resp, "request is not valid");
} catch (final Exception e) {
// Any problems with the data should be caught and force redirect to
// authorization endpoint.
LOG.log(Level.FINE, "validationException", e.getMessage());
LOG.throwing(this.getClass()
.getName(), "validateRequest", e);
return redirectToAuthorizationEndpoint(req, resp, e.getMessage());
}
}
}
| openid-connect-jaspic-module/src/main/java/net/trajano/openidconnect/jaspic/internal/OAuthModule.java | package net.trajano.openidconnect.jaspic.internal;
import static net.trajano.auth.internal.OAuthParameters.CLIENT_ID;
import static net.trajano.auth.internal.OAuthParameters.CODE;
import static net.trajano.auth.internal.OAuthParameters.GRANT_TYPE;
import static net.trajano.auth.internal.OAuthParameters.REDIRECT_URI;
import static net.trajano.auth.internal.OAuthParameters.RESPONSE_TYPE;
import static net.trajano.auth.internal.OAuthParameters.SCOPE;
import static net.trajano.auth.internal.OAuthParameters.STATE;
import static net.trajano.auth.internal.Utils.isGetRequest;
import static net.trajano.auth.internal.Utils.isHeadRequest;
import static net.trajano.auth.internal.Utils.isNullOrEmpty;
import static net.trajano.auth.internal.Utils.isRetrievalRequest;
import static net.trajano.auth.internal.Utils.validateIdToken;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.text.MessageFormat;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.crypto.SecretKey;
import javax.json.Json;
import javax.json.JsonObject;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.message.AuthException;
import javax.security.auth.message.AuthStatus;
import javax.security.auth.message.MessageInfo;
import javax.security.auth.message.MessagePolicy;
import javax.security.auth.message.callback.CallerPrincipalCallback;
import javax.security.auth.message.callback.GroupPrincipalCallback;
import javax.security.auth.message.config.ServerAuthContext;
import javax.security.auth.message.module.ServerAuthModule;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import net.trajano.auth.internal.CipherUtil;
import net.trajano.auth.internal.JsonWebKeySet;
import net.trajano.auth.internal.OAuthToken;
import net.trajano.auth.internal.TokenCookie;
import net.trajano.auth.internal.Utils;
import net.trajano.openidconnect.core.OpenIdProviderConfiguration;
import net.trajano.openidconnect.crypto.Base64Url;
/**
* OAuth 2.0 server authentication module. This is an implementation of the <a
* href="http://tools.ietf.org/html/rfc6749">OAuth 2.0 authentication
* framework</a>. This assumes no HttpSessions which makes it useful for RESTful
* applications and uses the OAuth token to manage the authentication state. The
* e-mail addresses are not requested.
*
* @author Archimedes Trajano
*/
public abstract class OAuthModule implements ServerAuthModule, ServerAuthContext {
/**
* Access token attribute name.
*/
public static final String ACCESS_TOKEN_KEY = "auth_access";
/**
* Client ID option key and JSON key.
*/
public static final String CLIENT_ID_KEY = "client_id";
/**
* Client secret option key and JSON key.
*/
public static final String CLIENT_SECRET_KEY = "client_secret";
/**
* Cookie context option key. The value is optional.
*/
public static final String COOKIE_CONTEXT_KEY = "cookie_context";
/**
* Disable HTTP certificate checks key. This this is set to true, the auth
* module will disable HTTPS certificate checks for the REST client
* connections. This should only be used in development.
*/
public static final String DISABLE_CERTIFICATE_CHECKS_KEY = "disable_certificate_checks";
/**
* https prefix.
*/
private static final String HTTPS_PREFIX = "https://";
/**
* Open ID token attribute name.
*/
public static final String ID_TOKEN_KEY = "auth_idtoken";
/**
* Logger.
*/
private static final Logger LOG;
/**
* Logger for configuration.
*/
private static final Logger LOGCONFIG;
/**
* URI to go to when the user has logged out relative to the context path.
*/
public static final String LOGOUT_GOTO_URI_KEY = "logout_goto_uri";
public static final String LOGOUT_URI_KEY = "logout_uri";
/**
* Messages resource path.
*/
private static final String MESSAGES = "META-INF/Messages";
/**
* Age cookie name. The value of this cookie is an encrypted version of the
* IP Address and will expire based on the max age of the token.
*/
public static final String NET_TRAJANO_AUTH_AGE = "net.trajano.auth.age";
/**
* ID token cookie name. This one expires when the browser closes.
*/
public static final String NET_TRAJANO_AUTH_ID = "net.trajano.auth.id";
/**
* Nonce cookie name. This one expires when the browser closes.
*/
public static final String NET_TRAJANO_AUTH_NONCE = "net.trajano.auth.nonce";
/**
* Resource bundle.
*/
private static final ResourceBundle R;
/**
* Redirection endpoint URI key. The value is optional and defaults to the
* context root of the application.
*/
public static final String REDIRECTION_ENDPOINT_URI_KEY = "redirection_endpoint"; //$NON-NLS-1$
/**
* Refresh token attribute name.
*/
public static final String REFRESH_TOKEN_KEY = "auth_refresh";
/**
* Scope option key. The value is optional and defaults to "openid"
*/
public static final String SCOPE_KEY = "scope";
/**
* Token URI key. The value is optional and if not specified, the token
* request functionality will not be available.
*/
public static final String TOKEN_URI_KEY = "token_uri";
/**
* User info attribute name.
*/
public static final String USERINFO_KEY = "auth_userinfo";
/**
* User Info URI key. The value is optional and if not specified, the
* userinfo request functionality will not be available.
*/
public static final String USERINFO_URI_KEY = "userinfo_uri";
static {
LOG = Logger.getLogger("net.trajano.auth.oauthsam", MESSAGES);
LOGCONFIG = Logger.getLogger("net.trajano.auth.oauthsam.config", MESSAGES);
R = ResourceBundle.getBundle(MESSAGES);
}
/**
* Client ID. This is set through {@value #CLIENT_ID_KEY} option.
*/
private String clientId;
/**
* Client secret. This is set through {@value #CLIENT_SECRET_KEY} option.
*/
private String clientSecret;
/**
* Cookie context path. Set through through "cookie_context" option. This is
* optional.
*/
private String cookieContext;
/**
* Callback handler.
*/
private CallbackHandler handler;
private String logoutGotoUri;
private String logoutUri;
/**
* Flag to indicate that authentication is mandatory.
*/
private boolean mandatory;
/**
* Options for the module.
*/
private Map<String, String> moduleOptions;
/**
* Randomizer.
*/
private final Random random = new SecureRandom();
/**
* Redirection endpoint URI. This is set through "redirection_endpoint"
* option. This must start with a forward slash. This value is optional.
*/
private String redirectionEndpointUri;
/**
* REST Client. This is not final so a different one can be put in for
* testing.
*/
private Client restClient;
/**
* Scope.
*/
private String scope;
/**
* Secret key used for module level ciphers.
*/
private SecretKey secret;
/**
* Token URI. This is set through "token_uri" option. This must start with a
* forward slash. This value is optional. The calling the token URI will
* return the contents of the JWT token object to the user. Make sure that
* this is intended before setting the value.
*/
private String tokenUri;
/**
* User info URI. This is set through "userinfo_uri" option. This must start
* with a forward slash. This value is optional. The calling the user info
* URI will return the contents of the user info object to the user. Make
* sure that this is intended before setting the value.
*/
private String userInfoUri;
/**
* Builds a REST client that bypasses SSL security checks. Made public so it
* can be used for testing.
*
* @return JAX-RS client.
*/
public Client buildUnsecureRestClient() throws GeneralSecurityException {
final SSLContext context = SSLContext.getInstance("TLSv1");
final TrustManager[] trustManagerArray = { NullX509TrustManager.INSTANCE };
context.init(null, trustManagerArray, null);
return ClientBuilder.newBuilder()
.hostnameVerifier(NullHostnameVerifier.INSTANCE)
.sslContext(context)
.build();
}
/**
* Does nothing.
*
* @param messageInfo
* message info
* @param subject
* subject
*/
@Override
public void cleanSubject(final MessageInfo messageInfo,
final Subject subject) throws AuthException {
// Does nothing.
}
private void deleteAuthCookies(final HttpServletResponse resp) {
for (final String cookieName : new String[] { NET_TRAJANO_AUTH_ID, NET_TRAJANO_AUTH_AGE, NET_TRAJANO_AUTH_NONCE }) {
final Cookie deleteCookie = new Cookie(cookieName, "");
deleteCookie.setMaxAge(0);
deleteCookie.setPath(cookieContext);
resp.addCookie(deleteCookie);
}
}
/**
* Client ID.
*
* @return the client ID.
*/
protected String getClientId() {
return clientId;
}
/**
* Client Secret.
*
* @return the client secret.
*/
protected String getClientSecret() {
return clientSecret;
}
/**
* Gets the ID token. This ensures that both cookies are present, if not
* then this will return <code>null</code>.
*
* @param req
* HTTP servlet request
* @return ID token
* @throws GeneralSecurityException
* @throws IOException
*/
private String getIdToken(final HttpServletRequest req) throws GeneralSecurityException,
IOException {
final Cookie[] cookies = req.getCookies();
if (cookies == null) {
return null;
}
String idToken = null;
boolean foundAge = false;
for (final Cookie cookie : cookies) {
if (NET_TRAJANO_AUTH_ID.equals(cookie.getName()) && !isNullOrEmpty(cookie.getValue())) {
idToken = cookie.getValue();
} else if (NET_TRAJANO_AUTH_AGE.equals(cookie.getName())) {
final String remoteAddr = req.getRemoteAddr();
final String cookieAddr = new String(CipherUtil.decrypt(Base64Url.decode(cookie.getValue()), secret), "US-ASCII");
if (!remoteAddr.equals(cookieAddr)) {
throw new AuthException(MessageFormat.format(R.getString("ipaddressMismatch"), remoteAddr, cookieAddr));
}
foundAge = true;
}
if (idToken != null && foundAge) {
return idToken;
}
}
return null;
}
/**
* Gets the nonce from the cookie.
*
* @param req
* @return
* @throws GeneralSecurityException
* @throws IOException
*/
private String getNonceFromCookie(final HttpServletRequest req) throws GeneralSecurityException,
IOException {
final Cookie[] cookies = req.getCookies();
if (cookies == null) {
return null;
}
for (final Cookie cookie : cookies) {
if (NET_TRAJANO_AUTH_NONCE.equals(cookie.getName())) {
return new String(CipherUtil.decrypt(Base64Url.decode(cookie.getValue()), secret), "US-ASCII");
}
}
return null;
}
/**
* Lets subclasses change the provider configuration.
*
* @param req
* request message
* @param client
* REST client
* @param options
* module options
* @return configuration
* @throws AuthException
* wraps exceptions thrown during processing
*/
protected abstract OpenIdProviderConfiguration getOpenIDProviderConfig(HttpServletRequest req,
Client client,
Map<String, String> options) throws AuthException;
/**
* This gets the redirection endpoint URI. It uses the
* {@link #REDIRECTION_ENDPOINT_URI_KEY} option resolved against the request
* URL to get the host name.
*
* @param req
* request
* @return redirection endpoint URI.
*/
protected URI getRedirectionEndpointUri(final HttpServletRequest req) {
return URI.create(req.getRequestURL()
.toString())
.resolve(redirectionEndpointUri);
}
/**
* Gets an option and ensures it is present.
*
* @param optionKey
* option key
* @return the option value
* @throws AuthException
* missing option exception
*/
private String getRequiredOption(final String optionKey) throws AuthException {
final String optionValue = moduleOptions.get(optionKey);
if (optionValue == null) {
LOG.log(Level.SEVERE, "missingOption", optionKey);
throw new AuthException(MessageFormat.format(R.getString("missingOption"), optionKey));
}
return optionValue;
}
/**
* REST client.
*
* @return REST client
*/
protected Client getRestClient() {
return restClient;
}
/**
* <p>
* Supported message types. For our case we only need to deal with HTTP
* servlet request and responses. On Java EE 7 this will handle WebSockets
* as well.
* </p>
* <p>
* This creates a new array for security at the expense of performance.
* </p>
*
* @return {@link HttpServletRequest} and {@link HttpServletResponse}
* classes.
*/
@SuppressWarnings("rawtypes")
@Override
public Class[] getSupportedMessageTypes() {
return new Class<?>[] { HttpServletRequest.class, HttpServletResponse.class };
}
/**
* Sends a request to the token endpoint to get the token for the code.
*
* @param req
* servlet request
* @param oidProviderConfig
* OpenID provider config
* @return token response
*/
protected OAuthToken getToken(final HttpServletRequest req,
final OpenIdProviderConfiguration oidProviderConfig) throws IOException {
final MultivaluedMap<String, String> requestData = new MultivaluedHashMap<>();
requestData.putSingle(CODE, req.getParameter("code"));
requestData.putSingle(GRANT_TYPE, "authorization_code");
requestData.putSingle(REDIRECT_URI, getRedirectionEndpointUri(req).toASCIIString());
try {
final String authorization = "Basic " + Base64Url.encode((clientId + ":" + clientSecret).getBytes("UTF8"));
final OAuthToken authorizationTokenResponse = restClient.target(oidProviderConfig.getTokenEndpoint())
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", authorization)
.post(Entity.form(requestData), OAuthToken.class);
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("authorization token response = " + authorizationTokenResponse);
}
return authorizationTokenResponse;
} catch (final BadRequestException e) {
// workaround for google that does not support BASIC authentication
// on their endpoint.
requestData.putSingle(CLIENT_ID, clientId);
requestData.putSingle(CLIENT_SECRET_KEY, clientSecret);
final OAuthToken authorizationTokenResponse = restClient.target(oidProviderConfig.getTokenEndpoint())
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.form(requestData), OAuthToken.class);
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("authorization token response = " + authorizationTokenResponse);
}
return authorizationTokenResponse;
}
}
/**
* Gets the web keys from the options and the OpenID provider configuration.
* This may be overridden by clients.
*
* @param options
* module options
* @param config
* provider configuration
* @return web keys
* @throws GeneralSecurityException
* wraps exceptions thrown during processing
*/
protected JsonWebKeySet getWebKeys(final Map<String, String> options,
final OpenIdProviderConfiguration config) throws GeneralSecurityException {
return new JsonWebKeySet(restClient.target(config.getJwksUri())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(JsonObject.class));
}
/**
* Workaround for the issuer value for Google. This was documented in
* 15.6.2. of the spec. In which case if the issuer does not start with
* https:// it will prepend it.
*
* @param issuer
* issuer
* @return updated issuer
*/
private String googleWorkaround(final String issuer) {
if (issuer.startsWith(HTTPS_PREFIX)) {
return issuer;
}
return HTTPS_PREFIX + issuer;
}
/**
* Handles the callback.
*
* @param req
* servlet request
* @param resp
* servlet response
* @param subject
* user subject
* @return status
* @throws GeneralSecurityException
*/
private AuthStatus handleCallback(final HttpServletRequest req,
final HttpServletResponse resp,
final Subject subject) throws GeneralSecurityException,
IOException {
final OpenIdProviderConfiguration oidProviderConfig = getOpenIDProviderConfig(req, restClient, moduleOptions);
final OAuthToken token = getToken(req, oidProviderConfig);
final JsonWebKeySet webKeys = getWebKeys(moduleOptions, oidProviderConfig);
LOG.log(Level.FINEST, "tokenValue", token);
final JsonObject claimsSet = Json.createReader(new ByteArrayInputStream(Utils.getJwsPayload(token.getIdToken(), webKeys)))
.readObject();
final String nonce = getNonceFromCookie(req);
validateIdToken(clientId, claimsSet, nonce);
final Cookie deleteNonceCookie = new Cookie(NET_TRAJANO_AUTH_NONCE, "");
deleteNonceCookie.setMaxAge(0);
deleteNonceCookie.setPath(cookieContext);
resp.addCookie(deleteNonceCookie);
final String iss = googleWorkaround(claimsSet.getString("iss"));
final String issuer = googleWorkaround(oidProviderConfig.getIssuer());
if (!iss.equals(issuer)) {
LOG.log(Level.SEVERE, "issuerMismatch", new Object[] { iss, issuer });
throw new GeneralSecurityException(MessageFormat.format(R.getString("issuerMismatch"), iss, issuer));
}
updateSubjectPrincipal(subject, claimsSet);
final TokenCookie tokenCookie;
if (oidProviderConfig.getUserinfoEndpoint() != null && Pattern.compile("\\bprofile\\b")
.matcher(scope)
.find()) {
final Response userInfoResponse = restClient.target(oidProviderConfig.getUserinfoEndpoint())
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", token.getTokenType() + " " + token.getAccessToken())
.get();
if (userInfoResponse.getStatus() == 200) {
tokenCookie = new TokenCookie(token.getAccessToken(), token.getRefreshToken(), claimsSet, userInfoResponse.readEntity(JsonObject.class));
} else {
LOG.log(Level.WARNING, "unableToGetProfile");
tokenCookie = new TokenCookie(claimsSet);
}
} else {
tokenCookie = new TokenCookie(claimsSet);
}
final String requestCookieContext;
if (isNullOrEmpty(cookieContext)) {
requestCookieContext = req.getContextPath();
} else {
requestCookieContext = cookieContext;
}
final Cookie idTokenCookie = new Cookie(NET_TRAJANO_AUTH_ID, tokenCookie.toCookieValue(clientId, clientSecret));
idTokenCookie.setMaxAge(-1);
idTokenCookie.setSecure(true);
idTokenCookie.setHttpOnly(true);
idTokenCookie.setPath(requestCookieContext);
resp.addCookie(idTokenCookie);
final Cookie ageCookie = new Cookie(NET_TRAJANO_AUTH_AGE, Base64Url.encode(CipherUtil.encrypt(req.getRemoteAddr()
.getBytes("US-ASCII"), secret)));
if (isNullOrEmpty(req.getParameter("expires_in"))) {
ageCookie.setMaxAge(3600);
} else {
ageCookie.setMaxAge(Integer.parseInt(req.getParameter("expires_in")));
}
ageCookie.setPath(requestCookieContext);
ageCookie.setSecure(true);
ageCookie.setHttpOnly(true);
resp.addCookie(ageCookie);
final String stateEncoded = req.getParameter("state");
final String redirectUri = new String(Base64Url.decode(stateEncoded));
resp.sendRedirect(resp.encodeRedirectURL(req.getContextPath() + redirectUri));
return AuthStatus.SEND_SUCCESS;
}
/**
* {@inheritDoc}
*
* @param requestPolicy
* request policy, ignored
* @param responsePolicy
* response policy, ignored
* @param h
* callback handler
* @param options
* options
*/
@SuppressWarnings("unchecked")
@Override
public void initialize(final MessagePolicy requestPolicy,
final MessagePolicy responsePolicy,
final CallbackHandler h,
@SuppressWarnings("rawtypes") final Map options) throws AuthException {
try {
moduleOptions = options;
clientId = getRequiredOption(CLIENT_ID_KEY);
cookieContext = moduleOptions.get(COOKIE_CONTEXT_KEY);
redirectionEndpointUri = getRequiredOption(REDIRECTION_ENDPOINT_URI_KEY);
tokenUri = moduleOptions.get(TOKEN_URI_KEY);
userInfoUri = moduleOptions.get(USERINFO_URI_KEY);
logoutUri = moduleOptions.get(LOGOUT_URI_KEY);
logoutGotoUri = moduleOptions.get(LOGOUT_GOTO_URI_KEY);
scope = moduleOptions.get(SCOPE_KEY);
if (isNullOrEmpty(scope)) {
scope = "openid";
}
clientSecret = getRequiredOption(CLIENT_SECRET_KEY);
LOGCONFIG.log(Level.CONFIG, "options", moduleOptions);
handler = h;
mandatory = requestPolicy.isMandatory();
secret = CipherUtil.buildSecretKey(clientId, clientSecret);
if (restClient == null) {
if (moduleOptions.get(DISABLE_CERTIFICATE_CHECKS_KEY) != null && Boolean.valueOf(moduleOptions.get(DISABLE_CERTIFICATE_CHECKS_KEY))) {
restClient = buildUnsecureRestClient();
} else {
restClient = ClientBuilder.newClient();
}
}
} catch (final Exception e) {
// Should not happen
LOG.log(Level.SEVERE, "initializeException", e);
throw new AuthException(MessageFormat.format(R.getString("initializeException"), e.getMessage()));
}
}
/**
* Checks to see whether the {@link ServerAuthModule} is called by the
* resource owner. This is indicated by the presence of a <code>code</code>
* and a <code>state</code> on the URL and is an idempotent request (i.e.
* GET or HEAD). The resource owner would be a web browser that got a
* redirect sent by the OAuth 2.0 provider.
*
* @param req
* HTTP servlet request
* @return the module is called by the resource owner.
*/
public boolean isCallback(final HttpServletRequest req) {
return moduleOptions.get(REDIRECTION_ENDPOINT_URI_KEY)
.equals(req.getRequestURI()) && isRetrievalRequest(req) && !isNullOrEmpty(req.getParameter(CODE)) && !isNullOrEmpty(req.getParameter(STATE));
}
/**
* Generate the next nonce.
*
* @return nonce
*/
private String nextNonce() {
final byte[] bytes = new byte[8];
random.nextBytes(bytes);
return Base64Url.encode(bytes);
}
/**
* Builds the token cookie and updates the subject principal and sets the
* token and user info attribute in the request. Any exceptions or
* validation problems during validation will make this return
* <code>null</code> to indicate that there was no valid token.
*
* @param subject
* subject
* @param req
* servlet request
* @return token cookie.
*/
private TokenCookie processTokenCookie(final Subject subject,
final HttpServletRequest req) {
try {
final String idToken = getIdToken(req);
TokenCookie tokenCookie = null;
if (idToken != null) {
tokenCookie = new TokenCookie(idToken, secret);
validateIdToken(clientId, tokenCookie.getIdToken(), null);
updateSubjectPrincipal(subject, tokenCookie.getIdToken());
req.setAttribute(ACCESS_TOKEN_KEY, tokenCookie.getAccessToken());
req.setAttribute(REFRESH_TOKEN_KEY, tokenCookie.getRefreshToken());
req.setAttribute(ID_TOKEN_KEY, tokenCookie.getIdToken());
if (tokenCookie.getUserInfo() != null) {
req.setAttribute(USERINFO_KEY, tokenCookie.getUserInfo());
}
}
return tokenCookie;
} catch (final GeneralSecurityException | IOException e) {
LOG.log(Level.FINE, "invalidToken", e.getMessage());
LOG.throwing(this.getClass()
.getName(), "validateRequest", e);
return null;
}
}
/**
* Sends a redirect to the authorization endpoint. It sends the current
* request URI as the state so that the user can be redirected back to the
* last place. However, this does not work for non-idempotent requests such
* as POST in those cases it will result in a 401 error and
* {@link AuthStatus#SEND_FAILURE}. For idempotent requests, it will build
* the redirect URI and return {@link AuthStatus#SEND_CONTINUE}. It will
* also destroy the cookies used for authorization as part of the response.
* <p>
* It stores an encrypted nonce in the cookies and uses it to verify the
* nonce value later.
* </p>
*
* @param req
* HTTP servlet request
* @param resp
* HTTP servlet response
* @param reason
* reason for redirect (used for logging)
* @return authentication status
* @throws AuthException
*/
private AuthStatus redirectToAuthorizationEndpoint(final HttpServletRequest req,
final HttpServletResponse resp,
final String reason) throws AuthException {
LOG.log(Level.FINE, "redirecting", new Object[] { reason });
URI authorizationEndpointUri = null;
try {
final OpenIdProviderConfiguration oidProviderConfig = getOpenIDProviderConfig(req, restClient, moduleOptions);
final StringBuilder stateBuilder = new StringBuilder(req.getRequestURI()
.substring(req.getContextPath()
.length()));
if (req.getQueryString() != null) {
stateBuilder.append('?');
stateBuilder.append(req.getQueryString());
}
final String state = Base64Url.encode(stateBuilder.toString()
.getBytes("UTF-8"));
final String requestCookieContext;
if (isNullOrEmpty(cookieContext)) {
requestCookieContext = req.getContextPath();
} else {
requestCookieContext = cookieContext;
}
final String nonce = nextNonce();
final Cookie nonceCookie = new Cookie(NET_TRAJANO_AUTH_NONCE, Base64Url.encode(CipherUtil.encrypt(nonce.getBytes(), secret)));
nonceCookie.setMaxAge(-1);
nonceCookie.setPath(requestCookieContext);
nonceCookie.setHttpOnly(true);
nonceCookie.setSecure(true);
resp.addCookie(nonceCookie);
authorizationEndpointUri = UriBuilder.fromUri(oidProviderConfig.getAuthorizationEndpoint())
.queryParam(CLIENT_ID, clientId)
.queryParam(RESPONSE_TYPE, "code")
.queryParam(SCOPE, scope)
.queryParam(REDIRECT_URI, URI.create(req.getRequestURL()
.toString())
.resolve(moduleOptions.get(REDIRECTION_ENDPOINT_URI_KEY)))
.queryParam(STATE, state)
.queryParam("nonce", nonce)
.build();
deleteAuthCookies(resp);
resp.sendRedirect(authorizationEndpointUri.toASCIIString());
return AuthStatus.SEND_CONTINUE;
} catch (final IOException | GeneralSecurityException e) {
// Should not happen
LOG.log(Level.SEVERE, "sendRedirectException", new Object[] { authorizationEndpointUri, e.getMessage() });
LOG.throwing(this.getClass()
.getName(), "redirectToAuthorizationEndpoint", e);
throw new AuthException(MessageFormat.format(R.getString("sendRedirectException"), authorizationEndpointUri, e.getMessage()));
}
}
/**
* Return {@link AuthStatus#SEND_SUCCESS}.
*
* @param messageInfo
* contains the request and response messages. At this point the
* response message is already committed so nothing can be
* changed.
* @param subject
* subject.
* @return {@link AuthStatus#SEND_SUCCESS}
*/
@Override
public AuthStatus secureResponse(final MessageInfo messageInfo,
final Subject subject) throws AuthException {
return AuthStatus.SEND_SUCCESS;
}
/**
* Override REST client for testing.
*
* @param restClient
* REST client. May be mocked.
*/
public void setRestClient(final Client restClient) {
this.restClient = restClient;
}
/**
* Updates the principal for the subject. This is done through the
* callbacks.
*
* @param subject
* subject
* @param jwtPayload
* JWT payload
* @throws AuthException
* @throws GeneralSecurityException
*/
private void updateSubjectPrincipal(final Subject subject,
final JsonObject jwtPayload) throws GeneralSecurityException {
try {
final String iss = googleWorkaround(jwtPayload.getString("iss"));
handler.handle(new Callback[] { new CallerPrincipalCallback(subject, UriBuilder.fromUri(iss)
.userInfo(jwtPayload.getString("sub"))
.build()
.toASCIIString()), new GroupPrincipalCallback(subject, new String[] { iss }) });
} catch (final IOException | UnsupportedCallbackException e) {
// Should not happen
LOG.log(Level.SEVERE, "updatePrincipalException", e.getMessage());
LOG.throwing(this.getClass()
.getName(), "updateSubjectPrincipal", e);
throw new AuthException(MessageFormat.format(R.getString("updatePrincipalException"), e.getMessage()));
}
}
/**
* Validates the request. The request must be secure otherwise it will
* return {@link AuthStatus#FAILURE}. It then tries to build the token
* cookie data if available, if the token is valid, subject is set correctly
* and user info data if present is stored in the request, then call HTTP
* method specific operations.
*
* @param messageInfo
* request and response
* @param clientSubject
* client subject
* @param serviceSubject
* service subject, ignored.
* @return Auth status
*/
@Override
public AuthStatus validateRequest(final MessageInfo messageInfo,
final Subject clientSubject,
final Subject serviceSubject) throws AuthException {
final HttpServletRequest req = (HttpServletRequest) messageInfo.getRequestMessage();
final HttpServletResponse resp = (HttpServletResponse) messageInfo.getResponseMessage();
try {
final TokenCookie tokenCookie = processTokenCookie(clientSubject, req);
if (tokenCookie != null && req.isSecure() && isGetRequest(req) && req.getRequestURI()
.equals(tokenUri)) {
resp.setContentType(MediaType.APPLICATION_JSON);
resp.getWriter()
.print(tokenCookie.getIdToken());
return AuthStatus.SEND_SUCCESS;
}
if (tokenCookie != null && req.isSecure() && isGetRequest(req) && req.getRequestURI()
.equals(userInfoUri)) {
resp.setContentType(MediaType.APPLICATION_JSON);
resp.getWriter()
.print(tokenCookie.getUserInfo());
return AuthStatus.SEND_SUCCESS;
}
if (tokenCookie != null && req.isSecure() && isGetRequest(req) && req.getRequestURI()
.equals(logoutUri)) {
deleteAuthCookies(resp);
if (logoutGotoUri == null) {
resp.sendRedirect(req.getServletContext() + "/");
} else {
resp.sendRedirect(logoutGotoUri);
}
return AuthStatus.SEND_SUCCESS;
}
if (!mandatory && !req.isSecure()) {
// successful if the module is not mandatory and the channel is
// not secure.
return AuthStatus.SUCCESS;
}
if (!req.isSecure() && mandatory) {
// Fail authorization 3.1.2.1
resp.sendError(HttpURLConnection.HTTP_FORBIDDEN, R.getString("SSLReq"));
return AuthStatus.SEND_FAILURE;
}
if (!req.isSecure() && isCallback(req)) {
resp.sendError(HttpURLConnection.HTTP_FORBIDDEN, R.getString("SSLReq"));
return AuthStatus.SEND_FAILURE;
}
if (req.isSecure() && isCallback(req)) {
return handleCallback(req, resp, clientSubject);
}
if (!mandatory || tokenCookie != null && !tokenCookie.isExpired()) {
return AuthStatus.SUCCESS;
}
if (req.isSecure() && isHeadRequest(req) && req.getRequestURI()
.equals(tokenUri)) {
resp.setContentType(MediaType.APPLICATION_JSON);
return AuthStatus.SEND_SUCCESS;
}
if (req.getRequestURI()
.equals(userInfoUri) && isHeadRequest(req)) {
resp.setContentType(MediaType.APPLICATION_JSON);
return AuthStatus.SEND_SUCCESS;
}
if (!isRetrievalRequest(req)) {
resp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "Unable to POST when unauthorized.");
return AuthStatus.SEND_FAILURE;
}
return redirectToAuthorizationEndpoint(req, resp, "request is not valid");
} catch (final Exception e) {
// Any problems with the data should be caught and force redirect to
// authorization endpoint.
LOG.log(Level.FINE, "validationException", e.getMessage());
LOG.throwing(this.getClass()
.getName(), "validateRequest", e);
return redirectToAuthorizationEndpoint(req, resp, e.getMessage());
}
}
}
| Removed more dependencies on server-auth-module | openid-connect-jaspic-module/src/main/java/net/trajano/openidconnect/jaspic/internal/OAuthModule.java | Removed more dependencies on server-auth-module | <ide><path>penid-connect-jaspic-module/src/main/java/net/trajano/openidconnect/jaspic/internal/OAuthModule.java
<ide>
<ide> import net.trajano.auth.internal.CipherUtil;
<ide> import net.trajano.auth.internal.JsonWebKeySet;
<del>import net.trajano.auth.internal.OAuthToken;
<ide> import net.trajano.auth.internal.TokenCookie;
<ide> import net.trajano.auth.internal.Utils;
<ide> import net.trajano.openidconnect.core.OpenIdProviderConfiguration;
<ide> import net.trajano.openidconnect.crypto.Base64Url;
<add>import net.trajano.openidconnect.token.IdTokenResponse;
<ide>
<ide> /**
<ide> * OAuth 2.0 server authentication module. This is an implementation of the <a
<ide> * OpenID provider config
<ide> * @return token response
<ide> */
<del> protected OAuthToken getToken(final HttpServletRequest req,
<add> protected IdTokenResponse getToken(final HttpServletRequest req,
<ide> final OpenIdProviderConfiguration oidProviderConfig) throws IOException {
<ide>
<ide> final MultivaluedMap<String, String> requestData = new MultivaluedHashMap<>();
<ide>
<ide> try {
<ide> final String authorization = "Basic " + Base64Url.encode((clientId + ":" + clientSecret).getBytes("UTF8"));
<del> final OAuthToken authorizationTokenResponse = restClient.target(oidProviderConfig.getTokenEndpoint())
<add> final IdTokenResponse authorizationTokenResponse = restClient.target(oidProviderConfig.getTokenEndpoint())
<ide> .request(MediaType.APPLICATION_JSON_TYPE)
<ide> .header("Authorization", authorization)
<del> .post(Entity.form(requestData), OAuthToken.class);
<add> .post(Entity.form(requestData), IdTokenResponse.class);
<ide> if (LOG.isLoggable(Level.FINEST)) {
<ide> LOG.finest("authorization token response = " + authorizationTokenResponse);
<ide> }
<ide> // on their endpoint.
<ide> requestData.putSingle(CLIENT_ID, clientId);
<ide> requestData.putSingle(CLIENT_SECRET_KEY, clientSecret);
<del> final OAuthToken authorizationTokenResponse = restClient.target(oidProviderConfig.getTokenEndpoint())
<add> final IdTokenResponse authorizationTokenResponse = restClient.target(oidProviderConfig.getTokenEndpoint())
<ide> .request(MediaType.APPLICATION_JSON_TYPE)
<del> .post(Entity.form(requestData), OAuthToken.class);
<add> .post(Entity.form(requestData), IdTokenResponse.class);
<ide> if (LOG.isLoggable(Level.FINEST)) {
<ide> LOG.finest("authorization token response = " + authorizationTokenResponse);
<ide> }
<ide> IOException {
<ide>
<ide> final OpenIdProviderConfiguration oidProviderConfig = getOpenIDProviderConfig(req, restClient, moduleOptions);
<del> final OAuthToken token = getToken(req, oidProviderConfig);
<add> final IdTokenResponse token = getToken(req, oidProviderConfig);
<ide> final JsonWebKeySet webKeys = getWebKeys(moduleOptions, oidProviderConfig);
<ide>
<ide> LOG.log(Level.FINEST, "tokenValue", token);
<del> final JsonObject claimsSet = Json.createReader(new ByteArrayInputStream(Utils.getJwsPayload(token.getIdToken(), webKeys)))
<add> final JsonObject claimsSet = Json.createReader(new ByteArrayInputStream(Utils.getJwsPayload(token.getEncodedIdToken(), webKeys)))
<ide> .readObject();
<ide>
<ide> final String nonce = getNonceFromCookie(req); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.