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 | epl-1.0 | a1dcecd2cc209db1a6371f56c578eb1a3e9f1256 | 0 | kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder | /*******************************************************************************
* Copyright (c) 2015-2018 Oak Ridge National Laboratory.
* 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.csstudio.display.builder.representation.javafx.widgets.plots;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import org.csstudio.javafx.rtplot.data.InstrumentedReadWriteLock;
import org.csstudio.javafx.rtplot.data.PlotDataItem;
import org.csstudio.javafx.rtplot.data.PlotDataProvider;
import org.csstudio.javafx.rtplot.data.SimpleDataItem;
import org.diirt.util.array.ArrayDouble;
import org.diirt.util.array.ListNumber;
/** Data provider for RTPlot
*
* <p>Adapts waveforms received from PV
* into samples for a trace in the RTPlot.
* <ul>
* <li>X and Y waveform: Plots Y over X
* <li>Y waveform with <code>null</code> for X: Plots Y over array index
* </ul>
*
* Error data may be
* <ul>
* <li><code>null</code> or zero elements: No error bars
* <li>One element: Use that error for all samples
* <li>One element per sample: Error bar for each sample
* </ul>
*
* @author Kay Kasemir
*/
public class XYVTypeDataProvider implements PlotDataProvider<Double>
{
public static final ListNumber EMPTY = new ArrayDouble(new double[0], true);
/** Sharing the _read_ half of just one lock.
* Never using the _write_ half, since this class is immutable
*/
private static final ReadWriteLock lock = new InstrumentedReadWriteLock();
private final PlotDataItem<Double>[] items;
/** Set the plot's data
* @param x_data X data, may be <code>null</code>
* @param y_data Y data
* @param error_data Error data
*/
@SuppressWarnings("unchecked")
public XYVTypeDataProvider(ListNumber x_data, ListNumber y_data, ListNumber error_data)
{
// In principle, error_data should have 1 element or same size as X and Y..
if (error_data == null)
error_data = EMPTY;
// Could create each PlotDataItem lazily in get(),
// but create array of PlotDataItems right now because
// plot will likely iterate over the data elements at least once to plot value,
// maybe again to plot outline, find value at cursor etc.
final int size = x_data == null ? y_data.size() : Math.min(x_data.size(), y_data.size());
items = new PlotDataItem[size];
for (int index=0; index < size; ++index)
{
final double x = x_data == null ? index : x_data.getDouble(index);
final double y = y_data.getDouble(index);
if (error_data.size() <= 0) // No error data
items[index] = new SimpleDataItem<Double>(x, y, Double.NaN, Double.NaN, Double.NaN, null);
else
{ // Use corresponding array element, or [0] for scalar error info
// (silently treating size(error) < size(Y) as a mix of error array and scalar)
final double error = (error_data.size() > index) ? error_data.getDouble(index) : error_data.getDouble(0);
items[index] = new SimpleDataItem<Double>(x, y, Double.NaN, y - error, y + error, null);
}
}
}
public XYVTypeDataProvider()
{
this(EMPTY, EMPTY, EMPTY);
}
@Override
public Lock getLock()
{
return lock.readLock();
}
@Override
public int size()
{
return items.length;
}
@Override
public PlotDataItem<Double> get(final int index)
{
return items[index];
}
@Override
public String toString()
{
return "XYVTypeDataProvider, lock: " + lock.toString();
}
}
| org.csstudio.display.builder.representation.javafx/src/org/csstudio/display/builder/representation/javafx/widgets/plots/XYVTypeDataProvider.java | /*******************************************************************************
* Copyright (c) 2015-2018 Oak Ridge National Laboratory.
* 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.csstudio.display.builder.representation.javafx.widgets.plots;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import org.csstudio.javafx.rtplot.data.InstrumentedReadWriteLock;
import org.csstudio.javafx.rtplot.data.PlotDataItem;
import org.csstudio.javafx.rtplot.data.PlotDataProvider;
import org.csstudio.javafx.rtplot.data.SimpleDataItem;
import org.diirt.util.array.ArrayDouble;
import org.diirt.util.array.ListNumber;
/** Data provider for RTPlot
*
* <p>Adapts waveforms received from PV
* into samples for a trace in the RTPlot.
* <ul>
* <li>X and Y waveform: Plots Y over X
* <li>Y waveform with <code>null</code> for X: Plots Y over array index
* </ul>
*
* Error data may be
* <ul>
* <li><code>null</code> or zero elements: No error bars
* <li>One element: Use that error for all samples
* <li>One element per sample: Error bar for each sample
* </ul>
*
* @author Kay Kasemir
*/
public class XYVTypeDataProvider implements PlotDataProvider<Double>
{
public static final ListNumber EMPTY = new ArrayDouble(new double[0], true);
/** Sharing the _read_ half of just one lock.
* Never using the _write_ half, since this class is immutable
*/
private static final ReadWriteLock lock = new InstrumentedReadWriteLock();
private final PlotDataItem<Double>[] items;
/** Set the plot's data
* @param x_data X data, may be <code>null</code>
* @param y_data Y data
* @param error_data Error data
*/
@SuppressWarnings("unchecked")
public XYVTypeDataProvider(ListNumber x_data, ListNumber y_data, ListNumber error_data)
{
// In principle, error_data should have 1 element or same size as X and Y..
if (error_data != null)
error_data = EMPTY;
// Could create each PlotDataItem lazily in get(),
// but create array of PlotDataItems right now because
// plot will likely iterate over the data elements at least once to plot value,
// maybe again to plot outline, find value at cursor etc.
final int size = x_data == null ? y_data.size() : Math.min(x_data.size(), y_data.size());
items = new PlotDataItem[size];
for (int index=0; index < size; ++index)
{
final double x = x_data == null ? index : x_data.getDouble(index);
final double y = y_data.getDouble(index);
if (error_data.size() <= 0) // No error data
items[index] = new SimpleDataItem<Double>(x, y, Double.NaN, Double.NaN, Double.NaN, null);
else
{ // Use corresponding array element, or [0] for scalar error info
// (silently treating size(error) < size(Y) as a mix of error array and scalar)
final double error = (error_data.size() > index) ? error_data.getDouble(index) : error_data.getDouble(0);
items[index] = new SimpleDataItem<Double>(x, y, Double.NaN, y - error, y + error, null);
}
}
}
public XYVTypeDataProvider()
{
this(EMPTY, EMPTY, EMPTY);
}
@Override
public Lock getLock()
{
return lock.readLock();
}
@Override
public int size()
{
return items.length;
}
@Override
public PlotDataItem<Double> get(final int index)
{
return items[index];
}
@Override
public String toString()
{
return "XYVTypeDataProvider, lock: " + lock.toString();
}
}
| XYPlot: Fix NPE with missing error data | org.csstudio.display.builder.representation.javafx/src/org/csstudio/display/builder/representation/javafx/widgets/plots/XYVTypeDataProvider.java | XYPlot: Fix NPE with missing error data | <ide><path>rg.csstudio.display.builder.representation.javafx/src/org/csstudio/display/builder/representation/javafx/widgets/plots/XYVTypeDataProvider.java
<ide> public XYVTypeDataProvider(ListNumber x_data, ListNumber y_data, ListNumber error_data)
<ide> {
<ide> // In principle, error_data should have 1 element or same size as X and Y..
<del> if (error_data != null)
<add> if (error_data == null)
<ide> error_data = EMPTY;
<ide>
<ide> // Could create each PlotDataItem lazily in get(), |
|
JavaScript | mit | 2b18076ddd008a0e864350467d0be04442a1a3ee | 0 | benelsen/luxapi | var express = require('express'),
app = express();
// Allow CORS
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// vdl
var vdl = require('./vdl');
app.get('/vdl/parking.json', vdl.parking.json);
app.get('/vdl/parking.geojson', vdl.parking.geojson);
app.listen(4003);
| server.js | var express = require('express');
var app = express();
// Allow CORS
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// vdl
var vdl = require('./vdl');
app.get('/vdl/parking.json', vdl.parking.json);
app.get('/vdl/parking.geojson', vdl.parking.geojson);
app.listen(4003);
| -whitespace
| server.js | -whitespace | <ide><path>erver.js
<del>var express = require('express');
<del>
<del>var app = express();
<add>var express = require('express'),
<add> app = express();
<ide>
<ide> // Allow CORS
<ide> app.all('/*', function(req, res, next) { |
|
Java | apache-2.0 | eb3307de61e4419d7ad56528906e3568f9958ca6 | 0 | MathieuDuponchelle/gdx,Wisienkas/libgdx,kagehak/libgdx,hyvas/libgdx,sinistersnare/libgdx,katiepino/libgdx,billgame/libgdx,titovmaxim/libgdx,309746069/libgdx,KrisLee/libgdx,stinsonga/libgdx,stinsonga/libgdx,TheAks999/libgdx,SidneyXu/libgdx,Xhanim/libgdx,andyvand/libgdx,alireza-hosseini/libgdx,nave966/libgdx,ttencate/libgdx,bgroenks96/libgdx,bsmr-java/libgdx,jsjolund/libgdx,js78/libgdx,saqsun/libgdx,billgame/libgdx,junkdog/libgdx,JFixby/libgdx,curtiszimmerman/libgdx,MetSystem/libgdx,TheAks999/libgdx,kzganesan/libgdx,zhimaijoy/libgdx,BlueRiverInteractive/libgdx,ThiagoGarciaAlves/libgdx,Dzamir/libgdx,billgame/libgdx,curtiszimmerman/libgdx,tell10glu/libgdx,josephknight/libgdx,bgroenks96/libgdx,ninoalma/libgdx,sjosegarcia/libgdx,nudelchef/libgdx,josephknight/libgdx,lordjone/libgdx,JDReutt/libgdx,tommyettinger/libgdx,tommyettinger/libgdx,yangweigbh/libgdx,copystudy/libgdx,junkdog/libgdx,saltares/libgdx,firefly2442/libgdx,JDReutt/libgdx,MathieuDuponchelle/gdx,saltares/libgdx,Deftwun/libgdx,kagehak/libgdx,gouessej/libgdx,josephknight/libgdx,MathieuDuponchelle/gdx,PedroRomanoBarbosa/libgdx,FyiurAmron/libgdx,nave966/libgdx,firefly2442/libgdx,ThiagoGarciaAlves/libgdx,bsmr-java/libgdx,davebaol/libgdx,antag99/libgdx,KrisLee/libgdx,MathieuDuponchelle/gdx,josephknight/libgdx,noelsison2/libgdx,andyvand/libgdx,TheAks999/libgdx,sarkanyi/libgdx,GreenLightning/libgdx,xpenatan/libgdx-LWJGL3,ya7lelkom/libgdx,titovmaxim/libgdx,junkdog/libgdx,nave966/libgdx,andyvand/libgdx,ninoalma/libgdx,haedri/libgdx-1,codepoke/libgdx,UnluckyNinja/libgdx,petugez/libgdx,antag99/libgdx,UnluckyNinja/libgdx,zhimaijoy/libgdx,nudelchef/libgdx,309746069/libgdx,Deftwun/libgdx,PedroRomanoBarbosa/libgdx,tell10glu/libgdx,fiesensee/libgdx,fwolff/libgdx,FredGithub/libgdx,czyzby/libgdx,gouessej/libgdx,cypherdare/libgdx,Gliby/libgdx,Xhanim/libgdx,hyvas/libgdx,FyiurAmron/libgdx,toa5/libgdx,djom20/libgdx,djom20/libgdx,jberberick/libgdx,andyvand/libgdx,alex-dorokhov/libgdx,del-sol/libgdx,Thotep/libgdx,FredGithub/libgdx,FyiurAmron/libgdx,Zonglin-Li6565/libgdx,Xhanim/libgdx,MathieuDuponchelle/gdx,Dzamir/libgdx,billgame/libgdx,SidneyXu/libgdx,mumer92/libgdx,UnluckyNinja/libgdx,ninoalma/libgdx,andyvand/libgdx,FyiurAmron/libgdx,MovingBlocks/libgdx,antag99/libgdx,xoppa/libgdx,flaiker/libgdx,saqsun/libgdx,sjosegarcia/libgdx,tommycli/libgdx,tommycli/libgdx,1yvT0s/libgdx,shiweihappy/libgdx,stickyd/libgdx,Badazdz/libgdx,del-sol/libgdx,Thotep/libgdx,nooone/libgdx,thepullman/libgdx,jsjolund/libgdx,snovak/libgdx,Senth/libgdx,codepoke/libgdx,libgdx/libgdx,ricardorigodon/libgdx,zommuter/libgdx,lordjone/libgdx,petugez/libgdx,1yvT0s/libgdx,basherone/libgdxcn,bsmr-java/libgdx,saqsun/libgdx,MikkelTAndersen/libgdx,Deftwun/libgdx,ryoenji/libgdx,samskivert/libgdx,kzganesan/libgdx,youprofit/libgdx,realitix/libgdx,Badazdz/libgdx,nrallakis/libgdx,realitix/libgdx,tell10glu/libgdx,Wisienkas/libgdx,bgroenks96/libgdx,ninoalma/libgdx,JDReutt/libgdx,Arcnor/libgdx,bsmr-java/libgdx,309746069/libgdx,firefly2442/libgdx,luischavez/libgdx,kagehak/libgdx,PedroRomanoBarbosa/libgdx,ThiagoGarciaAlves/libgdx,JFixby/libgdx,zhimaijoy/libgdx,JFixby/libgdx,zhimaijoy/libgdx,gf11speed/libgdx,nrallakis/libgdx,azakhary/libgdx,tommycli/libgdx,tell10glu/libgdx,haedri/libgdx-1,libgdx/libgdx,ttencate/libgdx,youprofit/libgdx,MetSystem/libgdx,Senth/libgdx,FredGithub/libgdx,jberberick/libgdx,EsikAntony/libgdx,saqsun/libgdx,petugez/libgdx,luischavez/libgdx,designcrumble/libgdx,Deftwun/libgdx,MadcowD/libgdx,Thotep/libgdx,nrallakis/libgdx,sinistersnare/libgdx,Dzamir/libgdx,sjosegarcia/libgdx,junkdog/libgdx,titovmaxim/libgdx,xoppa/libgdx,alireza-hosseini/libgdx,zhimaijoy/libgdx,thepullman/libgdx,Wisienkas/libgdx,js78/libgdx,toloudis/libgdx,gdos/libgdx,MathieuDuponchelle/gdx,xranby/libgdx,bsmr-java/libgdx,saqsun/libgdx,bgroenks96/libgdx,Dzamir/libgdx,Heart2009/libgdx,djom20/libgdx,ricardorigodon/libgdx,gouessej/libgdx,GreenLightning/libgdx,thepullman/libgdx,snovak/libgdx,flaiker/libgdx,JFixby/libgdx,tommyettinger/libgdx,jberberick/libgdx,KrisLee/libgdx,jasonwee/libgdx,czyzby/libgdx,copystudy/libgdx,jasonwee/libgdx,FyiurAmron/libgdx,yangweigbh/libgdx,309746069/libgdx,MovingBlocks/libgdx,EsikAntony/libgdx,junkdog/libgdx,FredGithub/libgdx,Zonglin-Li6565/libgdx,alex-dorokhov/libgdx,nelsonsilva/libgdx,Zonglin-Li6565/libgdx,bsmr-java/libgdx,nudelchef/libgdx,tell10glu/libgdx,js78/libgdx,KrisLee/libgdx,ztv/libgdx,Arcnor/libgdx,Xhanim/libgdx,fwolff/libgdx,PedroRomanoBarbosa/libgdx,yangweigbh/libgdx,PedroRomanoBarbosa/libgdx,realitix/libgdx,collinsmith/libgdx,samskivert/libgdx,ztv/libgdx,nelsonsilva/libgdx,kotcrab/libgdx,stickyd/libgdx,MetSystem/libgdx,gf11speed/libgdx,NathanSweet/libgdx,zommuter/libgdx,katiepino/libgdx,nave966/libgdx,sinistersnare/libgdx,xranby/libgdx,noelsison2/libgdx,thepullman/libgdx,sjosegarcia/libgdx,Gliby/libgdx,BlueRiverInteractive/libgdx,Thotep/libgdx,lordjone/libgdx,NathanSweet/libgdx,noelsison2/libgdx,jsjolund/libgdx,gouessej/libgdx,nave966/libgdx,thepullman/libgdx,basherone/libgdxcn,kagehak/libgdx,jberberick/libgdx,ryoenji/libgdx,alireza-hosseini/libgdx,lordjone/libgdx,tommycli/libgdx,saltares/libgdx,firefly2442/libgdx,designcrumble/libgdx,stickyd/libgdx,shiweihappy/libgdx,mumer92/libgdx,luischavez/libgdx,alex-dorokhov/libgdx,xoppa/libgdx,js78/libgdx,bladecoder/libgdx,PedroRomanoBarbosa/libgdx,zommuter/libgdx,nooone/libgdx,youprofit/libgdx,anserran/libgdx,czyzby/libgdx,ThiagoGarciaAlves/libgdx,Dzamir/libgdx,katiepino/libgdx,del-sol/libgdx,designcrumble/libgdx,Arcnor/libgdx,shiweihappy/libgdx,xoppa/libgdx,toa5/libgdx,kagehak/libgdx,FredGithub/libgdx,FredGithub/libgdx,ttencate/libgdx,Zomby2D/libgdx,snovak/libgdx,toa5/libgdx,nudelchef/libgdx,bladecoder/libgdx,shiweihappy/libgdx,andyvand/libgdx,zommuter/libgdx,gdos/libgdx,Xhanim/libgdx,Zonglin-Li6565/libgdx,anserran/libgdx,nelsonsilva/libgdx,firefly2442/libgdx,revo09/libgdx,realitix/libgdx,saltares/libgdx,gdos/libgdx,katiepino/libgdx,Xhanim/libgdx,anserran/libgdx,copystudy/libgdx,josephknight/libgdx,petugez/libgdx,gf11speed/libgdx,shiweihappy/libgdx,tommycli/libgdx,snovak/libgdx,yangweigbh/libgdx,flaiker/libgdx,toa5/libgdx,luischavez/libgdx,JFixby/libgdx,djom20/libgdx,1yvT0s/libgdx,Heart2009/libgdx,nudelchef/libgdx,stinsonga/libgdx,xpenatan/libgdx-LWJGL3,toa5/libgdx,nudelchef/libgdx,jberberick/libgdx,djom20/libgdx,MathieuDuponchelle/gdx,ya7lelkom/libgdx,jsjolund/libgdx,PedroRomanoBarbosa/libgdx,kzganesan/libgdx,BlueRiverInteractive/libgdx,flaiker/libgdx,MikkelTAndersen/libgdx,Arcnor/libgdx,collinsmith/libgdx,petugez/libgdx,josephknight/libgdx,EsikAntony/libgdx,MadcowD/libgdx,luischavez/libgdx,TheAks999/libgdx,xpenatan/libgdx-LWJGL3,noelsison2/libgdx,stickyd/libgdx,Zonglin-Li6565/libgdx,tell10glu/libgdx,czyzby/libgdx,stickyd/libgdx,Dzamir/libgdx,samskivert/libgdx,jsjolund/libgdx,xoppa/libgdx,Badazdz/libgdx,bsmr-java/libgdx,copystudy/libgdx,realitix/libgdx,flaiker/libgdx,KrisLee/libgdx,Gliby/libgdx,samskivert/libgdx,billgame/libgdx,MovingBlocks/libgdx,collinsmith/libgdx,ya7lelkom/libgdx,gdos/libgdx,flaiker/libgdx,ttencate/libgdx,curtiszimmerman/libgdx,MathieuDuponchelle/gdx,saqsun/libgdx,SidneyXu/libgdx,andyvand/libgdx,ryoenji/libgdx,toloudis/libgdx,bgroenks96/libgdx,azakhary/libgdx,nooone/libgdx,revo09/libgdx,xranby/libgdx,curtiszimmerman/libgdx,revo09/libgdx,Deftwun/libgdx,ttencate/libgdx,bgroenks96/libgdx,Senth/libgdx,basherone/libgdxcn,gdos/libgdx,MadcowD/libgdx,jasonwee/libgdx,antag99/libgdx,titovmaxim/libgdx,Zomby2D/libgdx,katiepino/libgdx,codepoke/libgdx,Gliby/libgdx,Dzamir/libgdx,BlueRiverInteractive/libgdx,fwolff/libgdx,tommyettinger/libgdx,junkdog/libgdx,xoppa/libgdx,snovak/libgdx,nudelchef/libgdx,youprofit/libgdx,billgame/libgdx,saqsun/libgdx,kzganesan/libgdx,TheAks999/libgdx,collinsmith/libgdx,firefly2442/libgdx,fiesensee/libgdx,KrisLee/libgdx,MikkelTAndersen/libgdx,titovmaxim/libgdx,309746069/libgdx,libgdx/libgdx,EsikAntony/libgdx,stinsonga/libgdx,luischavez/libgdx,petugez/libgdx,xranby/libgdx,ztv/libgdx,zhimaijoy/libgdx,fiesensee/libgdx,samskivert/libgdx,haedri/libgdx-1,saltares/libgdx,firefly2442/libgdx,SidneyXu/libgdx,Wisienkas/libgdx,MikkelTAndersen/libgdx,Deftwun/libgdx,sarkanyi/libgdx,JDReutt/libgdx,ninoalma/libgdx,toloudis/libgdx,titovmaxim/libgdx,josephknight/libgdx,fiesensee/libgdx,zhimaijoy/libgdx,bsmr-java/libgdx,GreenLightning/libgdx,Zonglin-Li6565/libgdx,bgroenks96/libgdx,toloudis/libgdx,Zomby2D/libgdx,jberberick/libgdx,realitix/libgdx,alireza-hosseini/libgdx,GreenLightning/libgdx,ryoenji/libgdx,srwonka/libGdx,xpenatan/libgdx-LWJGL3,gf11speed/libgdx,jsjolund/libgdx,nooone/libgdx,curtiszimmerman/libgdx,davebaol/libgdx,1yvT0s/libgdx,mumer92/libgdx,sjosegarcia/libgdx,titovmaxim/libgdx,designcrumble/libgdx,fwolff/libgdx,kzganesan/libgdx,Wisienkas/libgdx,MetSystem/libgdx,czyzby/libgdx,Dzamir/libgdx,JDReutt/libgdx,ThiagoGarciaAlves/libgdx,Zomby2D/libgdx,xpenatan/libgdx-LWJGL3,jberberick/libgdx,TheAks999/libgdx,stickyd/libgdx,realitix/libgdx,Xhanim/libgdx,Heart2009/libgdx,djom20/libgdx,thepullman/libgdx,lordjone/libgdx,kotcrab/libgdx,junkdog/libgdx,hyvas/libgdx,Heart2009/libgdx,kotcrab/libgdx,ryoenji/libgdx,gf11speed/libgdx,bladecoder/libgdx,tommyettinger/libgdx,hyvas/libgdx,nave966/libgdx,josephknight/libgdx,nrallakis/libgdx,sarkanyi/libgdx,309746069/libgdx,fwolff/libgdx,ricardorigodon/libgdx,sinistersnare/libgdx,revo09/libgdx,UnluckyNinja/libgdx,ya7lelkom/libgdx,srwonka/libGdx,lordjone/libgdx,ya7lelkom/libgdx,antag99/libgdx,fiesensee/libgdx,gf11speed/libgdx,srwonka/libGdx,haedri/libgdx-1,js78/libgdx,kzganesan/libgdx,gdos/libgdx,MovingBlocks/libgdx,snovak/libgdx,revo09/libgdx,kotcrab/libgdx,Gliby/libgdx,libgdx/libgdx,del-sol/libgdx,petugez/libgdx,JDReutt/libgdx,js78/libgdx,gouessej/libgdx,luischavez/libgdx,Arcnor/libgdx,ricardorigodon/libgdx,shiweihappy/libgdx,nrallakis/libgdx,kagehak/libgdx,Zomby2D/libgdx,yangweigbh/libgdx,MadcowD/libgdx,katiepino/libgdx,Senth/libgdx,haedri/libgdx-1,xpenatan/libgdx-LWJGL3,sarkanyi/libgdx,nrallakis/libgdx,ttencate/libgdx,snovak/libgdx,anserran/libgdx,jberberick/libgdx,youprofit/libgdx,ninoalma/libgdx,anserran/libgdx,fiesensee/libgdx,alex-dorokhov/libgdx,FredGithub/libgdx,Heart2009/libgdx,SidneyXu/libgdx,js78/libgdx,collinsmith/libgdx,toa5/libgdx,UnluckyNinja/libgdx,nave966/libgdx,del-sol/libgdx,youprofit/libgdx,designcrumble/libgdx,tommycli/libgdx,Senth/libgdx,JDReutt/libgdx,Deftwun/libgdx,Zonglin-Li6565/libgdx,mumer92/libgdx,bgroenks96/libgdx,toa5/libgdx,FyiurAmron/libgdx,Heart2009/libgdx,ricardorigodon/libgdx,EsikAntony/libgdx,UnluckyNinja/libgdx,zommuter/libgdx,firefly2442/libgdx,ninoalma/libgdx,samskivert/libgdx,zommuter/libgdx,junkdog/libgdx,zhimaijoy/libgdx,davebaol/libgdx,ThiagoGarciaAlves/libgdx,del-sol/libgdx,ttencate/libgdx,ricardorigodon/libgdx,xpenatan/libgdx-LWJGL3,xoppa/libgdx,zommuter/libgdx,curtiszimmerman/libgdx,Heart2009/libgdx,sjosegarcia/libgdx,jasonwee/libgdx,BlueRiverInteractive/libgdx,Wisienkas/libgdx,sarkanyi/libgdx,JFixby/libgdx,cypherdare/libgdx,TheAks999/libgdx,copystudy/libgdx,MikkelTAndersen/libgdx,NathanSweet/libgdx,Senth/libgdx,ryoenji/libgdx,ya7lelkom/libgdx,hyvas/libgdx,xranby/libgdx,jasonwee/libgdx,titovmaxim/libgdx,cypherdare/libgdx,BlueRiverInteractive/libgdx,designcrumble/libgdx,ztv/libgdx,azakhary/libgdx,MadcowD/libgdx,mumer92/libgdx,MikkelTAndersen/libgdx,ztv/libgdx,ya7lelkom/libgdx,kotcrab/libgdx,katiepino/libgdx,MikkelTAndersen/libgdx,basherone/libgdxcn,ya7lelkom/libgdx,toloudis/libgdx,ztv/libgdx,ztv/libgdx,kotcrab/libgdx,thepullman/libgdx,stickyd/libgdx,Thotep/libgdx,MadcowD/libgdx,billgame/libgdx,Gliby/libgdx,lordjone/libgdx,fiesensee/libgdx,tell10glu/libgdx,fwolff/libgdx,collinsmith/libgdx,MetSystem/libgdx,Wisienkas/libgdx,anserran/libgdx,haedri/libgdx-1,libgdx/libgdx,309746069/libgdx,yangweigbh/libgdx,youprofit/libgdx,Thotep/libgdx,nrallakis/libgdx,JDReutt/libgdx,anserran/libgdx,del-sol/libgdx,NathanSweet/libgdx,BlueRiverInteractive/libgdx,MovingBlocks/libgdx,gdos/libgdx,MetSystem/libgdx,nave966/libgdx,FyiurAmron/libgdx,codepoke/libgdx,bladecoder/libgdx,toloudis/libgdx,djom20/libgdx,fwolff/libgdx,alex-dorokhov/libgdx,TheAks999/libgdx,saltares/libgdx,noelsison2/libgdx,gf11speed/libgdx,youprofit/libgdx,EsikAntony/libgdx,antag99/libgdx,Wisienkas/libgdx,Xhanim/libgdx,davebaol/libgdx,309746069/libgdx,designcrumble/libgdx,del-sol/libgdx,noelsison2/libgdx,alex-dorokhov/libgdx,davebaol/libgdx,sarkanyi/libgdx,GreenLightning/libgdx,alireza-hosseini/libgdx,sjosegarcia/libgdx,toa5/libgdx,kagehak/libgdx,luischavez/libgdx,SidneyXu/libgdx,ThiagoGarciaAlves/libgdx,codepoke/libgdx,xranby/libgdx,sarkanyi/libgdx,Badazdz/libgdx,srwonka/libGdx,ztv/libgdx,jasonwee/libgdx,nelsonsilva/libgdx,1yvT0s/libgdx,kagehak/libgdx,ricardorigodon/libgdx,Badazdz/libgdx,curtiszimmerman/libgdx,copystudy/libgdx,gouessej/libgdx,sarkanyi/libgdx,Zonglin-Li6565/libgdx,sinistersnare/libgdx,basherone/libgdxcn,nooone/libgdx,bladecoder/libgdx,kotcrab/libgdx,collinsmith/libgdx,FyiurAmron/libgdx,thepullman/libgdx,KrisLee/libgdx,samskivert/libgdx,toloudis/libgdx,gf11speed/libgdx,ryoenji/libgdx,nrallakis/libgdx,yangweigbh/libgdx,haedri/libgdx-1,czyzby/libgdx,yangweigbh/libgdx,shiweihappy/libgdx,xranby/libgdx,basherone/libgdxcn,fiesensee/libgdx,nelsonsilva/libgdx,stinsonga/libgdx,Thotep/libgdx,mumer92/libgdx,Arcnor/libgdx,shiweihappy/libgdx,copystudy/libgdx,1yvT0s/libgdx,nudelchef/libgdx,revo09/libgdx,cypherdare/libgdx,saqsun/libgdx,GreenLightning/libgdx,UnluckyNinja/libgdx,ninoalma/libgdx,GreenLightning/libgdx,hyvas/libgdx,MadcowD/libgdx,katiepino/libgdx,alex-dorokhov/libgdx,azakhary/libgdx,Senth/libgdx,tommycli/libgdx,codepoke/libgdx,sjosegarcia/libgdx,flaiker/libgdx,stickyd/libgdx,billgame/libgdx,copystudy/libgdx,MovingBlocks/libgdx,mumer92/libgdx,realitix/libgdx,BlueRiverInteractive/libgdx,hyvas/libgdx,haedri/libgdx-1,revo09/libgdx,alireza-hosseini/libgdx,MetSystem/libgdx,ThiagoGarciaAlves/libgdx,noelsison2/libgdx,EsikAntony/libgdx,Badazdz/libgdx,codepoke/libgdx,EsikAntony/libgdx,NathanSweet/libgdx,Badazdz/libgdx,srwonka/libGdx,1yvT0s/libgdx,MadcowD/libgdx,Senth/libgdx,Deftwun/libgdx,gouessej/libgdx,jasonwee/libgdx,czyzby/libgdx,kotcrab/libgdx,saltares/libgdx,djom20/libgdx,Gliby/libgdx,revo09/libgdx,toloudis/libgdx,fwolff/libgdx,samskivert/libgdx,saltares/libgdx,Heart2009/libgdx,gdos/libgdx,PedroRomanoBarbosa/libgdx,ttencate/libgdx,noelsison2/libgdx,jsjolund/libgdx,andyvand/libgdx,MikkelTAndersen/libgdx,zommuter/libgdx,hyvas/libgdx,SidneyXu/libgdx,Badazdz/libgdx,curtiszimmerman/libgdx,antag99/libgdx,collinsmith/libgdx,lordjone/libgdx,alireza-hosseini/libgdx,MathieuDuponchelle/gdx,1yvT0s/libgdx,mumer92/libgdx,JFixby/libgdx,alex-dorokhov/libgdx,anserran/libgdx,davebaol/libgdx,petugez/libgdx,SidneyXu/libgdx,gouessej/libgdx,kzganesan/libgdx,MovingBlocks/libgdx,JFixby/libgdx,tommycli/libgdx,antag99/libgdx,srwonka/libGdx,codepoke/libgdx,xoppa/libgdx,MetSystem/libgdx,srwonka/libGdx,FredGithub/libgdx,sinistersnare/libgdx,designcrumble/libgdx,azakhary/libgdx,czyzby/libgdx,flaiker/libgdx,ricardorigodon/libgdx,snovak/libgdx,xpenatan/libgdx-LWJGL3,nooone/libgdx,UnluckyNinja/libgdx,cypherdare/libgdx,azakhary/libgdx,Thotep/libgdx,alireza-hosseini/libgdx,js78/libgdx,GreenLightning/libgdx,jsjolund/libgdx,nelsonsilva/libgdx,xranby/libgdx,srwonka/libGdx,tell10glu/libgdx,jasonwee/libgdx,MovingBlocks/libgdx,Gliby/libgdx,KrisLee/libgdx | /*******************************************************************************
* Copyright 2010 Mario Zechner ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.jogl;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Version;
import com.badlogic.gdx.utils.GdxRuntimeException;
/**
* An implemenation of the {@link Application} interface based on Jogl for Windows, Linux and Mac. Instantiate this class with
* apropriate parameters and then register {@link ApplicationListener}, {@link RenderListener} or {@link InputProcessor} instances.
*
* @author mzechner
*
*/
public final class JoglApplication implements Application {
static {
Version.loadLibrary();
}
JoglGraphics graphics;
JoglInput input;
JoglFiles files;
JoglAudio audio;
JFrame frame;
/**
* Creates a new {@link JoglApplication} with the given title and dimensions. If useGL20IfAvailable is set the JoglApplication
* will try to create an OpenGL 2.0 context which can then be used via {@link JoglApplication.getGraphics().getGL20()}. To query whether enabling OpenGL 2.0
* was successful use the {@link JoglApplication.getGraphics().isGL20Available()} method.
*
* @param listener the ApplicationListener implementing the program logic
* @param title the title of the application
* @param width the width of the surface in pixels
* @param height the height of the surface in pixels
* @param useGL20IfAvailable wheter to use OpenGL 2.0 if it is available or not
*/
public JoglApplication (final ApplicationListener listener, final String title, final int width, final int height, final boolean useGL20IfAvailable) {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
JoglNativesLoader.loadLibraries();
graphics = new JoglGraphics(listener, title, width, height, useGL20IfAvailable);
input = new JoglInput(graphics.getCanvas());
audio = new JoglAudio();
files = new JoglFiles();
Gdx.app = JoglApplication.this;
Gdx.graphics = JoglApplication.this.getGraphics();
Gdx.input = JoglApplication.this.getInput();
Gdx.audio = JoglApplication.this.getAudio();
Gdx.files = JoglApplication.this.getFiles();
initialize(title, width, height);
}
});
} catch (Exception e) {
throw new GdxRuntimeException("Creating window failed");
}
}
private void initialize(String title, int width, int height) {
frame = new JFrame(title);
graphics.getCanvas().setPreferredSize(new Dimension(width, height));
frame.setSize(width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + frame.getInsets().bottom
+ height);
frame.add(graphics.getCanvas(), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.addWindowListener( new WindowAdapter() {
@Override
public void windowOpened(WindowEvent arg0) {
graphics.getCanvas().requestFocus();
graphics.getCanvas().requestFocusInWindow();
}
@Override
public void windowIconified(WindowEvent arg0) {
graphics.pause();
}
@Override
public void windowDeiconified(WindowEvent arg0) {
graphics.resume();
}
@Override
public void windowClosing(WindowEvent arg0) {
graphics.pause();
graphics.destroy();
frame.remove(graphics.getCanvas());
}
});
frame.pack();
frame.setVisible(true);
graphics.create();
}
/**
* {@inheritDoc}
*/
@Override public Audio getAudio () {
return audio;
}
/**
* {@inheritDoc}
*/
@Override public Files getFiles () {
return files;
}
/**
* {@inheritDoc}
*/
@Override public Graphics getGraphics () {
return graphics;
}
/**
* {@inheritDoc}
*/
@Override public Input getInput () {
return input;
}
@Override public void log (String tag, String message) {
System.out.println(tag + ": " + message);
}
/**
* {@inheritDoc}
*/
@Override public ApplicationType getType () {
return ApplicationType.Desktop;
}
@Override public int getVersion () {
return 0;
}
public static void main(String[] argv) {
ApplicationListener listener = new ApplicationListener() {
@Override
public void resume() {
System.out.println("resumed");
}
@Override
public void render() {
System.out.println("render");
}
@Override
public void pause() {
System.out.println("paused");
}
@Override
public void dispose() {
System.out.println("destroy");
}
@Override
public void create() {
System.out.println("created");
}
@Override
public void resize(int width, int height) {
System.out.println("resize");
}
};
new JoglApplication(listener, "Jogl Application Test", 480, 320, false);
}
}
| backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplication.java | /*******************************************************************************
* Copyright 2010 Mario Zechner ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.jogl;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Version;
/**
* An implemenation of the {@link Application} interface based on Jogl for Windows, Linux and Mac. Instantiate this class with
* apropriate parameters and then register {@link ApplicationListener}, {@link RenderListener} or {@link InputProcessor} instances.
*
* @author mzechner
*
*/
public final class JoglApplication implements Application {
static {
JoglNativesLoader.loadLibraries();
Version.loadLibrary();
}
final JoglGraphics graphics;
final JoglInput input;
final JoglFiles files;
final JoglAudio audio;
JFrame frame;
/**
* Creates a new {@link JoglApplication} with the given title and dimensions. If useGL20IfAvailable is set the JoglApplication
* will try to create an OpenGL 2.0 context which can then be used via {@link JoglApplication.getGraphics().getGL20()}. To query whether enabling OpenGL 2.0
* was successful use the {@link JoglApplication.getGraphics().isGL20Available()} method.
*
* @param listener the ApplicationListener implementing the program logic
* @param title the title of the application
* @param width the width of the surface in pixels
* @param height the height of the surface in pixels
* @param useGL20IfAvailable wheter to use OpenGL 2.0 if it is available or not
*/
public JoglApplication (ApplicationListener listener, String title, int width, int height, boolean useGL20IfAvailable) {
graphics = new JoglGraphics(listener, title, width, height, useGL20IfAvailable);
input = new JoglInput(graphics.getCanvas());
audio = new JoglAudio();
files = new JoglFiles();
Gdx.app = this;
Gdx.graphics = this.getGraphics();
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
initialize(title, width, height);
}
private void initialize(String title, int width, int height) {
graphics.getCanvas().setPreferredSize(new Dimension(width, height));
frame = new JFrame(title);
frame.setSize(width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + frame.getInsets().bottom
+ height);
frame.add(graphics.getCanvas(), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.addWindowListener( new WindowAdapter() {
@Override
public void windowOpened(WindowEvent arg0) {
graphics.getCanvas().requestFocus();
graphics.getCanvas().requestFocusInWindow();
}
@Override
public void windowIconified(WindowEvent arg0) {
graphics.pause();
}
@Override
public void windowDeiconified(WindowEvent arg0) {
graphics.resume();
}
@Override
public void windowClosing(WindowEvent arg0) {
graphics.pause();
graphics.destroy();
frame.remove(graphics.getCanvas());
}
});
frame.pack();
frame.setVisible(true);
graphics.create();
}
/**
* {@inheritDoc}
*/
@Override public Audio getAudio () {
return audio;
}
/**
* {@inheritDoc}
*/
@Override public Files getFiles () {
return files;
}
/**
* {@inheritDoc}
*/
@Override public Graphics getGraphics () {
return graphics;
}
/**
* {@inheritDoc}
*/
@Override public Input getInput () {
return input;
}
@Override public void log (String tag, String message) {
System.out.println(tag + ": " + message);
}
/**
* {@inheritDoc}
*/
@Override public ApplicationType getType () {
return ApplicationType.Desktop;
}
@Override public int getVersion () {
return 0;
}
public static void main(String[] argv) {
ApplicationListener listener = new ApplicationListener() {
@Override
public void resume() {
System.out.println("resumed");
}
@Override
public void render() {
System.out.println("render");
}
@Override
public void pause() {
System.out.println("paused");
}
@Override
public void dispose() {
System.out.println("destroy");
}
@Override
public void create() {
System.out.println("created");
}
@Override
public void resize(int width, int height) {
System.out.println("resize");
}
};
new JoglApplication(listener, "Jogl Application Test", 480, 320, false);
}
}
| [fixed] everything gets loaded in the EDT now, swing sucks, jogl sucks everything sucks. The reason the tests worked but the demos didn't is that the test first opens a freaking swing jframe which will load jawt.so and mjawt.so magically.
| backends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplication.java | [fixed] everything gets loaded in the EDT now, swing sucks, jogl sucks everything sucks. The reason the tests worked but the demos didn't is that the test first opens a freaking swing jframe which will load jawt.so and mjawt.so magically. | <ide><path>ackends/gdx-backend-jogl/src/com/badlogic/gdx/backends/jogl/JoglApplication.java
<ide> import java.awt.event.WindowEvent;
<ide>
<ide> import javax.swing.JFrame;
<add>import javax.swing.SwingUtilities;
<ide>
<ide> import com.badlogic.gdx.Application;
<ide> import com.badlogic.gdx.ApplicationListener;
<ide> import com.badlogic.gdx.Input;
<ide> import com.badlogic.gdx.InputProcessor;
<ide> import com.badlogic.gdx.Version;
<add>import com.badlogic.gdx.utils.GdxRuntimeException;
<ide>
<ide> /**
<ide> * An implemenation of the {@link Application} interface based on Jogl for Windows, Linux and Mac. Instantiate this class with
<ide> *
<ide> */
<ide> public final class JoglApplication implements Application {
<del> static {
<del> JoglNativesLoader.loadLibraries();
<add> static {
<ide> Version.loadLibrary();
<ide> }
<ide>
<del> final JoglGraphics graphics;
<del> final JoglInput input;
<del> final JoglFiles files;
<del> final JoglAudio audio;
<add> JoglGraphics graphics;
<add> JoglInput input;
<add> JoglFiles files;
<add> JoglAudio audio;
<ide> JFrame frame;
<ide>
<ide>
<ide> * @param width the width of the surface in pixels
<ide> * @param height the height of the surface in pixels
<ide> * @param useGL20IfAvailable wheter to use OpenGL 2.0 if it is available or not
<del> */
<del> public JoglApplication (ApplicationListener listener, String title, int width, int height, boolean useGL20IfAvailable) {
<del> graphics = new JoglGraphics(listener, title, width, height, useGL20IfAvailable);
<del> input = new JoglInput(graphics.getCanvas());
<del> audio = new JoglAudio();
<del> files = new JoglFiles();
<del>
<del> Gdx.app = this;
<del> Gdx.graphics = this.getGraphics();
<del> Gdx.input = this.getInput();
<del> Gdx.audio = this.getAudio();
<del> Gdx.files = this.getFiles();
<del>
<del> initialize(title, width, height);
<add> */
<add> public JoglApplication (final ApplicationListener listener, final String title, final int width, final int height, final boolean useGL20IfAvailable) {
<add> try {
<add> SwingUtilities.invokeAndWait( new Runnable() {
<add> public void run() {
<add> JoglNativesLoader.loadLibraries();
<add> graphics = new JoglGraphics(listener, title, width, height, useGL20IfAvailable);
<add> input = new JoglInput(graphics.getCanvas());
<add> audio = new JoglAudio();
<add> files = new JoglFiles();
<add>
<add> Gdx.app = JoglApplication.this;
<add> Gdx.graphics = JoglApplication.this.getGraphics();
<add> Gdx.input = JoglApplication.this.getInput();
<add> Gdx.audio = JoglApplication.this.getAudio();
<add> Gdx.files = JoglApplication.this.getFiles();
<add>
<add> initialize(title, width, height);
<add> }
<add> });
<add> } catch (Exception e) {
<add> throw new GdxRuntimeException("Creating window failed");
<add> }
<ide> }
<ide>
<ide> private void initialize(String title, int width, int height) {
<del> graphics.getCanvas().setPreferredSize(new Dimension(width, height));
<del>
<del> frame = new JFrame(title);
<add> frame = new JFrame(title);
<add> graphics.getCanvas().setPreferredSize(new Dimension(width, height));
<ide> frame.setSize(width + frame.getInsets().left + frame.getInsets().right, frame.getInsets().top + frame.getInsets().bottom
<ide> + height);
<ide> frame.add(graphics.getCanvas(), BorderLayout.CENTER); |
|
Java | apache-2.0 | e0ae82e61ae19cda6d8e4fc3cade75cae7dd7e46 | 0 | bladecoder/bladecoder-adventure-engine,bladecoder/bladecoder-adventure-engine | package com.bladecoder.engine.ink;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.Serializable;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.reflect.ReflectionException;
import com.bladecoder.engine.actions.Action;
import com.bladecoder.engine.actions.ActionCallback;
import com.bladecoder.engine.actions.ActionFactory;
import com.bladecoder.engine.assets.EngineAssetManager;
import com.bladecoder.engine.i18n.I18N;
import com.bladecoder.engine.model.Text.Type;
import com.bladecoder.engine.model.VerbRunner;
import com.bladecoder.engine.model.World;
import com.bladecoder.engine.serialization.ActionCallbackSerializer;
import com.bladecoder.engine.serialization.BladeJson;
import com.bladecoder.engine.serialization.BladeJson.Mode;
import com.bladecoder.engine.util.ActionUtils;
import com.bladecoder.engine.util.EngineLogger;
import com.bladecoder.ink.runtime.Choice;
import com.bladecoder.ink.runtime.InkList;
import com.bladecoder.ink.runtime.ListDefinition;
import com.bladecoder.ink.runtime.Story;
public class InkManager implements Serializable {
public final static int KEY_SIZE = 10;
public final static char NAME_VALUE_TAG_SEPARATOR = ':';
public final static char NAME_VALUE_PARAM_SEPARATOR = '=';
private final static String PARAM_SEPARATOR = ",";
public final static char COMMAND_MARK = '>';
private ResourceBundle i18n;
private Story story = null;
private ActionCallback cb;
// Depending on the reading order of Inventory, InkManager and Actor verbs,
// the verbCallbacks may not exist. So, we search the Cb lazily when needed.
private String sCb;
private boolean wasInCutmode;
private String storyName;
private final World w;
private InkVerbRunner inkVerbRunner = new InkVerbRunner();
private Thread loaderThread;
public InkManager(World w) {
this.w = w;
}
public void newStory(final String name) throws Exception {
loadThreaded(name, null);
}
private void loadStory(String name) {
try {
FileHandle asset = EngineAssetManager.getInstance()
.getAsset(EngineAssetManager.MODEL_DIR + name + EngineAssetManager.INK_EXT);
long initTime = System.currentTimeMillis();
String json = getJsonString(asset.read());
story = new Story(json);
ExternalFunctions.bindExternalFunctions(w, story);
storyName = name;
loadI18NBundle();
EngineLogger.debug("INK STORY LOADING TIME (ms): " + (System.currentTimeMillis() - initTime));
} catch (Exception e) {
EngineLogger.error("Cannot load Ink Story: " + name + " " + e.getMessage());
story = null;
storyName = null;
}
}
private void loadStoryState(String stateString) {
try {
long initTime = System.currentTimeMillis();
story.getState().loadJson(stateString);
EngineLogger.debug("INK *SAVED STATE* LOADING TIME (ms): " + (System.currentTimeMillis() - initTime));
} catch (Exception e) {
EngineLogger.error("Cannot load Ink Story State for: " + storyName + " " + e.getMessage());
}
}
public void loadI18NBundle() {
if (getStoryName() != null
&& EngineAssetManager.getInstance().getModelFile(storyName + "-ink.properties").exists())
i18n = w.getI18N().getBundle(EngineAssetManager.MODEL_DIR + storyName + "-ink", true);
}
public String translateLine(String line) {
if (line.charAt(0) == I18N.PREFIX) {
String key = line.substring(1);
// In ink, several keys can be included in the same line.
String[] keys = key.split("@");
String translated = "";
for (String k : keys) {
try {
// some untranslated words may follow the key
String k2 = k.substring(0, KEY_SIZE);
translated += i18n.getString(k2);
if (k.length() > KEY_SIZE) {
String trailing = k.substring(KEY_SIZE);
translated += trailing;
}
} catch (Exception e) {
EngineLogger.error("MISSING TRANSLATION KEY: " + key);
return key;
}
}
// In translated lines, spaces can be escaped with '_'.
translated = translated.replace('_', ' ');
return translated;
}
return line;
}
public String getVariable(String name) {
return story.getVariablesState().get(name).toString();
}
public boolean compareVariable(String name, String value) {
waitIfNotLoaded();
if (story.getVariablesState().get(name) instanceof InkList) {
return ((InkList) story.getVariablesState().get(name)).ContainsItemNamed(value);
} else {
return story.getVariablesState().get(name).toString().equals(value == null ? "" : value);
}
}
public void setVariable(String name, String value) throws Exception {
waitIfNotLoaded();
if (story.getVariablesState().get(name) instanceof InkList) {
InkList rawList = (InkList) story.getVariablesState().get(name);
if (rawList.getOrigins() == null) {
List<String> names = rawList.getOriginNames();
if (names != null) {
ArrayList<ListDefinition> origins = new ArrayList<>();
for (String n : names) {
ListDefinition def = story.getListDefinitions().getListDefinition(n);
if (!origins.contains(def))
origins.add(def);
}
rawList.setOrigins(origins);
}
}
rawList.addItem(value);
} else
story.getVariablesState().set(name, value);
}
private void continueMaximally() {
waitIfNotLoaded();
String line = null;
// We create a new InkVerbRunner every ink loop to avoid pending cb.resume() to
// execute in the new actions
inkVerbRunner.cancel();
inkVerbRunner = new InkVerbRunner();
HashMap<String, String> currentLineParams = new HashMap<>();
while (story.canContinue()) {
try {
line = story.Continue();
currentLineParams.clear();
// Remove trailing '\n'
if (!line.isEmpty())
line = line.substring(0, line.length() - 1);
if (!line.isEmpty()) {
if (EngineLogger.debugMode())
EngineLogger.debug("INK LINE: " + translateLine(line));
processParams(story.getCurrentTags(), currentLineParams);
// PROCESS COMMANDS
if (line.charAt(0) == COMMAND_MARK) {
processCommand(currentLineParams, line);
} else {
processTextLine(currentLineParams, line);
}
} else {
EngineLogger.debug("INK EMPTY LINE!");
}
} catch (Exception e) {
EngineLogger.error(e.getMessage(), e);
}
if (story.getCurrentErrors() != null && !story.getCurrentErrors().isEmpty()) {
EngineLogger.error(story.getCurrentErrors().get(0));
}
}
if (inkVerbRunner.getActions().size() > 0) {
inkVerbRunner.run(null, null);
} else {
if (hasChoices()) {
wasInCutmode = w.inCutMode();
w.setCutMode(false);
w.getListener().dialogOptions();
} else if (cb != null || sCb != null) {
if (cb == null) {
cb = ActionCallbackSerializer.find(w, w.getCurrentScene(), sCb);
}
ActionCallback tmpcb = cb;
cb = null;
sCb = null;
tmpcb.resume();
}
}
}
private void processParams(List<String> input, HashMap<String, String> output) {
for (String t : input) {
String key;
String value;
int i = t.indexOf(NAME_VALUE_TAG_SEPARATOR);
// support ':' and '=' as param separator
if (i == -1)
i = t.indexOf(NAME_VALUE_PARAM_SEPARATOR);
if (i != -1) {
key = t.substring(0, i).trim();
value = t.substring(i + 1, t.length()).trim();
} else {
key = t.trim();
value = null;
}
EngineLogger.debug("PARAM: " + key + " value: " + value);
output.put(key, value);
}
}
private void processCommand(HashMap<String, String> params, String line) {
String commandName = null;
String commandParams[] = null;
int i = line.indexOf(NAME_VALUE_TAG_SEPARATOR);
if (i == -1) {
commandName = line.substring(1).trim();
} else {
commandName = line.substring(1, i).trim();
commandParams = line.substring(i + 1).split(PARAM_SEPARATOR);
processParams(Arrays.asList(commandParams), params);
}
if ("LeaveNow".equals(commandName)) {
boolean init = true;
String initVerb = null;
if (params.get("init") != null)
init = Boolean.parseBoolean(params.get("init"));
if (params.get("initVerb") != null)
initVerb = params.get("initVerb");
w.setCurrentScene(params.get("scene"), init, initVerb);
} else {
// Some preliminar validation to see if it's an action
if (commandName.length() > 0) {
// Try to create action by default
Action action;
try {
Class<?> c = ActionFactory.getClassTags().get(commandName);
if (c == null && commandName.indexOf('.') == -1) {
commandName = "com.bladecoder.engine.actions." + commandName + "Action";
}
action = ActionFactory.create(commandName, params);
action.init(w);
inkVerbRunner.getActions().add(action);
} catch (ClassNotFoundException | ReflectionException e) {
EngineLogger.error(e.getMessage(), e);
}
} else {
EngineLogger.error("Ink command not found: " + commandName);
}
}
}
private void processTextLine(HashMap<String, String> params, String line) {
// Get actor name from Line. Actor is separated by ':'.
// ej. "Johnny: Hello punks!"
if (!params.containsKey("actor")) {
int idx = line.indexOf(COMMAND_MARK);
if (idx != -1) {
params.put("actor", line.substring(0, idx).trim());
line = line.substring(idx + 1).trim();
}
}
if (!params.containsKey("actor") && w.getCurrentScene().getPlayer() != null) {
if (!params.containsKey("type")) {
params.put("type", Type.SUBTITLE.toString());
}
} else if (params.containsKey("actor") && !params.containsKey("type")) {
params.put("type", Type.TALK.toString());
} else if (!params.containsKey("type")) {
params.put("type", Type.SUBTITLE.toString());
}
params.put("text", translateLine(line));
try {
Action action = null;
if (!params.containsKey("actor")) {
action = ActionFactory.create("Text", params);
} else {
action = ActionFactory.create("Say", params);
}
action.init(w);
inkVerbRunner.getActions().add(action);
} catch (ClassNotFoundException | ReflectionException e) {
EngineLogger.error(e.getMessage(), e);
}
}
public Story getStory() {
waitIfNotLoaded();
return story;
}
public void runPath(String path, ActionCallback cb) throws Exception {
waitIfNotLoaded();
if (story == null) {
EngineLogger.error("Ink Story not loaded!");
return;
}
this.cb = cb;
sCb = null;
story.choosePathString(path);
continueMaximally();
}
public boolean hasChoices() {
waitIfNotLoaded();
return (story != null && inkVerbRunner.getActions().size() == 0 && story.getCurrentChoices().size() > 0);
}
public List<String> getChoices() {
List<Choice> options = story.getCurrentChoices();
List<String> choices = new ArrayList<>(options.size());
for (Choice o : options) {
String line = o.getText();
// the line maybe empty in default choices.
if (line.isEmpty())
continue;
int idx = line.indexOf(InkManager.COMMAND_MARK);
if (idx != -1) {
line = line.substring(idx + 1).trim();
}
choices.add(translateLine(line));
}
return choices;
}
private String getJsonString(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
// Replace the BOM mark
if (line != null)
line = line.replace('\uFEFF', ' ');
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
public void selectChoice(int i) {
w.setCutMode(wasInCutmode);
try {
story.chooseChoiceIndex(i);
continueMaximally();
} catch (Exception e) {
EngineLogger.error(e.getMessage(), e);
}
}
public String getStoryName() {
return storyName;
}
public void setStoryName(String storyName) {
this.storyName = storyName;
}
private void waitIfNotLoaded() {
if (loaderThread != null && loaderThread.isAlive()) {
EngineLogger.debug(">>> Loader thread not finished. Waiting for it!!!");
try {
loaderThread.join();
} catch (InterruptedException e) {
}
}
}
private void loadThreaded(final String name, final String state) {
EngineLogger.debug("LOADING INK STORY: " + name + (state == null ? "" : " WITH SAVED STATE."));
loaderThread = new Thread() {
@Override
public void run() {
if (name != null)
loadStory(name);
if (state != null)
loadStoryState(state);
}
};
loaderThread.start();
}
public InkVerbRunner getVerbRunner() {
return inkVerbRunner;
}
@Override
public void write(Json json) {
BladeJson bjson = (BladeJson) json;
World w = bjson.getWorld();
json.writeValue("storyName", storyName);
if (bjson.getMode() == Mode.STATE) {
json.writeValue("wasInCutmode", wasInCutmode);
if (cb == null && sCb != null)
cb = ActionCallbackSerializer.find(w, w.getCurrentScene(), sCb);
if (cb != null)
json.writeValue("cb", ActionCallbackSerializer.find(w, w.getCurrentScene(), cb));
// SAVE ACTIONS
json.writeArrayStart("actions");
for (Action a : inkVerbRunner.getActions()) {
ActionUtils.writeJson(a, json);
}
json.writeArrayEnd();
json.writeValue("ip", inkVerbRunner.getIP());
json.writeArrayStart("actionsSer");
for (Action a : inkVerbRunner.getActions()) {
if (a instanceof Serializable) {
json.writeObjectStart();
((Serializable) a).write(json);
json.writeObjectEnd();
}
}
json.writeArrayEnd();
// SAVE STORY
if (story != null) {
try {
json.writeValue("story", story.getState().toJson());
} catch (Exception e) {
EngineLogger.error(e.getMessage(), e);
}
}
}
}
@Override
public void read(Json json, JsonValue jsonData) {
BladeJson bjson = (BladeJson) json;
World w = bjson.getWorld();
final String name = json.readValue("storyName", String.class, jsonData);
if (bjson.getMode() == Mode.MODEL) {
story = null;
storyName = name;
// Only load in new game.
// If the SAVED_GAME_VERSION property exists we are loading a saved
// game and we will load the story in the STATE mode.
if (bjson.getInit()) {
loadThreaded(name, null);
}
} else {
wasInCutmode = json.readValue("wasInCutmode", Boolean.class, jsonData);
sCb = json.readValue("cb", String.class, jsonData);
// READ ACTIONS
JsonValue actionsValue = jsonData.get("actions");
inkVerbRunner = new InkVerbRunner();
for (int i = 0; i < actionsValue.size; i++) {
JsonValue aValue = actionsValue.get(i);
Action a = ActionUtils.readJson(w, json, aValue);
inkVerbRunner.getActions().add(a);
}
inkVerbRunner.setIP(json.readValue("ip", Integer.class, jsonData));
actionsValue = jsonData.get("actionsSer");
int i = 0;
for (Action a : inkVerbRunner.getActions()) {
if (a instanceof Serializable && i < actionsValue.size) {
if (actionsValue.get(i) == null)
break;
((Serializable) a).read(json, actionsValue.get(i));
i++;
}
}
// READ STORY
final String storyString = json.readValue("story", String.class, jsonData);
if (storyString != null) {
loadThreaded(name, storyString);
}
}
}
public final class InkVerbRunner implements VerbRunner {
private ArrayList<Action> actions;
private int ip = -1;
private boolean cancelled = false;
public InkVerbRunner() {
actions = new ArrayList<>();
}
@Override
public void resume() {
ip++;
nextStep();
}
@Override
public ArrayList<Action> getActions() {
return actions;
}
@Override
public void run(String currentTarget, ActionCallback cb) {
ip = 0;
nextStep();
}
@Override
public int getIP() {
return ip;
}
@Override
public void setIP(int ip) {
this.ip = ip;
}
@Override
public void cancel() {
cancelled = true;
ip = actions.size();
}
@Override
public String getCurrentTarget() {
return null;
}
private void nextStep() {
if (cancelled)
return;
if (ip < 0) {
continueMaximally();
} else {
boolean stop = false;
while (ip < actions.size() && !stop && !cancelled) {
Action a = actions.get(ip);
try {
if (a.run(this))
stop = true;
else
ip++;
} catch (Exception e) {
EngineLogger.error("EXCEPTION EXECUTING ACTION: InkManager - " + ip + " - "
+ a.getClass().getSimpleName() + " - " + e.getMessage(), e);
ip++;
}
}
if (ip >= actions.size() && !stop)
continueMaximally();
}
}
}
}
| blade-engine/src/com/bladecoder/engine/ink/InkManager.java | package com.bladecoder.engine.ink;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.Serializable;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.reflect.ReflectionException;
import com.bladecoder.engine.actions.Action;
import com.bladecoder.engine.actions.ActionCallback;
import com.bladecoder.engine.actions.ActionFactory;
import com.bladecoder.engine.assets.EngineAssetManager;
import com.bladecoder.engine.i18n.I18N;
import com.bladecoder.engine.model.Text.Type;
import com.bladecoder.engine.model.VerbRunner;
import com.bladecoder.engine.model.World;
import com.bladecoder.engine.serialization.ActionCallbackSerializer;
import com.bladecoder.engine.serialization.BladeJson;
import com.bladecoder.engine.serialization.BladeJson.Mode;
import com.bladecoder.engine.util.ActionUtils;
import com.bladecoder.engine.util.EngineLogger;
import com.bladecoder.ink.runtime.Choice;
import com.bladecoder.ink.runtime.InkList;
import com.bladecoder.ink.runtime.ListDefinition;
import com.bladecoder.ink.runtime.Story;
public class InkManager implements Serializable {
public final static int KEY_SIZE = 10;
public final static char NAME_VALUE_TAG_SEPARATOR = ':';
public final static char NAME_VALUE_PARAM_SEPARATOR = '=';
private final static String PARAM_SEPARATOR = ",";
public final static char COMMAND_MARK = '>';
private ResourceBundle i18n;
private Story story = null;
private ActionCallback cb;
// Depending on the reading order of Inventory, InkManager and Actor verbs,
// the verbCallbacks may not exist. So, we search the Cb lazily when needed.
private String sCb;
private boolean wasInCutmode;
private String storyName;
private final World w;
private InkVerbRunner inkVerbRunner = new InkVerbRunner();
private Thread loaderThread;
public InkManager(World w) {
this.w = w;
}
public void newStory(final String name) throws Exception {
loadThreaded(name, null);
}
private void loadStory(String name) {
try {
FileHandle asset = EngineAssetManager.getInstance()
.getAsset(EngineAssetManager.MODEL_DIR + name + EngineAssetManager.INK_EXT);
long initTime = System.currentTimeMillis();
String json = getJsonString(asset.read());
story = new Story(json);
ExternalFunctions.bindExternalFunctions(w, story);
storyName = name;
loadI18NBundle();
EngineLogger.debug("INK STORY LOADING TIME (ms): " + (System.currentTimeMillis() - initTime));
} catch (Exception e) {
EngineLogger.error("Cannot load Ink Story: " + name + " " + e.getMessage());
story = null;
storyName = null;
}
}
private void loadStoryState(String stateString) {
try {
long initTime = System.currentTimeMillis();
story.getState().loadJson(stateString);
EngineLogger.debug("INK *SAVED STATE* LOADING TIME (ms): " + (System.currentTimeMillis() - initTime));
} catch (Exception e) {
EngineLogger.error("Cannot load Ink Story State for: " + storyName + " " + e.getMessage());
}
}
public void loadI18NBundle() {
if (getStoryName() != null
&& EngineAssetManager.getInstance().getModelFile(storyName + "-ink.properties").exists())
i18n = w.getI18N().getBundle(EngineAssetManager.MODEL_DIR + storyName + "-ink", true);
}
public String translateLine(String line) {
if (line.charAt(0) == I18N.PREFIX) {
String key = line.substring(1);
// In ink, several keys can be included in the same line.
String[] keys = key.split("@");
String translated = "";
for (String k : keys) {
try {
// some untranslated words may follow the key
String k2 = k.substring(0, KEY_SIZE);
translated += i18n.getString(k2);
if (k.length() > KEY_SIZE) {
String trailing = k.substring(KEY_SIZE);
translated += trailing;
}
} catch (Exception e) {
EngineLogger.error("MISSING TRANSLATION KEY: " + key);
return key;
}
}
// In translated lines, spaces can be escaped with '_'.
translated = translated.replace('_', ' ');
return translated;
}
return line;
}
public String getVariable(String name) {
return story.getVariablesState().get(name).toString();
}
public boolean compareVariable(String name, String value) {
waitIfNotLoaded();
if (story.getVariablesState().get(name) instanceof InkList) {
return ((InkList) story.getVariablesState().get(name)).ContainsItemNamed(value);
} else {
return story.getVariablesState().get(name).toString().equals(value == null ? "" : value);
}
}
public void setVariable(String name, String value) throws Exception {
waitIfNotLoaded();
if (story.getVariablesState().get(name) instanceof InkList) {
InkList rawList = (InkList) story.getVariablesState().get(name);
if (rawList.getOrigins() == null) {
List<String> names = rawList.getOriginNames();
if (names != null) {
ArrayList<ListDefinition> origins = new ArrayList<>();
for (String n : names) {
ListDefinition def = story.getListDefinitions().getListDefinition(n);
if (!origins.contains(def))
origins.add(def);
}
rawList.setOrigins(origins);
}
}
rawList.addItem(value);
} else
story.getVariablesState().set(name, value);
}
private void continueMaximally() {
waitIfNotLoaded();
String line = null;
// We create a new InkVerbRunner every ink loop to avoid pending cb.resume() to
// execute in the new actions
inkVerbRunner.cancel();
inkVerbRunner = new InkVerbRunner();
HashMap<String, String> currentLineParams = new HashMap<>();
while (story.canContinue()) {
try {
line = story.Continue();
currentLineParams.clear();
// Remove trailing '\n'
if (!line.isEmpty())
line = line.substring(0, line.length() - 1);
if (!line.isEmpty()) {
if (EngineLogger.debugMode())
EngineLogger.debug("INK LINE: " + translateLine(line));
processParams(story.getCurrentTags(), currentLineParams);
// PROCESS COMMANDS
if (line.charAt(0) == COMMAND_MARK) {
processCommand(currentLineParams, line);
} else {
processTextLine(currentLineParams, line);
}
} else {
EngineLogger.debug("INK EMPTY LINE!");
}
} catch (Exception e) {
EngineLogger.error(e.getMessage(), e);
}
if (story.getCurrentErrors() != null && !story.getCurrentErrors().isEmpty()) {
EngineLogger.error(story.getCurrentErrors().get(0));
}
}
if (inkVerbRunner.getActions().size() > 0) {
inkVerbRunner.run(null, null);
} else {
if (hasChoices()) {
wasInCutmode = w.inCutMode();
w.setCutMode(false);
w.getListener().dialogOptions();
} else if (cb != null || sCb != null) {
if (cb == null) {
cb = ActionCallbackSerializer.find(w, w.getCurrentScene(), sCb);
}
ActionCallback tmpcb = cb;
cb = null;
sCb = null;
tmpcb.resume();
}
}
}
private void processParams(List<String> input, HashMap<String, String> output) {
for (String t : input) {
String key;
String value;
int i = t.indexOf(NAME_VALUE_TAG_SEPARATOR);
// support ':' and '=' as param separator
if (i == -1)
i = t.indexOf(NAME_VALUE_PARAM_SEPARATOR);
if (i != -1) {
key = t.substring(0, i).trim();
value = t.substring(i + 1, t.length()).trim();
} else {
key = t.trim();
value = null;
}
EngineLogger.debug("PARAM: " + key + " value: " + value);
output.put(key, value);
}
}
private void processCommand(HashMap<String, String> params, String line) {
String commandName = null;
String commandParams[] = null;
int i = line.indexOf(NAME_VALUE_TAG_SEPARATOR);
if (i == -1) {
commandName = line.substring(1).trim();
} else {
commandName = line.substring(1, i).trim();
commandParams = line.substring(i + 1).split(PARAM_SEPARATOR);
processParams(Arrays.asList(commandParams), params);
}
if ("LeaveNow".equals(commandName)) {
boolean init = true;
String initVerb = null;
if (params.get("init") != null)
init = Boolean.parseBoolean(params.get("init"));
if (params.get("initVerb") != null)
initVerb = params.get("initVerb");
w.setCurrentScene(params.get("scene"), init, initVerb);
} else {
// Some preliminar validation to see if it's an action
if (commandName.length() > 0) {
// Try to create action by default
Action action;
try {
Class<?> c = ActionFactory.getClassTags().get(commandName);
if (c == null && commandName.indexOf('.') == -1) {
commandName = "com.bladecoder.engine.actions." + commandName + "Action";
}
action = ActionFactory.create(commandName, params);
action.init(w);
inkVerbRunner.getActions().add(action);
} catch (ClassNotFoundException | ReflectionException e) {
EngineLogger.error(e.getMessage(), e);
}
} else {
EngineLogger.error("Ink command not found: " + commandName);
}
}
}
private void processTextLine(HashMap<String, String> params, String line) {
// Get actor name from Line. Actor is separated by ':'.
// ej. "Johnny: Hello punks!"
if (!params.containsKey("actor")) {
int idx = line.indexOf(COMMAND_MARK);
if (idx != -1) {
params.put("actor", line.substring(0, idx).trim());
line = line.substring(idx + 1).trim();
}
}
if (!params.containsKey("actor") && w.getCurrentScene().getPlayer() != null) {
// params.put("actor", Scene.VAR_PLAYER);
if (!params.containsKey("type")) {
params.put("type", Type.SUBTITLE.toString());
}
} else if (params.containsKey("actor") && !params.containsKey("type")) {
params.put("type", Type.TALK.toString());
} else if (!params.containsKey("type")) {
params.put("type", Type.SUBTITLE.toString());
}
params.put("text", translateLine(line));
try {
Action action = null;
if (!params.containsKey("actor")) {
action = ActionFactory.create("Text", params);
} else {
action = ActionFactory.create("Say", params);
}
action.init(w);
inkVerbRunner.getActions().add(action);
} catch (ClassNotFoundException | ReflectionException e) {
EngineLogger.error(e.getMessage(), e);
}
}
public Story getStory() {
waitIfNotLoaded();
return story;
}
public void runPath(String path, ActionCallback cb) throws Exception {
waitIfNotLoaded();
if (story == null) {
EngineLogger.error("Ink Story not loaded!");
return;
}
this.cb = cb;
sCb = null;
story.choosePathString(path);
continueMaximally();
}
public boolean hasChoices() {
waitIfNotLoaded();
return (story != null && inkVerbRunner.getActions().size() == 0 && story.getCurrentChoices().size() > 0);
}
public List<String> getChoices() {
List<Choice> options = story.getCurrentChoices();
List<String> choices = new ArrayList<>(options.size());
for (Choice o : options) {
String line = o.getText();
// the line maybe empty in default choices.
if (line.isEmpty())
continue;
int idx = line.indexOf(InkManager.COMMAND_MARK);
if (idx != -1) {
line = line.substring(idx + 1).trim();
}
choices.add(translateLine(line));
}
return choices;
}
private String getJsonString(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
// Replace the BOM mark
if (line != null)
line = line.replace('\uFEFF', ' ');
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
public void selectChoice(int i) {
w.setCutMode(wasInCutmode);
try {
story.chooseChoiceIndex(i);
continueMaximally();
} catch (Exception e) {
EngineLogger.error(e.getMessage(), e);
}
}
public String getStoryName() {
return storyName;
}
public void setStoryName(String storyName) {
this.storyName = storyName;
}
private void waitIfNotLoaded() {
if (loaderThread != null && loaderThread.isAlive()) {
EngineLogger.debug(">>> Loader thread not finished. Waiting for it!!!");
try {
loaderThread.join();
} catch (InterruptedException e) {
}
}
}
private void loadThreaded(final String name, final String state) {
EngineLogger.debug("LOADING INK STORY: " + name + (state == null ? "" : " WITH SAVED STATE."));
loaderThread = new Thread() {
@Override
public void run() {
if (name != null)
loadStory(name);
if (state != null)
loadStoryState(state);
}
};
loaderThread.start();
}
public InkVerbRunner getVerbRunner() {
return inkVerbRunner;
}
@Override
public void write(Json json) {
BladeJson bjson = (BladeJson) json;
World w = bjson.getWorld();
json.writeValue("storyName", storyName);
if (bjson.getMode() == Mode.STATE) {
json.writeValue("wasInCutmode", wasInCutmode);
if (cb == null && sCb != null)
cb = ActionCallbackSerializer.find(w, w.getCurrentScene(), sCb);
if (cb != null)
json.writeValue("cb", ActionCallbackSerializer.find(w, w.getCurrentScene(), cb));
// SAVE ACTIONS
json.writeArrayStart("actions");
for (Action a : inkVerbRunner.getActions()) {
ActionUtils.writeJson(a, json);
}
json.writeArrayEnd();
json.writeValue("ip", inkVerbRunner.getIP());
json.writeArrayStart("actionsSer");
for (Action a : inkVerbRunner.getActions()) {
if (a instanceof Serializable) {
json.writeObjectStart();
((Serializable) a).write(json);
json.writeObjectEnd();
}
}
json.writeArrayEnd();
// SAVE STORY
if (story != null) {
try {
json.writeValue("story", story.getState().toJson());
} catch (Exception e) {
EngineLogger.error(e.getMessage(), e);
}
}
}
}
@Override
public void read(Json json, JsonValue jsonData) {
BladeJson bjson = (BladeJson) json;
World w = bjson.getWorld();
final String name = json.readValue("storyName", String.class, jsonData);
if (bjson.getMode() == Mode.MODEL) {
story = null;
storyName = name;
// Only load in new game.
// If the SAVED_GAME_VERSION property exists we are loading a saved
// game and we will load the story in the STATE mode.
if (bjson.getInit()) {
loadThreaded(name, null);
}
} else {
wasInCutmode = json.readValue("wasInCutmode", Boolean.class, jsonData);
sCb = json.readValue("cb", String.class, jsonData);
// READ ACTIONS
JsonValue actionsValue = jsonData.get("actions");
inkVerbRunner = new InkVerbRunner();
for (int i = 0; i < actionsValue.size; i++) {
JsonValue aValue = actionsValue.get(i);
Action a = ActionUtils.readJson(w, json, aValue);
inkVerbRunner.getActions().add(a);
}
inkVerbRunner.setIP(json.readValue("ip", Integer.class, jsonData));
actionsValue = jsonData.get("actionsSer");
int i = 0;
for (Action a : inkVerbRunner.getActions()) {
if (a instanceof Serializable && i < actionsValue.size) {
if (actionsValue.get(i) == null)
break;
((Serializable) a).read(json, actionsValue.get(i));
i++;
}
}
// READ STORY
final String storyString = json.readValue("story", String.class, jsonData);
if (storyString != null) {
loadThreaded(name, storyString);
}
}
}
public final class InkVerbRunner implements VerbRunner {
private ArrayList<Action> actions;
private int ip = -1;
private boolean cancelled = false;
public InkVerbRunner() {
actions = new ArrayList<>();
}
@Override
public void resume() {
ip++;
nextStep();
}
@Override
public ArrayList<Action> getActions() {
return actions;
}
@Override
public void run(String currentTarget, ActionCallback cb) {
ip = 0;
nextStep();
}
@Override
public int getIP() {
return ip;
}
@Override
public void setIP(int ip) {
this.ip = ip;
}
@Override
public void cancel() {
cancelled = true;
ip = actions.size();
}
@Override
public String getCurrentTarget() {
return null;
}
private void nextStep() {
if (cancelled)
return;
if (ip < 0) {
continueMaximally();
} else {
boolean stop = false;
while (ip < actions.size() && !stop && !cancelled) {
Action a = actions.get(ip);
try {
if (a.run(this))
stop = true;
else
ip++;
} catch (Exception e) {
EngineLogger.error("EXCEPTION EXECUTING ACTION: InkManager - " + ip + " - "
+ a.getClass().getSimpleName() + " - " + e.getMessage(), e);
ip++;
}
}
if (ip >= actions.size() && !stop)
continueMaximally();
}
}
}
}
| Delete commented text.
| blade-engine/src/com/bladecoder/engine/ink/InkManager.java | Delete commented text. | <ide><path>lade-engine/src/com/bladecoder/engine/ink/InkManager.java
<ide> }
<ide>
<ide> if (!params.containsKey("actor") && w.getCurrentScene().getPlayer() != null) {
<del> // params.put("actor", Scene.VAR_PLAYER);
<del>
<ide> if (!params.containsKey("type")) {
<ide> params.put("type", Type.SUBTITLE.toString());
<ide> } |
|
Java | apache-2.0 | 1b6da11549beb256dfcf4668f4d5f987f57cbc8f | 0 | folio-org/okapi,funkymalc/okapi,funkymalc/okapi,julianladisch/okapi-acquisitions-poc,julianladisch/okapi-acquisitions-poc,folio-org/okapi,julianladisch/okapi-acquisitions-poc | /*
* Copyright (c) 2015-2016, Index Data
* All rights reserved.
* See the file LICENSE for details.
*/
package okapi.service;
import okapi.bean.ModuleDescriptor;
import okapi.bean.ModuleInstance;
import okapi.bean.Modules;
import okapi.bean.Ports;
import okapi.bean.ProcessModuleHandle;
import io.vertx.core.Vertx;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.Json;
import io.vertx.ext.web.RoutingContext;
public class ModuleService {
private Modules modules;
private Ports ports;
final private Vertx vertx;
public ModuleService(Vertx vertx, Modules modules, int port_start, int port_end) {
this.vertx = vertx;
this.ports = new Ports(port_start, port_end);
this.modules = modules;
}
public void create(RoutingContext ctx) {
try {
final ModuleDescriptor md = Json.decodeValue(ctx.getBodyAsString(),
ModuleDescriptor.class);
final String id = md.getId();
String url;
final int use_port = ports.get();
int spawn_port = -1;
ModuleInstance m = modules.get(id);
if (m != null) {
ctx.response().setStatusCode(400).end("module " + id
+ " already deployed");
return;
}
if (md.getUrl() == null) {
if (use_port == -1) {
ctx.response().setStatusCode(400).end("module " + id
+ " can not be deployed: all ports in use");
}
spawn_port = use_port;
url = "http://localhost:" + use_port;
} else {
ports.free(use_port);
url = md.getUrl();
}
if (md.getDescriptor() != null) {
// enable it now so that activation for 2nd one will fail
ProcessModuleHandle pmh = new ProcessModuleHandle(vertx, md.getDescriptor(),
spawn_port);
modules.put(id, new ModuleInstance(md, pmh, url));
pmh.start(future -> {
if (future.succeeded()) {
ctx.response().setStatusCode(201)
.putHeader("Location", ctx.request().uri() + "/" + id)
.end();
} else {
modules.remove(md.getId());
ports.free(use_port);
ctx.response().setStatusCode(500).end(future.cause().getMessage());
}
});
} else {
modules.put(id, new ModuleInstance(md, null, url));
ctx.response().setStatusCode(201)
.putHeader("Location", ctx.request().uri() + "/" + id)
.end();
}
} catch (DecodeException ex) {
ctx.response().setStatusCode(400).end(ex.getMessage());
}
}
public void get(RoutingContext ctx) {
final String id = ctx.request().getParam("id");
ModuleInstance m = modules.get(id);
if (m == null) {
ctx.response().setStatusCode(404).end();
return;
}
String s = Json.encodePrettily(modules.get(id).getModuleDescriptor());
ctx.response().end(s);
}
public void list(RoutingContext ctx) {
String s = Json.encodePrettily(modules.list());
ctx.response().end(s);
}
public void delete(RoutingContext ctx) {
final String id = ctx.request().getParam("id");
ModuleInstance m = modules.get(id);
if (m == null) {
ctx.response().setStatusCode(404).end();
return;
}
ProcessModuleHandle pmh = m.getProcessModuleHandle();
if (pmh == null) {
ctx.response().setStatusCode(204).end();
} else {
pmh.stop(future -> {
if (future.succeeded()) {
modules.remove(id);
ports.free(pmh.getPort());
ctx.response().setStatusCode(204).end();
} else {
ctx.response().setStatusCode(500).end(future.cause().getMessage());
}
});
}
}
} // class
| okapi-core/src/main/java/okapi/service/ModuleService.java | /*
* Copyright (c) 2015-2016, Index Data
* All rights reserved.
* See the file LICENSE for details.
*/
package okapi.service;
import okapi.bean.ModuleDescriptor;
import okapi.bean.ModuleInstance;
import okapi.bean.Modules;
import okapi.bean.Ports;
import okapi.bean.ProcessModuleHandle;
import okapi.bean.Tenant;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.Json;
import io.vertx.core.streams.ReadStream;
import io.vertx.ext.web.RoutingContext;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Iterator;
import okapi.bean.RoutingEntry;
public class ModuleService {
private Modules modules;
private Ports ports;
final private Vertx vertx;
public ModuleService(Vertx vertx, Modules modules, int port_start, int port_end) {
this.vertx = vertx;
this.ports = new Ports(port_start, port_end);
this.modules = modules;
}
public void create(RoutingContext ctx) {
try {
final ModuleDescriptor md = Json.decodeValue(ctx.getBodyAsString(),
ModuleDescriptor.class);
final String id = md.getId();
String url;
final int use_port = ports.get();
int spawn_port = -1;
ModuleInstance m = modules.get(id);
if (m != null) {
ctx.response().setStatusCode(400).end("module " + id
+ " already deployed");
return;
}
if (md.getUrl() == null) {
if (use_port == -1) {
ctx.response().setStatusCode(400).end("module " + id
+ " can not be deployed: all ports in use");
}
spawn_port = use_port;
url = "http://localhost:" + use_port;
} else {
ports.free(use_port);
url = md.getUrl();
}
if (md.getDescriptor() != null) {
// enable it now so that activation for 2nd one will fail
ProcessModuleHandle pmh = new ProcessModuleHandle(vertx, md.getDescriptor(),
spawn_port);
modules.put(id, new ModuleInstance(md, pmh, url));
pmh.start(future -> {
if (future.succeeded()) {
ctx.response().setStatusCode(201)
.putHeader("Location", ctx.request().uri() + "/" + id)
.end();
} else {
modules.remove(md.getId());
ports.free(use_port);
ctx.response().setStatusCode(500).end(future.cause().getMessage());
}
});
} else {
modules.put(id, new ModuleInstance(md, null, url));
ctx.response().setStatusCode(201)
.putHeader("Location", ctx.request().uri() + "/" + id)
.end();
}
} catch (DecodeException ex) {
ctx.response().setStatusCode(400).end(ex.getMessage());
}
}
public void get(RoutingContext ctx) {
final String id = ctx.request().getParam("id");
ModuleInstance m = modules.get(id);
if (m == null) {
ctx.response().setStatusCode(404).end();
return;
}
String s = Json.encodePrettily(modules.get(id).getModuleDescriptor());
ctx.response().end(s);
}
public void list(RoutingContext ctx) {
String s = Json.encodePrettily(modules.list());
ctx.response().end(s);
}
public void delete(RoutingContext ctx) {
final String id = ctx.request().getParam("id");
ModuleInstance m = modules.get(id);
if (m == null) {
ctx.response().setStatusCode(404).end();
return;
}
ProcessModuleHandle pmh = m.getProcessModuleHandle();
if (pmh == null) {
ctx.response().setStatusCode(204).end();
} else {
pmh.stop(future -> {
if (future.succeeded()) {
modules.remove(id);
ports.free(pmh.getPort());
ctx.response().setStatusCode(204).end();
} else {
ctx.response().setStatusCode(500).end(future.cause().getMessage());
}
});
}
}
} // class
| Remove unused inports
| okapi-core/src/main/java/okapi/service/ModuleService.java | Remove unused inports | <ide><path>kapi-core/src/main/java/okapi/service/ModuleService.java
<ide> import okapi.bean.Modules;
<ide> import okapi.bean.Ports;
<ide> import okapi.bean.ProcessModuleHandle;
<del>import okapi.bean.Tenant;
<ide> import io.vertx.core.Vertx;
<del>import io.vertx.core.buffer.Buffer;
<del>import io.vertx.core.http.HttpClient;
<del>import io.vertx.core.http.HttpClientRequest;
<del>import io.vertx.core.http.HttpServerRequest;
<ide> import io.vertx.core.json.DecodeException;
<ide> import io.vertx.core.json.Json;
<del>import io.vertx.core.streams.ReadStream;
<ide> import io.vertx.ext.web.RoutingContext;
<del>import java.util.ArrayList;
<del>import java.util.Comparator;
<del>import java.util.List;
<del>import java.util.Iterator;
<del>import okapi.bean.RoutingEntry;
<ide>
<ide> public class ModuleService {
<ide> private Modules modules; |
|
Java | apache-2.0 | 79a54b2c44a7ed0e40025b8a001ab7308d1e1d97 | 0 | phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida | package ca.corefacility.bioinformatics.irida.ria.config.thymeleaf.webpacker.processor;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.context.WebEngineContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;
import ca.corefacility.bioinformatics.irida.ria.config.thymeleaf.webpacker.WebpackerDialect;
import ca.corefacility.bioinformatics.irida.ria.config.thymeleaf.webpacker.util.WebpackerManifestParser;
import ca.corefacility.bioinformatics.irida.ria.config.thymeleaf.webpacker.util.WebpackerTagType;
/**
* Thymeleaf Tag Processor for elements of the form: <code><webpack:js entry="entry_name" /></code>
* <p>
* This processor will:
* - determine which js chunks need to be loaded from the webpack manifest file.
* - create new script element with the correct path to the files and add them to the template.
*/
public class WebpackerJavascriptElementTagProcessor extends AbstractElementTagProcessor {
private static final WebpackerTagType TAG_TYPE = WebpackerTagType.JS;
private static final int PRECEDENCE = 1000;
private static final String JAVASCRIPT_TAG = "script";
private static final String REQUEST_CHUNKS = "runtime_chunk";
private static final String INTERNATIONALIZATION_PREFIX = "i18n";
private static final String INTERNATIONALIZATION_ATTR = "th:replace";
private static final String INTERNATIONALIZATION_TAG = "th:block";
private static final String JAVASCRIPT_ATTR = "th:src";
public WebpackerJavascriptElementTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, TAG_TYPE.toString(), true, null, false, PRECEDENCE);
}
@Override
protected void doProcess(ITemplateContext context, IProcessableElementTag tag,
IElementTagStructureHandler structureHandler) {
/*
* Since multiple entry points can be added to a single page (e.g. base template > page template > samples template),
* we need to ensure that the same link is not added more than once. Keeping a set of the existing chunks
* allows us to ensure that a chunk is only added once to the page.
*/
Set<String> existingChunks = getExistingChunksFromRequest(context);
/*
* Read the 'entry' attribute from the tag.
*/
final String entry = tag.getAttributeValue(WebpackerDialect.ENTRY_ATTR);
if (entry != null) {
final IModelFactory modelFactory = context.getModelFactory();
final IModel model = modelFactory.createModel();
/*
* Each javascript entry may require its own internationalization messages. There is a custom webpack
* plugin (i18nThymeleafWebpackPlugin) which creates Thymeleaf fragments for these messages, and adds
* the path to the webpack manifest. We will get Thymeleaf to insert the fragments above the entry
* script.
*/
final List<String> htmlResources = WebpackerManifestParser
.getChunksForEntryType(entry, WebpackerTagType.HTML);
if (htmlResources != null) {
htmlResources.forEach(file -> {
if (file.startsWith(INTERNATIONALIZATION_PREFIX)) {
model.add(modelFactory.createOpenElementTag(INTERNATIONALIZATION_TAG, INTERNATIONALIZATION_ATTR,
String.format("../dist/i18n/%s :: i18n", entry), false));
model.add(modelFactory.createCloseElementTag(INTERNATIONALIZATION_TAG));
}
});
}
/*
* Add all javascript chunks for this entry to the page.
*/
final List<String> jsResources = WebpackerManifestParser.getChunksForEntryType(entry, WebpackerTagType.JS);
if (jsResources != null) {
jsResources.forEach(chunk -> {
if (!existingChunks.contains(chunk)) {
existingChunks.add(chunk);
model.add(modelFactory
.createOpenElementTag(JAVASCRIPT_TAG, JAVASCRIPT_ATTR, String.format("@{/dist/%s}", chunk)));
model.add(modelFactory.createCloseElementTag(JAVASCRIPT_TAG));
}
});
}
structureHandler.replaceWith(model, true);
}
setExistingChunksInRequest(context, existingChunks);
}
/**
* Get a {@link Set} of javascript chunks currently on the page. This is done
* to prevent any given chunk to be added multiple times if entry points on the page
* have common chunks.
* <p>
* This has a suppressed warning for unchecked because anything stored into a request is
* an Object and we KNOW we set it as a Set.
*
* @param context - {@link ITemplateContext} for the current template.
* @return {@link Set} of all javascript chunks currently added to the template.
*/
@SuppressWarnings("unchecked")
private Set<String> getExistingChunksFromRequest(ITemplateContext context) {
WebEngineContext webEngineContext = (WebEngineContext) context;
HttpServletRequest request = webEngineContext.getRequest();
Object chunksObject = request.getAttribute(REQUEST_CHUNKS);
return chunksObject != null ? (Set<String>) chunksObject : new HashSet<>();
}
/**
* Update the request with the all javascript chunks which are now loaded into the template.
*
* @param context - {@link ITemplateContext} for the current template.
* @param chunks - {@link Set} of all javascript chunks currently added to the template.
*/
private void setExistingChunksInRequest(ITemplateContext context, Set<String> chunks) {
WebEngineContext webEngineContext = (WebEngineContext) context;
HttpServletRequest request = webEngineContext.getRequest();
request.setAttribute(REQUEST_CHUNKS, chunks);
}
}
| src/main/java/ca/corefacility/bioinformatics/irida/ria/config/thymeleaf/webpacker/processor/WebpackerJavascriptElementTagProcessor.java | package ca.corefacility.bioinformatics.irida.ria.config.thymeleaf.webpacker.processor;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.context.WebEngineContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;
import ca.corefacility.bioinformatics.irida.ria.config.thymeleaf.webpacker.WebpackerDialect;
import ca.corefacility.bioinformatics.irida.ria.config.thymeleaf.webpacker.util.WebpackerManifestParser;
import ca.corefacility.bioinformatics.irida.ria.config.thymeleaf.webpacker.util.WebpackerTagType;
/**
* Thymeleaf Tag Processor for elements of the form: <code><webpack:js entry="entry_name" /></code>
* <p>
* This processor will:
* - determine which js chunks need to be loaded from the webpack manifest file.
* - create new script element with the correct path to the files and add them to the template.
*/
public class WebpackerJavascriptElementTagProcessor extends AbstractElementTagProcessor {
private static final WebpackerTagType TAG_TYPE = WebpackerTagType.JS;
private static final int PRECEDENCE = 1000;
private static final String JAVASCRIPT_TAG = "script";
private static final String REQUEST_CHUNKS = "runtime_chunk";
private static final String INTERNATIONALIZATION_PREFIX = "i18n";
private static final String INTERNATIONALIZATION_ATTR = "th:replace";
private static final String INTERNATIONALIZATION_TAG = "th:block";
private static final String JAVASCRIPT_ATTR = "th:src";
private static final String RESOURCE_PATH = "../dist/%s";
public WebpackerJavascriptElementTagProcessor(final String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, TAG_TYPE.toString(), true, null, false, PRECEDENCE);
}
@Override
protected void doProcess(ITemplateContext context, IProcessableElementTag tag,
IElementTagStructureHandler structureHandler) {
/*
* Since multiple entry points can be added to a single page (e.g. base template > page template > samples template),
* we need to ensure that the same link is not added more than once. Keeping a set of the existing chunks
* allows us to ensure that a chunk is only added once to the page.
*/
Set<String> existingChunks = getExistingChunksFromRequest(context);
/*
* Read the 'entry' attribute from the tag.
*/
final String entry = tag.getAttributeValue(WebpackerDialect.ENTRY_ATTR);
if (entry != null) {
final IModelFactory modelFactory = context.getModelFactory();
final IModel model = modelFactory.createModel();
/*
* Each javascript entry may require its own internationalization messages. There is a custom webpack
* plugin (i18nThymeleafWebpackPlugin) which creates Thymeleaf fragments for these messages, and adds
* the path to the webpack manifest. We will get Thymeleaf to insert the fragments above the entry
* script.
*/
final List<String> htmlResources = WebpackerManifestParser
.getChunksForEntryType(entry, WebpackerTagType.HTML);
if (htmlResources != null) {
htmlResources.forEach(file -> {
if (file.startsWith(INTERNATIONALIZATION_PREFIX)) {
model.add(modelFactory.createOpenElementTag(INTERNATIONALIZATION_TAG, INTERNATIONALIZATION_ATTR,
String.format(RESOURCE_PATH, file), false));
model.add(modelFactory.createCloseElementTag(INTERNATIONALIZATION_TAG));
}
});
}
/*
* Add all javascript chunks for this entry to the page.
*/
final List<String> jsResources = WebpackerManifestParser.getChunksForEntryType(entry, WebpackerTagType.JS);
if (jsResources != null) {
jsResources.forEach(chunk -> {
if (!existingChunks.contains(chunk)) {
existingChunks.add(chunk);
model.add(modelFactory
.createOpenElementTag(JAVASCRIPT_TAG, JAVASCRIPT_ATTR, String.format(RESOURCE_PATH, chunk)));
model.add(modelFactory.createCloseElementTag(JAVASCRIPT_TAG));
}
});
}
structureHandler.replaceWith(model, true);
}
setExistingChunksInRequest(context, existingChunks);
}
/**
* Get a {@link Set} of javascript chunks currently on the page. This is done
* to prevent any given chunk to be added multiple times if entry points on the page
* have common chunks.
* <p>
* This has a suppressed warning for unchecked because anything stored into a request is
* an Object and we KNOW we set it as a Set.
*
* @param context - {@link ITemplateContext} for the current template.
* @return {@link Set} of all javascript chunks currently added to the template.
*/
@SuppressWarnings("unchecked")
private Set<String> getExistingChunksFromRequest(ITemplateContext context) {
WebEngineContext webEngineContext = (WebEngineContext) context;
HttpServletRequest request = webEngineContext.getRequest();
Object chunksObject = request.getAttribute(REQUEST_CHUNKS);
return chunksObject != null ? (Set<String>) chunksObject : new HashSet<>();
}
/**
* Update the request with the all javascript chunks which are now loaded into the template.
*
* @param context - {@link ITemplateContext} for the current template.
* @param chunks - {@link Set} of all javascript chunks currently added to the template.
*/
private void setExistingChunksInRequest(ITemplateContext context, Set<String> chunks) {
WebEngineContext webEngineContext = (WebEngineContext) context;
HttpServletRequest request = webEngineContext.getRequest();
request.setAttribute(REQUEST_CHUNKS, chunks);
}
}
| Fixed issue with broken i18n paths
| src/main/java/ca/corefacility/bioinformatics/irida/ria/config/thymeleaf/webpacker/processor/WebpackerJavascriptElementTagProcessor.java | Fixed issue with broken i18n paths | <ide><path>rc/main/java/ca/corefacility/bioinformatics/irida/ria/config/thymeleaf/webpacker/processor/WebpackerJavascriptElementTagProcessor.java
<ide> private static final String INTERNATIONALIZATION_ATTR = "th:replace";
<ide> private static final String INTERNATIONALIZATION_TAG = "th:block";
<ide> private static final String JAVASCRIPT_ATTR = "th:src";
<del> private static final String RESOURCE_PATH = "../dist/%s";
<ide>
<ide> public WebpackerJavascriptElementTagProcessor(final String dialectPrefix) {
<ide> super(TemplateMode.HTML, dialectPrefix, TAG_TYPE.toString(), true, null, false, PRECEDENCE);
<ide> htmlResources.forEach(file -> {
<ide> if (file.startsWith(INTERNATIONALIZATION_PREFIX)) {
<ide> model.add(modelFactory.createOpenElementTag(INTERNATIONALIZATION_TAG, INTERNATIONALIZATION_ATTR,
<del> String.format(RESOURCE_PATH, file), false));
<add> String.format("../dist/i18n/%s :: i18n", entry), false));
<ide> model.add(modelFactory.createCloseElementTag(INTERNATIONALIZATION_TAG));
<ide> }
<ide> });
<ide> if (!existingChunks.contains(chunk)) {
<ide> existingChunks.add(chunk);
<ide> model.add(modelFactory
<del> .createOpenElementTag(JAVASCRIPT_TAG, JAVASCRIPT_ATTR, String.format(RESOURCE_PATH, chunk)));
<add> .createOpenElementTag(JAVASCRIPT_TAG, JAVASCRIPT_ATTR, String.format("@{/dist/%s}", chunk)));
<ide> model.add(modelFactory.createCloseElementTag(JAVASCRIPT_TAG));
<ide> }
<ide> }); |
|
Java | mit | c9c18d6efb41f1ca1e67712d90da3859662d5405 | 0 | judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin | /*
* The MIT License
*
* Copyright 2016 jvanek.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.fakekoji.core;
/* all known tags in time of writing
find ~/jenkins/jenkins_home/jobs/ -name config.xml -exec grep tag {} \; | sort | uniq
<tag>dist-5*-extras*</tag>
<tag>f23-*</tag>
<tag>f23-updates*</tag>
<tag>f24-*</tag>
<tag>f24*</tag>
<tag>f24-updates*</tag>
<tag>openjdk-win-candidate</tag>
<tag>oracle-java-rhel-5.*</tag>
<tag>oracle-java-rhel-6.*</tag>
<tag>oracle-java-rhel-7.*</tag>
<tag>RHEL-5.*-candidate</tag>
<tag>RHEL-6.*-candidate</tag>
<tag>rhel-6.*-supp*</tag>
<tag>rhel-7.*-candidate</tag>
<tag>supp-rhel-7.*</tag>
*/
/**
* This class is trying to emulate tags for static (and possibly other) builds, to some future wihtout need to recompile it with each new fedora.
*
*/
public class TagsProvider {
static String[] getSuplementaryRhel5LikeTag() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = "dist-" + (i + Ffrom) + ".X-extras-fakeTag";
}
return r;
}
private static final int Ffrom = 22;
private static final int Fto = 40;
//we do not support rhel 5 and older anymore
private static final int Rfrom = 6;
private static final int Rto = 9;
private static final int Wfrom = 0;
private static final int Wto = 1;
static String[] getFedoraTags() {
String[] r = new String[Fto - Ffrom];
for (int i = 0; i < r.length; i++) {
r[i] = getFedoraBase((i + Ffrom));
}
return r;
}
static String getFedoraBase(int i) {
return "f" + (i) + "-updates-fakeTag";
}
static String[] getWinTags() {
String[] r = new String[Wto - Wfrom];
for (int i = 0; i < r.length; i++) {
r[i] = "openjdk-win-fakeTag";
}
return r;
}
static String[] getOracleTags() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = getOracleBase(i + Rfrom);
}
return r;
}
private static String getOracleBase(int i) {
return "oracle-java-rhel-" + i + ".X";
}
static String[] getRHELtags() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = getRhel5Rhel6Base(i + Rfrom);
}
return r;
}
static String getRhel5Rhel6Base(int i) {
return "RHEL-" + (i) + ".X-candidate";
}
static String[] getRhelTags() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = getRhel7Base(i + Rfrom);
}
return r;
}
static String getRhel7Base(int i) {
return "rhel-" + (i) + ".0-candidate";
}
static String[] getSuplementaryRhel6LikeTag() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = getIbmRhel6Base(i + Rfrom);
}
return r;
}
private static String getIbmRhel6Base(int i) {
return "rhel-" + (i) + ".X-supp-fakeTag";
}
static String[] getSuplementaryRhel7LikeTag() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = getIbmRhel7Base(i + Rfrom);
}
return r;
}
private static String getIbmRhel7Base(int i) {
return "supp-rhel-" + (i) + "-X-fakeTag";
}
}
| fake-koji/src/main/java/org/fakekoji/core/TagsProvider.java | /*
* The MIT License
*
* Copyright 2016 jvanek.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.fakekoji.core;
/* all known tags in time of writing
find ~/jenkins/jenkins_home/jobs/ -name config.xml -exec grep tag {} \; | sort | uniq
<tag>dist-5*-extras*</tag>
<tag>f23-*</tag>
<tag>f23-updates*</tag>
<tag>f24-*</tag>
<tag>f24*</tag>
<tag>f24-updates*</tag>
<tag>openjdk-win-candidate</tag>
<tag>oracle-java-rhel-5.*</tag>
<tag>oracle-java-rhel-6.*</tag>
<tag>oracle-java-rhel-7.*</tag>
<tag>RHEL-5.*-candidate</tag>
<tag>RHEL-6.*-candidate</tag>
<tag>rhel-6.*-supp*</tag>
<tag>rhel-7.*-candidate</tag>
<tag>supp-rhel-7.*</tag>
*/
/**
* This class is trying to emulate tags for static (and possibly other) builds, to some future wihtout need to recompile it with each new fedora.
*
*/
public class TagsProvider {
static String[] getSuplementaryRhel5LikeTag() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = "dist-" + (i + Ffrom) + ".X-extras-fakeTag";
}
return r;
}
private static final int Ffrom = 22;
private static final int Fto = 40;
//we do not support rhel 5 and older anymore
private static final int Rfrom = 6;
private static final int Rto = 9;
private static final int Wfrom = 0;
private static final int Wto = 1;
static String[] getFedoraTags() {
String[] r = new String[Fto - Ffrom];
for (int i = 0; i < r.length; i++) {
r[i] = getFedoraBase((i + Ffrom));
}
return r;
}
static String getFedoraBase(int i) {
return "f" + (i) + "-updates-fakeTag";
}
static String[] getWinTags() {
String[] r = new String[Wto - Wfrom];
for (int i = 0; i < r.length; i++) {
r[i] = "openjdk-win-fakeTag";
}
return r;
}
static String[] getOracleTags() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = getOracleBase(i + Rfrom);
}
return r;
}
private static String getOracleBase(int i) {
return "oracle-java-rhel-" + i + ".X";
}
static String[] getRHELtags() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = getRhel5Rhel6Base(i + Rfrom);
}
return r;
}
static String getRhel5Rhel6Base(int i) {
return "RHEL-" + (i) + ".X-candidate";
}
static String[] getRhelTags() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = getRhel7Base(i + Rfrom);
}
return r;
}
static String getRhel7Base(int i) {
return "rhel-" + (i) + ".X-candidate";
}
static String[] getSuplementaryRhel6LikeTag() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = getIbmRhel6Base(i + Rfrom);
}
return r;
}
private static String getIbmRhel6Base(int i) {
return "rhel-" + (i) + ".X-supp-fakeTag";
}
static String[] getSuplementaryRhel7LikeTag() {
String[] r = new String[Rto - Rfrom];
for (int i = 0; i < r.length; i++) {
r[i] = getIbmRhel7Base(i + Rfrom);
}
return r;
}
private static String getIbmRhel7Base(int i) {
return "supp-rhel-" + (i) + "-X-fakeTag";
}
}
| Qucik hack to make rhel7 tags working
| fake-koji/src/main/java/org/fakekoji/core/TagsProvider.java | Qucik hack to make rhel7 tags working | <ide><path>ake-koji/src/main/java/org/fakekoji/core/TagsProvider.java
<ide> }
<ide>
<ide> static String getRhel7Base(int i) {
<del> return "rhel-" + (i) + ".X-candidate";
<add> return "rhel-" + (i) + ".0-candidate";
<ide> }
<ide>
<ide> static String[] getSuplementaryRhel6LikeTag() { |
|
JavaScript | apache-2.0 | 05b34af64b7ede16ad089d5f859f854588f58f31 | 0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | 'use strict';
const electron = require('electron');
const fs = require('fs');
const menuTemplate = require('./menu.js');
// Copy config file to appData if no config file exists in appData
function copyConfigFile(destPath, appDataPath) {
if (!fs.existsSync(appDataPath)) fs.mkdirSync(appDataPath);
if (!fs.existsSync(destPath)) {
console.log('Create config.json at ' + destPath);
fs.writeFileSync(destPath, JSON.stringify({"dbs":["test"]}));
}
}
// CONFIGURATION ---
var env = undefined;
if (process.argv && process.argv.length > 2) {
env = process.argv[2];
}
if (env) { // is environment 'dev' (npm start) or 'test' (npm run e2e)
global.configurationPath = 'config/Configuration.json';
}
if (!env || // is environment 'production' (packaged app)
env.indexOf('dev') !== -1) { // is environment 'development' (npm start)
global.appDataPath = electron.app.getPath('appData') + '/' + electron.app.getName();
copyConfigFile(global.appDataPath + '/config.json', global.appDataPath);
global.configPath = global.appDataPath + '/config.json';
if (!env) { // is environment 'production' (packaged app)
global.configurationPath = '../config/Configuration.json'
}
} else { // is environment 'test' (npm run e2e)
global.configPath = 'config/config.test.json';
global.appDataPath = 'test/test-temp';
}
console.log('Using config file: ' + global.configPath);
global.config = JSON.parse(fs.readFileSync(global.configPath, 'utf-8'));
// -- CONFIGURATION
// OTHER GLOBALS --
global.switches = {
prevent_reload: false,
destroy_before_create: false,
messages_timeout: 3500,
suppress_map_load_for_test: false,
provide_reset: false
};
if (env && env.indexOf('test') !== -1) { // is environment 'test'
global.switches.messages_timeout = undefined;
global.switches.prevent_reload = true;
global.switches.destroy_before_create = true;
global.switches.suppress_map_load_for_test = true;
global.switches.provide_reset = true;
}
// -- OTHER GLOBALS
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow;
function createWindow() {
const screenWidth = electron.screen.getPrimaryDisplay().workAreaSize.width;
const screenHeight = electron.screen.getPrimaryDisplay().workAreaSize.height;
mainWindow = new electron.BrowserWindow({
width: screenWidth >= 1680 ? 1680 : 1280,
height: screenHeight >= 1050 ? 1050 : 800,
minWidth: 1088,
minHeight: 600,
webPreferences: {
nodeIntegration: true,
webSecurity: false
}
});
// mainWindow.webContents
const menu = electron.Menu.buildFromTemplate(menuTemplate);
electron.Menu.setApplicationMenu(menu);
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html');
// Open the DevTools.
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
electron.app.on('ready', createWindow);
electron.app.on('activate', function() {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
// Quit when all windows are closed.
electron.app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
electron.app.quit();
}
}); | main.js | 'use strict';
const electron = require('electron');
const fs = require('fs');
const menuTemplate = require('./menu.js');
// Copy config file to appData if no config file exists in appData
function copyConfigFile(destPath, appDataPath) {
if (!fs.existsSync(appDataPath)) fs.mkdirSync(appDataPath);
if (!fs.existsSync(destPath)) {
console.log('Create config.json at ' + destPath);
fs.writeFileSync(destPath, JSON.stringify({"dbs":["test"]}));
}
}
// CONFIGURATION ---
var env = undefined;
if (process.argv && process.argv.length > 2) {
env = process.argv[2];
}
if (env) { // is environment 'dev' (npm start) or 'test' (npm run e2e)
global.configurationPath = 'config/Configuration.json';
}
if (!env || // is environment 'production' (packaged app)
env.indexOf('dev') !== -1) { // is environment 'development' (npm start)
global.appDataPath = electron.app.getPath('appData') + '/' + electron.app.getName();
copyConfigFile(global.appDataPath + '/config.json', global.appDataPath);
global.configPath = global.appDataPath + '/config.json';
if (!env) { // is environment 'production' (packaged app)
global.configurationPath = '../config/Configuration.json'
}
} else { // is environment 'test' (npm run e2e)
global.configPath = 'config/config.test.json';
global.appDataPath = 'test/test-temp';
}
console.log('Using config file: ' + global.configPath);
global.config = JSON.parse(fs.readFileSync(global.configPath, 'utf-8'));
// -- CONFIGURATION
// OTHER GLOBALS --
global.switches = {
prevent_reload: false,
destroy_before_create: false,
messages_timeout: 3500,
suppress_map_load_for_test: false,
provide_reset: false
};
if (env && env.indexOf('test') !== -1) { // is environment 'test'
global.switches.messages_timeout = undefined;
global.switches.prevent_reload = true;
global.switches.destroy_before_create = true;
global.switches.suppress_map_load_for_test = true;
global.switches.provide_reset = true;
}
// -- OTHER GLOBALS
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow;
function createWindow() {
const screenWidth = electron.screen.getPrimaryDisplay().workAreaSize.width;
const screenHeight = electron.screen.getPrimaryDisplay().workAreaSize.height;
mainWindow = new electron.BrowserWindow({
width: screenWidth >= 1680 ? 1680 : 1280,
height: screenHeight >= 1050 ? 1050 : 800,
minWidth: 1000,
minHeight: 600,
webPreferences: {
nodeIntegration: true,
webSecurity: false
}
});
// mainWindow.webContents
const menu = electron.Menu.buildFromTemplate(menuTemplate);
electron.Menu.setApplicationMenu(menu);
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html');
// Open the DevTools.
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
electron.app.on('ready', createWindow);
electron.app.on('activate', function() {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
// Quit when all windows are closed.
electron.app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
electron.app.quit();
}
}); | Adjust minWidth to prevent lineBreak in sidebar tabs on conflict
| main.js | Adjust minWidth to prevent lineBreak in sidebar tabs on conflict | <ide><path>ain.js
<ide> mainWindow = new electron.BrowserWindow({
<ide> width: screenWidth >= 1680 ? 1680 : 1280,
<ide> height: screenHeight >= 1050 ? 1050 : 800,
<del> minWidth: 1000,
<add> minWidth: 1088,
<ide> minHeight: 600,
<ide> webPreferences: {
<ide> nodeIntegration: true, |
|
JavaScript | mit | 4bb03207fc49d67c57925db07f7d4699325ba052 | 0 | pisi/Reel | /**
@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@ @@@@@@@@
@@@@@@@ @@@@@@@
@@@@@@@ @@@@@@@
@@@@@@@ @@@@@@@
@@@@@@@@ @ @@@@@@@@
@@@@@@@@@ @@@ @@@@@@@@@
@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@
@@@@@@@@@@@@ @@@
@@@@@@
@@@@
@@
*
* jQuery Reel
* ===========
* The 360° plugin for jQuery
*
* @license Copyright (c) 2009-2013 Petr Vostrel (http://petr.vostrel.cz/)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* jQuery Reel
* http://jquery.vostrel.net/reel
* Version: 1.2.2
* Updated: 2013-08-16
*
* Requires jQuery 1.5 or higher
*/
/*
* CDN
* ---
* - http://code.vostrel.net/jquery.reel-bundle.js (recommended)
* - http://code.vostrel.net/jquery.reel.js
* - http://code.vostrel.net/jquery.reel-debug.js
* - or http://code.vostrel.net/jquery.reel-edge.js if you feel like it ;)
*
* Optional Plugins
* ----------------
* - jQuery.mouseWheel [B] (Brandon Aaron, http://plugins.jquery.com/project/mousewheel)
* - or jQuery.event.special.wheel (Three Dub Media, http://blog.threedubmedia.com/2008/08/eventspecialwheel.html)
*
* [B] Marked plugins are contained (with permissions) in the "bundle" version from the CDN
*/
(function(factory){
// -----------------------
// [NEW] AMD Compatibility
// -----------------------
//
// Reel registers as an asynchronous module with dependency on jQuery for [AMD][1] compatible script loaders.
// Besides that it also complies with [CommonJS][2] module definition for Node and such.
// Of course, no fancy script loader is necessary and good old plain script tag still works too.
//
// [1]:http://en.wikipedia.org/wiki/Asynchronous_module_definition
// [2]:http://en.wikipedia.org/wiki/CommonJS
//
var
amd= typeof define == 'function' && define.amd && (define(['jquery'], factory) || true),
commonjs= !amd && typeof module == 'object' && typeof module.exports == 'object' && (module.exports= factory),
plain= !amd && !commonjs && factory()
})(function(){ return jQuery.reel || (function($, window, document, undefined){
// ------
// jQuery
// ------
//
// One vital requirement is the correct jQuery. Reel requires at least version 1.5
// and a make sure check is made at the very beginning.
//
if (!$ || +$().jquery.replace('.', __).substr(0, 2) < 15) return;
// ----------------
// Global Namespace
// ----------------
//
// `$.reel` (or `jQuery.reel`) namespace is provided for storage of all Reel belongings.
// It is locally referenced as just `reel` for speedier access.
//
var
reel= $.reel= {
// ### `$.reel.version`
//
// `String` (major.minor.patch), since 1.1
//
version: '1.2.2',
// Options
// -------
//
// When calling `.reel()` method you have plenty of options (far too many) available.
// You collect them into one hash and supply them with your call.
//
// _**Example:** Initiate a non-looping Reel with 12 frames:_
//
// .reel({
// frames: 12,
// looping: false
// })
//
//
// All options are optional and if omitted, default value is used instead.
// Defaults are being housed as members of `$.reel.def` hash.
// If you customize any default value therein, all subsequent `.reel()` calls
// will use the new value as default.
//
// _**Example:** Change default initial frame to 5th:_
//
// $.reel.def.frame = 5
//
// ---
// ### `$.reel.def` ######
// `Object`, since 1.1
//
def: {
//
// ### Basic Definition ######
//
// Reel is just fine with you not setting any options, however if you don't have
// 36 frames or beginning at frame 1, you will want to set total number
// of `frames` and pick a different starting `frame`.
//
// ---
// #### `frame` Option ####
// `Number` (frames), since 1.0
//
frame: 1,
// #### `frames` Option ####
// `Number` (frames), since 1.0
//
frames: 36,
// ~~~
//
// Another common characteristics of any Reel is whether it `loops` and covers
// entire 360° or not.
//
// ---
// #### `loops` Option ####
// `Boolean`, since 1.0
//
loops: true,
// ### Interaction ######
//
// Using boolean switches many user interaction aspects can be turned on and off.
// You can disable the mouse wheel control with `wheelable`, the drag & throw
// action with `throwable`, disallow the dragging completely with `draggable`,
// on "touchy" devices you can disable the browser's decision to scroll the page
// instead of Reel script and you can of course disable the stepping of Reel by
// clicking on either half of the image with `steppable`.
//
// You can even enable `clickfree` operation,
// which will cause Reel to bind to mouse enter/leave events instead of mouse down/up,
// thus allowing a click-free dragging.
//
// ---
// #### `clickfree` Option ####
// `Boolean`, since 1.1
//
clickfree: false,
// #### `draggable` Option ####
// `Boolean`, since 1.1
//
draggable: true,
// #### `scrollable` Option ####
// [NEW] `Boolean`, since 1.2
//
scrollable: true,
// #### `steppable` Option ####
// [NEW] `Boolean`, since 1.2
//
steppable: true,
// #### `throwable` Option ####
// `Boolean`, since 1.1; or `Number`, since 1.2.1
//
throwable: true,
// #### `wheelable` Option ####
// `Boolean`, since 1.1
//
wheelable: true,
// ### Order of Images ######
//
// Reel presumes counter-clockwise order of the pictures taken. If the nearer facing
// side doesn't follow your cursor/finger, you did clockwise. Use the `cw` option to
// correct this.
//
// ---
// #### `cw` Option ####
// `Boolean`, since 1.1
//
cw: false,
// ### Sensitivity ######
//
// In Reel sensitivity is set through the `revolution` parameter, which represents horizontal
// dragging distance one must cover to perform one full revolution. By default this value
// is calculated based on the setup you have - it is either twice the width of the image
// or half the width of stitched panorama. You may also set your own.
//
// Optionally `revolution` can be set as an Object with `x` member for horizontal revolution
// and/or `y` member for vertical revolution in multi-row movies.
//
// ---
// #### `revolution` Option ####
// `Number` (pixels) or `Object`, since 1.1, `Object` support since 1.2
//
revolution: undefined,
// ### Rectilinear Panorama ######
//
// The easiest of all is the stitched panorama mode. For this mode, instead of the sprite,
// a single seamlessly stitched stretched image is used and the view scrolls the image.
// This mode is triggered by setting a pixel width of the `stitched` image.
//
// ---
// #### `stitched` Option ####
// `Number` (pixels), since 1.0
//
stitched: 0,
// ### Directional Mode ######
//
// As you may have noticed on Reel's homepage or in [`example/object-movie-directional-sprite`][1]
// when you drag the arrow will point to either direction. In such `directional` mode, the sprite
// is actually 2 in 1 - one file contains two sprites one tightly following the other, one
// for visually going one way (`A`) and one for the other (`B`).
//
// A01 A02 A03 A04 A05 A06
// A07 A08 A09 A10 A11 A12
// A13 A14 A15 B01 B02 B03
// B04 B05 B06 B07 B08 B09
// B10 B11 B12 B13 B14 B15
//
// Switching between `A` and `B` frames is based on direction of the drag. Directional mode isn't
// limited to sprites only, sequences also apply. The figure below shows the very same setup like
// the above figure, only translated into actual frames of the sequence.
//
// 001 002 003 004 005 006
// 007 008 009 010 011 012
// 013 014 015 016 017 018
// 019 020 021 022 023 024
// 025 026 027 028 029 030
//
// Frame `016` represents the `B01` so it actually is first frame of the other direction.
//
// [1]:../example/object-movie-directional-sprite/
//
// ---
// #### `directional` Option ####
// `Boolean`, since 1.1
//
directional: false,
// ### Multi-Row Mode ######
//
// As [`example/object-movie-multirow-sequence`][1] very nicely demonstrates, in multi-row arrangement
// you can perform two-axis manipulation allowing you to add one or more vertical angles. Think of it as
// a layered cake, each new elevation of the camera during shooting creates one layer of the cake -
// - a _row_. One plain horizontal object movie full spin is one row:
//
// A01 A02 A03 A04 A05 A06
// A07 A08 A09 A10 A11 A12
// A13 A14 A15
//
// Second row tightly follows after the first one:
//
// A01 A02 A03 A04 A05 A06
// A07 A08 A09 A10 A11 A12
// A13 A14 A15 B01 B02 B03
// B04 B05 B06 B07 B08 B09
// B10 B11 B12 B13 B14 B15
// C01...
//
// This way you stack up any number of __`rows`__ you wish and set the initial `row` to start with.
// Again, not limited to sprites, sequences also apply.
//
// [1]:../example/object-movie-multirow-sequence/
//
// ---
// #### `row` Option ####
// `Number` (rows), since 1.1
//
row: 1,
// #### `rows` Option ####
// `Number` (rows), since 1.1
//
rows: 0,
// ### Dual-Orbit Mode ######
//
// Special form of multi-axis movie is the dual-axis mode. In this mode the object offers two plain
// spins - horizontal and vertical orbits combined together crossing each other at the `frame`
// forming sort of a cross if envisioned. [`example/object-movie-dual-orbit-sequence`][1] demonstrates
// this setup. When the phone in the example is facing you (marked in the example with green square
// in the top right), you are at the center. That is within the distance (in frames) defined
// by the `orbital` option. Translation from horizontal to vertical orbit can be achieved on this sweet-spot.
// By default horizontal orbit is chosen first, unless `vertical` option is used against.
//
// In case the image doesn't follow the vertical drag, you may have your vertical orbit `inversed`.
//
// Technically it is just a two-layer movie:
//
// A01 A02 A03 A04 A05 A06
// A07 A08 A09 A10 A11 A12
// A13 A14 A15 B01 B02 B03
// B04 B05 B06 B07 B08 B09
// B10 B11 B12 B13 B14 B15
//
// [1]:../example/object-movie-dual-orbit-sequence/
//
// ---
// #### `orbital` Option ####
// `Number` (frames), since 1.1
//
orbital: 0,
// #### `vertical` Option ####
// `Boolean`, since 1.1
//
vertical: false,
// #### `inversed` Option ####
// `Boolean`, since 1.1
//
inversed: false,
// ### Sprite Layout ######
//
// For both object movies and panoramas Reel presumes you use a combined _Sprite_ to hold all your
// frames in a single file. This powerful technique of using a sheet of several individual images
// has many advantages in terms of compactness, loading, caching, etc. However, know your enemy,
// be also aware of the limitations, which stem from memory limits of mobile
// (learn more in [FAQ](https://github.com/pisi/Reel/wiki/FAQ)).
//
// Inside the sprite, individual frames are laid down one by one, to the right of the previous one
// in a straight _Line_:
//
// 01 02 03 04 05 06
// 07...
//
// Horizontal length of the line is reffered to as `footage`. Unless frames `spacing` in pixels
// is set, edges of frames must touch.
//
// 01 02 03 04 05 06
// 07 08 09 10 11 12
// 13 14 15 16 17 18
// 19 20 21 22 23 24
// 25 26 27 28 29 30
// 31 32 33 34 35 36
//
// This is what you'll get by calling `.reel()` without any options. All frames laid out 6 in line.
// By default nicely even 6 x 6 grid like, which also inherits the aspect ratio of your frames.
//
// By setting `horizontal` to `false`, instead of forming lines, frames are expected to form
// _Columns_. All starts at the top left corner in both cases.
//
// 01 07 13 19 25 31
// 02 08 14 20 26 32
// 03 09 15 21 27 33
// 04 10 16 22 28 34
// 05 11 17 23 29 35
// 06 12 18 24 30 36
//
// URL for the sprite image file is being build from the name of the original `<img>` `src` image
// by adding a `suffix` to it. By default this results in `"object-reel.jpg"` for `"object.jpg"`.
// You can also take full control over the sprite `image` URL that will be used.
//
// ---
// #### `footage` Option ####
// `Number` (frames), since 1.0
//
footage: 6,
// #### `spacing` Option ####
// `Number` (pixels), since 1.0
//
spacing: 0,
// #### `horizontal` Option ####
// `Boolean`, since 1.0
//
horizontal: true,
// #### `suffix` Option ####
// `String`, since 1.0
//
suffix: '-reel',
// #### `image` Option ####
// `String`, since 1.1
//
image: undefined,
// ### Sequence ######
//
// Collection of individual frame images is called _Sequence_ and it this way one HTTP request per
// frame is made carried out as opposed to sprite with one request per entire sprite. Define it with
// string like: `"image_###.jpg"`. The `#` placeholders will be replaced with a numeric +1 counter
// padded to the placeholders length.
// Learn more about [sequences](Sequences).
//
// In case you work with hashed filenames like `64bc654d21cb.jpg`, where no counter element can
// be indentified, or you prefer direct control, `images` can also accept array of plain URL strings.
//
// All images are retrieved from a specified `path`.
//
// ---
// #### `images` Option ####
// [IMPROVED] `String` or `Array`, since 1.1
//
images: '',
// #### `path` Option ####
// `String` (URL path), since 1.1
//
path: '',
// ### Images Preload Order ######
//
// Given sequence images can be additionally reordered to achieve a perceived faster preloading.
// Value given to `preload` option must match a name of a pre-registered function within
// `$.reel.preload` object. There are two functions built-in:
//
// - `"fidelity"` - non-linear way that ensures even spreading of preloaded images around the entire
// revolution leaving the gaps in-between as small as possible. This results in a gradually
// increasing fidelity of the image rather than having one large shrinking gap. This is the default
// behavior.
// - `"linear"` - linear order of preloading
//
// ---
// #### `preload` Option ####
// [NEW] `String`, since 1.2
//
preload: 'fidelity',
// ### Animation ######
//
// Your object movie or a panorama can perform an autonomous sustained motion in one direction.
// When `speed` is set in revolutions per second (Hz), after a given `delay` the instance will
// animate and advance frames by itself.
//
// t
// |-------›|-----------›
// Delay Animation
//
// Start and resume of animation happens when given `timeout` has elapsed since user became idle.
//
// t
// |-----------›|= == == = === = = | |-----------›
// Animation User interaction Timeout Animation
//
// When a scene doesn't loop (see [`loops`](#loops-Option)) and the animation reaches one end,
// it stays there for a while and then reversing the direction of the animation it bounces back
// towards the other end. The time spent on the edge can be customized with `rebound`.
//
// ---
// #### `speed` Option ####
// `Number` (Hz), since 1.1
//
speed: 0,
// #### `delay` Option ####
// `Number` (seconds), since 1.1
//
delay: 0,
// #### `timeout` Option ####
// `Number` (seconds), since 1.1
//
timeout: 2,
// #### `duration` Option ####
// `Number` (seconds), EXPERIMENTAL
//
duration: undefined,
// #### `rebound` Option ####
// `Number` (seconds), since 1.1
//
rebound: 0.5,
// ### Opening Animation ######
//
// Chance is you want the object to spin a little to attract attention and then stop and wait
// for the user to engage. This is called "opening animation" and it is performed for given number
// of seconds (`opening`) at dedicated `entry` speed. The `entry` speed defaults to value of `speed`
// option. After the opening animation has passed, regular animation procedure begins starting with
// the delay (if any).
//
// t
// |--------›|-------›|-----------›
// Opening Delay Animation
//
// ---
// #### `entry` Option ####
// `Number` (Hz), since 1.1
//
entry: undefined,
// #### `opening` Option ####
// `Number` (seconds), since 1.1
//
opening: 0,
// ### Momentum ######
//
// Often also called inertial motion is a result of measuring a velocity of dragging. This velocity
// builds up momentum, so when a drag is released, the image still retains the momentum and continues
// to spin on itself. Naturally the momentum soon wears off as `brake` is being applied.
//
// One can utilize this momentum for a different kind of an opening animation. By setting initial
// `velocity`, the instance gets artificial momentum and spins to slow down to stop.
//
// ---
// #### `brake` Option ####
// `Number`, since 1.1, where it also has a different default `0.5`
//
brake: 0.23,
// #### `velocity` Option ####
// [NEW] `Number`, since 1.2
//
velocity: 0,
// ### Ticker ######
//
// For purposes of animation, Reel starts and maintains a timer device which emits ticks timing all
// animations. There is only one ticker running in the document and all instances subscribe to this
// one ticker. Ticker is equipped with a mechanism, which compensates for the measured costs
// of running Reels to ensure the ticker ticks on time. The `tempo` (in Hz) of the ticker can be
// specified.
//
// Please note, that ticker is synchronized with a _leader_, the oldest living instance on page,
// and adjusts to his tempo.
//
// ---
// #### `tempo` Option ####
// `Number` (Hz, ticks per second), since 1.1
//
tempo: 36,
// ~~~
//
// Since many mobile devices are sometimes considerably underpowered in comparison with desktops,
// they often can keep up with the 36 Hz rhythm. In Reel these are called __lazy devices__
// and everything mobile qualifies as lazy for the sake of the battery and interaction fluency.
// The ticker is under-clocked for them by a `laziness` factor, which is used to divide the `tempo`.
// Default `laziness` of `6` will effectively use 6 Hz instead (6 = 36 / 6) on lazy devices.
//
// ---
// #### `laziness` Option ####
// `Number`, since 1.1
//
laziness: 6,
// ### Customization ######
//
// You can customize Reel on both functional and visual front. The most visible thing you can
// customize is probably the `cursor`, size of the `preloader`, perhaps add visual `indicator`(s)
// of Reel's position within the range. You can also set custom `hint` for the tooltip, which appears
// when you mouse over the image area. Last but not least you can also add custom class name `klass`
// to the instance.
//
// ---
// #### `cursor` Option ####
// [NEW] `String`, since 1.2
//
cursor: undefined,
// #### `hint` Option ####
// `String`, since 1.0
//
hint: '',
// #### `indicator` Option ####
// `Number` (pixels), since 1.0
//
indicator: 0,
// #### `klass` Option ####
// `String`, since 1.0
//
klass: '',
// #### `preloader` Option ####
// `Number` (pixels), since 1.1
//
preloader: 2,
// ~~~
//
// You can use custom attributes (`attr`) on the node - it accepts the same name-value pairs object
// jQuery `.attr()` does. In case you want to delegate full interaction control over the instance
// to some other DOM element(s) on page, you can with `area`.
//
// ---
// #### `area` Option ####
// `jQuery`, since 1.1
//
area: undefined,
// #### `attr` Option ####
// [NEW] `Object`, since 1.2
//
attr: {},
// ### Annotations ######
//
// To further visually describe your scene you can place all kinds of in-picture HTML annotations
// by defining an `annotations` object. Learn more about [Annotations][1] in a dedicated article.
//
// [1]:https://github.com/pisi/Reel/wiki/Annotations
//
// ---
// #### `annotations` Option ####
// [NEW] `Object`, since 1.2
//
annotations: undefined,
// ### Mathematics ######
//
// When reeling, instance conforms to a graph function, which defines whether it will loop
// (`$.reel.math.hatch`) or it won't (`$.reel.math.envelope`). My math is far from flawless
// and I'm sure there are much better ways how to handle things. the `graph` option is there for you
// shall you need it. It accepts a function, which should process given criteria and return
// a fraction of 1.
//
// function( x, start, revolution, lo, hi, cwness, y ){
// return fraction // 0.0 - 1.0
// }
//
// ---
// #### `graph` Option ####
// `Function`, since 1.1
//
graph: undefined,
// ### Monitor ######
//
// Specify a string data key and you will see its real-time value dumped in the upper-left corner
// of the viewport. Its visual can be customized by CSS using `.jquery-reel-monitor` selector.
//
// ---
// #### `monitor` Option ####
// `String` (data key), since 1.1
//
monitor: undefined,
// ### Deprecated Options ######
//
// Two options are currently deprecated in version 1.2. Learn more about [Deprecations][1]
//
// [1]:https://github.com/pisi/Reel/wiki/Deprecations
//
// ---
// #### `step` Option ####
// `Number`, since 1.1
//
step: undefined, // use `frame` instead
// #### `steps` Option ####
// `Number`, since 1.1
//
steps: undefined // use `frames` instead
},
// -----------
// Quick Start
// -----------
//
// For basic Reel initialization, you don't even need to write any Javascript!
// All it takes is to add __class name__ `"reel"` to your `<img>` HTML tag,
// assign an unique __`id` attribute__ and decorate the tag with configuration __data attributes__.
// Result of which will be interactive Reel projection.
//
// <img src="some/image.jpg" width="300" height="200"
// id="my_image"
// class="reel"
// data-images="some/images/01.jpg, some/images/02.jpg"
// data-speed="0.5">
//
// All otherwise Javascript [options](#Options) are made available as HTML `data-*` attributes.
//
// Only the `annotations` option doesn't work this way. To quickly create annotations,
// simply have any HTML node (`<div>` prefferably) anywhere in the DOM,
// assign it __class name__ `"reel-annotation"`, an unique __`id` attribute__
// and add configuration __data attributes__.
//
// <div id="my_annotation"
// class="reel-annotation"
// data-for="my_image"
// data-x="120"
// data-y="60">
// Whatever HTML I'd like to have in the annotation
// </div>
//
// Most important is the `data-for` attribute, which references target Reel instance by `id`.
//
// ---
//
// Responsible for discovery and subsequent conversion of data-configured Reel images is
// `$.reel.scan()` method, which is being called automagically when the DOM becomes ready.
// Under normal circumstances you don't need to scan by yourself.
//
// It however comes in handy to re-scan when you happen to inject a data-configured Reel `<img>`
// into already ready DOM.
//
// ---
// ### `$.reel.scan()` Method ######
// returns `jQuery`, since 1.2.2
//
scan: function(){
return $(dot(klass)+':not('+dot(overlay_klass)+' >)').each(function(ix, image){
var
$image= $(image),
options= $image.data(),
images= options.images= soft_array(options.images),
annotations= {}
$(dot(annotation_klass)+'[data-for='+$image.attr(_id_)+']').each(function(ix, annotation){
var
$annotation= $(annotation),
def= $annotation.data(),
x= def.x= numerize_array(soft_array(def.x)),
y= def.y= numerize_array(soft_array(def.y)),
id= $annotation.attr(_id_),
node= def.node= $annotation.removeData()
annotations[id] = def;
});
options.annotations = annotations;
$image.removeData().reel(options);
});
},
// -------
// Methods
// -------
//
// Reel's methods extend jQuery core functions with members of its `$.reel.fn` object. Despite Reel
// being a typical one-method plug-in with its `.reel()` function, for convenience it also offers
// its dipolar twin `.unreel()`.
//
// ---
// ### `$.reel.fn` ######
// returns `Object`, since 1.1
//
fn: {
// ------------
// Construction
// ------------
//
// `.reel()` method is the core of Reel and similar to some jQuery functions, this one is three-fold.
// It either performs the following builder's duty or the [data duty](#Data).
//
// ---
// ### `.reel()` Method ######
// returns `jQuery`, since 1.0
//
reel: function(){
// The decision on what to actually do is made upon given arguments.
var
args= arguments,
t= $(this),
data= t.data(),
name= args[0] || {},
value= args[1]
if (typeof name == 'object'){
var
// Establish local `opt` object made by extending the defaults.
opt= $.extend({}, reel.def, name),
// Limit the given jQuery collection to just `<img>` tags with `src` attribute
// and dimensions defined.
applicable= t.filter(_img_).unreel().filter(function(){
var
$this= $(this),
attr= opt.attr,
src= attr.src || $this.attr('src'),
width= attr.width || $this.width(),
height= attr.height || $this.height()
if (src && width && height) return true;
}),
instances= []
// Backward-compatibility of [deprecated] legacy options
//
opt.step && (opt.frame= opt.step);
opt.steps && (opt.frames= opt.steps);
applicable.each(function(){
var
t= $(this),
// Quick data interface
set= function(name, value){ return t.reel(name, value) && t.data(name) },
get= function(name){ return t.reel(name) },
on= {
// --------------
// Initialization
// --------------
//
// This internally called private pseudo-handler:
//
// - initiates all data store keys,
// - binds to ticker
// - and triggers `"setup"` Event when finished.
//
setup: function(e){
if (t.hasClass(klass) && t.parent().hasClass(overlay_klass)) return;
set(_options_, opt);
var
src= t.attr(opt.attr).attr('src'),
id= set(_id_, t.attr(_id_) || t.attr(_id_, klass+'-'+(+new Date())).attr(_id_)),
styles= t.attr(_style_),
data= $.extend({}, t.data()),
images= set(_images_, opt.images || []),
stitched= opt.stitched,
loops= opt.loops,
orbital= opt.orbital,
revolution= opt.revolution,
rows= opt.rows,
footage= opt.footage,
size= { x: t.width(), y: t.height() },
frames= set(_frames_, orbital && footage || rows <= 1 && images.length || opt.frames),
multirow= rows > 1 || orbital,
revolution_x= set(_revolution_, axis('x', revolution) || stitched / 2 || size.x * 2),
revolution_y= set(_revolution_y_, !multirow ? 0 : (axis('y', revolution) || (rows > 3 ? size.y : size.y / (5 - rows)))),
rows= stitched ? 1 : ceil(frames / footage),
stage_id= hash(id+opt.suffix),
classes= t[0].className || __,
$overlay= $(tag(_div_), { id: stage_id.substr(1), 'class': classes+___+overlay_klass+___+frame_klass+'0' }),
$instance= t.wrap($overlay.addClass(opt.klass)).attr({ 'class': klass }),
instances_count= instances.push(add_instance($instance)[0]),
$overlay= $instance.parent().bind(on.instance)
set(_image_, images.length ? __ : opt.image || src.replace(reel.re.image, '$1' + opt.suffix + '.$2'));
set(_cached_, []);
set(_spacing_, opt.spacing);
set(_frame_, null);
set(_fraction_, null);
set(_row_, null);
set(_tier_, null);
set(_rows_, rows);
set(_dimensions_, size);
set(_bit_, 1 / (frames - (loops && !stitched ? 0 : 1)));
set(_stitched_travel_, stitched - (loops ? 0 : size.x));
set(_stitched_shift_, 0);
set(_stage_, stage_id);
set(_backwards_, set(_speed_, opt.speed) < 0);
set(_velocity_, 0);
set(_vertical_, opt.vertical);
set(_preloaded_, 0);
set(_cwish_, negative_when(1, !opt.cw && !stitched));
set(_clicked_location_, {});
set(_clicked_, false);
set(_clicked_on_, set(_clicked_tier_, 0));
set(_lo_, set(_hi_, 0));
set(_reeling_, false);
set(_reeled_, false);
set(_opening_, false);
set(_brake_, opt.brake);
set(_center_, !!orbital);
set(_tempo_, opt.tempo / (reel.lazy? opt.laziness : 1));
set(_opening_ticks_, -1);
set(_ticks_, -1);
set(_annotations_, opt.annotations || $overlay.unbind(dot(_annotations_)) && {});
set(_backup_, {
src: src,
classes: classes,
style: styles || __,
data: data
});
opt.steppable || $overlay.unbind('up.steppable');
opt.indicator || $overlay.unbind('.indicator');
css(__, { width: size.x, height: size.y, overflow: _hidden_, position: 'relative' });
css(____+___+dot(klass), { display: _block_ });
pool.bind(on.pool);
t.trigger('setup');
},
// ------
// Events
// ------
//
// Reel is completely event-driven meaning there are many events, which can be called
// (triggered). By binding event handler to any of the events you can easily hook on to any
// event to inject your custom behavior where and when this event was triggered.
//
// _**Example:** Make `#image` element reel and execute some code right after the newly
// created instance is initialized and completely loaded:_
//
// $("#image")
// .reel()
// .bind("loaded", function(ev){
// // Your code
// })
//
// Events bound to all individual instances.
//
instance: {
// ### `teardown` Event ######
// `Event`, since 1.1
//
// This event does do how it sounds like. It will teardown an instance with all its
// belongings leaving no trace.
//
// - It reconstructs the original `<img>` element,
// - wipes out the data store,
// - removes instance stylesheet
// - and unbinds all its events.
//
teardown: function(e){
var
backup= t.data(_backup_)
t.parent().unbind(on.instance);
get(_style_).remove();
get(_area_).unbind(ns);
remove_instance(t.unbind(ns).removeData().siblings().unbind(ns).remove().end().attr({
'class': backup.classes,
src: backup.src,
style: backup.style
}).data(backup.data).unwrap());
no_bias();
pool.unbind(on.pool);
pools.unbind(pns);
},
// ### `setup` Event ######
// `Event`, since 1.0
//
// `"setup"` Event continues with what has been started by the private `on.setup()`
// handler.
//
// - It prepares all additional on-stage DOM elements
// - and cursors for the instance stylesheet.
//
setup: function(e){
var
space= get(_dimensions_),
frames= get(_frames_),
id= t.attr(_id_),
rows= opt.rows,
stitched= opt.stitched,
$overlay= t.parent(),
$area= set(_area_, $(opt.area || $overlay )),
rows= opt.rows || 1
css(___+dot(klass), { MozUserSelect: _none_, WebkitUserSelect: _none_ });
if (touchy){
// workaround for downsizing-sprites-bug-in-iPhoneOS inspired by Katrin Ackermann
css(___+dot(klass), { WebkitBackgroundSize: get(_images_).length
? !stitched ? undefined : px(stitched)+___+px(space.y)
: stitched && px(stitched)+___+px((space.y + opt.spacing) * rows - opt.spacing)
|| px((space.x + opt.spacing) * opt.footage - opt.spacing)+___+px((space.y + opt.spacing) * get(_rows_) * rows * (opt.directional? 2:1) - opt.spacing)
});
$area
.bind(_touchstart_, press)
}else{
var
cursor= opt.cursor,
cursor_up= cursor == _hand_ ? drag_cursor : cursor || reel_cursor,
cursor_down= cursor == _hand_ ? drag_cursor_down+___+'!important' : undefined
css(__, { cursor: cdn(cursor_up) });
css(dot(loading_klass), { cursor: 'wait' });
css(dot(panning_klass)+____+dot(panning_klass)+' *', { cursor: cdn(cursor_down || cursor_up) }, true);
$area
.bind(opt.wheelable ? _mousewheel_ : null, wheel)
.bind(opt.clickfree ? _mouseenter_ : _mousedown_, press)
.bind(_dragstart_, function(){ return false })
}
function press(e){ return t.trigger('down', [finger(e).clientX, finger(e).clientY, e]) && e.give }
function wheel(e, delta){ return !delta || t.trigger('wheel', [delta, e]) && e.give }
opt.hint && $area.attr('title', opt.hint);
opt.indicator && $overlay.append(indicator('x'));
rows > 1 && opt.indicator && $overlay.append(indicator('y'));
opt.monitor && $overlay.append($monitor= $(tag(_div_), { 'class': monitor_klass }))
&& css(___+dot(monitor_klass), { position: _absolute_, left: 0, top: 0 });
css(___+dot(cached_klass), { display: _none_ });
},
// ### `preload` Event ######
// `Event`, since 1.1
//
// Reel keeps a cache of all images it needs for its operation. Either a sprite or all
// sequence images. Physically, this cache is made up of a hidden `<img>` sibling for each
// preloaded image. It first determines the order of requesting the images and then
// asynchronously loads all of them.
//
// - It preloads all frames and sprites.
//
preload: function(e){
var
space= get(_dimensions_),
$overlay= t.parent(),
images= get(_images_),
is_sprite= !images.length,
frames= get(_frames_),
footage= opt.footage,
order= reel.preload[opt.preload] || reel.preload[reel.def.preload],
preload= is_sprite ? [get(_image_)] : order(images.slice(0), opt, get),
to_load= preload.length,
preloaded= set(_preloaded_, is_sprite ? 0.5 : 0),
uris= []
$overlay.addClass(loading_klass).append(preloader());
// It also finalizes the instance stylesheet and prepends it to the head.
set(_style_, get(_style_) || $('<'+_style_+' type="text/css">'+css.rules.join('\n')+'</'+_style_+'>').prependTo(_head_));
t.trigger('stop');
while(preload.length){
var
uri= opt.path+preload.shift(),
width= space.x * (!is_sprite ? 1 : footage),
height= space.y * (!is_sprite ? 1 : frames / footage) * (!opt.directional ? 1 : 2),
$img= $(tag(_img_)).attr({ 'class': cached_klass, width: width, height: height }).appendTo($overlay)
// Each image, which finishes the load triggers `"preloaded"` Event.
$img.bind('load error abort', function(e){
e.type != 'load' && t.trigger(e.type);
return !!$(this).parent().length && t.trigger('preloaded') && false;
});
load(uri, $img);
uris.push(uri);
}
set(_cached_, uris);
function load(uri, $img){ setTimeout(function(){
$img.parent().length && $img.attr({ src: reen(uri) });
}, (to_load - preload.length) * 2) }
},
// ### `preloaded` Event ######
// `Event`, since 1.1
//
// This event is fired by every preloaded image and adjusts the preloader indicator's
// target position. Once all images are preloaded, `"loaded"` Event is triggered.
//
preloaded: function(e){
var
images= get(_images_).length || 1,
preloaded= set(_preloaded_, min(get(_preloaded_) + 1, images))
if (preloaded === images){
t.parent().removeClass(loading_klass).unbind(_preloaded_, on.instance.preloaded);
t.trigger('loaded');
}
if (preloaded === 1) var
frame= t.trigger('frameChange', [undefined, get(_frame_)])
},
// ### `loaded` Event ######
// `Event`, since 1.1
//
// `"loaded"` Event is the one announcing when the instance is "locked and loaded".
// At this time, all is prepared, preloaded and configured for user interaction
// or animation.
//
loaded: function(e){
get(_images_).length > 1 || t.css({ backgroundImage: url(opt.path+get(_image_)) }).attr({ src: cdn(transparent) });
opt.stitched && t.attr({ src: cdn(transparent) });
get(_reeled_) || set(_velocity_, opt.velocity || 0);
},
// ----------------
// Animation Events
// ----------------
//
// ### `opening` Event ######
// `Event`, since 1.1
//
// When [opening animation](#Opening-Animation) is configured for the instance, `"opening"`
// event engages the animation by pre-calculating some of its properties, which will make
// the tick handler
//
opening: function(e){
/*
- initiates opening animation
- or simply plays the reel when without opening
*/
if (!opt.opening) return t.trigger('openingDone');
var
opening= set(_opening_, true),
stopped= set(_stopped_, !get(_speed_)),
speed= opt.entry || opt.speed,
end= get(_fraction_),
duration= opt.opening,
start= set(_fraction_, end - speed * duration),
ticks= set(_opening_ticks_, ceil(duration * leader(_tempo_)))
},
// ### `openingDone` Event ######
// `Event`, since 1.1
//
// `"openingDone"` is fired onceWhen [opening animation](#Opening-Animation) is configured for the instance, `"opening"`
// event engages the animation by pre-calculating some of its properties, which will make
// the tick handler
//
openingDone: function(e){
var
playing= set(_playing_, false),
opening= set(_opening_, false),
evnt= _tick_+dot(_opening_)
pool.unbind(evnt, on.pool[evnt]);
if (opt.delay > 0) delay= setTimeout(function(){ t.trigger('play') }, opt.delay * 1000)
else t.trigger('play');
},
// -----------------------
// Playback Control Events
// -----------------------
//
// ### `play` Event ######
// `Event`, since 1.1
//
// `"play"` event can optionally accept a `speed` parameter (in Hz) to change the animation
// speed on the fly.
//
play: function(e, speed){
var
speed= speed ? set(_speed_, speed) : (get(_speed_) * negative_when(1, get(_backwards_))),
duration= opt.duration,
ticks= duration && set(_ticks_, ceil(duration * leader(_tempo_))),
backwards= set(_backwards_, speed < 0),
playing= set(_playing_, !!speed),
stopped= set(_stopped_, !playing)
idle();
},
// ### `pause` Event ######
// `Event`, since 1.1
//
// Triggering `"pause"` event will halt the playback for a time period designated
// by the `timeout` option. After this timenout, the playback is resumed again.
//
pause: function(e){
unidle();
},
// ### `stop` Event ######
// `Event`, since 1.1
//
// After `"stop"` event is triggered, the playback stops and stays still until `"play"`ed again.
//
stop: function(e){
var
stopped= set(_stopped_, true),
playing= set(_playing_, !stopped)
},
// ------------------------
// Human Interaction Events
// ------------------------
//
// ### `down` Event ######
// `Event`, since 1.1
//
// Marks the very beginning of touch or mouse interaction. It receives `x` and `y`
// coordinates in arguments.
//
// - It calibrates the center point (origin),
// - considers user active not idle,
// - flags the `<html>` tag with `.reel-panning` class name
// - and binds dragging events for move and lift. These
// are usually bound to the pool (document itself) to get a consistent treating regardless
// the event target element. However in click-free mode, it binds directly to the instance.
//
down: function(e, x, y, ev){
if (ev && ev.button != DRAG_BUTTON && !opt.clickfree) return;
if (opt.draggable){
var
clicked= set(_clicked_, get(_frame_)),
clickfree= opt.clickfree,
velocity= set(_velocity_, 0),
origin= last= recenter_mouse(get(_revolution_), x, y)
touchy || ev && ev.preventDefault();
unidle();
no_bias();
panned= 0;
$(_html_, pools).addClass(panning_klass);
// Browser events differ for touch and mouse, but both of them are treated equally and
// forwarded to the same `"pan"` or `"up"` Events.
if (touchy){
pools
.bind(_touchmove_, drag)
.bind(_touchend_+___+_touchcancel_, lift)
}else{
(clickfree ? get(_area_) : pools)
.bind(_mousemove_, drag)
.bind(clickfree ? _mouseleave_ : _mouseup_, lift)
}
}
function drag(e){ return t.trigger('pan', [finger(e).clientX, finger(e).clientY, e]) && e.give }
function lift(e){ return t.trigger('up', [e]) && e.give }
},
// ### `up` Event ######
// `Event`, since 1.1
//
// This marks the termination of user's interaction. She either released the mouse button
// or lift the finger of the touch screen. This event handler:
//
// - calculates the velocity of the drag at that very moment,
// - removes the `.reel-panning` class from `<body>`
// - and unbinds dragging events from the pool.
//
up: function(e, ev){
var
clicked= set(_clicked_, false),
reeling= set(_reeling_, false),
throwable = opt.throwable,
biases= abs(bias[0] + bias[1]) / 60,
velocity= set(_velocity_, !throwable ? 0 : throwable === true ? biases : min(throwable, biases)),
brakes= braking= velocity ? 1 : 0
unidle();
no_bias();
$(_html_, pools).removeClass(panning_klass);
(opt.clickfree ? get(_area_) : pools).unbind(pns);
},
// ### `pan` Event ######
// [RENAMED] `Event`, since 1.2
//
// Regardles the actual source of movement (mouse or touch), this event is always triggered
// in response and similar to the `"down"` Event it receives `x` and `y` coordinates
// in arguments and in addition it is passed a reference to the original browser event.
// This handler:
//
// - syncs with timer to achieve good performance,
// - calculates the distance from drag center and applies graph on it to get `fraction`,
// - recenters the drag when dragged over limits,
// - detects the direction of the motion
// - and builds up inertial motion bias.
//
// Historically `pan` was once called `slide` (conflicted with Mootools - [GH-51][1])
// or `drag` (that conflicted with MSIE).
//
// [1]:https://github.com/pisi/Reel/issues/51
//
pan: function(e, x, y, ev){
if (opt.draggable && slidable){
slidable= false;
unidle();
var
rows= opt.rows,
orbital= opt.orbital,
scrollable= touchy && !get(_reeling_) && rows <= 1 && !orbital && opt.scrollable,
delta= { x: x - last.x, y: y - last.y }
if (ev && scrollable && abs(delta.x) < abs(delta.y)) return ev.give = true;
if (abs(delta.x) > 0 || abs(delta.y) > 0){
ev && (ev.give = false);
panned= max(delta.x, delta.y);
last= { x: x, y: y };
var
revolution= get(_revolution_),
origin= get(_clicked_location_),
vertical= get(_vertical_),
fraction= set(_fraction_, graph(vertical ? y - origin.y : x - origin.x, get(_clicked_on_), revolution, get(_lo_), get(_hi_), get(_cwish_), vertical ? y - origin.y : x - origin.x)),
reeling= set(_reeling_, get(_reeling_) || get(_frame_) != get(_clicked_)),
motion= to_bias(vertical ? delta.y : delta.x || 0),
backwards= motion && set(_backwards_, motion < 0)
if (orbital && get(_center_)) var
vertical= set(_vertical_, abs(y - origin.y) > abs(x - origin.x)),
origin= recenter_mouse(revolution, x, y)
if (rows > 1) var
space_y= get(_dimensions_).y,
revolution_y= get(_revolution_y_),
start= get(_clicked_tier_),
lo= - start * revolution_y,
tier= set(_tier_, reel.math.envelope(y - origin.y, start, revolution_y, lo, lo + revolution_y, -1))
if (!(fraction % 1) && !opt.loops) var
origin= recenter_mouse(revolution, x, y)
}
}
},
// ### `wheel` Event ######
// `Event`, since 1.0
//
// Maps Reel to mouse wheel position change event which is provided by a nifty plug-in
// written by Brandon Aaron - the [Mousewheel plug-in][1], which you will need to enable
// the mousewheel wheel for reeling. You can also choose to use [Wheel Special Event
// plug-in][2] by Three Dub Media instead. Either way `"wheel"` Event handler receives
// the positive or negative wheeled distance in arguments. This event:
//
// - calculates wheel input delta and adjusts the `fraction` using the graph,
// - recenters the "drag" each and every time,
// - detects motion direction
// - and nullifies the velocity.
//
// [1]:https://github.com/brandonaaron/jquery-mousewheel
// [2]:http://blog.threedubmedia.com/2008/08/eventspecialwheel.html
//
wheel: function(e, distance, ev){
if (!distance) return;
wheeled= true;
var
delta= ceil(math.sqrt(abs(distance)) / 2),
delta= negative_when(delta, distance > 0),
revolution= 0.0833 * get(_revolution_), // Wheel's revolution is 1/12 of full revolution
origin= recenter_mouse(revolution),
backwards= delta && set(_backwards_, delta < 0),
velocity= set(_velocity_, 0),
fraction= set(_fraction_, graph(delta, get(_clicked_on_), revolution, get(_lo_), get(_hi_), get(_cwish_)))
ev && ev.preventDefault();
ev && (ev.give = false);
unidle();
t.trigger('up', [ev]);
},
// ------------------
// Data Change Events
// ------------------
//
// Besides Reel being event-driven, it also is data-driven respectively data-change-driven
// meaning that there is a mechanism in place, which detects real changes in data being
// stored with `.reel(name, value)`. Learn more about [data changes](#Changes).
//
// These data change bindings are for internal use only and you don't ever trigger them
// per se, you change data and that will trigger respective change event. If the value
// being stored is the same as the one already stored, nothing will be triggered.
//
// _**Example:** Change Reel's current `frame`:_
//
// .reel("frame", 15)
//
// Change events always receive the actual data key value in the third argument.
//
// _**Example:** Log each viewed frame number into the developers console:_
//
// .bind("frameChange", function(e, d, frame){
// console.log(frame)
// })
//
// ---
// ### `fractionChange` Event ######
// `Event`, since 1.0
//
// Internally Reel doesn't really work with the frames you set it up with. It uses
// __fraction__, which is a numeric value ranging from 0.0 to 1.0. When `fraction` changes
// this handler basically calculates and sets new value of `frame`.
//
fractionChange: function(e, set_fraction, fraction){
if (set_fraction !== undefined) return deprecated(set(_fraction_, set_fraction));
var
frame= 1 + floor(fraction / get(_bit_)),
multirow= opt.rows > 1,
orbital= opt.orbital,
center= set(_center_, !!orbital && (frame <= orbital || frame >= opt.footage - orbital + 2))
if (multirow) var
frame= frame + (get(_row_) - 1) * get(_frames_)
var
frame= set(_frame_, frame)
},
// ### `tierChange` Event ######
// `Event`, since 1.2
//
// The situation of `tier` is very much similar to the one of `fraction`. In multi-row
// movies, __tier__ is an internal value for the vertical axis. Its value also ranges from
// 0.0 to 1.0. Handler calculates and sets new value of `frame`.
//
tierChange: function(e, deprecated_set, tier){
if (deprecated_set === undefined) var
row= set(_row_, round(interpolate(tier, 1, opt.rows))),
frames= get(_frames_),
frame= get(_frame_) % frames || frames,
frame= set(_frame_, frame + row * frames - frames)
},
// ### `rowChange` Event ######
// `Event`, since 1.1
//
// The physical vertical position of Reel is expressed in __rows__ and ranges
// from 1 to the total number of rows defined with [`rows`](#rows-Option). This handler
// only converts `row` value to `tier` and sets it.
//
rowChange: function(e, set_row, row){
if (set_row !== undefined) return set(_row_, set_row);
var
tier= set(_tier_, 1 / (opt.rows - 1) * (row - 1))
},
// ### `frameChange` Event ######
// `Event`, since 1.0
//
// The physical horizontal position of Reel is expressed in __frames__ and ranges
// from 1 to the total number of frames configured with [`frames`](#frames-Option).
// This handler converts `row` value to `tier` and sets it. This default handler:
//
// - flags the instance's outter wrapper with `.frame-X` class name
// (where `X` is the actual frame number),
// - calculates and eventually sets `fraction` (and `tier` for multi-rows) from given frame,
// - for sequences, it switches the `<img>`'s `src` to the right frame
// - and for sprites it recalculates sprite's 'background position shift and applies it.
//
frameChange: function(e, set_frame, frame){
if (set_frame !== undefined) return deprecated(set(_frame_, set_frame));
this.className= this.className.replace(reel.re.frame_klass, frame_klass + frame);
var
frames= get(_frames_),
rows= opt.rows,
path= opt.path,
base= frame % frames || frames,
ready= !!get(_preloaded_),
frame_row= (frame - base) / frames + 1,
frame_tier= (frame_row - 1) / (rows - 1),
tier_row= round(interpolate(frame_tier, 1, rows)),
row= get(_row_),
tier= ready && tier_row === row ? get(_tier_) : set(_tier_, frame_tier),
frame_fraction= min((base - 1) / (frames - 1), 0.9999),
row_shift= row * frames - frames,
fraction_frame= round(interpolate(frame_fraction, row_shift + 1, row_shift + frames)),
same_spot= abs((get(_fraction_) || 0) - frame_fraction) < 1 / (get(_frames_) - 1),
fraction= ready && (fraction_frame === frame && same_spot) ? get(_fraction_) : set(_fraction_, frame_fraction),
footage= opt.footage
if (opt.orbital && get(_vertical_)) var
frame= opt.inversed ? footage + 1 - frame : frame,
frame= frame + footage
var
horizontal= opt.horizontal,
stitched= opt.stitched,
images= get(_images_),
is_sprite= !images.length || opt.stitched,
spacing= get(_spacing_),
space= get(_dimensions_)
if (!is_sprite){
var
frameshot= images[frame - 1]
ready && t.attr({ src: reen(path + frameshot) })
}else{
if (!stitched) var
minor= (frame % footage) - 1,
minor= minor < 0 ? footage - 1 : minor,
major= floor((frame - 0.1) / footage),
major= major + (rows > 1 ? 0 : (get(_backwards_) ? 0 : !opt.directional ? 0 : get(_rows_))),
a= major * ((horizontal ? space.y : space.x) + spacing),
b= minor * ((horizontal ? space.x : space.y) + spacing),
shift= images.length ? [0, 0] : horizontal ? [px(-b), px(-a)] : [px(-a), px(-b)]
else{
var
x= set(_stitched_shift_, round(interpolate(frame_fraction, 0, get(_stitched_travel_))) % stitched),
y= rows <= 1 ? 0 : (space.y + spacing) * (rows - row),
shift= [px(-x), px(-y)],
image= images.length > 1 && images[row - 1]
image && t.css('backgroundImage').search(path+image) < 0 && t.css({ backgroundImage: url(path+image) })
}
t.css({ backgroundPosition: shift.join(___) })
}
},
// ### `imageChange` Event ######
// `Event`, since 1.2.2
//
// When `image` or `images` is changed on the fly, this handler resets the loading cache and triggers
// new preload sequence. Images are actually switched only after the new image is fully loaded.
//
'imageChange imagesChange': function(e, nil, image){
preloader.$.remove();
t.siblings(dot(cached_klass)).remove();
t.parent().bind(_preloaded_, on.instance.preloaded);
pool.bind(_tick_+dot(_preload_), on.pool[_tick_+dot(_preload_)]);
t.trigger('preload');
},
// ---------
// Indicator
// ---------
//
// When configured with the [`indicator`](#indicator-Option) option, Reel adds to the scene
// a visual indicator in a form of a black rectangle traveling along the bottom edge
// of the image. It bears two distinct messages:
//
// - its horizontal position accurately reflects actual `fraction`
// - and its width reflect one frame's share on the whole (more frames mean narrower
// indicator).
//
'fractionChange.indicator': function(e, deprecated_set, fraction){
if (deprecated_set === undefined && opt.indicator) var
space= get(_dimensions_),
size= opt.indicator,
orbital= opt.orbital,
travel= orbital && get(_vertical_) ? space.y : space.x,
slots= orbital ? opt.footage : opt.images.length || get(_frames_),
weight= ceil(travel / slots),
travel= travel - weight,
indicate= round(interpolate(fraction, 0, travel)),
indicate= !opt.cw || opt.stitched ? indicate : travel - indicate,
$indicator= indicator.$x.css(get(_vertical_)
? { left: 0, top: px(indicate), bottom: _auto_, width: size, height: weight }
: { bottom: 0, left: px(indicate), top: _auto_, width: weight, height: size })
},
// For multi-row object movies, there's a second indicator sticked to the left edge
// and communicates:
//
// - its vertical position accurately reflects actual `tier`
// - and its height reflect one row's share on the whole (more rows mean narrower
// indicator).
//
'tierChange.indicator': function(e, deprecated_set, tier){
if (deprecated_set === undefined && opt.rows > 1 && opt.indicator) var
space= get(_dimensions_),
travel= space.y,
slots= opt.rows,
size= opt.indicator,
weight= ceil(travel / slots),
travel= travel - weight,
indicate= round(tier * travel),
$yindicator= indicator.$y.css({ left: 0, top: indicate, width: size, height: weight })
},
// Indicators are bound to `fraction` or `row` changes, meaning they alone can consume
// more CPU resources than the entire Reel scene. Use them for development only.
//
// -----------------
// [NEW] Annotations
// -----------------
//
// If you want to annotate features of your scene to better describe the subject,
// there's annotations for you. Annotations feature allows you to place virtually any
// HTML content over or into the image and have its position and visibility synchronized
// with the position of Reel. These two easy looking handlers do a lot more than to fit
// in here.
//
// Learn more about [Annotations][1] in the wiki, where a great care has been taken
// to in-depth explain this new exciting functionality.
//
// [1]:https://github.com/pisi/Reel/wiki/Annotations
//
'setup.annotations': function(e){
var
space= get(_dimensions_),
$overlay= t.parent(),
film_css= { position: _absolute_, width: space.x, height: space.y, left: 0, top: 0 }
$.each(get(_annotations_), function(ida, note){
var
$note= typeof note.node == _string_ ? $(note.node) : note.node || {},
$note= $note.jquery ? $note : $(tag(_div_), $note),
$note= $note.attr({ id: ida }).addClass(annotation_klass),
$image= note.image ? $(tag(_img_), note.image) : $(),
$link= note.link ? $(tag('a'), note.link).click(function(){ t.trigger('up.annotations', { target: $link }); }) : $()
css(hash(ida), { display: _none_, position: _absolute_ }, true);
note.image || note.link && $note.append($link);
note.link || note.image && $note.append($image);
note.link && note.image && $note.append($link.append($image));
$note.appendTo($overlay);
});
},
'frameChange.annotations': function(e, deprecation, frame){
var
space= get(_dimensions_),
stitched= opt.stitched,
ss= get(_stitched_shift_)
if (!get(_preloaded_)) return;
if (deprecation === undefined) $.each(get(_annotations_), function(ida, note){
var
$note= $(hash(ida)),
start= note.start || 1,
end= note.end,
offset= frame - 1,
at= note.at ? (note.at[offset] == '+') : false,
offset= note.at ? offset : offset - start + 1,
x= typeof note.x!=_object_ ? note.x : note.x[offset],
y= typeof note.y!=_object_ ? note.y : note.y[offset],
placed= x !== undefined && y !== undefined,
visible= placed && (note.at ? at : (offset >= 0 && (!end || offset <= end - start)))
if (stitched) var
on_edge= x < space.x && ss > stitched - space.x,
after_edge= x > stitched - space.x && ss >= 0 && ss < space.x,
x= !on_edge ? x : x + stitched,
x= !after_edge ? x : x - stitched,
x= x - ss
var
style= { display: visible ? _block_:_none_, left: px(x), top: px(y) }
$note.css(style);
});
},
'up.annotations': function(e, ev){
if (panned > 10 || wheeled) return;
var
$target= $(ev.target),
$link= ($target.is('a') ? $target : $target.parents('a')),
href= $link.attr('href')
href && (panned= 10);
},
// ---------------------------
// [NEW] Click Stepping Events
// ---------------------------
//
// For devices without drag support or for developers, who want to use some sort
// of left & right buttons on their site to control your instance from outside, Reel
// supports ordinary click with added detection of left half or right half and resulting
// triggering of `stepLeft` and `stepRight` events respectively.
//
// This behavior can be disabled by the [`steppable`](#steppable-Option) option.
//
'up.steppable': function(e, ev){
if (panned || wheeled) return;
t.trigger(get(_clicked_location_).x - t.offset().left > 0.5 * get(_dimensions_).x ? 'stepRight' : 'stepLeft')
},
'stepLeft stepRight': function(e){
unidle();
},
// ### `stepLeft` Event ######
// `Event`, since 1.2
//
stepLeft: function(e){
set(_backwards_, false);
set(_fraction_, get(_fraction_) - get(_bit_) * get(_cwish_));
},
// ### `stepRight` Event ######
// `Event`, since 1.2
//
stepRight: function(e){
set(_backwards_, true);
set(_fraction_, get(_fraction_) + get(_bit_) * get(_cwish_));
},
// ### `stepUp` Event ######
// `Event`, since 1.3
//
stepUp: function(e){
set(_row_, get(_row_) - 1);
},
// ### `stepDown` Event ######
// `Event`, since 1.3
//
stepDown: function(e){
set(_row_, get(_row_) + 1);
},
// ----------------
// Follow-up Events
// ----------------
//
// When some event as a result triggers another event, it preferably is not triggered
// directly, because it would disallow preventing the event propagation / chaining
// to happen. Instead a followup handler is bound to the first event and it triggers the
// second one.
//
'setup.fu': function(e){
var
frame= set(_frame_, opt.frame + (opt.row - 1) * get(_frames_))
t.trigger('preload')
},
'wheel.fu': function(){ wheeled= false },
'clean.fu': function(){ t.trigger('teardown') },
'loaded.fu': function(){ t.trigger('opening') }
},
// -------------
// Tick Handlers
// -------------
//
// As opposed to the events bound to the instance itself, there is a [ticker](#Ticker)
// in place, which emits `tick.reel` event on the document level by default every 1/36
// of a second and drives all the animations. Three handlers currently bind each instance
// to the tick.
//
pool: {
// This handler has a responsibility of continuously updating the preloading indicator
// until all images are loaded and to unbind itself then.
//
'tick.reel.preload': function(e){
var
space= get(_dimensions_),
current= number(preloader.$.css(_width_)),
images= get(_images_).length || 1,
target= round(1 / images * get(_preloaded_) * space.x)
preloader.$.css({ width: current + (target - current) / 3 + 1 })
if (get(_preloaded_) === images && current > space.x - 1){
preloader.$.fadeOut(300, function(){ preloader.$.remove() });
pool.unbind(_tick_+dot(_preload_), on.pool[_tick_+dot(_preload_)]);
}
},
// This handler binds to the document's ticks at all times, regardless the situation.
// It serves several tasks:
//
// - keeps track of how long the instance is being operated by the user,
// - or for how long it is braking the velocity inertia,
// - decreases gained velocity by applying power of the [`brake`](#brake-Option) option,
// - flags the instance as `slidable` again, so that `pan` event handler can be executed
// again,
// - updates the [`monitor`](#monitor-Option) value,
// - bounces off the edges for non-looping panoramas,
// - and most importantly it animates the Reel if [`speed`](#speed-Option) is configured.
//
'tick.reel': function(e){
var
velocity= get(_velocity_),
leader_tempo= leader(_tempo_),
monitor= opt.monitor
if (!reel.intense && offscreen()) return mute(e);
if (braking) var
braked= velocity - (get(_brake_) / leader_tempo * braking),
velocity= set(_velocity_, braked > 0.1 ? braked : (braking= operated= 0))
monitor && $monitor.text(get(monitor));
velocity && braking++;
operated && operated++;
to_bias(0);
slidable= true;
if (operated && !velocity) return mute(e);
if (get(_clicked_)) return mute(e, unidle());
if (get(_opening_ticks_) > 0) return;
if (!opt.loops && opt.rebound) var
edgy= !operated && !(get(_fraction_) % 1) ? on_edge++ : (on_edge= 0),
bounce= on_edge >= opt.rebound * 1000 / leader_tempo,
backwards= bounce && set(_backwards_, !get(_backwards_))
var
direction= get(_cwish_) * negative_when(1, get(_backwards_)),
ticks= get(_ticks_),
step= (!get(_playing_) || !ticks ? velocity : abs(get(_speed_)) + velocity) / leader(_tempo_),
fraction= set(_fraction_, get(_fraction_) - step * direction),
ticks= !opt.duration ? ticks : ticks > 0 && set(_ticks_, ticks - 1)
!ticks && get(_playing_) && t.trigger('stop');
},
// This handler performs the opening animation duty when during it the normal animation
// is halted until the opening finishes.
//
'tick.reel.opening': function(e){
if (!get(_opening_)) return;
var
speed= opt.entry || opt.speed,
step= speed / leader(_tempo_) * (opt.cw? -1:1),
ticks= set(_opening_ticks_, get(_opening_ticks_) - 1),
fraction= set(_fraction_, get(_fraction_) + step)
ticks || t.trigger('openingDone');
}
}
},
// ------------------------
// Instance Private Helpers
// ------------------------
//
// - Events propagation stopper / muter
//
mute= function(e, result){ return e.stopImmediatePropagation() || result },
// - User idle control
//
operated,
braking= 0,
idle= function(){ return operated= 0 },
unidle= function(){
clearTimeout(delay);
pool.unbind(_tick_+dot(_opening_), on.pool[_tick_+dot(_opening_)]);
set(_opening_ticks_, 0);
set(_reeled_, true);
return operated= -opt.timeout * leader(_tempo_)
},
panned= 0,
wheeled= false,
delay, // openingDone's delayed play pointer
// - Constructors of UI elements
//
$monitor= $(),
preloader= function(){
var
size= opt.preloader
css(___+dot(preloader_klass), {
position: _absolute_,
left: 0, top: get(_dimensions_).y - size,
height: size,
overflow: _hidden_,
backgroundColor: '#000'
});
return preloader.$= $(tag(_div_), { 'class': preloader_klass })
},
indicator= function(axis){
css(___+dot(indicator_klass)+dot(axis), {
position: _absolute_,
width: 0, height: 0,
overflow: _hidden_,
backgroundColor: '#000'
});
return indicator['$'+axis]= $(tag(_div_), { 'class': indicator_klass+___+axis })
},
// - CSS rules & stylesheet
//
css= function(selector, definition, global){
var
stage= global ? __ : get(_stage_),
selector= selector.replace(/^/, stage).replace(____, ____+stage)
return css.rules.push(selector+cssize(definition)) && definition
function cssize(values){
var rules= [];
$.each(values, function(key, value){ rules.push(key.replace(/([A-Z])/g, '-$1').toLowerCase()+':'+px(value)+';') });
return '{'+rules.join(__)+'}'
}
},
$style,
// - Off screen detection (vertical only for performance)
//
offscreen= function(){
var
height= get(_dimensions_).y,
rect= t[0].getBoundingClientRect()
return rect.top < -height ||
rect.bottom > height + $(window).height()
},
// - Inertia rotation control
//
on_edge= 0,
last= { x: 0, y: 0 },
to_bias= function(value){ return bias.push(value) && bias.shift() && value },
no_bias= function(){ return bias= [0,0] },
bias= no_bias(),
// - Graph function to be used
//
graph= opt.graph || reel.math[opt.loops ? 'hatch' : 'envelope'],
normal= reel.normal,
// - Interaction graph's zero point reset
//
recenter_mouse= function(revolution, x, y){
var
fraction= set(_clicked_on_, get(_fraction_)),
tier= set(_clicked_tier_, get(_tier_)),
loops= opt.loops
set(_lo_, loops ? 0 : - fraction * revolution);
set(_hi_, loops ? revolution : revolution - fraction * revolution);
return x && set(_clicked_location_, { x: x, y: y }) || undefined
},
slidable= true,
// ~~~
//
// Global events are bound to the pool (`document`), but to make it work inside an `<iframe>`
// we need to bind to the parent document too to maintain the dragging even outside the area
// of the `<iframe>`.
//
pools= pool
try{ if (pool[0] != top.document) pools= pool.add(top.document) }
catch(e){}
// A private flag `$iframe` is established to indicate Reel being viewed inside `<iframe>`.
//
var
$iframe= top === self ? $() : (function sense_iframe($ifr){
$('iframe', pools.last()).each(function(){
try{ if ($(this).contents().find(_head_).html() == $(_head_).html()) return ($ifr= $(this)) && false }
catch(e){}
})
return $ifr
})()
css.rules= [];
on.setup();
});
// ~~~
//
// Reel maintains a ticker, which guides all animations. There's only one ticker per document
// and all instances bind to it. Ticker's mechanism measures and compares times before and after
// the `tick.reel` event trigger to estimate the time spent on executing `tick.reel`'s handlers.
// The actual timeout time is then adjusted by the amount to run as close to expected tempo
// as possible.
//
ticker= ticker || (function tick(){
var
start= +new Date(),
tempo= leader(_tempo_)
if (!tempo) return ticker= null;
pool.trigger(_tick_);
reel.cost= (+new Date() + reel.cost - start) / 2;
return ticker= setTimeout(tick, max(4, 1000 / tempo - reel.cost));
})();
return $(instances);
}else{
// ----
// Data
// ----
//
// Reel stores all its inner state values with the standard DOM [data interface][1] interface
// while adding an additional change-detecting event layer, which makes Reel entirely data-driven.
//
// [1]:http://api.jquery.com/data
//
// _**Example:** Find out on what frame a Reel instance currently is:_
//
// .reel('frame') // Returns the frame number
//
// Think of `.reel()` as a synonym for `.data()`. Note, that you can therefore easily inspect
// the entire datastore with `.data()` (without arguments). Use it for debugging only.
// For real-time data watch use [`monitor`](#Monitor) option instead of manually hooking into
// the data.
//
// ---
// #### `.reel( name )` ######
// can return anything, since 1.2
//
if (typeof name == 'string'){
if (args.length == 1){
var
value= data[name]
t.trigger('recall', [name, value]);
return value;
}
// ### Write Access ###
//
// You can store any value the very same way by passing the value as the second function
// argument.
//
// _**Example:** Jump to frame 12:_
//
// .reel('frame', 12)
//
// Only a handful of data keys is suitable for external manipulation. These include `area`,
// `backwards`, `brake`, __`fraction`__, __`frame`__, `playing`, `reeling`, __`row`__, `speed`,
// `stopped`, `velocity` and `vertical`. Use the rest of the keys for reading only, you can
// mess up easily changing them.
//
// ---
// #### `.reel( name, value )` ######
// returns `jQuery`, since 1.2
//
else{
if (value !== undefined){
reel.normal[name] && (value= reel.normal[name](value, data));
// ### Changes ######
//
// Any value that does not equal (`===`) the old value is considered _new value_ and
// in such a case Reel will trigger a _change event_ to announce the change. The event
// type takes form of _`key`_`Change`, where _`key`_ will be the data key/name you've
// just assigned.
//
// _**Example:** Setting `"frame"` to `12` in the above example will trigger
// `"frameChange"`._
//
// Some of these _change events_ (like `frame` or `fraction`) have a
// default handler attached.
//
// You can easily bind to any of the data key change with standard event
// binding methods.
//
// _**Example:** React on instance being manipulated or not:_
//
// .bind('reelingChange', function(evnt, nothing, reeling){
// if (reeling) console.log('Rock & reel!')
// else console.log('Not reeling...')
// })
//
// ---
// The handler function will be executed every time the value changes and
// it will be supplied with three arguments. First one is the event object
// as usual, second is `undefined` and the third will be the actual value.
// In this case it was a boolean type value.
// If the second argument is not `undefined` it is the backward compatible
// "before" event triggered from outside Reel.
//
if (data[name] === undefined) data[name]= value
else if (data[name] !== value) t.trigger(name+'Change', [ undefined, data[name]= value ]);
}
return t.trigger('store', [name, value]);
}
}
}
},
// -----------
// Destruction
// -----------
//
// The evil-twin of `.reel()`. Tears down and wipes off entire instance.
//
// ---
// ### `.unreel()` Method ######
// returns `jQuery`, since 1.2
//
unreel: function(){
return this.trigger('teardown');
}
},
// -------------------
// Regular Expressions
// -------------------
//
// Few regular expressions is used here and there mostly for options validation and verification
// levels of user agent's capabilities.
//
// ---
// ### `$.reel.re` ######
// `RegExp`, since 1.1
//
re: {
/* Valid image file format */
image: /^(.*)\.(jpg|jpeg|png|gif)\??.*$/i,
/* User agent failsafe stack */
ua: [
/(msie|opera|firefox|chrome|safari)[ \/:]([\d.]+)/i,
/(webkit)\/([\d.]+)/i,
/(mozilla)\/([\d.]+)/i
],
/* Array in a string (comma-separated values) */
array: / *, */,
/* Multi touch devices */
touchy_agent: /iphone|ipod|ipad|android|fennec|rim tablet/i,
/* Lazy (low-CPU mobile devices) */
lazy_agent: /\(iphone|ipod|android|fennec|blackberry/i,
/* Format of frame class flag on the instance */
frame_klass: /frame-\d+/,
/* [Sequence](#Sequence) string format */
sequence: /(^[^#|]*([#]+)[^#|]*)($|[|]([0-9]+)\.\.([0-9]+))($|[|]([0-9]+)$)/
},
// ------------------------
// Content Delivery Network
// ------------------------
//
// [CDN][1] is used for distributing mouse cursors to all instances running world-wide. It runs
// on Google cloud infrastructure. If you want to ease up on the servers, please consider setting up
// your own location with the cursors.
//
// [1]:https://github.com/pisi/Reel/wiki/CDN
//
// ---
// ### `$.reel.cdn` ######
// `String` (URL path), since 1.1
//
cdn: 'http://code.vostrel.net/',
// -----------
// Math Behind
// -----------
//
// Surprisingly there's very little math behind Reel, just two equations (graph functions). These two
// functions receive the same set of options.
//
// ---
// ### `$.reel.math` ######
// `Object`, since 1.1
//
math: {
// 1 | ********
// | **
// | **
// | **
// | **
// | ********
// 0 ----------------------------›
//
envelope: function(x, start, revolution, lo, hi, cwness, y){
return start + min_max(lo, hi, - x * cwness) / revolution
},
// 1 | ** **
// | ** **
// | ** **
// | ** **
// | ** **
// | ** **
// 0 ----------------------------›
//
hatch: function(x, start, revolution, lo, hi, cwness, y){
var
x= (x < lo ? hi : 0) + x % hi, // Looping
fraction= start + (- x * cwness) / revolution
return fraction - floor(fraction)
},
// And an equation for interpolating `fraction` (and `tier`) value into `frame` and `row`.
//
interpolate: function(fraction, lo, hi){
return lo + fraction * (hi - lo)
}
},
// ----------------
// Preloading Modes
// ----------------
//
// Reel doesn't load frames in a linear manner from first to last (alhough it can if configured
// that way with the [`preload`](#preload-Option) option). Reel will take the linear configured
// sequence and hand it over to one of `$.reel.preload` functions, along with reference to options
// and the RO data intearface, and it expects the function to reorder the incoming Array and return
// it back.
//
// ---
// ### `$.reel.preload` ######
// `Object`, since 1.2
//
preload: {
// The best (and default) option is the `fidelity` processor, which is designed for a faster and
// better perceived loading.
//
// 
//
fidelity: function(sequence, opt, get){
var
orbital= opt.orbital,
rows= orbital ? 2 : opt.rows || 1,
frames= orbital ? opt.footage : get(_frames_),
start= (opt.row-1) * frames,
values= new Array().concat(sequence),
present= new Array(sequence.length + 1),
priority= rows < 2 ? [] : values.slice(start, start + frames)
return spread(priority, 1, start).concat(spread(values, rows, 0))
function spread(sequence, rows, offset){
if (!sequence.length) return [];
var
order= [],
passes= 4 * rows,
start= opt.frame,
frames= sequence.length,
plus= true,
granule= frames / passes
for(var i= 0; i < passes; i++)
add(start + round(i * granule));
while(granule > 1)
for(var i= 0, length= order.length, granule= granule / 2, p= plus= !plus; i < length; i++)
add(order[i] + (plus? 1:-1) * round(granule));
for(var i=0; i <= frames; i++) add(i);
for(var i= 0; i < order.length; i++)
order[i]= sequence[order[i] - 1];
return order
function add(frame){
while(!(frame >= 1 && frame <= frames))
frame+= frame < 1 ? +frames : -frames;
return present[offset + frame] || (present[offset + frame]= !!order.push(frame))
}
}
},
// You can opt for a `linear` loading order too, but that has a drawback of leaving large gap
// of unloaded frames.
//
linear: function(sequence, opt, get){
return sequence
}
},
// ------------------------
// Data Value Normalization
// ------------------------
//
// On all data values being stored with `.reel()` an attempt is made to normalize the value. Like
// for example normalization of frame `55` when there's just `45` frames total. These are the built-in
// normalizations. Normalization function has the same name as the data key it is assigned to
// and is given the raw value in arguments, along with reference to the instances data object,
// and it has to return the normalized value.
//
// ---
// ### `$.reel.normal` ######
// `Object`, since 1.2
//
normal: {
fraction: function(fraction, data){
if (fraction === null) return fraction;
return data[_options_].loops ? fraction - floor(fraction) : min_max(0, 1, fraction)
},
tier: function(tier, data){
if (tier === null) return tier;
return min_max(0, 1, tier)
},
row: function(row, data){
if (row === null) return row;
return round(min_max(1, data[_options_].rows, row))
},
frame: function(frame, data){
if (frame === null) return frame;
var
opt= data[_options_],
frames= data[_frames_] * (opt.orbital ? 2 : opt.rows || 1),
result= round(opt.loops ? frame % frames || frames : min_max(1, frames, frame))
return result < 0 ? result + frames : result
},
images: function(images, data){
var
sequence= reel.re.sequence.exec(images),
result= !sequence ? images : reel.sequence(sequence, data[_options_])
return result;
}
},
// -----------------
// Sequence Build-up
// -----------------
//
// When configured with a String value for [`images`](#images-Option) like `image##.jpg`, it first has
// to be converted into an actual Array by engaging the counter placeholder.
//
// ---
// ### `$.reel.sequence()` ######
// `Function`, since 1.2
//
sequence: function(sequence, opt){
if (sequence.length <= 1) return opt.images;
var
images= [],
orbital= opt.orbital,
url= sequence[1],
placeholder= sequence[2],
start= +sequence[4] || 1,
rows= orbital ? 2 : opt.rows || 1,
frames= orbital ? opt.footage : opt.stitched ? 1 : opt.frames,
end= +(sequence[5] || rows * frames),
total= end - start,
increment= +sequence[7] || 1,
counter= 0
while(counter <= total){
images.push(url.replace(placeholder, pad((start + counter + __), placeholder.length, '0')));
counter+= increment;
}
return images;
},
// --------------
// Reel Instances
// --------------
//
// `$.reel.instances` holds an inventory of all running instances in the DOM document.
//
// ---
// ### `$.reel.instances` ######
// `jQuery`, since 1.1
//
instances: $(),
// For ticker-synchronization-related purposes Reel maintains a reference to the leaders data object
// all the time.
//
// ---
// ### `$.reel.leader` ######
// `Object` (DOM data), since 1.1
//
leader: leader,
// `$.reel.cost` holds document-wide costs in miliseconds of running all Reel instances. It is used
// to adjust actual timeout of the ticker.
//
// ---
// ### `$.reel.cost` ######
// `Number`, since 1.1
//
cost: 0
},
// ------------------------
// Private-scoped Variables
// ------------------------
//
pool= $(document),
client= navigator.userAgent,
browser= reel.re.ua[0].exec(client) || reel.re.ua[1].exec(client) || reel.re.ua[2].exec(client),
browser_version= +browser[2].split('.').slice(0,2).join('.'),
ie= browser[1] == 'MSIE',
knows_data_urls= !(ie && browser_version < 8),
ticker,
// ---------------
// CSS Class Names
// ---------------
//
// These are all the class names assigned by Reel to various DOM elements during initialization of the UI
// and they all share same base `"reel"`, which in isolation also is the class of the `<img>` node you
// converted into Reel.
//
klass= 'reel',
// Rest of the class names only extend this base class forming for example `.reel-overlay`, a class
// assigned to the outter instance wrapper (`<img>`'s injected parent).
//
overlay_klass= klass + '-overlay',
indicator_klass= klass + '-indicator',
preloader_klass= klass + '-preloader',
cached_klass= klass + '-cached',
monitor_klass= klass + '-monitor',
annotation_klass= klass + '-annotation',
panning_klass= klass + '-panning',
loading_klass= klass + '-loading',
// The instance wrapper is flagged with actual frame number using a this class.
//
// _**Example:** Reel on frame 10 will carry a class name `frame-10`._
//
frame_klass= 'frame-',
// --------------------------------
// Shortcuts And Minification Cache
// --------------------------------
//
// Several math functions are referenced inside the private scope to yield smaller filesize
// when the code is minified.
//
math= Math,
round= math.round, floor= math.floor, ceil= math.ceil,
min= math.min, max= math.max, abs= math.abs,
number= parseInt,
interpolate= reel.math.interpolate,
// For the very same reason all storage key Strings are cached into local vars.
//
_annotations_= 'annotations',
_area_= 'area', _auto_= 'auto', _backup_= 'backup', _backwards_= 'backwards', _bit_= 'bit', _brake_= 'brake', _cached_= 'cached', _center_= 'center',
_clicked_= 'clicked', _clicked_location_= 'clicked_location', _clicked_on_= 'clicked_on', _clicked_tier_= 'clicked_tier',
_cwish_= 'cwish', _dimensions_= 'dimensions', _fraction_= 'fraction', _frame_= 'frame',
_frames_= 'frames', _hi_= 'hi', _hidden_= 'hidden', _image_= 'image', _images_= 'images', _opening_= 'opening', _opening_ticks_= _opening_+'_ticks',
_lo_= 'lo', _options_= 'options', _playing_= 'playing', _preloaded_= 'preloaded', _reeling_= 'reeling', _reeled_= 'reeled', _revolution_= 'revolution',
_revolution_y_= 'revolution_y', _row_= 'row', _rows_= 'rows', _spacing_= 'spacing', _speed_= 'speed', _stage_= 'stage',
_stitched_shift_= 'stitched_shift', _stitched_travel_= 'stitched_travel', _stopped_= 'stopped', _style_= 'style', _tempo_= 'tempo', _ticks_= 'ticks',
_tier_= 'tier', _velocity_= 'velocity', _vertical_= 'vertical',
// And the same goes for browser events too.
//
ns= dot(klass),
pns= dot('pan') + ns,
_touch_= 'touch', _mouse_= 'mouse', _dragstart_= 'dragstart'+ns,
_mousedown_= _mouse_+'down'+ns, _mouseenter_= _mouse_+'enter'+ns,
_mouseleave_= _mouse_+'leave'+pns, _mousemove_= _mouse_+'move'+pns, _mouseup_= _mouse_+'up'+pns,
_mousewheel_= _mouse_+'wheel'+ns, _tick_= 'tick'+ns, _touchcancel_= _touch_+'cancel'+pns,
_touchend_= _touch_+'end'+pns, _touchstart_= _touch_+'start'+ns, _touchmove_= _touch_+'move'+pns,
// And some other frequently used Strings.
//
__= '', ___= ' ', ____=',', _absolute_= 'absolute', _block_= 'block', _cdn_= '@CDN@', _div_= 'div',
_hand_= 'hand', _head_= 'head', _height_= 'height', _html_= 'html', _id_= 'id',
_img_= 'img', _jquery_reel_= 'jquery.'+klass, _move_= 'move', _none_= 'none', _object_= 'object',
_preload_= 'preload', _string_= 'string',
_width_= 'width',
// ---------------
// Image Resources
// ---------------
//
// Alhough we do what we can to hide the fact, Reel actually needs a few image resources to support
// some of its actions. First, we may need a transparent image for the original `<img>` to uncover
// the sprite applied to its background. This one is embedded in the code as it is very small.
//
transparent= knows_data_urls ? embedded('CAAIAIAAAAAAAAAAACH5BAEAAAAALAAAAAAIAAgAAAIHhI+py+1dAAA7') : _cdn_+'blank.gif',
// Proper cross-browser cursors however need to come in an odd format, which essentially is not
// compressed at all and this means bigger filesize. While it is no more than ~15k, it is unfit
// for embedding directly here, so a [`CDN`](#Content-Delivery-Network) is employed to retrieve
// the images from in an effective gzipped and cachable manner.
//
reel_cursor= url(_cdn_+_jquery_reel_+'.cur')+____+_move_,
drag_cursor= url(_cdn_+_jquery_reel_+'-drag.cur')+____+_move_,
drag_cursor_down= url(_cdn_+_jquery_reel_+'-drag-down.cur')+____+_move_,
// ~~~
//
// We then only identify the user's browser's capabilities and route around a MSIE's left button
// identification quirk (IE 8- reports left as right).
//
touchy= reel.touchy= (reel.re.touchy_agent).test(client),
lazy= reel.lazy= (reel.re.lazy_agent).test(client),
DRAG_BUTTON= touchy ? undefined : (ie && browser_version < 9) ? 1 : 0,
// ~~~
//
// So far jQuery doesn't have a proper built-in mechanism to detect/report DOM node removal.
// But internally, jQuery calls `$.cleanData()` to flush the DOM data and minimize memory leaks.
// Reel wraps this function and as a result `clean` event handler is triggered for every element.
// Note, that the `clean` event does not bubble.
//
cleanData= $.cleanData,
cleanDataEvent= $.cleanData= function(elements){
cleanData($(elements).each(function(){ $(this).triggerHandler('clean'); }));
}
// Expose plugin functions as jQuery methods, do the initial global scan for data-configured
// `<img`> tags to become enhanced and export the entire namespace module.
//
$.extend($.fn, reel.fn) && $(reel.scan);
return reel;
// Bunch of very useful helpers.
//
function add_instance($instance){ return (reel.instances.push($instance[0])) && $instance }
function remove_instance($instance){ return (reel.instances= reel.instances.not(hash($instance.attr(_id_)))) && $instance }
function leader(key){ return reel.instances.first().data(key) }
function embedded(image){ return 'data:image/gif;base64,R0lGODlh' + image }
function tag(string){ return '<' + string + '/>' }
function dot(string){ return '.' + (string || '') }
function cdn(path){ return path.replace(_cdn_, reel.cdn) }
function url(location){ return 'url(\'' + reen(location) + '\')' }
function axis(key, value){ return typeof value == _object_ ? value[key] : value }
function min_max(minimum, maximum, number){ return max(minimum, min(maximum, number)) }
function negative_when(value, condition){ return abs(value) * (condition ? -1 : 1) }
function finger(e){ return touchy ? e.touch || e.originalEvent.touches[0] : e }
function px(value){ return value === undefined ? 0 : typeof value == _string_ ? value : value + 'px' }
function hash(value){ return '#' + value }
function pad(string, len, fill){ while (string.length < len) string= fill + string; return string }
function reen(uri){ return encodeURI(decodeURI(uri)) }
function soft_array(string){ return reel.re.array.exec(string) ? string.split(reel.re.array) : string }
function numerize_array(array){ return typeof array == _string_ ? array : $.each(array, function(ix, it){ array[ix]= it ? +it : undefined }) }
function deprecated(input){ try{ console.warn('Deprecation - Please consult https://github.com/pisi/Reel/wiki/Deprecations') }catch(e){} return input }
})(jQuery, window, document);
});
| jquery.reel.js | /**
@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@ @@@@@@@@
@@@@@@@ @@@@@@@
@@@@@@@ @@@@@@@
@@@@@@@ @@@@@@@
@@@@@@@@ @ @@@@@@@@
@@@@@@@@@ @@@ @@@@@@@@@
@@@@@@@@@@@@@@ @@@@@@@@@@@
@@@@@@@@@@@@@ @@@@@@@
@@@@@@@@@@@@ @@@
@@@@@@
@@@@
@@
*
* jQuery Reel
* ===========
* The 360° plugin for jQuery
*
* @license Copyright (c) 2009-2013 Petr Vostrel (http://petr.vostrel.cz/)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* jQuery Reel
* http://jquery.vostrel.net/reel
* Version: 1.2.2
* Updated: 2013-08-16
*
* Requires jQuery 1.5 or higher
*/
/*
* CDN
* ---
* - http://code.vostrel.net/jquery.reel-bundle.js (recommended)
* - http://code.vostrel.net/jquery.reel.js
* - http://code.vostrel.net/jquery.reel-debug.js
* - or http://code.vostrel.net/jquery.reel-edge.js if you feel like it ;)
*
* Optional Plugins
* ----------------
* - jQuery.mouseWheel [B] (Brandon Aaron, http://plugins.jquery.com/project/mousewheel)
* - or jQuery.event.special.wheel (Three Dub Media, http://blog.threedubmedia.com/2008/08/eventspecialwheel.html)
*
* [B] Marked plugins are contained (with permissions) in the "bundle" version from the CDN
*/
(function(factory){
// -----------------------
// [NEW] AMD Compatibility
// -----------------------
//
// Reel registers as an asynchronous module with dependency on jQuery for [AMD][1] compatible script loaders.
// Besides that it also complies with [CommonJS][2] module definition for Node and such.
// Of course, no fancy script loader is necessary and good old plain script tag still works too.
//
// [1]:http://en.wikipedia.org/wiki/Asynchronous_module_definition
// [2]:http://en.wikipedia.org/wiki/CommonJS
//
var
amd= typeof define == 'function' && define.amd && (define(['jquery'], factory) || true),
commonjs= !amd && typeof module == 'object' && typeof module.exports == 'object' && (module.exports= factory),
plain= !amd && !commonjs && factory()
})(function(){ return jQuery.reel || (function($, window, document, undefined){
// ------
// jQuery
// ------
//
// One vital requirement is the correct jQuery. Reel requires at least version 1.5
// and a make sure check is made at the very beginning.
//
if (!$ || +$().jquery.replace('.', __).substr(0, 2) < 15) return;
// ----------------
// Global Namespace
// ----------------
//
// `$.reel` (or `jQuery.reel`) namespace is provided for storage of all Reel belongings.
// It is locally referenced as just `reel` for speedier access.
//
var
reel= $.reel= {
// ### `$.reel.version`
//
// `String` (major.minor.patch), since 1.1
//
version: '1.2.2',
// Options
// -------
//
// When calling `.reel()` method you have plenty of options (far too many) available.
// You collect them into one hash and supply them with your call.
//
// _**Example:** Initiate a non-looping Reel with 12 frames:_
//
// .reel({
// frames: 12,
// looping: false
// })
//
//
// All options are optional and if omitted, default value is used instead.
// Defaults are being housed as members of `$.reel.def` hash.
// If you customize any default value therein, all subsequent `.reel()` calls
// will use the new value as default.
//
// _**Example:** Change default initial frame to 5th:_
//
// $.reel.def.frame = 5
//
// ---
// ### `$.reel.def` ######
// `Object`, since 1.1
//
def: {
//
// ### Basic Definition ######
//
// Reel is just fine with you not setting any options, however if you don't have
// 36 frames or beginning at frame 1, you will want to set total number
// of `frames` and pick a different starting `frame`.
//
// ---
// #### `frame` Option ####
// `Number` (frames), since 1.0
//
frame: 1,
// #### `frames` Option ####
// `Number` (frames), since 1.0
//
frames: 36,
// ~~~
//
// Another common characteristics of any Reel is whether it `loops` and covers
// entire 360° or not.
//
// ---
// #### `loops` Option ####
// `Boolean`, since 1.0
//
loops: true,
// ### Interaction ######
//
// Using boolean switches many user interaction aspects can be turned on and off.
// You can disable the mouse wheel control with `wheelable`, the drag & throw
// action with `throwable`, disallow the dragging completely with `draggable`,
// on "touchy" devices you can disable the browser's decision to scroll the page
// instead of Reel script and you can of course disable the stepping of Reel by
// clicking on either half of the image with `steppable`.
//
// You can even enable `clickfree` operation,
// which will cause Reel to bind to mouse enter/leave events instead of mouse down/up,
// thus allowing a click-free dragging.
//
// ---
// #### `clickfree` Option ####
// `Boolean`, since 1.1
//
clickfree: false,
// #### `draggable` Option ####
// `Boolean`, since 1.1
//
draggable: true,
// #### `scrollable` Option ####
// [NEW] `Boolean`, since 1.2
//
scrollable: true,
// #### `steppable` Option ####
// [NEW] `Boolean`, since 1.2
//
steppable: true,
// #### `throwable` Option ####
// `Boolean`, since 1.1; or `Number`, since 1.2.1
//
throwable: true,
// #### `wheelable` Option ####
// `Boolean`, since 1.1
//
wheelable: true,
// ### Order of Images ######
//
// Reel presumes counter-clockwise order of the pictures taken. If the nearer facing
// side doesn't follow your cursor/finger, you did clockwise. Use the `cw` option to
// correct this.
//
// ---
// #### `cw` Option ####
// `Boolean`, since 1.1
//
cw: false,
// ### Sensitivity ######
//
// In Reel sensitivity is set through the `revolution` parameter, which represents horizontal
// dragging distance one must cover to perform one full revolution. By default this value
// is calculated based on the setup you have - it is either twice the width of the image
// or half the width of stitched panorama. You may also set your own.
//
// Optionally `revolution` can be set as an Object with `x` member for horizontal revolution
// and/or `y` member for vertical revolution in multi-row movies.
//
// ---
// #### `revolution` Option ####
// `Number` (pixels) or `Object`, since 1.1, `Object` support since 1.2
//
revolution: undefined,
// ### Rectilinear Panorama ######
//
// The easiest of all is the stitched panorama mode. For this mode, instead of the sprite,
// a single seamlessly stitched stretched image is used and the view scrolls the image.
// This mode is triggered by setting a pixel width of the `stitched` image.
//
// ---
// #### `stitched` Option ####
// `Number` (pixels), since 1.0
//
stitched: 0,
// ### Directional Mode ######
//
// As you may have noticed on Reel's homepage or in [`example/object-movie-directional-sprite`][1]
// when you drag the arrow will point to either direction. In such `directional` mode, the sprite
// is actually 2 in 1 - one file contains two sprites one tightly following the other, one
// for visually going one way (`A`) and one for the other (`B`).
//
// A01 A02 A03 A04 A05 A06
// A07 A08 A09 A10 A11 A12
// A13 A14 A15 B01 B02 B03
// B04 B05 B06 B07 B08 B09
// B10 B11 B12 B13 B14 B15
//
// Switching between `A` and `B` frames is based on direction of the drag. Directional mode isn't
// limited to sprites only, sequences also apply. The figure below shows the very same setup like
// the above figure, only translated into actual frames of the sequence.
//
// 001 002 003 004 005 006
// 007 008 009 010 011 012
// 013 014 015 016 017 018
// 019 020 021 022 023 024
// 025 026 027 028 029 030
//
// Frame `016` represents the `B01` so it actually is first frame of the other direction.
//
// [1]:../example/object-movie-directional-sprite/
//
// ---
// #### `directional` Option ####
// `Boolean`, since 1.1
//
directional: false,
// ### Multi-Row Mode ######
//
// As [`example/object-movie-multirow-sequence`][1] very nicely demonstrates, in multi-row arrangement
// you can perform two-axis manipulation allowing you to add one or more vertical angles. Think of it as
// a layered cake, each new elevation of the camera during shooting creates one layer of the cake -
// - a _row_. One plain horizontal object movie full spin is one row:
//
// A01 A02 A03 A04 A05 A06
// A07 A08 A09 A10 A11 A12
// A13 A14 A15
//
// Second row tightly follows after the first one:
//
// A01 A02 A03 A04 A05 A06
// A07 A08 A09 A10 A11 A12
// A13 A14 A15 B01 B02 B03
// B04 B05 B06 B07 B08 B09
// B10 B11 B12 B13 B14 B15
// C01...
//
// This way you stack up any number of __`rows`__ you wish and set the initial `row` to start with.
// Again, not limited to sprites, sequences also apply.
//
// [1]:../example/object-movie-multirow-sequence/
//
// ---
// #### `row` Option ####
// `Number` (rows), since 1.1
//
row: 1,
// #### `rows` Option ####
// `Number` (rows), since 1.1
//
rows: 0,
// ### Dual-Orbit Mode ######
//
// Special form of multi-axis movie is the dual-axis mode. In this mode the object offers two plain
// spins - horizontal and vertical orbits combined together crossing each other at the `frame`
// forming sort of a cross if envisioned. [`example/object-movie-dual-orbit-sequence`][1] demonstrates
// this setup. When the phone in the example is facing you (marked in the example with green square
// in the top right), you are at the center. That is within the distance (in frames) defined
// by the `orbital` option. Translation from horizontal to vertical orbit can be achieved on this sweet-spot.
// By default horizontal orbit is chosen first, unless `vertical` option is used against.
//
// In case the image doesn't follow the vertical drag, you may have your vertical orbit `inversed`.
//
// Technically it is just a two-layer movie:
//
// A01 A02 A03 A04 A05 A06
// A07 A08 A09 A10 A11 A12
// A13 A14 A15 B01 B02 B03
// B04 B05 B06 B07 B08 B09
// B10 B11 B12 B13 B14 B15
//
// [1]:../example/object-movie-dual-orbit-sequence/
//
// ---
// #### `orbital` Option ####
// `Number` (frames), since 1.1
//
orbital: 0,
// #### `vertical` Option ####
// `Boolean`, since 1.1
//
vertical: false,
// #### `inversed` Option ####
// `Boolean`, since 1.1
//
inversed: false,
// ### Sprite Layout ######
//
// For both object movies and panoramas Reel presumes you use a combined _Sprite_ to hold all your
// frames in a single file. This powerful technique of using a sheet of several individual images
// has many advantages in terms of compactness, loading, caching, etc. However, know your enemy,
// be also aware of the limitations, which stem from memory limits of mobile
// (learn more in [FAQ](https://github.com/pisi/Reel/wiki/FAQ)).
//
// Inside the sprite, individual frames are laid down one by one, to the right of the previous one
// in a straight _Line_:
//
// 01 02 03 04 05 06
// 07...
//
// Horizontal length of the line is reffered to as `footage`. Unless frames `spacing` in pixels
// is set, edges of frames must touch.
//
// 01 02 03 04 05 06
// 07 08 09 10 11 12
// 13 14 15 16 17 18
// 19 20 21 22 23 24
// 25 26 27 28 29 30
// 31 32 33 34 35 36
//
// This is what you'll get by calling `.reel()` without any options. All frames laid out 6 in line.
// By default nicely even 6 x 6 grid like, which also inherits the aspect ratio of your frames.
//
// By setting `horizontal` to `false`, instead of forming lines, frames are expected to form
// _Columns_. All starts at the top left corner in both cases.
//
// 01 07 13 19 25 31
// 02 08 14 20 26 32
// 03 09 15 21 27 33
// 04 10 16 22 28 34
// 05 11 17 23 29 35
// 06 12 18 24 30 36
//
// URL for the sprite image file is being build from the name of the original `<img>` `src` image
// by adding a `suffix` to it. By default this results in `"object-reel.jpg"` for `"object.jpg"`.
// You can also take full control over the sprite `image` URL that will be used.
//
// ---
// #### `footage` Option ####
// `Number` (frames), since 1.0
//
footage: 6,
// #### `spacing` Option ####
// `Number` (pixels), since 1.0
//
spacing: 0,
// #### `horizontal` Option ####
// `Boolean`, since 1.0
//
horizontal: true,
// #### `suffix` Option ####
// `String`, since 1.0
//
suffix: '-reel',
// #### `image` Option ####
// `String`, since 1.1
//
image: undefined,
// ### Sequence ######
//
// Collection of individual frame images is called _Sequence_ and it this way one HTTP request per
// frame is made carried out as opposed to sprite with one request per entire sprite. Define it with
// string like: `"image_###.jpg"`. The `#` placeholders will be replaced with a numeric +1 counter
// padded to the placeholders length.
// Learn more about [sequences](Sequences).
//
// In case you work with hashed filenames like `64bc654d21cb.jpg`, where no counter element can
// be indentified, or you prefer direct control, `images` can also accept array of plain URL strings.
//
// All images are retrieved from a specified `path`.
//
// ---
// #### `images` Option ####
// [IMPROVED] `String` or `Array`, since 1.1
//
images: '',
// #### `path` Option ####
// `String` (URL path), since 1.1
//
path: '',
// ### Images Preload Order ######
//
// Given sequence images can be additionally reordered to achieve a perceived faster preloading.
// Value given to `preload` option must match a name of a pre-registered function within
// `$.reel.preload` object. There are two functions built-in:
//
// - `"fidelity"` - non-linear way that ensures even spreading of preloaded images around the entire
// revolution leaving the gaps in-between as small as possible. This results in a gradually
// increasing fidelity of the image rather than having one large shrinking gap. This is the default
// behavior.
// - `"linear"` - linear order of preloading
//
// ---
// #### `preload` Option ####
// [NEW] `String`, since 1.2
//
preload: 'fidelity',
// ### Animation ######
//
// Your object movie or a panorama can perform an autonomous sustained motion in one direction.
// When `speed` is set in revolutions per second (Hz), after a given `delay` the instance will
// animate and advance frames by itself.
//
// t
// |-------›|-----------›
// Delay Animation
//
// Start and resume of animation happens when given `timeout` has elapsed since user became idle.
//
// t
// |-----------›|= == == = === = = | |-----------›
// Animation User interaction Timeout Animation
//
// When a scene doesn't loop (see [`loops`](#loops-Option)) and the animation reaches one end,
// it stays there for a while and then reversing the direction of the animation it bounces back
// towards the other end. The time spent on the edge can be customized with `rebound`.
//
// ---
// #### `speed` Option ####
// `Number` (Hz), since 1.1
//
speed: 0,
// #### `delay` Option ####
// `Number` (seconds), since 1.1
//
delay: 0,
// #### `timeout` Option ####
// `Number` (seconds), since 1.1
//
timeout: 2,
// #### `duration` Option ####
// `Number` (seconds), EXPERIMENTAL
//
duration: undefined,
// #### `rebound` Option ####
// `Number` (seconds), since 1.1
//
rebound: 0.5,
// ### Opening Animation ######
//
// Chance is you want the object to spin a little to attract attention and then stop and wait
// for the user to engage. This is called "opening animation" and it is performed for given number
// of seconds (`opening`) at dedicated `entry` speed. The `entry` speed defaults to value of `speed`
// option. After the opening animation has passed, regular animation procedure begins starting with
// the delay (if any).
//
// t
// |--------›|-------›|-----------›
// Opening Delay Animation
//
// ---
// #### `entry` Option ####
// `Number` (Hz), since 1.1
//
entry: undefined,
// #### `opening` Option ####
// `Number` (seconds), since 1.1
//
opening: 0,
// ### Momentum ######
//
// Often also called inertial motion is a result of measuring a velocity of dragging. This velocity
// builds up momentum, so when a drag is released, the image still retains the momentum and continues
// to spin on itself. Naturally the momentum soon wears off as `brake` is being applied.
//
// One can utilize this momentum for a different kind of an opening animation. By setting initial
// `velocity`, the instance gets artificial momentum and spins to slow down to stop.
//
// ---
// #### `brake` Option ####
// `Number`, since 1.1, where it also has a different default `0.5`
//
brake: 0.23,
// #### `velocity` Option ####
// [NEW] `Number`, since 1.2
//
velocity: 0,
// ### Ticker ######
//
// For purposes of animation, Reel starts and maintains a timer device which emits ticks timing all
// animations. There is only one ticker running in the document and all instances subscribe to this
// one ticker. Ticker is equipped with a mechanism, which compensates for the measured costs
// of running Reels to ensure the ticker ticks on time. The `tempo` (in Hz) of the ticker can be
// specified.
//
// Please note, that ticker is synchronized with a _leader_, the oldest living instance on page,
// and adjusts to his tempo.
//
// ---
// #### `tempo` Option ####
// `Number` (Hz, ticks per second), since 1.1
//
tempo: 36,
// ~~~
//
// Since many mobile devices are sometimes considerably underpowered in comparison with desktops,
// they often can keep up with the 36 Hz rhythm. In Reel these are called __lazy devices__
// and everything mobile qualifies as lazy for the sake of the battery and interaction fluency.
// The ticker is under-clocked for them by a `laziness` factor, which is used to divide the `tempo`.
// Default `laziness` of `6` will effectively use 6 Hz instead (6 = 36 / 6) on lazy devices.
//
// ---
// #### `laziness` Option ####
// `Number`, since 1.1
//
laziness: 6,
// ### Customization ######
//
// You can customize Reel on both functional and visual front. The most visible thing you can
// customize is probably the `cursor`, size of the `preloader`, perhaps add visual `indicator`(s)
// of Reel's position within the range. You can also set custom `hint` for the tooltip, which appears
// when you mouse over the image area. Last but not least you can also add custom class name `klass`
// to the instance.
//
// ---
// #### `cursor` Option ####
// [NEW] `String`, since 1.2
//
cursor: undefined,
// #### `hint` Option ####
// `String`, since 1.0
//
hint: '',
// #### `indicator` Option ####
// `Number` (pixels), since 1.0
//
indicator: 0,
// #### `klass` Option ####
// `String`, since 1.0
//
klass: '',
// #### `preloader` Option ####
// `Number` (pixels), since 1.1
//
preloader: 2,
// ~~~
//
// You can use custom attributes (`attr`) on the node - it accepts the same name-value pairs object
// jQuery `.attr()` does. In case you want to delegate full interaction control over the instance
// to some other DOM element(s) on page, you can with `area`.
//
// ---
// #### `area` Option ####
// `jQuery`, since 1.1
//
area: undefined,
// #### `attr` Option ####
// [NEW] `Object`, since 1.2
//
attr: {},
// ### Annotations ######
//
// To further visually describe your scene you can place all kinds of in-picture HTML annotations
// by defining an `annotations` object. Learn more about [Annotations][1] in a dedicated article.
//
// [1]:https://github.com/pisi/Reel/wiki/Annotations
//
// ---
// #### `annotations` Option ####
// [NEW] `Object`, since 1.2
//
annotations: undefined,
// ### Mathematics ######
//
// When reeling, instance conforms to a graph function, which defines whether it will loop
// (`$.reel.math.hatch`) or it won't (`$.reel.math.envelope`). My math is far from flawless
// and I'm sure there are much better ways how to handle things. the `graph` option is there for you
// shall you need it. It accepts a function, which should process given criteria and return
// a fraction of 1.
//
// function( x, start, revolution, lo, hi, cwness, y ){
// return fraction // 0.0 - 1.0
// }
//
// ---
// #### `graph` Option ####
// `Function`, since 1.1
//
graph: undefined,
// ### Monitor ######
//
// Specify a string data key and you will see its real-time value dumped in the upper-left corner
// of the viewport. Its visual can be customized by CSS using `.jquery-reel-monitor` selector.
//
// ---
// #### `monitor` Option ####
// `String` (data key), since 1.1
//
monitor: undefined,
// ### Deprecated Options ######
//
// Two options are currently deprecated in version 1.2. Learn more about [Deprecations][1]
//
// [1]:https://github.com/pisi/Reel/wiki/Deprecations
//
// ---
// #### `step` Option ####
// `Number`, since 1.1
//
step: undefined, // use `frame` instead
// #### `steps` Option ####
// `Number`, since 1.1
//
steps: undefined // use `frames` instead
},
// -----------
// Quick Start
// -----------
//
// For basic Reel initialization, you don't even need to write any Javascript!
// All it takes is to add __class name__ `"reel"` to your `<img>` HTML tag,
// assign an unique __`id` attribute__ and decorate the tag with configuration __data attributes__.
// Result of which will be interactive Reel projection.
//
// <img src="some/image.jpg" width="300" height="200"
// id="my_image"
// class="reel"
// data-images="some/images/01.jpg, some/images/02.jpg"
// data-speed="0.5">
//
// All otherwise Javascript [options](#Options) are made available as HTML `data-*` attributes.
//
// Only the `annotations` option doesn't work this way. To quickly create annotations,
// simply have any HTML node (`<div>` prefferably) anywhere in the DOM,
// assign it __class name__ `"reel-annotation"`, an unique __`id` attribute__
// and add configuration __data attributes__.
//
// <div id="my_annotation"
// class="reel-annotation"
// data-for="my_image"
// data-x="120"
// data-y="60">
// Whatever HTML I'd like to have in the annotation
// </div>
//
// Most important is the `data-for` attribute, which references target Reel instance by `id`.
//
// ---
//
// Responsible for discovery and subsequent conversion of data-configured Reel images is
// `$.reel.scan()` method, which is being called automagically when the DOM becomes ready.
// Under normal circumstances you don't need to scan by yourself.
//
// It however comes in handy to re-scan when you happen to inject a data-configured Reel `<img>`
// into already ready DOM.
//
// ---
// ### `$.reel.scan()` Method ######
// returns `jQuery`, since 1.2.2
//
scan: function(){
return $(dot(klass)+':not('+dot(overlay_klass)+' >)').each(function(ix, image){
var
$image= $(image),
options= $image.data(),
images= options.images= soft_array(options.images),
annotations= {}
$(dot(annotation_klass)+'[data-for='+$image.attr(_id_)+']').each(function(ix, annotation){
var
$annotation= $(annotation),
def= $annotation.data(),
x= def.x= numerize_array(soft_array(def.x)),
y= def.y= numerize_array(soft_array(def.y)),
id= $annotation.attr(_id_),
node= def.node= $annotation.removeData()
annotations[id] = def;
});
options.annotations = annotations;
$image.removeData().reel(options);
});
},
// -------
// Methods
// -------
//
// Reel's methods extend jQuery core functions with members of its `$.reel.fn` object. Despite Reel
// being a typical one-method plug-in with its `.reel()` function, for convenience it also offers
// its dipolar twin `.unreel()`.
//
// ---
// ### `$.reel.fn` ######
// returns `Object`, since 1.1
//
fn: {
// ------------
// Construction
// ------------
//
// `.reel()` method is the core of Reel and similar to some jQuery functions, this one is three-fold.
// It either performs the following builder's duty or the [data duty](#Data).
//
// ---
// ### `.reel()` Method ######
// returns `jQuery`, since 1.0
//
reel: function(){
// The decision on what to actually do is made upon given arguments.
var
args= arguments,
t= $(this),
data= t.data(),
name= args[0] || {},
value= args[1]
if (typeof name == 'object'){
var
// Establish local `opt` object made by extending the defaults.
opt= $.extend({}, reel.def, name),
// Limit the given jQuery collection to just `<img>` tags with `src` attribute
// and dimensions defined.
applicable= t.filter(_img_).unreel().filter(function(){
var
$this= $(this),
attr= opt.attr,
src= attr.src || $this.attr('src'),
width= attr.width || $this.width(),
height= attr.height || $this.height()
if (src && width && height) return true;
}),
instances= []
// Backward-compatibility of [deprecated] legacy options
//
opt.step && (opt.frame= opt.step);
opt.steps && (opt.frames= opt.steps);
applicable.each(function(){
var
t= $(this),
// Quick data interface
set= function(name, value){ return t.reel(name, value) && t.data(name) },
get= function(name){ return t.reel(name) },
on= {
// --------------
// Initialization
// --------------
//
// This internally called private pseudo-handler:
//
// - initiates all data store keys,
// - binds to ticker
// - and triggers `"setup"` Event when finished.
//
setup: function(e){
if (t.hasClass(klass) && t.parent().hasClass(overlay_klass)) return;
set(_options_, opt);
var
src= t.attr(opt.attr).attr('src'),
id= set(_id_, t.attr(_id_) || t.attr(_id_, klass+'-'+(+new Date())).attr(_id_)),
styles= t.attr(_style_),
data= $.extend({}, t.data()),
images= set(_images_, opt.images || []),
stitched= opt.stitched,
loops= opt.loops,
orbital= opt.orbital,
revolution= opt.revolution,
rows= opt.rows,
footage= opt.footage,
size= { x: t.width(), y: t.height() },
frames= set(_frames_, orbital && footage || rows <= 1 && images.length || opt.frames),
multirow= rows > 1 || orbital,
revolution_x= set(_revolution_, axis('x', revolution) || stitched / 2 || size.x * 2),
revolution_y= set(_revolution_y_, !multirow ? 0 : (axis('y', revolution) || (rows > 3 ? size.y : size.y / (5 - rows)))),
rows= stitched ? 1 : ceil(frames / footage),
stage_id= hash(id+opt.suffix),
classes= t[0].className || __,
$overlay= $(tag(_div_), { id: stage_id.substr(1), 'class': classes+___+overlay_klass+___+frame_klass+'0' }),
$instance= t.wrap($overlay.addClass(opt.klass)).attr({ 'class': klass }),
instances_count= instances.push(add_instance($instance)[0]),
$overlay= $instance.parent().bind(on.instance)
set(_image_, images.length ? __ : opt.image || src.replace(reel.re.image, '$1' + opt.suffix + '.$2'));
set(_cached_, []);
set(_spacing_, opt.spacing);
set(_frame_, null);
set(_fraction_, null);
set(_row_, null);
set(_tier_, null);
set(_rows_, rows);
set(_dimensions_, size);
set(_bit_, 1 / (frames - (loops && !stitched ? 0 : 1)));
set(_stitched_travel_, stitched - (loops ? 0 : size.x));
set(_stitched_shift_, 0);
set(_stage_, stage_id);
set(_backwards_, set(_speed_, opt.speed) < 0);
set(_velocity_, 0);
set(_vertical_, opt.vertical);
set(_preloaded_, 0);
set(_cwish_, negative_when(1, !opt.cw && !stitched));
set(_clicked_location_, {});
set(_clicked_, false);
set(_clicked_on_, set(_clicked_tier_, 0));
set(_lo_, set(_hi_, 0));
set(_reeling_, false);
set(_reeled_, false);
set(_opening_, false);
set(_brake_, opt.brake);
set(_center_, !!orbital);
set(_tempo_, opt.tempo / (reel.lazy? opt.laziness : 1));
set(_opening_ticks_, -1);
set(_ticks_, -1);
set(_annotations_, opt.annotations || $overlay.unbind(dot(_annotations_)) && {});
set(_backup_, {
src: src,
classes: classes,
style: styles || __,
data: data
});
opt.steppable || $overlay.unbind('up.steppable');
opt.indicator || $overlay.unbind('.indicator');
css(__, { width: size.x, height: size.y, overflow: _hidden_, position: 'relative' });
css(____+___+dot(klass), { display: _block_ });
pool.bind(on.pool);
t.trigger('setup');
},
// ------
// Events
// ------
//
// Reel is completely event-driven meaning there are many events, which can be called
// (triggered). By binding event handler to any of the events you can easily hook on to any
// event to inject your custom behavior where and when this event was triggered.
//
// _**Example:** Make `#image` element reel and execute some code right after the newly
// created instance is initialized and completely loaded:_
//
// $("#image")
// .reel()
// .bind("loaded", function(ev){
// // Your code
// })
//
// Events bound to all individual instances.
//
instance: {
// ### `teardown` Event ######
// `Event`, since 1.1
//
// This event does do how it sounds like. It will teardown an instance with all its
// belongings leaving no trace.
//
// - It reconstructs the original `<img>` element,
// - wipes out the data store,
// - removes instance stylesheet
// - and unbinds all its events.
//
teardown: function(e){
var
backup= t.data(_backup_)
t.parent().unbind(on.instance);
get(_style_).remove();
get(_area_).unbind(ns);
remove_instance(t.unbind(ns).removeData().siblings().unbind(ns).remove().end().attr({
'class': backup.classes,
src: backup.src,
style: backup.style
}).data(backup.data).unwrap());
no_bias();
pool.unbind(on.pool);
pools.unbind(pns);
},
// ### `setup` Event ######
// `Event`, since 1.0
//
// `"setup"` Event continues with what has been started by the private `on.setup()`
// handler.
//
// - It prepares all additional on-stage DOM elements
// - and cursors for the instance stylesheet.
//
setup: function(e){
var
space= get(_dimensions_),
frames= get(_frames_),
id= t.attr(_id_),
rows= opt.rows,
stitched= opt.stitched,
$overlay= t.parent(),
$area= set(_area_, $(opt.area || $overlay )),
rows= opt.rows || 1
css(___+dot(klass), { MozUserSelect: _none_, WebkitUserSelect: _none_ });
if (touchy){
// workaround for downsizing-sprites-bug-in-iPhoneOS inspired by Katrin Ackermann
css(___+dot(klass), { WebkitBackgroundSize: get(_images_).length
? !stitched ? undefined : px(stitched)+___+px(space.y)
: stitched && px(stitched)+___+px((space.y + opt.spacing) * rows - opt.spacing)
|| px((space.x + opt.spacing) * opt.footage - opt.spacing)+___+px((space.y + opt.spacing) * get(_rows_) * rows * (opt.directional? 2:1) - opt.spacing)
});
$area
.bind(_touchstart_, press)
}else{
var
cursor= opt.cursor,
cursor_up= cursor == _hand_ ? drag_cursor : cursor || reel_cursor,
cursor_down= cursor == _hand_ ? drag_cursor_down+___+'!important' : undefined
css(__, { cursor: cdn(cursor_up) });
css(dot(loading_klass), { cursor: 'wait' });
css(dot(panning_klass)+____+dot(panning_klass)+' *', { cursor: cdn(cursor_down || cursor_up) }, true);
$area
.bind(opt.wheelable ? _mousewheel_ : null, wheel)
.bind(opt.clickfree ? _mouseenter_ : _mousedown_, press)
.bind(_dragstart_, function(){ return false })
}
function press(e){ return t.trigger('down', [finger(e).clientX, finger(e).clientY, e]) && e.give }
function wheel(e, delta){ return !delta || t.trigger('wheel', [delta, e]) && e.give }
opt.hint && $area.attr('title', opt.hint);
opt.indicator && $overlay.append(indicator('x'));
rows > 1 && opt.indicator && $overlay.append(indicator('y'));
opt.monitor && $overlay.append($monitor= $(tag(_div_), { 'class': monitor_klass }))
&& css(___+dot(monitor_klass), { position: _absolute_, left: 0, top: 0 });
css(___+dot(cached_klass), { display: _none_ });
},
// ### `preload` Event ######
// `Event`, since 1.1
//
// Reel keeps a cache of all images it needs for its operation. Either a sprite or all
// sequence images. Physically, this cache is made up of a hidden `<img>` sibling for each
// preloaded image. It first determines the order of requesting the images and then
// asynchronously loads all of them.
//
// - It preloads all frames and sprites.
//
preload: function(e){
var
space= get(_dimensions_),
$overlay= t.parent(),
images= get(_images_),
is_sprite= !images.length,
frames= get(_frames_),
footage= opt.footage,
order= reel.preload[opt.preload] || reel.preload[reel.def.preload],
preload= is_sprite ? [get(_image_)] : order(images.slice(0), opt, get),
to_load= preload.length,
preloaded= set(_preloaded_, is_sprite ? 0.5 : 0),
uris= []
$overlay.addClass(loading_klass).append(preloader());
// It also finalizes the instance stylesheet and prepends it to the head.
set(_style_, get(_style_) || $('<'+_style_+' type="text/css">'+css.rules.join('\n')+'</'+_style_+'>').prependTo(_head_));
t.trigger('stop');
while(preload.length){
var
uri= opt.path+preload.shift(),
width= space.x * (!is_sprite ? 1 : footage),
height= space.y * (!is_sprite ? 1 : frames / footage) * (!opt.directional ? 1 : 2),
$img= $(tag(_img_)).attr({ 'class': cached_klass, width: width, height: height }).appendTo($overlay)
// Each image, which finishes the load triggers `"preloaded"` Event.
$img.bind('load error abort', function(e){
e.type != 'load' && t.trigger(e.type);
return !!$(this).parent().length && t.trigger('preloaded') && false;
});
load(uri, $img);
uris.push(uri);
}
set(_cached_, uris);
function load(uri, $img){ setTimeout(function(){
$img.parent().length && $img.attr({ src: reen(uri) });
}, (to_load - preload.length) * 2) }
},
// ### `preloaded` Event ######
// `Event`, since 1.1
//
// This event is fired by every preloaded image and adjusts the preloader indicator's
// target position. Once all images are preloaded, `"loaded"` Event is triggered.
//
preloaded: function(e){
var
images= get(_images_).length || 1,
preloaded= set(_preloaded_, min(get(_preloaded_) + 1, images))
if (preloaded === images){
t.parent().removeClass(loading_klass).unbind(_preloaded_, on.instance.preloaded);
t.trigger('loaded');
}
if (preloaded === 1) var
frame= t.trigger('frameChange', [undefined, get(_frame_)])
},
// ### `loaded` Event ######
// `Event`, since 1.1
//
// `"loaded"` Event is the one announcing when the instance is "locked and loaded".
// At this time, all is prepared, preloaded and configured for user interaction
// or animation.
//
loaded: function(e){
get(_images_).length > 1 || t.css({ backgroundImage: url(opt.path+get(_image_)) }).attr({ src: cdn(transparent) });
opt.stitched && t.attr({ src: cdn(transparent) });
get(_reeled_) || set(_velocity_, opt.velocity || 0);
},
// ----------------
// Animation Events
// ----------------
//
// ### `opening` Event ######
// `Event`, since 1.1
//
// When [opening animation](#Opening-Animation) is configured for the instance, `"opening"`
// event engages the animation by pre-calculating some of its properties, which will make
// the tick handler
//
opening: function(e){
/*
- initiates opening animation
- or simply plays the reel when without opening
*/
if (!opt.opening) return t.trigger('openingDone');
var
opening= set(_opening_, true),
stopped= set(_stopped_, !get(_speed_)),
speed= opt.entry || opt.speed,
end= get(_fraction_),
duration= opt.opening,
start= set(_fraction_, end - speed * duration),
ticks= set(_opening_ticks_, ceil(duration * leader(_tempo_)))
},
// ### `openingDone` Event ######
// `Event`, since 1.1
//
// `"openingDone"` is fired onceWhen [opening animation](#Opening-Animation) is configured for the instance, `"opening"`
// event engages the animation by pre-calculating some of its properties, which will make
// the tick handler
//
openingDone: function(e){
var
playing= set(_playing_, false),
opening= set(_opening_, false),
evnt= _tick_+dot(_opening_)
pool.unbind(evnt, on.pool[evnt]);
if (opt.delay > 0) delay= setTimeout(function(){ t.trigger('play') }, opt.delay * 1000)
else t.trigger('play');
},
// -----------------------
// Playback Control Events
// -----------------------
//
// ### `play` Event ######
// `Event`, since 1.1
//
// `"play"` event can optionally accept a `speed` parameter (in Hz) to change the animation
// speed on the fly.
//
play: function(e, speed){
var
speed= speed ? set(_speed_, speed) : (get(_speed_) * negative_when(1, get(_backwards_))),
duration= opt.duration,
ticks= duration && set(_ticks_, ceil(duration * leader(_tempo_))),
backwards= set(_backwards_, speed < 0),
playing= set(_playing_, !!speed),
stopped= set(_stopped_, !playing)
idle();
},
// ### `pause` Event ######
// `Event`, since 1.1
//
// Triggering `"pause"` event will halt the playback for a time period designated
// by the `timeout` option. After this timenout, the playback is resumed again.
//
pause: function(e){
unidle();
},
// ### `stop` Event ######
// `Event`, since 1.1
//
// After `"stop"` event is triggered, the playback stops and stays still until `"play"`ed again.
//
stop: function(e){
var
stopped= set(_stopped_, true),
playing= set(_playing_, !stopped)
},
// ------------------------
// Human Interaction Events
// ------------------------
//
// ### `down` Event ######
// `Event`, since 1.1
//
// Marks the very beginning of touch or mouse interaction. It receives `x` and `y`
// coordinates in arguments.
//
// - It calibrates the center point (origin),
// - considers user active not idle,
// - flags the `<html>` tag with `.reel-panning` class name
// - and binds dragging events for move and lift. These
// are usually bound to the pool (document itself) to get a consistent treating regardless
// the event target element. However in click-free mode, it binds directly to the instance.
//
down: function(e, x, y, ev){
if (ev && ev.button != DRAG_BUTTON && !opt.clickfree) return;
if (opt.draggable){
var
clicked= set(_clicked_, get(_frame_)),
clickfree= opt.clickfree,
velocity= set(_velocity_, 0),
origin= last= recenter_mouse(get(_revolution_), x, y)
touchy || ev && ev.preventDefault();
unidle();
no_bias();
panned= 0;
$(_html_, pools).addClass(panning_klass);
// Browser events differ for touch and mouse, but both of them are treated equally and
// forwarded to the same `"pan"` or `"up"` Events.
if (touchy){
pools
.bind(_touchmove_, drag)
.bind(_touchend_+___+_touchcancel_, lift)
}else{
(clickfree ? get(_area_) : pools)
.bind(_mousemove_, drag)
.bind(clickfree ? _mouseleave_ : _mouseup_, lift)
}
}
function drag(e){ return t.trigger('pan', [finger(e).clientX, finger(e).clientY, e]) && e.give }
function lift(e){ return t.trigger('up', [e]) && e.give }
},
// ### `up` Event ######
// `Event`, since 1.1
//
// This marks the termination of user's interaction. She either released the mouse button
// or lift the finger of the touch screen. This event handler:
//
// - calculates the velocity of the drag at that very moment,
// - removes the `.reel-panning` class from `<body>`
// - and unbinds dragging events from the pool.
//
up: function(e, ev){
var
clicked= set(_clicked_, false),
reeling= set(_reeling_, false),
throwable = opt.throwable,
biases= abs(bias[0] + bias[1]) / 60,
velocity= set(_velocity_, !throwable ? 0 : throwable === true ? biases : min(throwable, biases)),
brakes= braking= velocity ? 1 : 0
unidle();
no_bias();
$(_html_, pools).removeClass(panning_klass);
(opt.clickfree ? get(_area_) : pools).unbind(pns);
},
// ### `pan` Event ######
// [RENAMED] `Event`, since 1.2
//
// Regardles the actual source of movement (mouse or touch), this event is always triggered
// in response and similar to the `"down"` Event it receives `x` and `y` coordinates
// in arguments and in addition it is passed a reference to the original browser event.
// This handler:
//
// - syncs with timer to achieve good performance,
// - calculates the distance from drag center and applies graph on it to get `fraction`,
// - recenters the drag when dragged over limits,
// - detects the direction of the motion
// - and builds up inertial motion bias.
//
// Historically `pan` was once called `slide` (conflicted with Mootools - [GH-51][1])
// or `drag` (that conflicted with MSIE).
//
// [1]:https://github.com/pisi/Reel/issues/51
//
pan: function(e, x, y, ev){
if (opt.draggable && slidable){
slidable= false;
unidle();
var
rows= opt.rows,
orbital= opt.orbital,
scrollable= touchy && !get(_reeling_) && rows <= 1 && !orbital && opt.scrollable,
delta= { x: x - last.x, y: y - last.y }
if (ev && scrollable && abs(delta.x) < abs(delta.y)) return ev.give = true;
if (abs(delta.x) > 0 || abs(delta.y) > 0){
ev && (ev.give = false);
panned= max(delta.x, delta.y);
last= { x: x, y: y };
var
revolution= get(_revolution_),
origin= get(_clicked_location_),
vertical= get(_vertical_),
fraction= set(_fraction_, graph(vertical ? y - origin.y : x - origin.x, get(_clicked_on_), revolution, get(_lo_), get(_hi_), get(_cwish_), vertical ? y - origin.y : x - origin.x)),
reeling= set(_reeling_, get(_reeling_) || get(_frame_) != get(_clicked_)),
motion= to_bias(vertical ? delta.y : delta.x || 0),
backwards= motion && set(_backwards_, motion < 0)
if (orbital && get(_center_)) var
vertical= set(_vertical_, abs(y - origin.y) > abs(x - origin.x)),
origin= recenter_mouse(revolution, x, y)
if (rows > 1) var
space_y= get(_dimensions_).y,
revolution_y= get(_revolution_y_),
start= get(_clicked_tier_),
lo= - start * revolution_y,
tier= set(_tier_, reel.math.envelope(y - origin.y, start, revolution_y, lo, lo + revolution_y, -1))
if (!(fraction % 1) && !opt.loops) var
origin= recenter_mouse(revolution, x, y)
}
}
},
// ### `wheel` Event ######
// `Event`, since 1.0
//
// Maps Reel to mouse wheel position change event which is provided by a nifty plug-in
// written by Brandon Aaron - the [Mousewheel plug-in][1], which you will need to enable
// the mousewheel wheel for reeling. You can also choose to use [Wheel Special Event
// plug-in][2] by Three Dub Media instead. Either way `"wheel"` Event handler receives
// the positive or negative wheeled distance in arguments. This event:
//
// - calculates wheel input delta and adjusts the `fraction` using the graph,
// - recenters the "drag" each and every time,
// - detects motion direction
// - and nullifies the velocity.
//
// [1]:https://github.com/brandonaaron/jquery-mousewheel
// [2]:http://blog.threedubmedia.com/2008/08/eventspecialwheel.html
//
wheel: function(e, distance, ev){
if (!distance) return;
wheeled= true;
var
delta= ceil(math.sqrt(abs(distance)) / 2),
delta= negative_when(delta, distance > 0),
revolution= 0.0833 * get(_revolution_), // Wheel's revolution is 1/12 of full revolution
origin= recenter_mouse(revolution),
backwards= delta && set(_backwards_, delta < 0),
velocity= set(_velocity_, 0),
fraction= set(_fraction_, graph(delta, get(_clicked_on_), revolution, get(_lo_), get(_hi_), get(_cwish_)))
ev && ev.preventDefault();
ev && (ev.give = false);
unidle();
t.trigger('up', [ev]);
},
// ------------------
// Data Change Events
// ------------------
//
// Besides Reel being event-driven, it also is data-driven respectively data-change-driven
// meaning that there is a mechanism in place, which detects real changes in data being
// stored with `.reel(name, value)`. Learn more about [data changes](#Changes).
//
// These data change bindings are for internal use only and you don't ever trigger them
// per se, you change data and that will trigger respective change event. If the value
// being stored is the same as the one already stored, nothing will be triggered.
//
// _**Example:** Change Reel's current `frame`:_
//
// .reel("frame", 15)
//
// Change events always receive the actual data key value in the third argument.
//
// _**Example:** Log each viewed frame number into the developers console:_
//
// .bind("frameChange", function(e, d, frame){
// console.log(frame)
// })
//
// ---
// ### `fractionChange` Event ######
// `Event`, since 1.0
//
// Internally Reel doesn't really work with the frames you set it up with. It uses
// __fraction__, which is a numeric value ranging from 0.0 to 1.0. When `fraction` changes
// this handler basically calculates and sets new value of `frame`.
//
fractionChange: function(e, set_fraction, fraction){
if (set_fraction !== undefined) return deprecated(set(_fraction_, set_fraction));
var
frame= 1 + floor(fraction / get(_bit_)),
multirow= opt.rows > 1,
orbital= opt.orbital,
center= set(_center_, !!orbital && (frame <= orbital || frame >= opt.footage - orbital + 2))
if (multirow) var
frame= frame + (get(_row_) - 1) * get(_frames_)
var
frame= set(_frame_, frame)
},
// ### `tierChange` Event ######
// `Event`, since 1.2
//
// The situation of `tier` is very much similar to the one of `fraction`. In multi-row
// movies, __tier__ is an internal value for the vertical axis. Its value also ranges from
// 0.0 to 1.0. Handler calculates and sets new value of `frame`.
//
tierChange: function(e, deprecated_set, tier){
if (deprecated_set === undefined) var
row= set(_row_, round(interpolate(tier, 1, opt.rows))),
frames= get(_frames_),
frame= get(_frame_) % frames || frames,
frame= set(_frame_, frame + row * frames - frames)
},
// ### `rowChange` Event ######
// `Event`, since 1.1
//
// The physical vertical position of Reel is expressed in __rows__ and ranges
// from 1 to the total number of rows defined with [`rows`](#rows-Option). This handler
// only converts `row` value to `tier` and sets it.
//
rowChange: function(e, set_row, row){
if (set_row !== undefined) return set(_row_, set_row);
var
tier= set(_tier_, 1 / (opt.rows - 1) * (row - 1))
},
// ### `frameChange` Event ######
// `Event`, since 1.0
//
// The physical horizontal position of Reel is expressed in __frames__ and ranges
// from 1 to the total number of frames configured with [`frames`](#frames-Option).
// This handler converts `row` value to `tier` and sets it. This default handler:
//
// - flags the instance's outter wrapper with `.frame-X` class name
// (where `X` is the actual frame number),
// - calculates and eventually sets `fraction` (and `tier` for multi-rows) from given frame,
// - for sequences, it switches the `<img>`'s `src` to the right frame
// - and for sprites it recalculates sprite's 'background position shift and applies it.
//
frameChange: function(e, set_frame, frame){
if (set_frame !== undefined) return deprecated(set(_frame_, set_frame));
this.className= this.className.replace(reel.re.frame_klass, frame_klass + frame);
var
frames= get(_frames_),
rows= opt.rows,
path= opt.path,
base= frame % frames || frames,
ready= !!get(_preloaded_),
frame_row= (frame - base) / frames + 1,
frame_tier= (frame_row - 1) / (rows - 1),
tier_row= round(interpolate(frame_tier, 1, rows)),
row= get(_row_),
tier= ready && tier_row === row ? get(_tier_) : set(_tier_, frame_tier),
frame_fraction= min((base - 1) / (frames - 1), 0.9999),
row_shift= row * frames - frames,
fraction_frame= round(interpolate(frame_fraction, row_shift + 1, row_shift + frames)),
same_spot= abs((get(_fraction_) || 0) - frame_fraction) < 1 / (get(_frames_) - 1),
fraction= ready && (fraction_frame === frame && same_spot) ? get(_fraction_) : set(_fraction_, frame_fraction),
footage= opt.footage
if (opt.orbital && get(_vertical_)) var
frame= opt.inversed ? footage + 1 - frame : frame,
frame= frame + footage
var
horizontal= opt.horizontal,
stitched= opt.stitched,
images= get(_images_),
is_sprite= !images.length || opt.stitched,
spacing= get(_spacing_),
space= get(_dimensions_)
if (!is_sprite){
var
frameshot= images[frame - 1]
ready && t.attr({ src: reen(path + frameshot) })
}else{
if (!stitched) var
minor= (frame % footage) - 1,
minor= minor < 0 ? footage - 1 : minor,
major= floor((frame - 0.1) / footage),
major= major + (rows > 1 ? 0 : (get(_backwards_) ? 0 : !opt.directional ? 0 : get(_rows_))),
a= major * ((horizontal ? space.y : space.x) + spacing),
b= minor * ((horizontal ? space.x : space.y) + spacing),
shift= images.length ? [0, 0] : horizontal ? [px(-b), px(-a)] : [px(-a), px(-b)]
else{
var
x= set(_stitched_shift_, round(interpolate(frame_fraction, 0, get(_stitched_travel_))) % stitched),
y= rows <= 1 ? 0 : (space.y + spacing) * (rows - row),
shift= [px(-x), px(-y)],
image= images.length > 1 && images[row - 1]
image && t.css('backgroundImage').search(path+image) < 0 && t.css({ backgroundImage: url(path+image) })
}
t.css({ backgroundPosition: shift.join(___) })
}
},
// ### `imageChange` Event ######
// `Event`, since 1.2.2
//
// When `image` or `images` is changed on the fly, this handler resets the loading cache and triggers
// new preload sequence. Images are actually switched only after the new image is fully loaded.
//
'imageChange imagesChange': function(e, nil, image){
preloader.$.remove();
t.siblings(dot(cached_klass)).remove();
t.parent().bind(_preloaded_, on.instance.preloaded);
pool.bind(_tick_+dot(_preload_), on.pool[_tick_+dot(_preload_)]);
t.trigger('preload');
},
// ---------
// Indicator
// ---------
//
// When configured with the [`indicator`](#indicator-Option) option, Reel adds to the scene
// a visual indicator in a form of a black rectangle traveling along the bottom edge
// of the image. It bears two distinct messages:
//
// - its horizontal position accurately reflects actual `fraction`
// - and its width reflect one frame's share on the whole (more frames mean narrower
// indicator).
//
'fractionChange.indicator': function(e, deprecated_set, fraction){
if (deprecated_set === undefined && opt.indicator) var
space= get(_dimensions_),
size= opt.indicator,
orbital= opt.orbital,
travel= orbital && get(_vertical_) ? space.y : space.x,
slots= orbital ? opt.footage : opt.images.length || get(_frames_),
weight= ceil(travel / slots),
travel= travel - weight,
indicate= round(interpolate(fraction, 0, travel)),
indicate= !opt.cw || opt.stitched ? indicate : travel - indicate,
$indicator= indicator.$x.css(get(_vertical_)
? { left: 0, top: px(indicate), bottom: _auto_, width: size, height: weight }
: { bottom: 0, left: px(indicate), top: _auto_, width: weight, height: size })
},
// For multi-row object movies, there's a second indicator sticked to the left edge
// and communicates:
//
// - its vertical position accurately reflects actual `tier`
// - and its height reflect one row's share on the whole (more rows mean narrower
// indicator).
//
'tierChange.indicator': function(e, deprecated_set, tier){
if (deprecated_set === undefined && opt.rows > 1 && opt.indicator) var
space= get(_dimensions_),
travel= space.y,
slots= opt.rows,
size= opt.indicator,
weight= ceil(travel / slots),
travel= travel - weight,
indicate= round(tier * travel),
$yindicator= indicator.$y.css({ left: 0, top: indicate, width: size, height: weight })
},
// Indicators are bound to `fraction` or `row` changes, meaning they alone can consume
// more CPU resources than the entire Reel scene. Use them for development only.
//
// -----------------
// [NEW] Annotations
// -----------------
//
// If you want to annotate features of your scene to better describe the subject,
// there's annotations for you. Annotations feature allows you to place virtually any
// HTML content over or into the image and have its position and visibility synchronized
// with the position of Reel. These two easy looking handlers do a lot more than to fit
// in here.
//
// Learn more about [Annotations][1] in the wiki, where a great care has been taken
// to in-depth explain this new exciting functionality.
//
// [1]:https://github.com/pisi/Reel/wiki/Annotations
//
'setup.annotations': function(e){
var
space= get(_dimensions_),
$overlay= t.parent(),
film_css= { position: _absolute_, width: space.x, height: space.y, left: 0, top: 0 }
$.each(get(_annotations_), function(ida, note){
var
$note= typeof note.node == _string_ ? $(note.node) : note.node || {},
$note= $note.jquery ? $note : $(tag(_div_), $note),
$note= $note.attr({ id: ida }).addClass(annotation_klass),
$image= note.image ? $(tag(_img_), note.image) : $(),
$link= note.link ? $(tag('a'), note.link).click(function(){ t.trigger('up.annotations', { target: $link }); }) : $()
css(hash(ida), { display: _none_, position: _absolute_ }, true);
note.image || note.link && $note.append($link);
note.link || note.image && $note.append($image);
note.link && note.image && $note.append($link.append($image));
$note.appendTo($overlay);
});
},
'frameChange.annotations': function(e, deprecation, frame){
var
space= get(_dimensions_),
stitched= opt.stitched,
ss= get(_stitched_shift_)
if (!get(_preloaded_)) return;
if (deprecation === undefined) $.each(get(_annotations_), function(ida, note){
var
$note= $(hash(ida)),
start= note.start || 1,
end= note.end,
offset= frame - 1,
at= note.at ? (note.at[offset] == '+') : false,
offset= note.at ? offset : offset - start + 1,
x= typeof note.x!=_object_ ? note.x : note.x[offset],
y= typeof note.y!=_object_ ? note.y : note.y[offset],
placed= x !== undefined && y !== undefined,
visible= placed && (note.at ? at : (offset >= 0 && (!end || offset <= end - start)))
if (stitched) var
on_edge= x < space.x && ss > stitched - space.x,
after_edge= x > stitched - space.x && ss >= 0 && ss < space.x,
x= !on_edge ? x : x + stitched,
x= !after_edge ? x : x - stitched,
x= x - ss
var
style= { display: visible ? _block_:_none_, left: px(x), top: px(y) }
$note.css(style);
});
},
'up.annotations': function(e, ev){
if (panned > 10 || wheeled) return;
var
$target= $(ev.target),
$link= ($target.is('a') ? $target : $target.parents('a')),
href= $link.attr('href')
href && (panned= true);
},
// ---------------------------
// [NEW] Click Stepping Events
// ---------------------------
//
// For devices without drag support or for developers, who want to use some sort
// of left & right buttons on their site to control your instance from outside, Reel
// supports ordinary click with added detection of left half or right half and resulting
// triggering of `stepLeft` and `stepRight` events respectively.
//
// This behavior can be disabled by the [`steppable`](#steppable-Option) option.
//
'up.steppable': function(e, ev){
if (panned || wheeled) return;
t.trigger(get(_clicked_location_).x - t.offset().left > 0.5 * get(_dimensions_).x ? 'stepRight' : 'stepLeft')
},
'stepLeft stepRight': function(e){
unidle();
},
// ### `stepLeft` Event ######
// `Event`, since 1.2
//
stepLeft: function(e){
set(_backwards_, false);
set(_fraction_, get(_fraction_) - get(_bit_) * get(_cwish_));
},
// ### `stepRight` Event ######
// `Event`, since 1.2
//
stepRight: function(e){
set(_backwards_, true);
set(_fraction_, get(_fraction_) + get(_bit_) * get(_cwish_));
},
// ### `stepUp` Event ######
// `Event`, since 1.3
//
stepUp: function(e){
set(_row_, get(_row_) - 1);
},
// ### `stepDown` Event ######
// `Event`, since 1.3
//
stepDown: function(e){
set(_row_, get(_row_) + 1);
},
// ----------------
// Follow-up Events
// ----------------
//
// When some event as a result triggers another event, it preferably is not triggered
// directly, because it would disallow preventing the event propagation / chaining
// to happen. Instead a followup handler is bound to the first event and it triggers the
// second one.
//
'setup.fu': function(e){
var
frame= set(_frame_, opt.frame + (opt.row - 1) * get(_frames_))
t.trigger('preload')
},
'wheel.fu': function(){ wheeled= false },
'clean.fu': function(){ t.trigger('teardown') },
'loaded.fu': function(){ t.trigger('opening') }
},
// -------------
// Tick Handlers
// -------------
//
// As opposed to the events bound to the instance itself, there is a [ticker](#Ticker)
// in place, which emits `tick.reel` event on the document level by default every 1/36
// of a second and drives all the animations. Three handlers currently bind each instance
// to the tick.
//
pool: {
// This handler has a responsibility of continuously updating the preloading indicator
// until all images are loaded and to unbind itself then.
//
'tick.reel.preload': function(e){
var
space= get(_dimensions_),
current= number(preloader.$.css(_width_)),
images= get(_images_).length || 1,
target= round(1 / images * get(_preloaded_) * space.x)
preloader.$.css({ width: current + (target - current) / 3 + 1 })
if (get(_preloaded_) === images && current > space.x - 1){
preloader.$.fadeOut(300, function(){ preloader.$.remove() });
pool.unbind(_tick_+dot(_preload_), on.pool[_tick_+dot(_preload_)]);
}
},
// This handler binds to the document's ticks at all times, regardless the situation.
// It serves several tasks:
//
// - keeps track of how long the instance is being operated by the user,
// - or for how long it is braking the velocity inertia,
// - decreases gained velocity by applying power of the [`brake`](#brake-Option) option,
// - flags the instance as `slidable` again, so that `pan` event handler can be executed
// again,
// - updates the [`monitor`](#monitor-Option) value,
// - bounces off the edges for non-looping panoramas,
// - and most importantly it animates the Reel if [`speed`](#speed-Option) is configured.
//
'tick.reel': function(e){
var
velocity= get(_velocity_),
leader_tempo= leader(_tempo_),
monitor= opt.monitor
if (!reel.intense && offscreen()) return mute(e);
if (braking) var
braked= velocity - (get(_brake_) / leader_tempo * braking),
velocity= set(_velocity_, braked > 0.1 ? braked : (braking= operated= 0))
monitor && $monitor.text(get(monitor));
velocity && braking++;
operated && operated++;
to_bias(0);
slidable= true;
if (operated && !velocity) return mute(e);
if (get(_clicked_)) return mute(e, unidle());
if (get(_opening_ticks_) > 0) return;
if (!opt.loops && opt.rebound) var
edgy= !operated && !(get(_fraction_) % 1) ? on_edge++ : (on_edge= 0),
bounce= on_edge >= opt.rebound * 1000 / leader_tempo,
backwards= bounce && set(_backwards_, !get(_backwards_))
var
direction= get(_cwish_) * negative_when(1, get(_backwards_)),
ticks= get(_ticks_),
step= (!get(_playing_) || !ticks ? velocity : abs(get(_speed_)) + velocity) / leader(_tempo_),
fraction= set(_fraction_, get(_fraction_) - step * direction),
ticks= !opt.duration ? ticks : ticks > 0 && set(_ticks_, ticks - 1)
!ticks && get(_playing_) && t.trigger('stop');
},
// This handler performs the opening animation duty when during it the normal animation
// is halted until the opening finishes.
//
'tick.reel.opening': function(e){
if (!get(_opening_)) return;
var
speed= opt.entry || opt.speed,
step= speed / leader(_tempo_) * (opt.cw? -1:1),
ticks= set(_opening_ticks_, get(_opening_ticks_) - 1),
fraction= set(_fraction_, get(_fraction_) + step)
ticks || t.trigger('openingDone');
}
}
},
// ------------------------
// Instance Private Helpers
// ------------------------
//
// - Events propagation stopper / muter
//
mute= function(e, result){ return e.stopImmediatePropagation() || result },
// - User idle control
//
operated,
braking= 0,
idle= function(){ return operated= 0 },
unidle= function(){
clearTimeout(delay);
pool.unbind(_tick_+dot(_opening_), on.pool[_tick_+dot(_opening_)]);
set(_opening_ticks_, 0);
set(_reeled_, true);
return operated= -opt.timeout * leader(_tempo_)
},
panned= 0,
wheeled= false,
delay, // openingDone's delayed play pointer
// - Constructors of UI elements
//
$monitor= $(),
preloader= function(){
var
size= opt.preloader
css(___+dot(preloader_klass), {
position: _absolute_,
left: 0, top: get(_dimensions_).y - size,
height: size,
overflow: _hidden_,
backgroundColor: '#000'
});
return preloader.$= $(tag(_div_), { 'class': preloader_klass })
},
indicator= function(axis){
css(___+dot(indicator_klass)+dot(axis), {
position: _absolute_,
width: 0, height: 0,
overflow: _hidden_,
backgroundColor: '#000'
});
return indicator['$'+axis]= $(tag(_div_), { 'class': indicator_klass+___+axis })
},
// - CSS rules & stylesheet
//
css= function(selector, definition, global){
var
stage= global ? __ : get(_stage_),
selector= selector.replace(/^/, stage).replace(____, ____+stage)
return css.rules.push(selector+cssize(definition)) && definition
function cssize(values){
var rules= [];
$.each(values, function(key, value){ rules.push(key.replace(/([A-Z])/g, '-$1').toLowerCase()+':'+px(value)+';') });
return '{'+rules.join(__)+'}'
}
},
$style,
// - Off screen detection (vertical only for performance)
//
offscreen= function(){
var
height= get(_dimensions_).y,
rect= t[0].getBoundingClientRect()
return rect.top < -height ||
rect.bottom > height + $(window).height()
},
// - Inertia rotation control
//
on_edge= 0,
last= { x: 0, y: 0 },
to_bias= function(value){ return bias.push(value) && bias.shift() && value },
no_bias= function(){ return bias= [0,0] },
bias= no_bias(),
// - Graph function to be used
//
graph= opt.graph || reel.math[opt.loops ? 'hatch' : 'envelope'],
normal= reel.normal,
// - Interaction graph's zero point reset
//
recenter_mouse= function(revolution, x, y){
var
fraction= set(_clicked_on_, get(_fraction_)),
tier= set(_clicked_tier_, get(_tier_)),
loops= opt.loops
set(_lo_, loops ? 0 : - fraction * revolution);
set(_hi_, loops ? revolution : revolution - fraction * revolution);
return x && set(_clicked_location_, { x: x, y: y }) || undefined
},
slidable= true,
// ~~~
//
// Global events are bound to the pool (`document`), but to make it work inside an `<iframe>`
// we need to bind to the parent document too to maintain the dragging even outside the area
// of the `<iframe>`.
//
pools= pool
try{ if (pool[0] != top.document) pools= pool.add(top.document) }
catch(e){}
// A private flag `$iframe` is established to indicate Reel being viewed inside `<iframe>`.
//
var
$iframe= top === self ? $() : (function sense_iframe($ifr){
$('iframe', pools.last()).each(function(){
try{ if ($(this).contents().find(_head_).html() == $(_head_).html()) return ($ifr= $(this)) && false }
catch(e){}
})
return $ifr
})()
css.rules= [];
on.setup();
});
// ~~~
//
// Reel maintains a ticker, which guides all animations. There's only one ticker per document
// and all instances bind to it. Ticker's mechanism measures and compares times before and after
// the `tick.reel` event trigger to estimate the time spent on executing `tick.reel`'s handlers.
// The actual timeout time is then adjusted by the amount to run as close to expected tempo
// as possible.
//
ticker= ticker || (function tick(){
var
start= +new Date(),
tempo= leader(_tempo_)
if (!tempo) return ticker= null;
pool.trigger(_tick_);
reel.cost= (+new Date() + reel.cost - start) / 2;
return ticker= setTimeout(tick, max(4, 1000 / tempo - reel.cost));
})();
return $(instances);
}else{
// ----
// Data
// ----
//
// Reel stores all its inner state values with the standard DOM [data interface][1] interface
// while adding an additional change-detecting event layer, which makes Reel entirely data-driven.
//
// [1]:http://api.jquery.com/data
//
// _**Example:** Find out on what frame a Reel instance currently is:_
//
// .reel('frame') // Returns the frame number
//
// Think of `.reel()` as a synonym for `.data()`. Note, that you can therefore easily inspect
// the entire datastore with `.data()` (without arguments). Use it for debugging only.
// For real-time data watch use [`monitor`](#Monitor) option instead of manually hooking into
// the data.
//
// ---
// #### `.reel( name )` ######
// can return anything, since 1.2
//
if (typeof name == 'string'){
if (args.length == 1){
var
value= data[name]
t.trigger('recall', [name, value]);
return value;
}
// ### Write Access ###
//
// You can store any value the very same way by passing the value as the second function
// argument.
//
// _**Example:** Jump to frame 12:_
//
// .reel('frame', 12)
//
// Only a handful of data keys is suitable for external manipulation. These include `area`,
// `backwards`, `brake`, __`fraction`__, __`frame`__, `playing`, `reeling`, __`row`__, `speed`,
// `stopped`, `velocity` and `vertical`. Use the rest of the keys for reading only, you can
// mess up easily changing them.
//
// ---
// #### `.reel( name, value )` ######
// returns `jQuery`, since 1.2
//
else{
if (value !== undefined){
reel.normal[name] && (value= reel.normal[name](value, data));
// ### Changes ######
//
// Any value that does not equal (`===`) the old value is considered _new value_ and
// in such a case Reel will trigger a _change event_ to announce the change. The event
// type takes form of _`key`_`Change`, where _`key`_ will be the data key/name you've
// just assigned.
//
// _**Example:** Setting `"frame"` to `12` in the above example will trigger
// `"frameChange"`._
//
// Some of these _change events_ (like `frame` or `fraction`) have a
// default handler attached.
//
// You can easily bind to any of the data key change with standard event
// binding methods.
//
// _**Example:** React on instance being manipulated or not:_
//
// .bind('reelingChange', function(evnt, nothing, reeling){
// if (reeling) console.log('Rock & reel!')
// else console.log('Not reeling...')
// })
//
// ---
// The handler function will be executed every time the value changes and
// it will be supplied with three arguments. First one is the event object
// as usual, second is `undefined` and the third will be the actual value.
// In this case it was a boolean type value.
// If the second argument is not `undefined` it is the backward compatible
// "before" event triggered from outside Reel.
//
if (data[name] === undefined) data[name]= value
else if (data[name] !== value) t.trigger(name+'Change', [ undefined, data[name]= value ]);
}
return t.trigger('store', [name, value]);
}
}
}
},
// -----------
// Destruction
// -----------
//
// The evil-twin of `.reel()`. Tears down and wipes off entire instance.
//
// ---
// ### `.unreel()` Method ######
// returns `jQuery`, since 1.2
//
unreel: function(){
return this.trigger('teardown');
}
},
// -------------------
// Regular Expressions
// -------------------
//
// Few regular expressions is used here and there mostly for options validation and verification
// levels of user agent's capabilities.
//
// ---
// ### `$.reel.re` ######
// `RegExp`, since 1.1
//
re: {
/* Valid image file format */
image: /^(.*)\.(jpg|jpeg|png|gif)\??.*$/i,
/* User agent failsafe stack */
ua: [
/(msie|opera|firefox|chrome|safari)[ \/:]([\d.]+)/i,
/(webkit)\/([\d.]+)/i,
/(mozilla)\/([\d.]+)/i
],
/* Array in a string (comma-separated values) */
array: / *, */,
/* Multi touch devices */
touchy_agent: /iphone|ipod|ipad|android|fennec|rim tablet/i,
/* Lazy (low-CPU mobile devices) */
lazy_agent: /\(iphone|ipod|android|fennec|blackberry/i,
/* Format of frame class flag on the instance */
frame_klass: /frame-\d+/,
/* [Sequence](#Sequence) string format */
sequence: /(^[^#|]*([#]+)[^#|]*)($|[|]([0-9]+)\.\.([0-9]+))($|[|]([0-9]+)$)/
},
// ------------------------
// Content Delivery Network
// ------------------------
//
// [CDN][1] is used for distributing mouse cursors to all instances running world-wide. It runs
// on Google cloud infrastructure. If you want to ease up on the servers, please consider setting up
// your own location with the cursors.
//
// [1]:https://github.com/pisi/Reel/wiki/CDN
//
// ---
// ### `$.reel.cdn` ######
// `String` (URL path), since 1.1
//
cdn: 'http://code.vostrel.net/',
// -----------
// Math Behind
// -----------
//
// Surprisingly there's very little math behind Reel, just two equations (graph functions). These two
// functions receive the same set of options.
//
// ---
// ### `$.reel.math` ######
// `Object`, since 1.1
//
math: {
// 1 | ********
// | **
// | **
// | **
// | **
// | ********
// 0 ----------------------------›
//
envelope: function(x, start, revolution, lo, hi, cwness, y){
return start + min_max(lo, hi, - x * cwness) / revolution
},
// 1 | ** **
// | ** **
// | ** **
// | ** **
// | ** **
// | ** **
// 0 ----------------------------›
//
hatch: function(x, start, revolution, lo, hi, cwness, y){
var
x= (x < lo ? hi : 0) + x % hi, // Looping
fraction= start + (- x * cwness) / revolution
return fraction - floor(fraction)
},
// And an equation for interpolating `fraction` (and `tier`) value into `frame` and `row`.
//
interpolate: function(fraction, lo, hi){
return lo + fraction * (hi - lo)
}
},
// ----------------
// Preloading Modes
// ----------------
//
// Reel doesn't load frames in a linear manner from first to last (alhough it can if configured
// that way with the [`preload`](#preload-Option) option). Reel will take the linear configured
// sequence and hand it over to one of `$.reel.preload` functions, along with reference to options
// and the RO data intearface, and it expects the function to reorder the incoming Array and return
// it back.
//
// ---
// ### `$.reel.preload` ######
// `Object`, since 1.2
//
preload: {
// The best (and default) option is the `fidelity` processor, which is designed for a faster and
// better perceived loading.
//
// 
//
fidelity: function(sequence, opt, get){
var
orbital= opt.orbital,
rows= orbital ? 2 : opt.rows || 1,
frames= orbital ? opt.footage : get(_frames_),
start= (opt.row-1) * frames,
values= new Array().concat(sequence),
present= new Array(sequence.length + 1),
priority= rows < 2 ? [] : values.slice(start, start + frames)
return spread(priority, 1, start).concat(spread(values, rows, 0))
function spread(sequence, rows, offset){
if (!sequence.length) return [];
var
order= [],
passes= 4 * rows,
start= opt.frame,
frames= sequence.length,
plus= true,
granule= frames / passes
for(var i= 0; i < passes; i++)
add(start + round(i * granule));
while(granule > 1)
for(var i= 0, length= order.length, granule= granule / 2, p= plus= !plus; i < length; i++)
add(order[i] + (plus? 1:-1) * round(granule));
for(var i=0; i <= frames; i++) add(i);
for(var i= 0; i < order.length; i++)
order[i]= sequence[order[i] - 1];
return order
function add(frame){
while(!(frame >= 1 && frame <= frames))
frame+= frame < 1 ? +frames : -frames;
return present[offset + frame] || (present[offset + frame]= !!order.push(frame))
}
}
},
// You can opt for a `linear` loading order too, but that has a drawback of leaving large gap
// of unloaded frames.
//
linear: function(sequence, opt, get){
return sequence
}
},
// ------------------------
// Data Value Normalization
// ------------------------
//
// On all data values being stored with `.reel()` an attempt is made to normalize the value. Like
// for example normalization of frame `55` when there's just `45` frames total. These are the built-in
// normalizations. Normalization function has the same name as the data key it is assigned to
// and is given the raw value in arguments, along with reference to the instances data object,
// and it has to return the normalized value.
//
// ---
// ### `$.reel.normal` ######
// `Object`, since 1.2
//
normal: {
fraction: function(fraction, data){
if (fraction === null) return fraction;
return data[_options_].loops ? fraction - floor(fraction) : min_max(0, 1, fraction)
},
tier: function(tier, data){
if (tier === null) return tier;
return min_max(0, 1, tier)
},
row: function(row, data){
if (row === null) return row;
return round(min_max(1, data[_options_].rows, row))
},
frame: function(frame, data){
if (frame === null) return frame;
var
opt= data[_options_],
frames= data[_frames_] * (opt.orbital ? 2 : opt.rows || 1),
result= round(opt.loops ? frame % frames || frames : min_max(1, frames, frame))
return result < 0 ? result + frames : result
},
images: function(images, data){
var
sequence= reel.re.sequence.exec(images),
result= !sequence ? images : reel.sequence(sequence, data[_options_])
return result;
}
},
// -----------------
// Sequence Build-up
// -----------------
//
// When configured with a String value for [`images`](#images-Option) like `image##.jpg`, it first has
// to be converted into an actual Array by engaging the counter placeholder.
//
// ---
// ### `$.reel.sequence()` ######
// `Function`, since 1.2
//
sequence: function(sequence, opt){
if (sequence.length <= 1) return opt.images;
var
images= [],
orbital= opt.orbital,
url= sequence[1],
placeholder= sequence[2],
start= +sequence[4] || 1,
rows= orbital ? 2 : opt.rows || 1,
frames= orbital ? opt.footage : opt.stitched ? 1 : opt.frames,
end= +(sequence[5] || rows * frames),
total= end - start,
increment= +sequence[7] || 1,
counter= 0
while(counter <= total){
images.push(url.replace(placeholder, pad((start + counter + __), placeholder.length, '0')));
counter+= increment;
}
return images;
},
// --------------
// Reel Instances
// --------------
//
// `$.reel.instances` holds an inventory of all running instances in the DOM document.
//
// ---
// ### `$.reel.instances` ######
// `jQuery`, since 1.1
//
instances: $(),
// For ticker-synchronization-related purposes Reel maintains a reference to the leaders data object
// all the time.
//
// ---
// ### `$.reel.leader` ######
// `Object` (DOM data), since 1.1
//
leader: leader,
// `$.reel.cost` holds document-wide costs in miliseconds of running all Reel instances. It is used
// to adjust actual timeout of the ticker.
//
// ---
// ### `$.reel.cost` ######
// `Number`, since 1.1
//
cost: 0
},
// ------------------------
// Private-scoped Variables
// ------------------------
//
pool= $(document),
client= navigator.userAgent,
browser= reel.re.ua[0].exec(client) || reel.re.ua[1].exec(client) || reel.re.ua[2].exec(client),
browser_version= +browser[2].split('.').slice(0,2).join('.'),
ie= browser[1] == 'MSIE',
knows_data_urls= !(ie && browser_version < 8),
ticker,
// ---------------
// CSS Class Names
// ---------------
//
// These are all the class names assigned by Reel to various DOM elements during initialization of the UI
// and they all share same base `"reel"`, which in isolation also is the class of the `<img>` node you
// converted into Reel.
//
klass= 'reel',
// Rest of the class names only extend this base class forming for example `.reel-overlay`, a class
// assigned to the outter instance wrapper (`<img>`'s injected parent).
//
overlay_klass= klass + '-overlay',
indicator_klass= klass + '-indicator',
preloader_klass= klass + '-preloader',
cached_klass= klass + '-cached',
monitor_klass= klass + '-monitor',
annotation_klass= klass + '-annotation',
panning_klass= klass + '-panning',
loading_klass= klass + '-loading',
// The instance wrapper is flagged with actual frame number using a this class.
//
// _**Example:** Reel on frame 10 will carry a class name `frame-10`._
//
frame_klass= 'frame-',
// --------------------------------
// Shortcuts And Minification Cache
// --------------------------------
//
// Several math functions are referenced inside the private scope to yield smaller filesize
// when the code is minified.
//
math= Math,
round= math.round, floor= math.floor, ceil= math.ceil,
min= math.min, max= math.max, abs= math.abs,
number= parseInt,
interpolate= reel.math.interpolate,
// For the very same reason all storage key Strings are cached into local vars.
//
_annotations_= 'annotations',
_area_= 'area', _auto_= 'auto', _backup_= 'backup', _backwards_= 'backwards', _bit_= 'bit', _brake_= 'brake', _cached_= 'cached', _center_= 'center',
_clicked_= 'clicked', _clicked_location_= 'clicked_location', _clicked_on_= 'clicked_on', _clicked_tier_= 'clicked_tier',
_cwish_= 'cwish', _dimensions_= 'dimensions', _fraction_= 'fraction', _frame_= 'frame',
_frames_= 'frames', _hi_= 'hi', _hidden_= 'hidden', _image_= 'image', _images_= 'images', _opening_= 'opening', _opening_ticks_= _opening_+'_ticks',
_lo_= 'lo', _options_= 'options', _playing_= 'playing', _preloaded_= 'preloaded', _reeling_= 'reeling', _reeled_= 'reeled', _revolution_= 'revolution',
_revolution_y_= 'revolution_y', _row_= 'row', _rows_= 'rows', _spacing_= 'spacing', _speed_= 'speed', _stage_= 'stage',
_stitched_shift_= 'stitched_shift', _stitched_travel_= 'stitched_travel', _stopped_= 'stopped', _style_= 'style', _tempo_= 'tempo', _ticks_= 'ticks',
_tier_= 'tier', _velocity_= 'velocity', _vertical_= 'vertical',
// And the same goes for browser events too.
//
ns= dot(klass),
pns= dot('pan') + ns,
_touch_= 'touch', _mouse_= 'mouse', _dragstart_= 'dragstart'+ns,
_mousedown_= _mouse_+'down'+ns, _mouseenter_= _mouse_+'enter'+ns,
_mouseleave_= _mouse_+'leave'+pns, _mousemove_= _mouse_+'move'+pns, _mouseup_= _mouse_+'up'+pns,
_mousewheel_= _mouse_+'wheel'+ns, _tick_= 'tick'+ns, _touchcancel_= _touch_+'cancel'+pns,
_touchend_= _touch_+'end'+pns, _touchstart_= _touch_+'start'+ns, _touchmove_= _touch_+'move'+pns,
// And some other frequently used Strings.
//
__= '', ___= ' ', ____=',', _absolute_= 'absolute', _block_= 'block', _cdn_= '@CDN@', _div_= 'div',
_hand_= 'hand', _head_= 'head', _height_= 'height', _html_= 'html', _id_= 'id',
_img_= 'img', _jquery_reel_= 'jquery.'+klass, _move_= 'move', _none_= 'none', _object_= 'object',
_preload_= 'preload', _string_= 'string',
_width_= 'width',
// ---------------
// Image Resources
// ---------------
//
// Alhough we do what we can to hide the fact, Reel actually needs a few image resources to support
// some of its actions. First, we may need a transparent image for the original `<img>` to uncover
// the sprite applied to its background. This one is embedded in the code as it is very small.
//
transparent= knows_data_urls ? embedded('CAAIAIAAAAAAAAAAACH5BAEAAAAALAAAAAAIAAgAAAIHhI+py+1dAAA7') : _cdn_+'blank.gif',
// Proper cross-browser cursors however need to come in an odd format, which essentially is not
// compressed at all and this means bigger filesize. While it is no more than ~15k, it is unfit
// for embedding directly here, so a [`CDN`](#Content-Delivery-Network) is employed to retrieve
// the images from in an effective gzipped and cachable manner.
//
reel_cursor= url(_cdn_+_jquery_reel_+'.cur')+____+_move_,
drag_cursor= url(_cdn_+_jquery_reel_+'-drag.cur')+____+_move_,
drag_cursor_down= url(_cdn_+_jquery_reel_+'-drag-down.cur')+____+_move_,
// ~~~
//
// We then only identify the user's browser's capabilities and route around a MSIE's left button
// identification quirk (IE 8- reports left as right).
//
touchy= reel.touchy= (reel.re.touchy_agent).test(client),
lazy= reel.lazy= (reel.re.lazy_agent).test(client),
DRAG_BUTTON= touchy ? undefined : (ie && browser_version < 9) ? 1 : 0,
// ~~~
//
// So far jQuery doesn't have a proper built-in mechanism to detect/report DOM node removal.
// But internally, jQuery calls `$.cleanData()` to flush the DOM data and minimize memory leaks.
// Reel wraps this function and as a result `clean` event handler is triggered for every element.
// Note, that the `clean` event does not bubble.
//
cleanData= $.cleanData,
cleanDataEvent= $.cleanData= function(elements){
cleanData($(elements).each(function(){ $(this).triggerHandler('clean'); }));
}
// Expose plugin functions as jQuery methods, do the initial global scan for data-configured
// `<img`> tags to become enhanced and export the entire namespace module.
//
$.extend($.fn, reel.fn) && $(reel.scan);
return reel;
// Bunch of very useful helpers.
//
function add_instance($instance){ return (reel.instances.push($instance[0])) && $instance }
function remove_instance($instance){ return (reel.instances= reel.instances.not(hash($instance.attr(_id_)))) && $instance }
function leader(key){ return reel.instances.first().data(key) }
function embedded(image){ return 'data:image/gif;base64,R0lGODlh' + image }
function tag(string){ return '<' + string + '/>' }
function dot(string){ return '.' + (string || '') }
function cdn(path){ return path.replace(_cdn_, reel.cdn) }
function url(location){ return 'url(\'' + reen(location) + '\')' }
function axis(key, value){ return typeof value == _object_ ? value[key] : value }
function min_max(minimum, maximum, number){ return max(minimum, min(maximum, number)) }
function negative_when(value, condition){ return abs(value) * (condition ? -1 : 1) }
function finger(e){ return touchy ? e.touch || e.originalEvent.touches[0] : e }
function px(value){ return value === undefined ? 0 : typeof value == _string_ ? value : value + 'px' }
function hash(value){ return '#' + value }
function pad(string, len, fill){ while (string.length < len) string= fill + string; return string }
function reen(uri){ return encodeURI(decodeURI(uri)) }
function soft_array(string){ return reel.re.array.exec(string) ? string.split(reel.re.array) : string }
function numerize_array(array){ return typeof array == _string_ ? array : $.each(array, function(ix, it){ array[ix]= it ? +it : undefined }) }
function deprecated(input){ try{ console.warn('Deprecation - Please consult https://github.com/pisi/Reel/wiki/Deprecations') }catch(e){} return input }
})(jQuery, window, document);
});
| Private `panned` should always be a number
| jquery.reel.js | Private `panned` should always be a number | <ide><path>query.reel.js
<ide> $target= $(ev.target),
<ide> $link= ($target.is('a') ? $target : $target.parents('a')),
<ide> href= $link.attr('href')
<del> href && (panned= true);
<add> href && (panned= 10);
<ide> },
<ide>
<ide> // --------------------------- |
|
Java | bsd-2-clause | d11bdf66f0a97524510e1104b931fc6b42086317 | 0 | runelite/runelite,runelite/runelite,Sethtroll/runelite,runelite/runelite,Sethtroll/runelite | /*
* Copyright (c) 2017, Seth <[email protected]>
* Copyright (c) 2018, Jordan Atwood <[email protected]>
* Copyright (c) 2019, winterdaze
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.timers;
import com.google.inject.Provides;
import java.time.Duration;
import java.time.Instant;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Actor;
import net.runelite.api.AnimationID;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.Constants;
import net.runelite.api.EquipmentInventorySlot;
import net.runelite.api.GameState;
import net.runelite.api.InventoryID;
import net.runelite.api.Item;
import net.runelite.api.ItemContainer;
import net.runelite.api.ItemID;
import static net.runelite.api.ItemID.FIRE_CAPE;
import static net.runelite.api.ItemID.INFERNAL_CAPE;
import net.runelite.api.NPC;
import net.runelite.api.NpcID;
import net.runelite.api.Player;
import net.runelite.api.VarPlayer;
import net.runelite.api.Varbits;
import net.runelite.api.WorldType;
import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.ActorDeath;
import net.runelite.api.events.AnimationChanged;
import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick;
import net.runelite.api.events.GraphicChanged;
import net.runelite.api.events.ItemContainerChanged;
import net.runelite.api.events.MenuOptionClicked;
import net.runelite.api.events.NpcDespawned;
import net.runelite.api.events.VarbitChanged;
import net.runelite.api.events.WidgetHiddenChanged;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetID;
import net.runelite.api.widgets.WidgetInfo;
import static net.runelite.api.widgets.WidgetInfo.PVP_WORLD_SAFE_ZONE;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.events.ConfigChanged;
import net.runelite.client.game.ItemManager;
import net.runelite.client.game.SpriteManager;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import static net.runelite.client.plugins.timers.GameIndicator.VENGEANCE_ACTIVE;
import static net.runelite.client.plugins.timers.GameTimer.*;
import net.runelite.client.ui.overlay.infobox.InfoBoxManager;
import org.apache.commons.lang3.ArrayUtils;
@PluginDescriptor(
name = "Timers",
description = "Show various timers in an infobox",
tags = {"combat", "items", "magic", "potions", "prayer", "overlay", "abyssal", "sire", "inferno", "fight", "caves", "cape", "timer", "tzhaar"}
)
@Slf4j
public class TimersPlugin extends Plugin
{
private static final String ANTIFIRE_DRINK_MESSAGE = "You drink some of your antifire potion.";
private static final String ANTIFIRE_EXPIRED_MESSAGE = "<col=7f007f>Your antifire potion has expired.</col>";
private static final String CANNON_FURNACE_MESSAGE = "You add the furnace.";
private static final String CANNON_PICKUP_MESSAGE = "You pick up the cannon. It's really heavy.";
private static final String CANNON_REPAIR_MESSAGE = "You repair your cannon, restoring it to working order.";
private static final String CHARGE_EXPIRED_MESSAGE = "<col=ef1020>Your magical charge fades away.</col>";
private static final String CHARGE_MESSAGE = "<col=ef1020>You feel charged with magic power.</col>";
private static final String EXTENDED_ANTIFIRE_DRINK_MESSAGE = "You drink some of your extended antifire potion.";
private static final String EXTENDED_SUPER_ANTIFIRE_DRINK_MESSAGE = "You drink some of your extended super antifire potion.";
private static final String FROZEN_MESSAGE = "<col=ef1020>You have been frozen!</col>";
private static final String GAUNTLET_ENTER_MESSAGE = "You enter the Gauntlet.";
private static final String GOD_WARS_ALTAR_MESSAGE = "you recharge your prayer.";
private static final String IMBUED_HEART_READY_MESSAGE = "<col=ef1020>Your imbued heart has regained its magical power.</col>";
private static final String MAGIC_IMBUE_EXPIRED_MESSAGE = "Your Magic Imbue charge has ended.";
private static final String MAGIC_IMBUE_MESSAGE = "You are charged to combine runes!";
private static final String STAFF_OF_THE_DEAD_SPEC_EXPIRED_MESSAGE = "Your protection fades away";
private static final String STAFF_OF_THE_DEAD_SPEC_MESSAGE = "Spirits of deceased evildoers offer you their protection";
private static final String STAMINA_DRINK_MESSAGE = "You drink some of your stamina potion.";
private static final String STAMINA_SHARED_DRINK_MESSAGE = "You have received a shared dose of stamina potion.";
private static final String STAMINA_EXPIRED_MESSAGE = "<col=8f4808>Your stamina potion has expired.</col>";
private static final String SUPER_ANTIFIRE_DRINK_MESSAGE = "You drink some of your super antifire potion";
private static final String SUPER_ANTIFIRE_EXPIRED_MESSAGE = "<col=7f007f>Your super antifire potion has expired.</col>";
private static final String KILLED_TELEBLOCK_OPPONENT_TEXT = "Your Tele Block has been removed because you killed ";
private static final String PRAYER_ENHANCE_EXPIRED = "<col=ff0000>Your prayer enhance effect has worn off.</col>";
private static final String ENDURANCE_EFFECT_MESSAGE = "Your Ring of endurance doubles the duration of your stamina potion's effect.";
private static final Pattern TELEBLOCK_PATTERN = Pattern.compile("A Tele Block spell has been cast on you(?: by .+)?\\. It will expire in (?<mins>\\d+) minutes?(?:, (?<secs>\\d+) seconds?)?\\.");
private static final Pattern DIVINE_POTION_PATTERN = Pattern.compile("You drink some of your divine (.+) potion\\.");
private static final int VENOM_VALUE_CUTOFF = -40; // Antivenom < -40 <= Antipoison < 0
private static final int POISON_TICK_LENGTH = 30;
static final int FIGHT_CAVES_REGION_ID = 9551;
static final int INFERNO_REGION_ID = 9043;
private static final Pattern TZHAAR_WAVE_MESSAGE = Pattern.compile("Wave: (\\d+)");
private static final String TZHAAR_DEFEATED_MESSAGE = "You have been defeated!";
private static final Pattern TZHAAR_COMPLETE_MESSAGE = Pattern.compile("Your (TzTok-Jad|TzKal-Zuk) kill count is:");
private static final Pattern TZHAAR_PAUSED_MESSAGE = Pattern.compile("The (Inferno|Fight Cave) has been paused. You may now log out.");
private TimerTimer freezeTimer;
private int freezeTime = -1; // time frozen, in game ticks
private TimerTimer staminaTimer;
private boolean wasWearingEndurance;
private int lastRaidVarb;
private int lastWildernessVarb;
private int lastVengCooldownVarb;
private int lastIsVengeancedVarb;
private int lastPoisonVarp;
private int nextPoisonTick;
private WorldPoint lastPoint;
private TeleportWidget lastTeleportClicked;
private int lastAnimation;
private boolean loggedInRace;
private boolean widgetHiddenChangedOnPvpWorld;
private ElapsedTimer tzhaarTimer;
@Inject
private ItemManager itemManager;
@Inject
private SpriteManager spriteManager;
@Inject
private Client client;
@Inject
private TimersConfig config;
@Inject
private InfoBoxManager infoBoxManager;
@Provides
TimersConfig getConfig(ConfigManager configManager)
{
return configManager.getConfig(TimersConfig.class);
}
@Override
protected void shutDown() throws Exception
{
infoBoxManager.removeIf(t -> t instanceof TimerTimer);
lastRaidVarb = -1;
lastPoint = null;
lastTeleportClicked = null;
lastAnimation = -1;
loggedInRace = false;
widgetHiddenChangedOnPvpWorld = false;
lastPoisonVarp = 0;
nextPoisonTick = 0;
removeTzhaarTimer();
staminaTimer = null;
}
@Subscribe
public void onVarbitChanged(VarbitChanged event)
{
int raidVarb = client.getVar(Varbits.IN_RAID);
int vengCooldownVarb = client.getVar(Varbits.VENGEANCE_COOLDOWN);
int isVengeancedVarb = client.getVar(Varbits.VENGEANCE_ACTIVE);
int poisonVarp = client.getVar(VarPlayer.POISON);
if (lastRaidVarb != raidVarb)
{
removeGameTimer(OVERLOAD_RAID);
removeGameTimer(PRAYER_ENHANCE);
lastRaidVarb = raidVarb;
}
if (lastVengCooldownVarb != vengCooldownVarb && config.showVengeance())
{
if (vengCooldownVarb == 1)
{
createGameTimer(VENGEANCE);
}
else
{
removeGameTimer(VENGEANCE);
}
lastVengCooldownVarb = vengCooldownVarb;
}
if (lastIsVengeancedVarb != isVengeancedVarb && config.showVengeanceActive())
{
if (isVengeancedVarb == 1)
{
createGameIndicator(VENGEANCE_ACTIVE);
}
else
{
removeGameIndicator(VENGEANCE_ACTIVE);
}
lastIsVengeancedVarb = isVengeancedVarb;
}
int inWilderness = client.getVar(Varbits.IN_WILDERNESS);
if (lastWildernessVarb != inWilderness
&& client.getGameState() == GameState.LOGGED_IN
&& !loggedInRace)
{
if (!WorldType.isPvpWorld(client.getWorldType())
&& inWilderness == 0)
{
log.debug("Left wilderness in non-PVP world, clearing Teleblock timer.");
removeGameTimer(TELEBLOCK);
}
lastWildernessVarb = inWilderness;
}
if (lastPoisonVarp != poisonVarp && config.showAntiPoison())
{
final int tickCount = client.getTickCount();
if (nextPoisonTick - tickCount <= 0 || lastPoisonVarp == 0)
{
nextPoisonTick = tickCount + POISON_TICK_LENGTH;
}
if (poisonVarp >= 0)
{
removeGameTimer(ANTIPOISON);
removeGameTimer(ANTIVENOM);
}
else if (poisonVarp >= VENOM_VALUE_CUTOFF)
{
Duration duration = Duration.ofMillis((long) Constants.GAME_TICK_LENGTH * (nextPoisonTick - tickCount + Math.abs((poisonVarp + 1) * POISON_TICK_LENGTH)));
removeGameTimer(ANTIVENOM);
createGameTimer(ANTIPOISON, duration);
}
else
{
Duration duration = Duration.ofMillis((long) Constants.GAME_TICK_LENGTH * (nextPoisonTick - tickCount + Math.abs((poisonVarp + 1 - VENOM_VALUE_CUTOFF) * POISON_TICK_LENGTH)));
removeGameTimer(ANTIPOISON);
createGameTimer(ANTIVENOM, duration);
}
lastPoisonVarp = poisonVarp;
}
}
@Subscribe
public void onWidgetHiddenChanged(WidgetHiddenChanged event)
{
Widget widget = event.getWidget();
if (WorldType.isPvpWorld(client.getWorldType())
&& WidgetInfo.TO_GROUP(widget.getId()) == WidgetID.PVP_GROUP_ID)
{
widgetHiddenChangedOnPvpWorld = true;
}
}
@Subscribe
public void onConfigChanged(ConfigChanged event)
{
if (!config.showHomeMinigameTeleports())
{
removeGameTimer(HOME_TELEPORT);
removeGameTimer(MINIGAME_TELEPORT);
}
if (!config.showAntiFire())
{
removeGameTimer(ANTIFIRE);
removeGameTimer(EXANTIFIRE);
removeGameTimer(SUPERANTIFIRE);
}
if (!config.showStamina())
{
removeGameTimer(STAMINA);
}
if (!config.showOverload())
{
removeGameTimer(OVERLOAD);
removeGameTimer(OVERLOAD_RAID);
}
if (!config.showPrayerEnhance())
{
removeGameTimer(PRAYER_ENHANCE);
}
if (!config.showDivine())
{
removeGameTimer(DIVINE_SUPER_ATTACK);
removeGameTimer(DIVINE_SUPER_STRENGTH);
removeGameTimer(DIVINE_SUPER_DEFENCE);
removeGameTimer(DIVINE_SUPER_COMBAT);
removeGameTimer(DIVINE_RANGING);
removeGameTimer(DIVINE_MAGIC);
}
if (!config.showCannon())
{
removeGameTimer(CANNON);
}
if (!config.showMagicImbue())
{
removeGameTimer(MAGICIMBUE);
}
if (!config.showCharge())
{
removeGameTimer(CHARGE);
}
if (!config.showImbuedHeart())
{
removeGameTimer(IMBUEDHEART);
}
if (!config.showStaffOfTheDead())
{
removeGameTimer(STAFF_OF_THE_DEAD);
}
if (!config.showVengeance())
{
removeGameTimer(VENGEANCE);
}
if (!config.showVengeanceActive())
{
removeGameIndicator(VENGEANCE_ACTIVE);
}
if (!config.showTeleblock())
{
removeGameTimer(TELEBLOCK);
}
if (!config.showFreezes())
{
removeGameTimer(BIND);
removeGameTimer(SNARE);
removeGameTimer(ENTANGLE);
removeGameTimer(ICERUSH);
removeGameTimer(ICEBURST);
removeGameTimer(ICEBLITZ);
removeGameTimer(ICEBARRAGE);
}
if (!config.showAntiPoison())
{
removeGameTimer(ANTIPOISON);
removeGameTimer(ANTIVENOM);
}
if (!config.showTzhaarTimers())
{
removeTzhaarTimer();
}
}
@Subscribe
public void onMenuOptionClicked(MenuOptionClicked event)
{
if (config.showStamina()
&& event.getMenuOption().contains("Drink")
&& (event.getId() == ItemID.STAMINA_MIX1
|| event.getId() == ItemID.STAMINA_MIX2
|| event.getId() == ItemID.EGNIOL_POTION_1
|| event.getId() == ItemID.EGNIOL_POTION_2
|| event.getId() == ItemID.EGNIOL_POTION_3
|| event.getId() == ItemID.EGNIOL_POTION_4))
{
// Needs menu option hook because mixes use a common drink message, distinct from their standard potion messages
createStaminaTimer();
return;
}
if (config.showAntiFire()
&& event.getMenuOption().contains("Drink")
&& (event.getId() == ItemID.ANTIFIRE_MIX1
|| event.getId() == ItemID.ANTIFIRE_MIX2))
{
// Needs menu option hook because mixes use a common drink message, distinct from their standard potion messages
createGameTimer(ANTIFIRE);
return;
}
if (config.showAntiFire()
&& event.getMenuOption().contains("Drink")
&& (event.getId() == ItemID.EXTENDED_ANTIFIRE_MIX1
|| event.getId() == ItemID.EXTENDED_ANTIFIRE_MIX2))
{
// Needs menu option hook because mixes use a common drink message, distinct from their standard potion messages
createGameTimer(EXANTIFIRE);
return;
}
if (config.showAntiFire()
&& event.getMenuOption().contains("Drink")
&& (event.getId() == ItemID.SUPER_ANTIFIRE_MIX1
|| event.getId() == ItemID.SUPER_ANTIFIRE_MIX2))
{
// Needs menu option hook because mixes use a common drink message, distinct from their standard potion messages
createGameTimer(SUPERANTIFIRE);
return;
}
if (config.showAntiFire()
&& event.getMenuOption().contains("Drink")
&& (event.getId() == ItemID.EXTENDED_SUPER_ANTIFIRE_MIX1
|| event.getId() == ItemID.EXTENDED_SUPER_ANTIFIRE_MIX2))
{
// Needs menu option hook because mixes use a common drink message, distinct from their standard potion messages
createGameTimer(EXSUPERANTIFIRE);
return;
}
TeleportWidget teleportWidget = TeleportWidget.of(event.getWidgetId());
if (teleportWidget != null)
{
lastTeleportClicked = teleportWidget;
}
}
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() != ChatMessageType.SPAM && event.getType() != ChatMessageType.GAMEMESSAGE)
{
return;
}
if (event.getMessage().equals(ENDURANCE_EFFECT_MESSAGE))
{
wasWearingEndurance = true;
}
if (config.showStamina() && (event.getMessage().equals(STAMINA_DRINK_MESSAGE) || event.getMessage().equals(STAMINA_SHARED_DRINK_MESSAGE)))
{
createStaminaTimer();
}
if (event.getMessage().equals(STAMINA_EXPIRED_MESSAGE) || event.getMessage().equals(GAUNTLET_ENTER_MESSAGE))
{
removeGameTimer(STAMINA);
staminaTimer = null;
}
if (config.showAntiFire() && event.getMessage().equals(ANTIFIRE_DRINK_MESSAGE))
{
createGameTimer(ANTIFIRE);
}
if (config.showAntiFire() && event.getMessage().equals(EXTENDED_ANTIFIRE_DRINK_MESSAGE))
{
createGameTimer(EXANTIFIRE);
}
if (config.showGodWarsAltar() && event.getMessage().equalsIgnoreCase(GOD_WARS_ALTAR_MESSAGE))//Normal altars are "You recharge your Prayer points." while gwd is "You recharge your Prayer."
{
createGameTimer(GOD_WARS_ALTAR);
}
if (config.showAntiFire() && event.getMessage().equals(EXTENDED_SUPER_ANTIFIRE_DRINK_MESSAGE))
{
createGameTimer(EXSUPERANTIFIRE);
}
if (config.showAntiFire() && event.getMessage().equals(ANTIFIRE_EXPIRED_MESSAGE))
{
//they have the same expired message
removeGameTimer(ANTIFIRE);
removeGameTimer(EXANTIFIRE);
}
if (config.showOverload() && event.getMessage().startsWith("You drink some of your") && event.getMessage().contains("overload"))
{
if (client.getVar(Varbits.IN_RAID) == 1)
{
createGameTimer(OVERLOAD_RAID);
}
else
{
createGameTimer(OVERLOAD);
}
}
if (config.showCannon() && (event.getMessage().equals(CANNON_FURNACE_MESSAGE) || event.getMessage().contains(CANNON_REPAIR_MESSAGE)))
{
TimerTimer cannonTimer = createGameTimer(CANNON);
cannonTimer.setTooltip(cannonTimer.getTooltip() + " - World " + client.getWorld());
}
if (config.showCannon() && event.getMessage().equals(CANNON_PICKUP_MESSAGE))
{
removeGameTimer(CANNON);
}
if (config.showMagicImbue() && event.getMessage().equals(MAGIC_IMBUE_MESSAGE))
{
createGameTimer(MAGICIMBUE);
}
if (event.getMessage().equals(MAGIC_IMBUE_EXPIRED_MESSAGE))
{
removeGameTimer(MAGICIMBUE);
}
if (config.showTeleblock())
{
Matcher m = TELEBLOCK_PATTERN.matcher(event.getMessage());
if (m.find())
{
String minss = m.group("mins");
String secss = m.group("secs");
int mins = Integer.parseInt(minss);
int secs = secss != null ? Integer.parseInt(secss) : 0;
createGameTimer(TELEBLOCK, Duration.ofSeconds(mins * 60 + secs));
}
else if (event.getMessage().contains(KILLED_TELEBLOCK_OPPONENT_TEXT))
{
removeGameTimer(TELEBLOCK);
}
}
if (config.showAntiFire() && event.getMessage().contains(SUPER_ANTIFIRE_DRINK_MESSAGE))
{
createGameTimer(SUPERANTIFIRE);
}
if (config.showAntiFire() && event.getMessage().equals(SUPER_ANTIFIRE_EXPIRED_MESSAGE))
{
removeGameTimer(SUPERANTIFIRE);
}
if (config.showImbuedHeart() && event.getMessage().equals(IMBUED_HEART_READY_MESSAGE))
{
removeGameTimer(IMBUEDHEART);
}
if (config.showPrayerEnhance() && event.getMessage().startsWith("You drink some of your") && event.getMessage().contains("prayer enhance"))
{
createGameTimer(PRAYER_ENHANCE);
}
if (config.showPrayerEnhance() && event.getMessage().equals(PRAYER_ENHANCE_EXPIRED))
{
removeGameTimer(PRAYER_ENHANCE);
}
if (config.showCharge() && event.getMessage().equals(CHARGE_MESSAGE))
{
createGameTimer(CHARGE);
}
if (config.showCharge() && event.getMessage().equals(CHARGE_EXPIRED_MESSAGE))
{
removeGameTimer(CHARGE);
}
if (config.showStaffOfTheDead() && event.getMessage().contains(STAFF_OF_THE_DEAD_SPEC_MESSAGE))
{
createGameTimer(STAFF_OF_THE_DEAD);
}
if (config.showStaffOfTheDead() && event.getMessage().contains(STAFF_OF_THE_DEAD_SPEC_EXPIRED_MESSAGE))
{
removeGameTimer(STAFF_OF_THE_DEAD);
}
if (config.showFreezes() && event.getMessage().equals(FROZEN_MESSAGE))
{
freezeTimer = createGameTimer(ICEBARRAGE);
freezeTime = client.getTickCount();
}
if (config.showDivine())
{
Matcher mDivine = DIVINE_POTION_PATTERN.matcher(event.getMessage());
if (mDivine.find())
{
switch (mDivine.group(1))
{
case "super attack":
createGameTimer(DIVINE_SUPER_ATTACK);
break;
case "super strength":
createGameTimer(DIVINE_SUPER_STRENGTH);
break;
case "super defence":
createGameTimer(DIVINE_SUPER_DEFENCE);
break;
case "combat":
createGameTimer(DIVINE_SUPER_COMBAT);
break;
case "ranging":
createGameTimer(DIVINE_RANGING);
break;
case "magic":
createGameTimer(DIVINE_MAGIC);
break;
case "bastion":
createGameTimer(DIVINE_BASTION);
break;
case "battlemage":
createGameTimer(DIVINE_BATTLEMAGE);
break;
}
}
}
if (config.showTzhaarTimers())
{
String message = event.getMessage();
Matcher matcher = TZHAAR_COMPLETE_MESSAGE.matcher(message);
if (message.contains(TZHAAR_DEFEATED_MESSAGE) || matcher.matches())
{
removeTzhaarTimer();
config.tzhaarStartTime(null);
config.tzhaarLastTime(null);
return;
}
Instant now = Instant.now();
matcher = TZHAAR_PAUSED_MESSAGE.matcher(message);
if (matcher.find())
{
config.tzhaarLastTime(now);
createTzhaarTimer();
return;
}
matcher = TZHAAR_WAVE_MESSAGE.matcher(message);
if (!matcher.find())
{
return;
}
if (config.tzhaarStartTime() == null)
{
int wave = Integer.parseInt(matcher.group(1));
if (wave == 1)
{
if (isInInferno())
{
// The first wave message of the inferno comes six seconds after the ingame timer starts counting
config.tzhaarStartTime(now.minus(Duration.ofSeconds(6)));
}
else
{
config.tzhaarStartTime(now);
}
createTzhaarTimer();
}
}
else if (config.tzhaarLastTime() != null)
{
log.debug("Unpausing tzhaar timer");
// Advance start time by how long it has been paused
Instant tzhaarStartTime = config.tzhaarStartTime();
tzhaarStartTime = tzhaarStartTime.plus(Duration.between(config.tzhaarLastTime(), now));
config.tzhaarStartTime(tzhaarStartTime);
config.tzhaarLastTime(null);
createTzhaarTimer();
}
}
}
private boolean isInFightCaves()
{
return client.getMapRegions() != null && ArrayUtils.contains(client.getMapRegions(), FIGHT_CAVES_REGION_ID);
}
private boolean isInInferno()
{
return client.getMapRegions() != null && ArrayUtils.contains(client.getMapRegions(), INFERNO_REGION_ID);
}
private void createTzhaarTimer()
{
removeTzhaarTimer();
int imageItem = isInFightCaves() ? FIRE_CAPE : (isInInferno() ? INFERNAL_CAPE : -1);
if (imageItem == -1)
{
return;
}
tzhaarTimer = new ElapsedTimer(itemManager.getImage(imageItem), this, config.tzhaarStartTime(), config.tzhaarLastTime());
infoBoxManager.addInfoBox(tzhaarTimer);
}
private void removeTzhaarTimer()
{
if (tzhaarTimer != null)
{
infoBoxManager.removeInfoBox(tzhaarTimer);
tzhaarTimer = null;
}
}
@Subscribe
public void onGameTick(GameTick event)
{
loggedInRace = false;
Player player = client.getLocalPlayer();
WorldPoint currentWorldPoint = player.getWorldLocation();
if (freezeTimer != null)
{
// assume movement means unfrozen
if (freezeTime != client.getTickCount()
&& !currentWorldPoint.equals(lastPoint))
{
removeGameTimer(freezeTimer.getTimer());
freezeTimer = null;
}
}
lastPoint = currentWorldPoint;
if (!widgetHiddenChangedOnPvpWorld)
{
return;
}
widgetHiddenChangedOnPvpWorld = false;
Widget widget = client.getWidget(PVP_WORLD_SAFE_ZONE);
if (widget != null && !widget.isSelfHidden())
{
log.debug("Entered safe zone in PVP world, clearing Teleblock timer.");
removeGameTimer(TELEBLOCK);
}
}
@Subscribe
public void onGameStateChanged(GameStateChanged gameStateChanged)
{
switch (gameStateChanged.getGameState())
{
case LOADING:
if (tzhaarTimer != null && !isInFightCaves() && !isInInferno())
{
removeTzhaarTimer();
config.tzhaarStartTime(null);
config.tzhaarLastTime(null);
}
break;
case HOPPING:
case LOGIN_SCREEN:
// pause tzhaar timer if logged out without pausing
if (config.tzhaarStartTime() != null && config.tzhaarLastTime() == null)
{
config.tzhaarLastTime(Instant.now());
log.debug("Pausing tzhaar timer");
}
removeTzhaarTimer(); // will be readded by the wave message
removeGameTimer(TELEBLOCK);
break;
case LOGGED_IN:
loggedInRace = true;
break;
}
}
@Subscribe
public void onAnimationChanged(AnimationChanged event)
{
Actor actor = event.getActor();
if (config.showAbyssalSireStun()
&& actor instanceof NPC)
{
int npcId = ((NPC)actor).getId();
switch (npcId)
{
// Show the countdown when the Sire enters the stunned state.
case NpcID.ABYSSAL_SIRE_5888:
createGameTimer(ABYSSAL_SIRE_STUN);
break;
// Hide the countdown if the Sire isn't in the stunned state.
// This is necessary because the Sire leaves the stunned
// state early once all all four respiratory systems are killed.
case NpcID.ABYSSAL_SIRE:
case NpcID.ABYSSAL_SIRE_5887:
case NpcID.ABYSSAL_SIRE_5889:
case NpcID.ABYSSAL_SIRE_5890:
case NpcID.ABYSSAL_SIRE_5891:
case NpcID.ABYSSAL_SIRE_5908:
removeGameTimer(ABYSSAL_SIRE_STUN);
break;
}
}
if (actor != client.getLocalPlayer())
{
return;
}
if (config.showHomeMinigameTeleports()
&& client.getLocalPlayer().getAnimation() == AnimationID.IDLE
&& (lastAnimation == AnimationID.BOOK_HOME_TELEPORT_5
|| lastAnimation == AnimationID.COW_HOME_TELEPORT_6))
{
if (lastTeleportClicked == TeleportWidget.HOME_TELEPORT)
{
createGameTimer(HOME_TELEPORT);
}
else if (lastTeleportClicked == TeleportWidget.MINIGAME_TELEPORT)
{
createGameTimer(MINIGAME_TELEPORT);
}
}
if (config.showDFSSpecial() && lastAnimation == AnimationID.DRAGONFIRE_SHIELD_SPECIAL)
{
createGameTimer(DRAGON_FIRE_SHIELD);
}
lastAnimation = client.getLocalPlayer().getAnimation();
}
@Subscribe
public void onGraphicChanged(GraphicChanged event)
{
Actor actor = event.getActor();
if (actor != client.getLocalPlayer())
{
return;
}
if (config.showImbuedHeart() && actor.getGraphic() == IMBUEDHEART.getGraphicId())
{
createGameTimer(IMBUEDHEART);
}
if (config.showFreezes())
{
if (actor.getGraphic() == BIND.getGraphicId())
{
createGameTimer(BIND);
}
if (actor.getGraphic() == SNARE.getGraphicId())
{
createGameTimer(SNARE);
}
if (actor.getGraphic() == ENTANGLE.getGraphicId())
{
createGameTimer(ENTANGLE);
}
// downgrade freeze based on graphic, if at the same tick as the freeze message
if (freezeTime == client.getTickCount())
{
if (actor.getGraphic() == ICERUSH.getGraphicId())
{
removeGameTimer(ICEBARRAGE);
freezeTimer = createGameTimer(ICERUSH);
}
if (actor.getGraphic() == ICEBURST.getGraphicId())
{
removeGameTimer(ICEBARRAGE);
freezeTimer = createGameTimer(ICEBURST);
}
if (actor.getGraphic() == ICEBLITZ.getGraphicId())
{
removeGameTimer(ICEBARRAGE);
freezeTimer = createGameTimer(ICEBLITZ);
}
}
}
}
/**
* Remove SOTD timer and update stamina timer when equipment is changed.
*/
@Subscribe
public void onItemContainerChanged(ItemContainerChanged itemContainerChanged)
{
if (itemContainerChanged.getContainerId() != InventoryID.EQUIPMENT.getId())
{
return;
}
ItemContainer container = itemContainerChanged.getItemContainer();
Item weapon = container.getItem(EquipmentInventorySlot.WEAPON.getSlotIdx());
if (weapon == null ||
(weapon.getId() != ItemID.STAFF_OF_THE_DEAD &&
weapon.getId() != ItemID.TOXIC_STAFF_OF_THE_DEAD &&
weapon.getId() != ItemID.STAFF_OF_LIGHT &&
weapon.getId() != ItemID.TOXIC_STAFF_UNCHARGED))
{
// remove sotd timer if the staff has been unwielded
removeGameTimer(STAFF_OF_THE_DEAD);
}
if (wasWearingEndurance)
{
Item ring = container.getItem(EquipmentInventorySlot.RING.getSlotIdx());
// when using the last ring charge the ring changes to the uncharged version, ignore that and don't
// halve the timer
if (ring == null || (ring.getId() != ItemID.RING_OF_ENDURANCE && ring.getId() != ItemID.RING_OF_ENDURANCE_UNCHARGED_24844))
{
wasWearingEndurance = false;
if (staminaTimer != null)
{
// Remaining duration gets divided by 2
Duration remainingDuration = Duration.between(Instant.now(), staminaTimer.getEndTime()).dividedBy(2);
// This relies on the chat message to be removed, which could be after the timer has been culled;
// so check there is still remaining time
if (!remainingDuration.isNegative() && !remainingDuration.isZero())
{
log.debug("Halving stamina timer");
staminaTimer.setDuration(remainingDuration);
}
}
}
}
}
@Subscribe
public void onNpcDespawned(NpcDespawned npcDespawned)
{
NPC npc = npcDespawned.getNpc();
if (!npc.isDead())
{
return;
}
int npcId = npc.getId();
if (npcId == NpcID.ZOMBIFIED_SPAWN || npcId == NpcID.ZOMBIFIED_SPAWN_8063)
{
removeGameTimer(ICEBARRAGE);
}
}
@Subscribe
public void onActorDeath(ActorDeath actorDeath)
{
if (actorDeath.getActor() == client.getLocalPlayer())
{
infoBoxManager.removeIf(t -> t instanceof TimerTimer && ((TimerTimer) t).getTimer().isRemovedOnDeath());
}
}
private void createStaminaTimer()
{
Duration duration = Duration.ofMinutes(wasWearingEndurance ? 4 : 2);
staminaTimer = createGameTimer(STAMINA, duration);
}
private TimerTimer createGameTimer(final GameTimer timer)
{
if (timer.getDuration() == null)
{
throw new IllegalArgumentException("Timer with no duration");
}
return createGameTimer(timer, timer.getDuration());
}
private TimerTimer createGameTimer(final GameTimer timer, Duration duration)
{
removeGameTimer(timer);
TimerTimer t = new TimerTimer(timer, duration, this);
switch (timer.getImageType())
{
case SPRITE:
spriteManager.getSpriteAsync(timer.getImageId(), 0, t);
break;
case ITEM:
t.setImage(itemManager.getImage(timer.getImageId()));
break;
}
t.setTooltip(timer.getDescription());
infoBoxManager.addInfoBox(t);
return t;
}
private void removeGameTimer(GameTimer timer)
{
infoBoxManager.removeIf(t -> t instanceof TimerTimer && ((TimerTimer) t).getTimer() == timer);
}
private IndicatorIndicator createGameIndicator(GameIndicator gameIndicator)
{
removeGameIndicator(gameIndicator);
IndicatorIndicator indicator = new IndicatorIndicator(gameIndicator, this);
switch (gameIndicator.getImageType())
{
case SPRITE:
spriteManager.getSpriteAsync(gameIndicator.getImageId(), 0, indicator);
break;
case ITEM:
indicator.setImage(itemManager.getImage(gameIndicator.getImageId()));
break;
}
indicator.setTooltip(gameIndicator.getDescription());
infoBoxManager.addInfoBox(indicator);
return indicator;
}
private void removeGameIndicator(GameIndicator indicator)
{
infoBoxManager.removeIf(t -> t instanceof IndicatorIndicator && ((IndicatorIndicator) t).getIndicator() == indicator);
}
}
| runelite-client/src/main/java/net/runelite/client/plugins/timers/TimersPlugin.java | /*
* Copyright (c) 2017, Seth <[email protected]>
* Copyright (c) 2018, Jordan Atwood <[email protected]>
* Copyright (c) 2019, winterdaze
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.timers;
import com.google.inject.Provides;
import java.time.Duration;
import java.time.Instant;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Actor;
import net.runelite.api.AnimationID;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.Constants;
import net.runelite.api.EquipmentInventorySlot;
import net.runelite.api.GameState;
import net.runelite.api.InventoryID;
import net.runelite.api.Item;
import net.runelite.api.ItemContainer;
import net.runelite.api.ItemID;
import static net.runelite.api.ItemID.FIRE_CAPE;
import static net.runelite.api.ItemID.INFERNAL_CAPE;
import net.runelite.api.NPC;
import net.runelite.api.NpcID;
import net.runelite.api.Player;
import net.runelite.api.VarPlayer;
import net.runelite.api.Varbits;
import net.runelite.api.WorldType;
import net.runelite.api.coords.WorldPoint;
import net.runelite.api.events.ActorDeath;
import net.runelite.api.events.AnimationChanged;
import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.GameTick;
import net.runelite.api.events.GraphicChanged;
import net.runelite.api.events.ItemContainerChanged;
import net.runelite.api.events.MenuOptionClicked;
import net.runelite.api.events.NpcDespawned;
import net.runelite.api.events.VarbitChanged;
import net.runelite.api.events.WidgetHiddenChanged;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetID;
import net.runelite.api.widgets.WidgetInfo;
import static net.runelite.api.widgets.WidgetInfo.PVP_WORLD_SAFE_ZONE;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.events.ConfigChanged;
import net.runelite.client.game.ItemManager;
import net.runelite.client.game.SpriteManager;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import static net.runelite.client.plugins.timers.GameIndicator.VENGEANCE_ACTIVE;
import static net.runelite.client.plugins.timers.GameTimer.*;
import net.runelite.client.ui.overlay.infobox.InfoBoxManager;
import org.apache.commons.lang3.ArrayUtils;
@PluginDescriptor(
name = "Timers",
description = "Show various timers in an infobox",
tags = {"combat", "items", "magic", "potions", "prayer", "overlay", "abyssal", "sire", "inferno", "fight", "caves", "cape", "timer", "tzhaar"}
)
@Slf4j
public class TimersPlugin extends Plugin
{
private static final String ANTIFIRE_DRINK_MESSAGE = "You drink some of your antifire potion.";
private static final String ANTIFIRE_EXPIRED_MESSAGE = "<col=7f007f>Your antifire potion has expired.</col>";
private static final String CANNON_FURNACE_MESSAGE = "You add the furnace.";
private static final String CANNON_PICKUP_MESSAGE = "You pick up the cannon. It's really heavy.";
private static final String CANNON_REPAIR_MESSAGE = "You repair your cannon, restoring it to working order.";
private static final String CHARGE_EXPIRED_MESSAGE = "<col=ef1020>Your magical charge fades away.</col>";
private static final String CHARGE_MESSAGE = "<col=ef1020>You feel charged with magic power.</col>";
private static final String EXTENDED_ANTIFIRE_DRINK_MESSAGE = "You drink some of your extended antifire potion.";
private static final String EXTENDED_SUPER_ANTIFIRE_DRINK_MESSAGE = "You drink some of your extended super antifire potion.";
private static final String FROZEN_MESSAGE = "<col=ef1020>You have been frozen!</col>";
private static final String GAUNTLET_ENTER_MESSAGE = "You enter the Gauntlet.";
private static final String GOD_WARS_ALTAR_MESSAGE = "you recharge your prayer.";
private static final String IMBUED_HEART_READY_MESSAGE = "<col=ef1020>Your imbued heart has regained its magical power.</col>";
private static final String MAGIC_IMBUE_EXPIRED_MESSAGE = "Your Magic Imbue charge has ended.";
private static final String MAGIC_IMBUE_MESSAGE = "You are charged to combine runes!";
private static final String STAFF_OF_THE_DEAD_SPEC_EXPIRED_MESSAGE = "Your protection fades away";
private static final String STAFF_OF_THE_DEAD_SPEC_MESSAGE = "Spirits of deceased evildoers offer you their protection";
private static final String STAMINA_DRINK_MESSAGE = "You drink some of your stamina potion.";
private static final String STAMINA_SHARED_DRINK_MESSAGE = "You have received a shared dose of stamina potion.";
private static final String STAMINA_EXPIRED_MESSAGE = "<col=8f4808>Your stamina potion has expired.</col>";
private static final String SUPER_ANTIFIRE_DRINK_MESSAGE = "You drink some of your super antifire potion";
private static final String SUPER_ANTIFIRE_EXPIRED_MESSAGE = "<col=7f007f>Your super antifire potion has expired.</col>";
private static final String KILLED_TELEBLOCK_OPPONENT_TEXT = "Your Tele Block has been removed because you killed ";
private static final String PRAYER_ENHANCE_EXPIRED = "<col=ff0000>Your prayer enhance effect has worn off.</col>";
private static final String ENDURANCE_EFFECT_MESSAGE = "Your Ring of endurance doubles the duration of your stamina potion's effect.";
private static final Pattern TELEBLOCK_PATTERN = Pattern.compile("A Tele Block spell has been cast on you(?: by .+)?\\. It will expire in (?<mins>\\d+) minutes?(?:, (?<secs>\\d+) seconds?)?\\.");
private static final Pattern DIVINE_POTION_PATTERN = Pattern.compile("You drink some of your divine (.+) potion\\.");
private static final int VENOM_VALUE_CUTOFF = -40; // Antivenom < -40 <= Antipoison < 0
private static final int POISON_TICK_LENGTH = 30;
static final int FIGHT_CAVES_REGION_ID = 9551;
static final int INFERNO_REGION_ID = 9043;
private static final Pattern TZHAAR_WAVE_MESSAGE = Pattern.compile("Wave: (\\d+)");
private static final String TZHAAR_DEFEATED_MESSAGE = "You have been defeated!";
private static final Pattern TZHAAR_COMPLETE_MESSAGE = Pattern.compile("Your (TzTok-Jad|TzKal-Zuk) kill count is:");
private static final Pattern TZHAAR_PAUSED_MESSAGE = Pattern.compile("The (Inferno|Fight Cave) has been paused. You may now log out.");
private TimerTimer freezeTimer;
private int freezeTime = -1; // time frozen, in game ticks
private TimerTimer staminaTimer;
private boolean wasWearingEndurance;
private int lastRaidVarb;
private int lastWildernessVarb;
private int lastVengCooldownVarb;
private int lastIsVengeancedVarb;
private int lastPoisonVarp;
private int nextPoisonTick;
private WorldPoint lastPoint;
private TeleportWidget lastTeleportClicked;
private int lastAnimation;
private boolean loggedInRace;
private boolean widgetHiddenChangedOnPvpWorld;
private ElapsedTimer tzhaarTimer;
@Inject
private ItemManager itemManager;
@Inject
private SpriteManager spriteManager;
@Inject
private Client client;
@Inject
private TimersConfig config;
@Inject
private InfoBoxManager infoBoxManager;
@Provides
TimersConfig getConfig(ConfigManager configManager)
{
return configManager.getConfig(TimersConfig.class);
}
@Override
protected void shutDown() throws Exception
{
infoBoxManager.removeIf(t -> t instanceof TimerTimer);
lastRaidVarb = -1;
lastPoint = null;
lastTeleportClicked = null;
lastAnimation = -1;
loggedInRace = false;
widgetHiddenChangedOnPvpWorld = false;
lastPoisonVarp = 0;
nextPoisonTick = 0;
removeTzhaarTimer();
staminaTimer = null;
}
@Subscribe
public void onVarbitChanged(VarbitChanged event)
{
int raidVarb = client.getVar(Varbits.IN_RAID);
int vengCooldownVarb = client.getVar(Varbits.VENGEANCE_COOLDOWN);
int isVengeancedVarb = client.getVar(Varbits.VENGEANCE_ACTIVE);
int poisonVarp = client.getVar(VarPlayer.POISON);
if (lastRaidVarb != raidVarb)
{
removeGameTimer(OVERLOAD_RAID);
removeGameTimer(PRAYER_ENHANCE);
lastRaidVarb = raidVarb;
}
if (lastVengCooldownVarb != vengCooldownVarb && config.showVengeance())
{
if (vengCooldownVarb == 1)
{
createGameTimer(VENGEANCE);
}
else
{
removeGameTimer(VENGEANCE);
}
lastVengCooldownVarb = vengCooldownVarb;
}
if (lastIsVengeancedVarb != isVengeancedVarb && config.showVengeanceActive())
{
if (isVengeancedVarb == 1)
{
createGameIndicator(VENGEANCE_ACTIVE);
}
else
{
removeGameIndicator(VENGEANCE_ACTIVE);
}
lastIsVengeancedVarb = isVengeancedVarb;
}
int inWilderness = client.getVar(Varbits.IN_WILDERNESS);
if (lastWildernessVarb != inWilderness
&& client.getGameState() == GameState.LOGGED_IN
&& !loggedInRace)
{
if (!WorldType.isPvpWorld(client.getWorldType())
&& inWilderness == 0)
{
log.debug("Left wilderness in non-PVP world, clearing Teleblock timer.");
removeGameTimer(TELEBLOCK);
}
lastWildernessVarb = inWilderness;
}
if (lastPoisonVarp != poisonVarp && config.showAntiPoison())
{
final int tickCount = client.getTickCount();
if (nextPoisonTick - tickCount <= 0 || lastPoisonVarp == 0)
{
nextPoisonTick = tickCount + POISON_TICK_LENGTH;
}
if (poisonVarp >= 0)
{
removeGameTimer(ANTIPOISON);
removeGameTimer(ANTIVENOM);
}
else if (poisonVarp >= VENOM_VALUE_CUTOFF)
{
Duration duration = Duration.ofMillis((long) Constants.GAME_TICK_LENGTH * (nextPoisonTick - tickCount + Math.abs((poisonVarp + 1) * POISON_TICK_LENGTH)));
removeGameTimer(ANTIVENOM);
createGameTimer(ANTIPOISON, duration);
}
else
{
Duration duration = Duration.ofMillis((long) Constants.GAME_TICK_LENGTH * (nextPoisonTick - tickCount + Math.abs((poisonVarp + 1 - VENOM_VALUE_CUTOFF) * POISON_TICK_LENGTH)));
removeGameTimer(ANTIPOISON);
createGameTimer(ANTIVENOM, duration);
}
lastPoisonVarp = poisonVarp;
}
}
@Subscribe
public void onWidgetHiddenChanged(WidgetHiddenChanged event)
{
Widget widget = event.getWidget();
if (WorldType.isPvpWorld(client.getWorldType())
&& WidgetInfo.TO_GROUP(widget.getId()) == WidgetID.PVP_GROUP_ID)
{
widgetHiddenChangedOnPvpWorld = true;
}
}
@Subscribe
public void onConfigChanged(ConfigChanged event)
{
if (!config.showHomeMinigameTeleports())
{
removeGameTimer(HOME_TELEPORT);
removeGameTimer(MINIGAME_TELEPORT);
}
if (!config.showAntiFire())
{
removeGameTimer(ANTIFIRE);
removeGameTimer(EXANTIFIRE);
removeGameTimer(SUPERANTIFIRE);
}
if (!config.showStamina())
{
removeGameTimer(STAMINA);
}
if (!config.showOverload())
{
removeGameTimer(OVERLOAD);
removeGameTimer(OVERLOAD_RAID);
}
if (!config.showPrayerEnhance())
{
removeGameTimer(PRAYER_ENHANCE);
}
if (!config.showDivine())
{
removeGameTimer(DIVINE_SUPER_ATTACK);
removeGameTimer(DIVINE_SUPER_STRENGTH);
removeGameTimer(DIVINE_SUPER_DEFENCE);
removeGameTimer(DIVINE_SUPER_COMBAT);
removeGameTimer(DIVINE_RANGING);
removeGameTimer(DIVINE_MAGIC);
}
if (!config.showCannon())
{
removeGameTimer(CANNON);
}
if (!config.showMagicImbue())
{
removeGameTimer(MAGICIMBUE);
}
if (!config.showCharge())
{
removeGameTimer(CHARGE);
}
if (!config.showImbuedHeart())
{
removeGameTimer(IMBUEDHEART);
}
if (!config.showStaffOfTheDead())
{
removeGameTimer(STAFF_OF_THE_DEAD);
}
if (!config.showVengeance())
{
removeGameTimer(VENGEANCE);
}
if (!config.showVengeanceActive())
{
removeGameIndicator(VENGEANCE_ACTIVE);
}
if (!config.showTeleblock())
{
removeGameTimer(TELEBLOCK);
}
if (!config.showFreezes())
{
removeGameTimer(BIND);
removeGameTimer(SNARE);
removeGameTimer(ENTANGLE);
removeGameTimer(ICERUSH);
removeGameTimer(ICEBURST);
removeGameTimer(ICEBLITZ);
removeGameTimer(ICEBARRAGE);
}
if (!config.showAntiPoison())
{
removeGameTimer(ANTIPOISON);
removeGameTimer(ANTIVENOM);
}
if (!config.showTzhaarTimers())
{
removeTzhaarTimer();
}
}
@Subscribe
public void onMenuOptionClicked(MenuOptionClicked event)
{
if (config.showStamina()
&& event.getMenuOption().contains("Drink")
&& (event.getId() == ItemID.STAMINA_MIX1
|| event.getId() == ItemID.STAMINA_MIX2
|| event.getId() == ItemID.EGNIOL_POTION_1
|| event.getId() == ItemID.EGNIOL_POTION_2
|| event.getId() == ItemID.EGNIOL_POTION_3
|| event.getId() == ItemID.EGNIOL_POTION_4))
{
// Needs menu option hook because mixes use a common drink message, distinct from their standard potion messages
createStaminaTimer();
return;
}
if (config.showAntiFire()
&& event.getMenuOption().contains("Drink")
&& (event.getId() == ItemID.ANTIFIRE_MIX1
|| event.getId() == ItemID.ANTIFIRE_MIX2))
{
// Needs menu option hook because mixes use a common drink message, distinct from their standard potion messages
createGameTimer(ANTIFIRE);
return;
}
if (config.showAntiFire()
&& event.getMenuOption().contains("Drink")
&& (event.getId() == ItemID.EXTENDED_ANTIFIRE_MIX1
|| event.getId() == ItemID.EXTENDED_ANTIFIRE_MIX2))
{
// Needs menu option hook because mixes use a common drink message, distinct from their standard potion messages
createGameTimer(EXANTIFIRE);
return;
}
if (config.showAntiFire()
&& event.getMenuOption().contains("Drink")
&& (event.getId() == ItemID.SUPER_ANTIFIRE_MIX1
|| event.getId() == ItemID.SUPER_ANTIFIRE_MIX2))
{
// Needs menu option hook because mixes use a common drink message, distinct from their standard potion messages
createGameTimer(SUPERANTIFIRE);
return;
}
if (config.showAntiFire()
&& event.getMenuOption().contains("Drink")
&& (event.getId() == ItemID.EXTENDED_SUPER_ANTIFIRE_MIX1
|| event.getId() == ItemID.EXTENDED_SUPER_ANTIFIRE_MIX2))
{
// Needs menu option hook because mixes use a common drink message, distinct from their standard potion messages
createGameTimer(EXSUPERANTIFIRE);
return;
}
TeleportWidget teleportWidget = TeleportWidget.of(event.getWidgetId());
if (teleportWidget != null)
{
lastTeleportClicked = teleportWidget;
}
}
@Subscribe
public void onChatMessage(ChatMessage event)
{
if (event.getType() != ChatMessageType.SPAM && event.getType() != ChatMessageType.GAMEMESSAGE)
{
return;
}
if (event.getMessage().equals(ENDURANCE_EFFECT_MESSAGE))
{
wasWearingEndurance = true;
}
if (config.showStamina() && (event.getMessage().equals(STAMINA_DRINK_MESSAGE) || event.getMessage().equals(STAMINA_SHARED_DRINK_MESSAGE)))
{
createStaminaTimer();
}
if (event.getMessage().equals(STAMINA_EXPIRED_MESSAGE) || event.getMessage().equals(GAUNTLET_ENTER_MESSAGE))
{
removeGameTimer(STAMINA);
staminaTimer = null;
}
if (config.showAntiFire() && event.getMessage().equals(ANTIFIRE_DRINK_MESSAGE))
{
createGameTimer(ANTIFIRE);
}
if (config.showAntiFire() && event.getMessage().equals(EXTENDED_ANTIFIRE_DRINK_MESSAGE))
{
createGameTimer(EXANTIFIRE);
}
if (config.showGodWarsAltar() && event.getMessage().equalsIgnoreCase(GOD_WARS_ALTAR_MESSAGE))//Normal altars are "You recharge your Prayer points." while gwd is "You recharge your Prayer."
{
createGameTimer(GOD_WARS_ALTAR);
}
if (config.showAntiFire() && event.getMessage().equals(EXTENDED_SUPER_ANTIFIRE_DRINK_MESSAGE))
{
createGameTimer(EXSUPERANTIFIRE);
}
if (config.showAntiFire() && event.getMessage().equals(ANTIFIRE_EXPIRED_MESSAGE))
{
//they have the same expired message
removeGameTimer(ANTIFIRE);
removeGameTimer(EXANTIFIRE);
}
if (config.showOverload() && event.getMessage().startsWith("You drink some of your") && event.getMessage().contains("overload"))
{
if (client.getVar(Varbits.IN_RAID) == 1)
{
createGameTimer(OVERLOAD_RAID);
}
else
{
createGameTimer(OVERLOAD);
}
}
if (config.showCannon() && (event.getMessage().equals(CANNON_FURNACE_MESSAGE) || event.getMessage().contains(CANNON_REPAIR_MESSAGE)))
{
createGameTimer(CANNON);
}
if (config.showCannon() && event.getMessage().equals(CANNON_PICKUP_MESSAGE))
{
removeGameTimer(CANNON);
}
if (config.showMagicImbue() && event.getMessage().equals(MAGIC_IMBUE_MESSAGE))
{
createGameTimer(MAGICIMBUE);
}
if (event.getMessage().equals(MAGIC_IMBUE_EXPIRED_MESSAGE))
{
removeGameTimer(MAGICIMBUE);
}
if (config.showTeleblock())
{
Matcher m = TELEBLOCK_PATTERN.matcher(event.getMessage());
if (m.find())
{
String minss = m.group("mins");
String secss = m.group("secs");
int mins = Integer.parseInt(minss);
int secs = secss != null ? Integer.parseInt(secss) : 0;
createGameTimer(TELEBLOCK, Duration.ofSeconds(mins * 60 + secs));
}
else if (event.getMessage().contains(KILLED_TELEBLOCK_OPPONENT_TEXT))
{
removeGameTimer(TELEBLOCK);
}
}
if (config.showAntiFire() && event.getMessage().contains(SUPER_ANTIFIRE_DRINK_MESSAGE))
{
createGameTimer(SUPERANTIFIRE);
}
if (config.showAntiFire() && event.getMessage().equals(SUPER_ANTIFIRE_EXPIRED_MESSAGE))
{
removeGameTimer(SUPERANTIFIRE);
}
if (config.showImbuedHeart() && event.getMessage().equals(IMBUED_HEART_READY_MESSAGE))
{
removeGameTimer(IMBUEDHEART);
}
if (config.showPrayerEnhance() && event.getMessage().startsWith("You drink some of your") && event.getMessage().contains("prayer enhance"))
{
createGameTimer(PRAYER_ENHANCE);
}
if (config.showPrayerEnhance() && event.getMessage().equals(PRAYER_ENHANCE_EXPIRED))
{
removeGameTimer(PRAYER_ENHANCE);
}
if (config.showCharge() && event.getMessage().equals(CHARGE_MESSAGE))
{
createGameTimer(CHARGE);
}
if (config.showCharge() && event.getMessage().equals(CHARGE_EXPIRED_MESSAGE))
{
removeGameTimer(CHARGE);
}
if (config.showStaffOfTheDead() && event.getMessage().contains(STAFF_OF_THE_DEAD_SPEC_MESSAGE))
{
createGameTimer(STAFF_OF_THE_DEAD);
}
if (config.showStaffOfTheDead() && event.getMessage().contains(STAFF_OF_THE_DEAD_SPEC_EXPIRED_MESSAGE))
{
removeGameTimer(STAFF_OF_THE_DEAD);
}
if (config.showFreezes() && event.getMessage().equals(FROZEN_MESSAGE))
{
freezeTimer = createGameTimer(ICEBARRAGE);
freezeTime = client.getTickCount();
}
if (config.showDivine())
{
Matcher mDivine = DIVINE_POTION_PATTERN.matcher(event.getMessage());
if (mDivine.find())
{
switch (mDivine.group(1))
{
case "super attack":
createGameTimer(DIVINE_SUPER_ATTACK);
break;
case "super strength":
createGameTimer(DIVINE_SUPER_STRENGTH);
break;
case "super defence":
createGameTimer(DIVINE_SUPER_DEFENCE);
break;
case "combat":
createGameTimer(DIVINE_SUPER_COMBAT);
break;
case "ranging":
createGameTimer(DIVINE_RANGING);
break;
case "magic":
createGameTimer(DIVINE_MAGIC);
break;
case "bastion":
createGameTimer(DIVINE_BASTION);
break;
case "battlemage":
createGameTimer(DIVINE_BATTLEMAGE);
break;
}
}
}
if (config.showTzhaarTimers())
{
String message = event.getMessage();
Matcher matcher = TZHAAR_COMPLETE_MESSAGE.matcher(message);
if (message.contains(TZHAAR_DEFEATED_MESSAGE) || matcher.matches())
{
removeTzhaarTimer();
config.tzhaarStartTime(null);
config.tzhaarLastTime(null);
return;
}
Instant now = Instant.now();
matcher = TZHAAR_PAUSED_MESSAGE.matcher(message);
if (matcher.find())
{
config.tzhaarLastTime(now);
createTzhaarTimer();
return;
}
matcher = TZHAAR_WAVE_MESSAGE.matcher(message);
if (!matcher.find())
{
return;
}
if (config.tzhaarStartTime() == null)
{
int wave = Integer.parseInt(matcher.group(1));
if (wave == 1)
{
if (isInInferno())
{
// The first wave message of the inferno comes six seconds after the ingame timer starts counting
config.tzhaarStartTime(now.minus(Duration.ofSeconds(6)));
}
else
{
config.tzhaarStartTime(now);
}
createTzhaarTimer();
}
}
else if (config.tzhaarLastTime() != null)
{
log.debug("Unpausing tzhaar timer");
// Advance start time by how long it has been paused
Instant tzhaarStartTime = config.tzhaarStartTime();
tzhaarStartTime = tzhaarStartTime.plus(Duration.between(config.tzhaarLastTime(), now));
config.tzhaarStartTime(tzhaarStartTime);
config.tzhaarLastTime(null);
createTzhaarTimer();
}
}
}
private boolean isInFightCaves()
{
return client.getMapRegions() != null && ArrayUtils.contains(client.getMapRegions(), FIGHT_CAVES_REGION_ID);
}
private boolean isInInferno()
{
return client.getMapRegions() != null && ArrayUtils.contains(client.getMapRegions(), INFERNO_REGION_ID);
}
private void createTzhaarTimer()
{
removeTzhaarTimer();
int imageItem = isInFightCaves() ? FIRE_CAPE : (isInInferno() ? INFERNAL_CAPE : -1);
if (imageItem == -1)
{
return;
}
tzhaarTimer = new ElapsedTimer(itemManager.getImage(imageItem), this, config.tzhaarStartTime(), config.tzhaarLastTime());
infoBoxManager.addInfoBox(tzhaarTimer);
}
private void removeTzhaarTimer()
{
if (tzhaarTimer != null)
{
infoBoxManager.removeInfoBox(tzhaarTimer);
tzhaarTimer = null;
}
}
@Subscribe
public void onGameTick(GameTick event)
{
loggedInRace = false;
Player player = client.getLocalPlayer();
WorldPoint currentWorldPoint = player.getWorldLocation();
if (freezeTimer != null)
{
// assume movement means unfrozen
if (freezeTime != client.getTickCount()
&& !currentWorldPoint.equals(lastPoint))
{
removeGameTimer(freezeTimer.getTimer());
freezeTimer = null;
}
}
lastPoint = currentWorldPoint;
if (!widgetHiddenChangedOnPvpWorld)
{
return;
}
widgetHiddenChangedOnPvpWorld = false;
Widget widget = client.getWidget(PVP_WORLD_SAFE_ZONE);
if (widget != null && !widget.isSelfHidden())
{
log.debug("Entered safe zone in PVP world, clearing Teleblock timer.");
removeGameTimer(TELEBLOCK);
}
}
@Subscribe
public void onGameStateChanged(GameStateChanged gameStateChanged)
{
switch (gameStateChanged.getGameState())
{
case LOADING:
if (tzhaarTimer != null && !isInFightCaves() && !isInInferno())
{
removeTzhaarTimer();
config.tzhaarStartTime(null);
config.tzhaarLastTime(null);
}
break;
case HOPPING:
case LOGIN_SCREEN:
// pause tzhaar timer if logged out without pausing
if (config.tzhaarStartTime() != null && config.tzhaarLastTime() == null)
{
config.tzhaarLastTime(Instant.now());
log.debug("Pausing tzhaar timer");
}
removeTzhaarTimer(); // will be readded by the wave message
removeGameTimer(TELEBLOCK);
break;
case LOGGED_IN:
loggedInRace = true;
break;
}
}
@Subscribe
public void onAnimationChanged(AnimationChanged event)
{
Actor actor = event.getActor();
if (config.showAbyssalSireStun()
&& actor instanceof NPC)
{
int npcId = ((NPC)actor).getId();
switch (npcId)
{
// Show the countdown when the Sire enters the stunned state.
case NpcID.ABYSSAL_SIRE_5888:
createGameTimer(ABYSSAL_SIRE_STUN);
break;
// Hide the countdown if the Sire isn't in the stunned state.
// This is necessary because the Sire leaves the stunned
// state early once all all four respiratory systems are killed.
case NpcID.ABYSSAL_SIRE:
case NpcID.ABYSSAL_SIRE_5887:
case NpcID.ABYSSAL_SIRE_5889:
case NpcID.ABYSSAL_SIRE_5890:
case NpcID.ABYSSAL_SIRE_5891:
case NpcID.ABYSSAL_SIRE_5908:
removeGameTimer(ABYSSAL_SIRE_STUN);
break;
}
}
if (actor != client.getLocalPlayer())
{
return;
}
if (config.showHomeMinigameTeleports()
&& client.getLocalPlayer().getAnimation() == AnimationID.IDLE
&& (lastAnimation == AnimationID.BOOK_HOME_TELEPORT_5
|| lastAnimation == AnimationID.COW_HOME_TELEPORT_6))
{
if (lastTeleportClicked == TeleportWidget.HOME_TELEPORT)
{
createGameTimer(HOME_TELEPORT);
}
else if (lastTeleportClicked == TeleportWidget.MINIGAME_TELEPORT)
{
createGameTimer(MINIGAME_TELEPORT);
}
}
if (config.showDFSSpecial() && lastAnimation == AnimationID.DRAGONFIRE_SHIELD_SPECIAL)
{
createGameTimer(DRAGON_FIRE_SHIELD);
}
lastAnimation = client.getLocalPlayer().getAnimation();
}
@Subscribe
public void onGraphicChanged(GraphicChanged event)
{
Actor actor = event.getActor();
if (actor != client.getLocalPlayer())
{
return;
}
if (config.showImbuedHeart() && actor.getGraphic() == IMBUEDHEART.getGraphicId())
{
createGameTimer(IMBUEDHEART);
}
if (config.showFreezes())
{
if (actor.getGraphic() == BIND.getGraphicId())
{
createGameTimer(BIND);
}
if (actor.getGraphic() == SNARE.getGraphicId())
{
createGameTimer(SNARE);
}
if (actor.getGraphic() == ENTANGLE.getGraphicId())
{
createGameTimer(ENTANGLE);
}
// downgrade freeze based on graphic, if at the same tick as the freeze message
if (freezeTime == client.getTickCount())
{
if (actor.getGraphic() == ICERUSH.getGraphicId())
{
removeGameTimer(ICEBARRAGE);
freezeTimer = createGameTimer(ICERUSH);
}
if (actor.getGraphic() == ICEBURST.getGraphicId())
{
removeGameTimer(ICEBARRAGE);
freezeTimer = createGameTimer(ICEBURST);
}
if (actor.getGraphic() == ICEBLITZ.getGraphicId())
{
removeGameTimer(ICEBARRAGE);
freezeTimer = createGameTimer(ICEBLITZ);
}
}
}
}
/**
* Remove SOTD timer and update stamina timer when equipment is changed.
*/
@Subscribe
public void onItemContainerChanged(ItemContainerChanged itemContainerChanged)
{
if (itemContainerChanged.getContainerId() != InventoryID.EQUIPMENT.getId())
{
return;
}
ItemContainer container = itemContainerChanged.getItemContainer();
Item weapon = container.getItem(EquipmentInventorySlot.WEAPON.getSlotIdx());
if (weapon == null ||
(weapon.getId() != ItemID.STAFF_OF_THE_DEAD &&
weapon.getId() != ItemID.TOXIC_STAFF_OF_THE_DEAD &&
weapon.getId() != ItemID.STAFF_OF_LIGHT &&
weapon.getId() != ItemID.TOXIC_STAFF_UNCHARGED))
{
// remove sotd timer if the staff has been unwielded
removeGameTimer(STAFF_OF_THE_DEAD);
}
if (wasWearingEndurance)
{
Item ring = container.getItem(EquipmentInventorySlot.RING.getSlotIdx());
// when using the last ring charge the ring changes to the uncharged version, ignore that and don't
// halve the timer
if (ring == null || (ring.getId() != ItemID.RING_OF_ENDURANCE && ring.getId() != ItemID.RING_OF_ENDURANCE_UNCHARGED_24844))
{
wasWearingEndurance = false;
if (staminaTimer != null)
{
// Remaining duration gets divided by 2
Duration remainingDuration = Duration.between(Instant.now(), staminaTimer.getEndTime()).dividedBy(2);
// This relies on the chat message to be removed, which could be after the timer has been culled;
// so check there is still remaining time
if (!remainingDuration.isNegative() && !remainingDuration.isZero())
{
log.debug("Halving stamina timer");
staminaTimer.setDuration(remainingDuration);
}
}
}
}
}
@Subscribe
public void onNpcDespawned(NpcDespawned npcDespawned)
{
NPC npc = npcDespawned.getNpc();
if (!npc.isDead())
{
return;
}
int npcId = npc.getId();
if (npcId == NpcID.ZOMBIFIED_SPAWN || npcId == NpcID.ZOMBIFIED_SPAWN_8063)
{
removeGameTimer(ICEBARRAGE);
}
}
@Subscribe
public void onActorDeath(ActorDeath actorDeath)
{
if (actorDeath.getActor() == client.getLocalPlayer())
{
infoBoxManager.removeIf(t -> t instanceof TimerTimer && ((TimerTimer) t).getTimer().isRemovedOnDeath());
}
}
private void createStaminaTimer()
{
Duration duration = Duration.ofMinutes(wasWearingEndurance ? 4 : 2);
staminaTimer = createGameTimer(STAMINA, duration);
}
private TimerTimer createGameTimer(final GameTimer timer)
{
if (timer.getDuration() == null)
{
throw new IllegalArgumentException("Timer with no duration");
}
return createGameTimer(timer, timer.getDuration());
}
private TimerTimer createGameTimer(final GameTimer timer, Duration duration)
{
removeGameTimer(timer);
TimerTimer t = new TimerTimer(timer, duration, this);
switch (timer.getImageType())
{
case SPRITE:
spriteManager.getSpriteAsync(timer.getImageId(), 0, t);
break;
case ITEM:
t.setImage(itemManager.getImage(timer.getImageId()));
break;
}
t.setTooltip(timer.getDescription());
infoBoxManager.addInfoBox(t);
return t;
}
private void removeGameTimer(GameTimer timer)
{
infoBoxManager.removeIf(t -> t instanceof TimerTimer && ((TimerTimer) t).getTimer() == timer);
}
private IndicatorIndicator createGameIndicator(GameIndicator gameIndicator)
{
removeGameIndicator(gameIndicator);
IndicatorIndicator indicator = new IndicatorIndicator(gameIndicator, this);
switch (gameIndicator.getImageType())
{
case SPRITE:
spriteManager.getSpriteAsync(gameIndicator.getImageId(), 0, indicator);
break;
case ITEM:
indicator.setImage(itemManager.getImage(gameIndicator.getImageId()));
break;
}
indicator.setTooltip(gameIndicator.getDescription());
infoBoxManager.addInfoBox(indicator);
return indicator;
}
private void removeGameIndicator(GameIndicator indicator)
{
infoBoxManager.removeIf(t -> t instanceof IndicatorIndicator && ((IndicatorIndicator) t).getIndicator() == indicator);
}
}
| timers: add world placed to cannon timer tooltip
| runelite-client/src/main/java/net/runelite/client/plugins/timers/TimersPlugin.java | timers: add world placed to cannon timer tooltip | <ide><path>unelite-client/src/main/java/net/runelite/client/plugins/timers/TimersPlugin.java
<ide>
<ide> if (config.showCannon() && (event.getMessage().equals(CANNON_FURNACE_MESSAGE) || event.getMessage().contains(CANNON_REPAIR_MESSAGE)))
<ide> {
<del> createGameTimer(CANNON);
<add> TimerTimer cannonTimer = createGameTimer(CANNON);
<add> cannonTimer.setTooltip(cannonTimer.getTooltip() + " - World " + client.getWorld());
<ide> }
<ide>
<ide> if (config.showCannon() && event.getMessage().equals(CANNON_PICKUP_MESSAGE)) |
|
Java | apache-2.0 | 7522cefe9ea838dd35464334c4cf87a92d2a2dbe | 0 | quanticc/sentry,quanticc/sentry,quanticc/sentry | package top.quantic.sentry.config;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import top.quantic.sentry.config.scheduler.AutowiringSpringBeanJobFactory;
import java.io.IOException;
import java.util.Properties;
@Configuration
@AutoConfigureAfter(DatabaseConfiguration.class)
public class SchedulerConfiguration {
@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
@Bean
public SchedulerFactoryBean schedulerFactory(JobFactory jobFactory) throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setSchedulerName("Sentry");
factory.setJobFactory(jobFactory);
factory.setQuartzProperties(quartzProperties());
// this allows to update triggers in DB when updating settings in config file:
factory.setOverwriteExistingJobs(true);
return factory;
}
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocations(new FileSystemResource("quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}
}
| src/main/java/top/quantic/sentry/config/SchedulerConfiguration.java | package top.quantic.sentry.config;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import top.quantic.sentry.config.scheduler.AutowiringSpringBeanJobFactory;
import java.io.IOException;
import java.util.Properties;
@Configuration
@AutoConfigureAfter(DatabaseConfiguration.class)
public class SchedulerConfiguration {
@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
@Bean
public SchedulerFactoryBean schedulerFactory(JobFactory jobFactory) throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setSchedulerName("Sentry");
factory.setJobFactory(jobFactory);
factory.setQuartzProperties(quartzProperties());
// this allows to update triggers in DB when updating settings in config file:
factory.setOverwriteExistingJobs(true);
return factory;
}
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}
}
| Use quartz.properties from filesystem
| src/main/java/top/quantic/sentry/config/SchedulerConfiguration.java | Use quartz.properties from filesystem | <ide><path>rc/main/java/top/quantic/sentry/config/SchedulerConfiguration.java
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<del>import org.springframework.core.io.ClassPathResource;
<add>import org.springframework.core.io.FileSystemResource;
<ide> import org.springframework.scheduling.quartz.SchedulerFactoryBean;
<ide> import top.quantic.sentry.config.scheduler.AutowiringSpringBeanJobFactory;
<ide>
<ide> @Bean
<ide> public Properties quartzProperties() throws IOException {
<ide> PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
<del> propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
<add> propertiesFactoryBean.setLocations(new FileSystemResource("quartz.properties"));
<ide> propertiesFactoryBean.afterPropertiesSet();
<ide> return propertiesFactoryBean.getObject();
<ide> } |
|
Java | bsd-3-clause | 58442bb99ce7081019bd63df0b4d188733683870 | 0 | ndexbio/ndex-common | /**
* Copyright (c) 2013, 2015, The Regents of the University of California, The Cytoscape Consortium
* 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. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.ndexbio.common.models.dao.orientdb;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.logging.Logger;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.ndexbio.common.NdexClasses;
import org.ndexbio.common.access.NdexDatabase;
import org.ndexbio.common.solr.SingleNetworkSolrIdxManager;
import org.ndexbio.model.exceptions.*;
import org.ndexbio.model.object.Membership;
import org.ndexbio.model.object.MembershipType;
import org.ndexbio.model.object.NdexPropertyValuePair;
import org.ndexbio.model.object.Permissions;
import org.ndexbio.model.object.PropertiedObject;
import org.ndexbio.model.object.SimplePropertyValuePair;
import org.ndexbio.model.object.network.Edge;
import org.ndexbio.model.object.network.FunctionTerm;
import org.ndexbio.model.object.network.Namespace;
import org.ndexbio.model.object.network.Network;
import org.ndexbio.model.object.network.NetworkSourceFormat;
import org.ndexbio.model.object.network.NetworkSummary;
import org.ndexbio.model.object.network.Node;
import org.ndexbio.model.object.network.PropertyGraphEdge;
import org.ndexbio.model.object.network.PropertyGraphNetwork;
import org.ndexbio.model.object.network.PropertyGraphNode;
import org.ndexbio.model.object.network.ReifiedEdgeTerm;
import org.ndexbio.model.object.network.VisibilityType;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.orientechnologies.common.concur.ONeedRetryException;
import com.orientechnologies.orient.core.command.traverse.OTraverse;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.filter.OSQLPredicate;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.orientechnologies.orient.core.id.ORID;
public class NetworkDAO extends NetworkDocDAO {
private OrientGraph graph;
private static final int CLEANUP_BATCH_SIZE = 50000;
private static final String[] networkElementType = {NdexClasses.Network_E_BaseTerms, NdexClasses.Network_E_Nodes, NdexClasses.Network_E_Citations,
NdexClasses.Network_E_Edges, NdexClasses.Network_E_FunctionTerms, NdexClasses.Network_E_Namespace,
NdexClasses.Network_E_ReifiedEdgeTerms, NdexClasses.Network_E_Supports
// , NdexClasses.E_ndexPresentationProps, NdexClasses.E_ndexProperties
};
static Logger logger = Logger.getLogger(NetworkDAO.class.getName());
public NetworkDAO (ODatabaseDocumentTx db) {
super(db);
graph = new OrientGraph(this.db,false);
graph.setAutoScaleEdgeType(true);
graph.setEdgeContainerEmbedded2TreeThreshold(40);
graph.setUseLightweightEdges(true);
}
public NetworkDAO () throws NdexException {
this(NdexDatabase.getInstance().getAConnection());
}
public int deleteNetwork (String UUID) throws ObjectNotFoundException, NdexException {
int counter = 0, cnt = 0;
do {
cnt = cleanupDeleteNetwork(UUID);
if (cnt <0 )
counter += -1*cnt;
else
counter += cnt;
} while ( cnt < 0 );
return counter;
}
/**
* Delete up to CLEANUP_BATCH_SIZE vertices in a network. This function is for cleaning up a logically
* deleted network in the database.
* @param uuid
* @return Number of vertices being deleted. If the returned number is negative, it means the elements
* of the network are not completely deleted yet, and the number of vertices deleted are abs(returned number).
* @throws ObjectNotFoundException
* @throws NdexException
*/
public int cleanupDeleteNetwork(String uuid) throws ObjectNotFoundException, NdexException {
ODocument networkDoc = getRecordByUUID(UUID.fromString(uuid), NdexClasses.Network);
int count = cleanupNetworkElements(networkDoc);
if ( count >= CLEANUP_BATCH_SIZE) {
return (-1) * count;
}
// remove the network node.
networkDoc.reload();
for (int retry = 0; retry < NdexDatabase.maxRetries; ++retry) {
try {
graph.removeVertex(graph.getVertex(networkDoc));
break;
} catch(ONeedRetryException e) {
logger.warning("Retry: "+ e.getMessage());
networkDoc.reload();
}
}
return count++;
}
/**
* Delete up to CLEANUP_BATCH_SIZE vertices in a network. This function is for cleaning up a logically
* deleted network in the database.
* @param networkDoc
* @return the number of vertices being deleted.
* @throws NdexException
* @throws ObjectNotFoundException
*/
private int cleanupNetworkElements(ODocument networkDoc) throws ObjectNotFoundException, NdexException {
int counter = 0;
for ( String fieldName : networkElementType) {
counter = cleanupElementsByEdge(networkDoc, fieldName, counter);
if ( counter >= CLEANUP_BATCH_SIZE) {
return counter;
}
}
return counter;
}
/**
* Cleanup up to CLEANUP_BATCH_SIZE vertices in the out going edge of fieldName.
* @param doc The ODocument record to be clean up on.
* @param fieldName
* @param currentCounter
* @return the number of vertices being deleted.
*/
private int cleanupElementsByEdge(ODocument doc, String fieldName, int currentCounter) {
Object f = doc.field("out_"+fieldName);
if ( f != null ) {
if ( f instanceof ORidBag ) {
ORidBag e = (ORidBag)f;
int counter = currentCounter;
for ( OIdentifiable rid : e) {
counter = cleanupElement((ODocument)rid, counter);
if ( counter >= CLEANUP_BATCH_SIZE) {
return counter;
}
}
return counter;
}
return cleanupElement((ODocument)f, currentCounter);
}
return currentCounter;
}
private int cleanupElement(ODocument doc, int currentCount) {
int counter = currentCount;
doc.reload();
for (int retry = 0; retry < NdexDatabase.maxRetries; ++retry) {
try {
graph.removeVertex(graph.getVertex(doc));
break;
} catch(ONeedRetryException e) {
logger.warning("Retry: "+ e.getMessage());
doc.reload();
}
}
counter ++;
if ( counter % 2000 == 0 ) {
graph.commit();
if (counter % 10000 == 0 ) {
logger.info("Deleted " + counter + " vertexes from network during cleanup.");
}
}
return counter;
}
public int logicalDeleteNetwork (String uuid) throws ObjectNotFoundException, NdexException {
ODocument networkDoc = getRecordByUUID(UUID.fromString(uuid), NdexClasses.Network);
if ( networkDoc != null) {
networkDoc.fields(NdexClasses.ExternalObj_isDeleted,true,
NdexClasses.ExternalObj_mTime, new Date()).save();
}
commit();
// remove the solr Index
SingleNetworkSolrIdxManager idxManager = new SingleNetworkSolrIdxManager(uuid);
try {
idxManager.dropIndex();
} catch (SolrServerException | HttpSolrClient.RemoteSolrException | IOException se ) {
logger.warning("node term index for network "+ uuid +" not found in Solr. Ignore deleteing solr index for it: " + se.getMessage());
}
return 1;
}
public int deleteNetworkElements(String UUID) {
int counter = 0;
String query = "traverse * from ( traverse out_networkNodes,out_BaseTerms,out_networkNS from (select from network where UUID='"
+ UUID + "')) while @class <> 'network'";
final List<ODocument> elements = db.query(new OSQLSynchQuery<ODocument>(query));
for ( ODocument element : elements ) {
element.reload();
graph.removeVertex(graph.getVertex(element));
counter ++;
if ( counter % 1500 == 0 ) {
graph.commit();
if (counter % 6000 == 0 ) {
logger.info("Deleted " + counter + " vertexes from network during cleanup." + UUID);
}
}
}
return counter;
}
/**
* delete all ndex and presentation properties from a network record.
* Properities on network elements won't be deleted.
*/
public static void deleteNetworkProperties(ODocument networkDoc) {
networkDoc.removeField(NdexClasses.ndexProperties);
networkDoc.save();
}
public PropertyGraphNetwork getProperytGraphNetworkById (UUID networkID, int skipBlocks, int blockSize) throws NdexException {
return new PropertyGraphNetwork( getNetwork(networkID,skipBlocks,blockSize));
}
public PropertyGraphNetwork getProperytGraphNetworkById(UUID id) throws NdexException {
return new PropertyGraphNetwork(this.getNetworkById(id));
}
/**************************************************************************
* getNetworkUserMemberships
*
* @param networkId
* UUID for network
* @param permission
* Type of memberships to retrieve, ADMIN, WRITE, or READ
* @param skipBlocks
* amount of blocks to skip
* @param blockSize
* The size of blocks to be skipped and retrieved
* @throws NdexException
* Invalid parameters or an error occurred while accessing the database
* @throws ObjectNotFoundException
* Invalid groupId
**************************************************************************/
public List<Membership> getNetworkUserMemberships(UUID networkId, Permissions permission, int skipBlocks, int blockSize)
throws ObjectNotFoundException, NdexException {
Preconditions.checkArgument(!Strings.isNullOrEmpty(networkId.toString()),
"A network UUID is required");
if ( permission !=null )
Preconditions.checkArgument(
(permission.equals( Permissions.ADMIN) )
|| (permission.equals( Permissions.WRITE ))
|| (permission.equals( Permissions.READ )),
"Valid permission required");
ODocument network = this.getRecordByUUID(networkId, NdexClasses.Network);
final int startIndex = skipBlocks
* blockSize;
List<Membership> memberships = new ArrayList<>();
String networkRID = network.getIdentity().toString();
String traverseCondition = null;
if ( permission != null)
traverseCondition = NdexClasses.Network +".in_"+ permission.name().toString();
else
traverseCondition = "in_" + Permissions.ADMIN + ",in_" + Permissions.READ + ",in_" + Permissions.WRITE;
OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<>(
"SELECT " + NdexClasses.account_P_accountName + "," +
NdexClasses.ExternalObj_ID + ", $path" +
" FROM"
+ " (TRAVERSE "+ traverseCondition.toLowerCase() +" FROM"
+ " " + networkRID
+ " WHILE $depth <=1)"
+ " WHERE @class = '" + NdexClasses.User + "'"
+ " OR @class='" + NdexClasses.Group + "'"
+ " ORDER BY " + NdexClasses.ExternalObj_cTime + " DESC " + " SKIP " + startIndex
+ " LIMIT " + blockSize);
List<ODocument> records = this.db.command(query).execute();
for(ODocument member: records) {
Membership membership = new Membership();
membership.setMembershipType( MembershipType.NETWORK );
membership.setMemberAccountName( (String) member.field(NdexClasses.account_P_accountName) );
membership.setMemberUUID( UUID.fromString( (String) member.field(NdexClasses.ExternalObj_ID) ) );
membership.setPermissions( Helper.getNetworkPermissionFromInPath ((String)member.field("$path") ));
membership.setResourceName( (String) network.field("name") );
membership.setResourceUUID( networkId );
memberships.add(membership);
}
logger.info("Successfuly retrieved network-user memberships");
return memberships;
}
public int grantPrivilege(String networkUUID, String accountUUID, Permissions permission) throws NdexException {
// check if the edge already exists?
Permissions p = Helper.getNetworkPermissionByAccout(db,networkUUID, accountUUID);
if ( p!=null && p == permission) {
logger.info("Permission " + permission + " already exists between account " + accountUUID +
" and network " + networkUUID + ". Igore grant request.");
return 0;
}
//check if this network has other admins
if ( permission != Permissions.ADMIN && !Helper.canRemoveAdmin(db, networkUUID, accountUUID)) {
throw new NdexException ("Privilege change failed. Network " + networkUUID +" will not have an administrator if permission " +
permission + " are granted to account " + accountUUID);
}
ODocument networkdoc = this.getNetworkDocByUUID(UUID.fromString(networkUUID));
ODocument accountdoc = this.getRecordByUUID(UUID.fromString(accountUUID), null);
OrientVertex networkV = graph.getVertex(networkdoc);
OrientVertex accountV = graph.getVertex(accountdoc);
for ( com.tinkerpop.blueprints.Edge e : accountV.getEdges(networkV, Direction.OUT)) {
for (int retry = 0; retry < NdexDatabase.maxRetries; ++retry) {
try {
graph.removeEdge(e);
break;
} catch(ONeedRetryException ex) {
logger.warning("Retry removing edge between account and network: " + ex.getMessage());
networkdoc.reload();
accountdoc.reload();
// networkV.reload();
// accountV.reload();
}
}
}
networkdoc.reload();
accountdoc.reload();
for (int retry = 0; retry < NdexDatabase.maxRetries; ++retry) {
try {
accountV.addEdge(permission.toString().toLowerCase(), networkV);
break;
} catch(ONeedRetryException e) {
logger.warning("Retry adding edge between account and network: " + e.getMessage());
networkdoc.reload();
accountdoc.reload();
// taskV.getRecord().removeField("out_"+ NdexClasses.Task_E_owner);
}
}
return 1;
}
public int revokePrivilege(String networkUUID, String accountUUID) throws NdexException {
// check if the edge exists?
Permissions p = Helper.getNetworkPermissionByAccout(this.db,networkUUID, accountUUID);
if ( p ==null ) {
logger.info("Permission doesn't exists between account " + accountUUID +
" and network " + networkUUID + ". Igore revoke request.");
return 0;
}
//check if this network has other admins
if ( p == Permissions.ADMIN && !Helper.canRemoveAdmin(this.db, networkUUID, accountUUID)) {
throw new NdexException ("Privilege revoke failed. Network " + networkUUID +" only has account " + accountUUID
+ " as the administrator.");
}
ODocument networkdoc = this.getNetworkDocByUUID(UUID.fromString(networkUUID));
ODocument accountdoc = this.getRecordByUUID(UUID.fromString(accountUUID), null);
OrientVertex networkV = graph.getVertex(networkdoc);
OrientVertex accountV = graph.getVertex(accountdoc);
for ( com.tinkerpop.blueprints.Edge e : accountV.getEdges(networkV, Direction.OUT)) {
for (int retry = 0; retry < NdexDatabase.maxRetries; ++retry) {
try {
graph.removeEdge(e);
break;
} catch(ONeedRetryException ex) {
logger.warning("Retry removing edge between account and network: " + ex.getMessage());
// networkdoc.reload();
// accountdoc.reload();
networkV.reload();
accountV.reload();
}
}
break;
}
return 1;
}
public void rollback() {
graph.rollback();
}
@Override
public void commit() {
graph.commit();
}
@Override
public void close() {
graph.shutdown();
}
public void updateNetworkProfile(UUID networkId, NetworkSummary newSummary) {
ODocument doc = this.getNetworkDocByUUID(networkId);
Helper.updateNetworkProfile(doc, newSummary);
}
}
| src/main/java/org/ndexbio/common/models/dao/orientdb/NetworkDAO.java | /**
* Copyright (c) 2013, 2015, The Regents of the University of California, The Cytoscape Consortium
* 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. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.ndexbio.common.models.dao.orientdb;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.logging.Logger;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.ndexbio.common.NdexClasses;
import org.ndexbio.common.access.NdexDatabase;
import org.ndexbio.common.solr.SingleNetworkSolrIdxManager;
import org.ndexbio.model.exceptions.*;
import org.ndexbio.model.object.Membership;
import org.ndexbio.model.object.MembershipType;
import org.ndexbio.model.object.NdexPropertyValuePair;
import org.ndexbio.model.object.Permissions;
import org.ndexbio.model.object.PropertiedObject;
import org.ndexbio.model.object.SimplePropertyValuePair;
import org.ndexbio.model.object.network.Edge;
import org.ndexbio.model.object.network.FunctionTerm;
import org.ndexbio.model.object.network.Namespace;
import org.ndexbio.model.object.network.Network;
import org.ndexbio.model.object.network.NetworkSourceFormat;
import org.ndexbio.model.object.network.NetworkSummary;
import org.ndexbio.model.object.network.Node;
import org.ndexbio.model.object.network.PropertyGraphEdge;
import org.ndexbio.model.object.network.PropertyGraphNetwork;
import org.ndexbio.model.object.network.PropertyGraphNode;
import org.ndexbio.model.object.network.ReifiedEdgeTerm;
import org.ndexbio.model.object.network.VisibilityType;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.orientechnologies.common.concur.ONeedRetryException;
import com.orientechnologies.orient.core.command.traverse.OTraverse;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.filter.OSQLPredicate;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.orientechnologies.orient.core.id.ORID;
public class NetworkDAO extends NetworkDocDAO {
private OrientGraph graph;
private static final int CLEANUP_BATCH_SIZE = 50000;
private static final String[] networkElementType = {NdexClasses.Network_E_BaseTerms, NdexClasses.Network_E_Nodes, NdexClasses.Network_E_Citations,
NdexClasses.Network_E_Edges, NdexClasses.Network_E_FunctionTerms, NdexClasses.Network_E_Namespace,
NdexClasses.Network_E_ReifiedEdgeTerms, NdexClasses.Network_E_Supports
// , NdexClasses.E_ndexPresentationProps, NdexClasses.E_ndexProperties
};
static Logger logger = Logger.getLogger(NetworkDAO.class.getName());
public NetworkDAO (ODatabaseDocumentTx db) {
super(db);
graph = new OrientGraph(this.db,false);
graph.setAutoScaleEdgeType(true);
graph.setEdgeContainerEmbedded2TreeThreshold(40);
graph.setUseLightweightEdges(true);
}
public NetworkDAO () throws NdexException {
this(NdexDatabase.getInstance().getAConnection());
}
public int deleteNetwork (String UUID) throws ObjectNotFoundException, NdexException {
int counter = 0, cnt = 0;
do {
cnt = cleanupDeleteNetwork(UUID);
if (cnt <0 )
counter += -1*cnt;
else
counter += cnt;
} while ( cnt < 0 );
return counter;
}
/**
* Delete up to CLEANUP_BATCH_SIZE vertices in a network. This function is for cleaning up a logically
* deleted network in the database.
* @param uuid
* @return Number of vertices being deleted. If the returned number is negative, it means the elements
* of the network are not completely deleted yet, and the number of vertices deleted are abs(returned number).
* @throws ObjectNotFoundException
* @throws NdexException
*/
public int cleanupDeleteNetwork(String uuid) throws ObjectNotFoundException, NdexException {
ODocument networkDoc = getRecordByUUID(UUID.fromString(uuid), NdexClasses.Network);
int count = cleanupNetworkElements(networkDoc);
if ( count >= CLEANUP_BATCH_SIZE) {
return (-1) * count;
}
// remove the network node.
networkDoc.reload();
for (int retry = 0; retry < NdexDatabase.maxRetries; ++retry) {
try {
graph.removeVertex(graph.getVertex(networkDoc));
break;
} catch(ONeedRetryException e) {
logger.warning("Retry: "+ e.getMessage());
networkDoc.reload();
}
}
return count++;
}
/**
* Delete up to CLEANUP_BATCH_SIZE vertices in a network. This function is for cleaning up a logically
* deleted network in the database.
* @param networkDoc
* @return the number of vertices being deleted.
* @throws NdexException
* @throws ObjectNotFoundException
*/
private int cleanupNetworkElements(ODocument networkDoc) throws ObjectNotFoundException, NdexException {
int counter = 0;
for ( String fieldName : networkElementType) {
counter = cleanupElementsByEdge(networkDoc, fieldName, counter);
if ( counter >= CLEANUP_BATCH_SIZE) {
return counter;
}
}
return counter;
}
/**
* Cleanup up to CLEANUP_BATCH_SIZE vertices in the out going edge of fieldName.
* @param doc The ODocument record to be clean up on.
* @param fieldName
* @param currentCounter
* @return the number of vertices being deleted.
*/
private int cleanupElementsByEdge(ODocument doc, String fieldName, int currentCounter) {
Object f = doc.field("out_"+fieldName);
if ( f != null ) {
if ( f instanceof ORidBag ) {
ORidBag e = (ORidBag)f;
int counter = currentCounter;
for ( OIdentifiable rid : e) {
counter = cleanupElement((ODocument)rid, counter);
if ( counter >= CLEANUP_BATCH_SIZE) {
return counter;
}
}
return counter;
}
return cleanupElement((ODocument)f, currentCounter);
}
return currentCounter;
}
private int cleanupElement(ODocument doc, int currentCount) {
int counter = currentCount;
doc.reload();
for (int retry = 0; retry < NdexDatabase.maxRetries; ++retry) {
try {
graph.removeVertex(graph.getVertex(doc));
break;
} catch(ONeedRetryException e) {
logger.warning("Retry: "+ e.getMessage());
doc.reload();
}
}
counter ++;
if ( counter % 2000 == 0 ) {
graph.commit();
if (counter % 10000 == 0 ) {
logger.info("Deleted " + counter + " vertexes from network during cleanup.");
}
}
return counter;
}
public int logicalDeleteNetwork (String uuid) throws ObjectNotFoundException, NdexException {
ODocument networkDoc = getRecordByUUID(UUID.fromString(uuid), NdexClasses.Network);
if ( networkDoc != null) {
networkDoc.fields(NdexClasses.ExternalObj_isDeleted,true,
NdexClasses.ExternalObj_mTime, new Date()).save();
}
commit();
// remove the solr Index
SingleNetworkSolrIdxManager idxManager = new SingleNetworkSolrIdxManager(uuid);
try {
idxManager.dropIndex();
} catch (SolrServerException | HttpSolrClient.RemoteSolrException | IOException se ) {
logger.warning("node term index for network "+ uuid +" not found in Solr. Ignore deleteing solr index for it: " + se.getMessage());
}
return 1;
}
public int deleteNetworkElements(String UUID) {
int counter = 0;
String query = "traverse * from ( traverse out_networkNodes,out_BaseTerms,out_networkNS from (select from network where UUID='"
+ UUID + "')) while @class <> 'network'";
final List<ODocument> elements = db.query(new OSQLSynchQuery<ODocument>(query));
for ( ODocument element : elements ) {
element.reload();
graph.removeVertex(graph.getVertex(element));
counter ++;
if ( counter % 1500 == 0 ) {
graph.commit();
if (counter % 6000 == 0 ) {
logger.info("Deleted " + counter + " vertexes from network during cleanup." + UUID);
}
}
}
return counter;
}
/**
* delete all ndex and presentation properties from a network record.
* Properities on network elements won't be deleted.
*/
public static void deleteNetworkProperties(ODocument networkDoc) {
networkDoc.removeField(NdexClasses.ndexProperties);
networkDoc.save();
}
public PropertyGraphNetwork getProperytGraphNetworkById (UUID networkID, int skipBlocks, int blockSize) throws NdexException {
return new PropertyGraphNetwork( getNetwork(networkID,skipBlocks,blockSize));
}
public PropertyGraphNetwork getProperytGraphNetworkById(UUID id) throws NdexException {
return new PropertyGraphNetwork(this.getNetworkById(id));
}
/**************************************************************************
* getNetworkUserMemberships
*
* @param networkId
* UUID for network
* @param permission
* Type of memberships to retrieve, ADMIN, WRITE, or READ
* @param skipBlocks
* amount of blocks to skip
* @param blockSize
* The size of blocks to be skipped and retrieved
* @throws NdexException
* Invalid parameters or an error occurred while accessing the database
* @throws ObjectNotFoundException
* Invalid groupId
**************************************************************************/
public List<Membership> getNetworkUserMemberships(UUID networkId, Permissions permission, int skipBlocks, int blockSize)
throws ObjectNotFoundException, NdexException {
Preconditions.checkArgument(!Strings.isNullOrEmpty(networkId.toString()),
"A network UUID is required");
if ( permission !=null )
Preconditions.checkArgument(
(permission.equals( Permissions.ADMIN) )
|| (permission.equals( Permissions.WRITE ))
|| (permission.equals( Permissions.READ )),
"Valid permission required");
ODocument network = this.getRecordByUUID(networkId, NdexClasses.Network);
final int startIndex = skipBlocks
* blockSize;
List<Membership> memberships = new ArrayList<>();
String networkRID = network.getIdentity().toString();
String traverseCondition = null;
if ( permission != null)
traverseCondition = NdexClasses.Network +".in_"+ permission.name().toString();
else
traverseCondition = "in_" + Permissions.ADMIN + ",in_" + Permissions.READ + ",in_" + Permissions.WRITE;
OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<>(
"SELECT " + NdexClasses.account_P_accountName + "," +
NdexClasses.ExternalObj_ID + ", $path" +
" FROM"
+ " (TRAVERSE "+ traverseCondition.toLowerCase() +" FROM"
+ " " + networkRID
+ " WHILE $depth <=1)"
+ " WHERE @class = '" + NdexClasses.User + "'"
+ " OR @class='" + NdexClasses.Group + "'"
+ " ORDER BY " + NdexClasses.ExternalObj_cTime + " DESC " + " SKIP " + startIndex
+ " LIMIT " + blockSize);
List<ODocument> records = this.db.command(query).execute();
for(ODocument member: records) {
Membership membership = new Membership();
membership.setMembershipType( MembershipType.NETWORK );
membership.setMemberAccountName( (String) member.field(NdexClasses.account_P_accountName) );
membership.setMemberUUID( UUID.fromString( (String) member.field(NdexClasses.ExternalObj_ID) ) );
membership.setPermissions( Helper.getNetworkPermissionFromInPath ((String)member.field("$path") ));
membership.setResourceName( (String) network.field("name") );
membership.setResourceUUID( networkId );
memberships.add(membership);
}
logger.info("Successfuly retrieved network-user memberships");
return memberships;
}
public int grantPrivilege(String networkUUID, String accountUUID, Permissions permission) throws NdexException {
// check if the edge already exists?
Permissions p = Helper.getNetworkPermissionByAccout(db,networkUUID, accountUUID);
if ( p!=null && p == permission) {
logger.info("Permission " + permission + " already exists between account " + accountUUID +
" and network " + networkUUID + ". Igore grant request.");
return 0;
}
//check if this network has other admins
if ( permission != Permissions.ADMIN && !Helper.canRemoveAdmin(db, networkUUID, accountUUID)) {
throw new NdexException ("Privilege change failed. Network " + networkUUID +" will not have an administrator if permission " +
permission + " are granted to account " + accountUUID);
}
ODocument networkdoc = this.getNetworkDocByUUID(UUID.fromString(networkUUID));
ODocument accountdoc = this.getRecordByUUID(UUID.fromString(accountUUID), null);
OrientVertex networkV = graph.getVertex(networkdoc);
OrientVertex accountV = graph.getVertex(accountdoc);
for ( com.tinkerpop.blueprints.Edge e : accountV.getEdges(networkV, Direction.OUT)) {
for (int retry = 0; retry < NdexDatabase.maxRetries; ++retry) {
try {
graph.removeEdge(e);
break;
} catch(ONeedRetryException ex) {
logger.warning("Retry adding edge between account and network: " + ex.getMessage());
// networkdoc.reload();
// accountdoc.reload();
networkV.reload();
accountV.reload();
}
}
break;
}
networkdoc.reload();
accountdoc.reload();
for (int retry = 0; retry < NdexDatabase.maxRetries; ++retry) {
try {
accountV.addEdge(permission.toString().toLowerCase(), networkV);
break;
} catch(ONeedRetryException e) {
logger.warning("Retry adding edge between account and network: " + e.getMessage());
networkdoc.reload();
accountdoc.reload();
// taskV.getRecord().removeField("out_"+ NdexClasses.Task_E_owner);
}
}
return 1;
}
public int revokePrivilege(String networkUUID, String accountUUID) throws NdexException {
// check if the edge exists?
Permissions p = Helper.getNetworkPermissionByAccout(this.db,networkUUID, accountUUID);
if ( p ==null ) {
logger.info("Permission doesn't exists between account " + accountUUID +
" and network " + networkUUID + ". Igore revoke request.");
return 0;
}
//check if this network has other admins
if ( p == Permissions.ADMIN && !Helper.canRemoveAdmin(this.db, networkUUID, accountUUID)) {
throw new NdexException ("Privilege revoke failed. Network " + networkUUID +" only has account " + accountUUID
+ " as the administrator.");
}
ODocument networkdoc = this.getNetworkDocByUUID(UUID.fromString(networkUUID));
ODocument accountdoc = this.getRecordByUUID(UUID.fromString(accountUUID), null);
OrientVertex networkV = graph.getVertex(networkdoc);
OrientVertex accountV = graph.getVertex(accountdoc);
for ( com.tinkerpop.blueprints.Edge e : accountV.getEdges(networkV, Direction.OUT)) {
for (int retry = 0; retry < NdexDatabase.maxRetries; ++retry) {
try {
graph.removeEdge(e);
break;
} catch(ONeedRetryException ex) {
logger.warning("Retry adding edge between account and network: " + ex.getMessage());
// networkdoc.reload();
// accountdoc.reload();
networkV.reload();
accountV.reload();
}
}
break;
}
return 1;
}
public void rollback() {
graph.rollback();
}
@Override
public void commit() {
graph.commit();
}
@Override
public void close() {
graph.shutdown();
}
public void updateNetworkProfile(UUID networkId, NetworkSummary newSummary) {
ODocument doc = this.getNetworkDocByUUID(networkId);
Helper.updateNetworkProfile(doc, newSummary);
}
}
| Logging info was wrong. | src/main/java/org/ndexbio/common/models/dao/orientdb/NetworkDAO.java | Logging info was wrong. | <ide><path>rc/main/java/org/ndexbio/common/models/dao/orientdb/NetworkDAO.java
<ide> graph.removeEdge(e);
<ide> break;
<ide> } catch(ONeedRetryException ex) {
<del> logger.warning("Retry adding edge between account and network: " + ex.getMessage());
<del> // networkdoc.reload();
<del> // accountdoc.reload();
<del> networkV.reload();
<del> accountV.reload();
<add> logger.warning("Retry removing edge between account and network: " + ex.getMessage());
<add> networkdoc.reload();
<add> accountdoc.reload();
<add>// networkV.reload();
<add>// accountV.reload();
<ide> }
<ide> }
<del> break;
<ide> }
<ide>
<ide> networkdoc.reload();
<ide> graph.removeEdge(e);
<ide> break;
<ide> } catch(ONeedRetryException ex) {
<del> logger.warning("Retry adding edge between account and network: " + ex.getMessage());
<add> logger.warning("Retry removing edge between account and network: " + ex.getMessage());
<ide> // networkdoc.reload();
<ide> // accountdoc.reload();
<ide> networkV.reload(); |
|
Java | apache-2.0 | fb30153d9994a04e4a65b7d3ba05373261b95359 | 0 | jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2002-2011 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.jaamsim.basicsim;
import java.io.File;
import javax.swing.JFrame;
import com.jaamsim.events.EventManager;
import com.jaamsim.input.BooleanInput;
import com.jaamsim.input.DirInput;
import com.jaamsim.input.EntityListInput;
import com.jaamsim.input.Input;
import com.jaamsim.input.InputAgent;
import com.jaamsim.input.IntegerInput;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.Output;
import com.jaamsim.input.ValueInput;
import com.jaamsim.math.Vec3d;
import com.jaamsim.ui.EditBox;
import com.jaamsim.ui.EntityPallet;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.ui.GUIFrame;
import com.jaamsim.ui.LogBox;
import com.jaamsim.ui.ObjectSelector;
import com.jaamsim.ui.OutputBox;
import com.jaamsim.ui.PropertyBox;
import com.jaamsim.units.DistanceUnit;
import com.jaamsim.units.TimeUnit;
import com.jaamsim.units.Unit;
/**
* Simulation provides the basic structure for the Entity model lifetime of earlyInit,
* startUp and doEndAt. The initial processtargets required to start the model are
* added to the eventmanager here. This class also acts as a bridge to the UI by
* providing controls for the various windows.
*/
public class Simulation extends Entity {
// Key Inputs tab
@Keyword(description = "The duration of the simulation run in which all statistics will be recorded.",
example = "Simulation Duration { 8760 h }")
private static final ValueInput runDuration;
@Keyword(description = "The initialization interval for the simulation run. The model will run "
+ "for the InitializationDuration interval and then clear the statistics and execute for the "
+ "specified RunDuration interval. The total length of the simulation run will be the sum of "
+ "the InitializationDuration and RunDuration inputs.",
example = "Simulation Initialization { 720 h }")
private static final ValueInput initializationTime;
@Keyword(description = "Indicates whether an output report will be printed at the end of the simulation run.",
example = "Simulation PrintReport { TRUE }")
private static final BooleanInput printReport;
@Keyword(description = "The directory in which to place the output report. Defaults to the "
+ "directory containing the configuration file for the run.",
example = "Simulation ReportDirectory { 'c:\reports\' }")
private static final DirInput reportDirectory;
@Keyword(description = "The length of time represented by one simulation tick.",
example = "Simulation TickLength { 1e-6 s }")
private static final ValueInput tickLengthInput;
@Keyword(description = "Indicates whether to close the program on completion of the simulation run.",
example = "Simulation ExitAtStop { TRUE }")
private static final BooleanInput exitAtStop;
@Keyword(description = "Global seed that sets the substream for each probability distribution. "
+ "Must be an integer >= 0. GlobalSubstreamSeed works together with each probability "
+ "distribution's RandomSeed keyword to determine its random sequence. It allows the "
+ "user to change all the random sequences in a model with a single input.",
example = "Simulation GlobalSubstreamSeed { 5 }")
private static final IntegerInput globalSeedInput;
// GUI tab
@Keyword(description = "An optional list of units to be used for displaying model outputs.",
example = "Simulation DisplayedUnits { h kt }")
private static final EntityListInput<? extends Unit> displayedUnits;
@Keyword(description = "If TRUE, a dragged object will be positioned to the nearest grid point.",
example = "Simulation SnapToGrid { TRUE }")
private static final BooleanInput snapToGrid;
@Keyword(description = "The distance between snap grid points.",
example = "Simulation SnapGridSpacing { 1 m }")
private static final ValueInput snapGridSpacing;
@Keyword(description = "The distance moved by the selected entity when the an arrow key is pressed.",
example = "Simulation IncrementSize { 1 cm }")
private static final ValueInput incrementSize;
@Keyword(description = "A Boolean to turn on or off real time in the simulation run",
example = "Simulation RealTime { TRUE }")
private static final BooleanInput realTime;
@Keyword(description = "The real time speed up factor",
example = "Simulation RealTimeFactor { 1200 }")
private static final IntegerInput realTimeFactor;
public static final int DEFAULT_REAL_TIME_FACTOR = 1;
public static final int MIN_REAL_TIME_FACTOR = 1;
public static final int MAX_REAL_TIME_FACTOR= 1000000;
@Keyword(description = "The time at which the simulation will be paused.",
example = "Simulation PauseTime { 200 h }")
private static final ValueInput pauseTime;
@Keyword(description = "Indicates whether the Model Builder tool should be shown on startup.",
example = "Simulation ShowModelBuilder { TRUE }")
private static final BooleanInput showModelBuilder;
@Keyword(description = "Indicates whether the Object Selector tool should be shown on startup.",
example = "Simulation ShowObjectSelector { TRUE }")
private static final BooleanInput showObjectSelector;
@Keyword(description = "Indicates whether the Input Editor tool should be shown on startup.",
example = "Simulation ShowInputEditor { TRUE }")
private static final BooleanInput showInputEditor;
@Keyword(description = "Indicates whether the Output Viewer tool should be shown on startup.",
example = "Simulation ShowOutputViewer { TRUE }")
private static final BooleanInput showOutputViewer;
@Keyword(description = "Indicates whether the Output Viewer tool should be shown on startup.",
example = "Simulation ShowPropertyViewer { TRUE }")
private static final BooleanInput showPropertyViewer;
@Keyword(description = "Indicates whether the Log Viewer tool should be shown on startup.",
example = "Simulation ShowLogViewer { TRUE }")
private static final BooleanInput showLogViewer;
@Keyword(description = "Time at which the simulation run is started (hh:mm).",
example = "Simulation StartTime { 2160 h }")
private static final ValueInput startTimeInput;
// Hidden keywords
@Keyword(description = "If the value is TRUE, then the input report file will be printed after "
+ "loading the configuration file. The input report can always be generated when "
+ "needed by selecting \"Print Input Report\" under the File menu.",
example = "Simulation PrintInputReport { TRUE }")
private static final BooleanInput printInputReport;
@Keyword(description = "This is placeholder description text",
example = "This is placeholder example text")
private static final BooleanInput traceEventsInput;
@Keyword(description = "This is placeholder description text",
example = "This is placeholder example text")
private static final BooleanInput verifyEventsInput;
private static double timeScale; // the scale from discrete to continuous time
private static double startTime; // simulation time (seconds) for the start of the run (not necessarily zero)
private static double endTime; // simulation time (seconds) for the end of the run
private static Simulation myInstance;
private static String modelName = "JaamSim";
static {
// Key Inputs tab
runDuration = new ValueInput("RunDuration", "Key Inputs", 31536000.0d);
runDuration.setUnitType(TimeUnit.class);
runDuration.setValidRange(1e-15d, Double.POSITIVE_INFINITY);
initializationTime = new ValueInput("InitializationDuration", "Key Inputs", 0.0);
initializationTime.setUnitType(TimeUnit.class);
initializationTime.setValidRange(0.0d, Double.POSITIVE_INFINITY);
printReport = new BooleanInput("PrintReport", "Key Inputs", false);
reportDirectory = new DirInput("ReportDirectory", "Key Inputs", null);
reportDirectory.setDefaultText("Configuration File Directory");
tickLengthInput = new ValueInput("TickLength", "Key Inputs", 1e-6d);
tickLengthInput.setUnitType(TimeUnit.class);
tickLengthInput.setValidRange(1e-9d, 5.0d);
exitAtStop = new BooleanInput("ExitAtStop", "Key Inputs", false);
globalSeedInput = new IntegerInput("GlobalSubstreamSeed", "Key Inputs", 0);
globalSeedInput.setValidRange(0, Integer.MAX_VALUE);
// GUI tab
displayedUnits = new EntityListInput<>(Unit.class, "DisplayedUnits", "GUI", null);
displayedUnits.setDefaultText("SI Units");
displayedUnits.setPromptReqd(false);
realTime = new BooleanInput("RealTime", "GUI", false);
realTime.setPromptReqd(false);
snapToGrid = new BooleanInput("SnapToGrid", "GUI", false);
snapToGrid.setPromptReqd(false);
snapGridSpacing = new ValueInput("SnapGridSpacing", "GUI", 0.1d);
snapGridSpacing.setUnitType(DistanceUnit.class);
snapGridSpacing.setValidRange(1.0e-6, Double.POSITIVE_INFINITY);
snapGridSpacing.setPromptReqd(false);
incrementSize = new ValueInput("IncrementSize", "GUI", 0.1d);
incrementSize.setUnitType(DistanceUnit.class);
incrementSize.setValidRange(1.0e-6, Double.POSITIVE_INFINITY);
incrementSize.setPromptReqd(false);
realTimeFactor = new IntegerInput("RealTimeFactor", "GUI", DEFAULT_REAL_TIME_FACTOR);
realTimeFactor.setValidRange(MIN_REAL_TIME_FACTOR, MAX_REAL_TIME_FACTOR);
realTimeFactor.setPromptReqd(false);
pauseTime = new ValueInput("PauseTime", "GUI", Double.POSITIVE_INFINITY);
pauseTime.setUnitType(TimeUnit.class);
pauseTime.setValidRange(0.0d, Double.POSITIVE_INFINITY);
pauseTime.setPromptReqd(false);
showModelBuilder = new BooleanInput("ShowModelBuilder", "GUI", false);
showModelBuilder.setPromptReqd(false);
showObjectSelector = new BooleanInput("ShowObjectSelector", "GUI", false);
showObjectSelector.setPromptReqd(false);
showInputEditor = new BooleanInput("ShowInputEditor", "GUI", false);
showInputEditor.setPromptReqd(false);
showOutputViewer = new BooleanInput("ShowOutputViewer", "GUI", false);
showOutputViewer.setPromptReqd(false);
showPropertyViewer = new BooleanInput("ShowPropertyViewer", "GUI", false);
showPropertyViewer.setPromptReqd(false);
showLogViewer = new BooleanInput("ShowLogViewer", "GUI", false);
showLogViewer.setPromptReqd(false);
// Hidden keywords
startTimeInput = new ValueInput("StartTime", "Key Inputs", 0.0d);
startTimeInput.setUnitType(TimeUnit.class);
startTimeInput.setValidRange(0.0d, Double.POSITIVE_INFINITY);
traceEventsInput = new BooleanInput("TraceEvents", "Key Inputs", false);
verifyEventsInput = new BooleanInput("VerifyEvents", "Key Inputs", false);
printInputReport = new BooleanInput("PrintInputReport", "Key Inputs", false);
// Initialize basic model information
startTime = 0.0;
endTime = 8760.0*3600.0;
}
{
// Key Inputs tab
this.addInput(runDuration);
this.addInput(initializationTime);
this.addInput(printReport);
this.addInput(reportDirectory);
this.addInput(tickLengthInput);
this.addInput(exitAtStop);
this.addInput(globalSeedInput);
// GUI tab
this.addInput(displayedUnits);
this.addInput(snapToGrid);
this.addInput(snapGridSpacing);
this.addInput(incrementSize);
this.addInput(realTime);
this.addInput(realTimeFactor);
this.addInput(pauseTime);
this.addInput(showModelBuilder);
this.addInput(showObjectSelector);
this.addInput(showInputEditor);
this.addInput(showOutputViewer);
this.addInput(showPropertyViewer);
this.addInput(showLogViewer);
// Hidden keywords
this.addInput(startTimeInput);
this.addInput(traceEventsInput);
this.addInput(verifyEventsInput);
this.addInput(printInputReport);
// Hide various keywords
startTimeInput.setHidden(true);
traceEventsInput.setHidden(true);
verifyEventsInput.setHidden(true);
printInputReport.setHidden(true);
}
public Simulation() {}
public static Simulation getInstance() {
if (myInstance == null) {
for (Entity ent : Entity.getAll()) {
if (ent instanceof Simulation ) {
myInstance = (Simulation) ent;
break;
}
}
}
return myInstance;
}
@Override
public void updateForInput( Input<?> in ) {
super.updateForInput( in );
if(in == realTimeFactor || in == realTime) {
updateRealTime();
return;
}
if (in == pauseTime) {
updatePauseTime();
return;
}
if (in == reportDirectory) {
InputAgent.setReportDirectory(reportDirectory.getDir());
return;
}
if (in == displayedUnits) {
if (displayedUnits.getValue() == null)
return;
for (Unit u : displayedUnits.getValue()) {
Unit.setPreferredUnit(u.getClass(), u);
}
return;
}
if (in == showModelBuilder) {
setWindowVisible(EntityPallet.getInstance(), showModelBuilder.getValue());
return;
}
if (in == showObjectSelector) {
setWindowVisible(ObjectSelector.getInstance(), showObjectSelector.getValue());
return;
}
if (in == showInputEditor) {
setWindowVisible(EditBox.getInstance(), showInputEditor.getValue());
FrameBox.reSelectEntity();
return;
}
if (in == showOutputViewer) {
setWindowVisible(OutputBox.getInstance(), showOutputViewer.getValue());
FrameBox.reSelectEntity();
return;
}
if (in == showPropertyViewer) {
setWindowVisible(PropertyBox.getInstance(), showPropertyViewer.getValue());
FrameBox.reSelectEntity();
return;
}
if (in == showLogViewer) {
setWindowVisible(LogBox.getInstance(), showLogViewer.getValue());
FrameBox.reSelectEntity();
return;
}
}
public static void clear() {
initializationTime.reset();
runDuration.reset();
pauseTime.reset();
tickLengthInput.reset();
traceEventsInput.reset();
verifyEventsInput.reset();
printInputReport.reset();
realTimeFactor.reset();
realTime.reset();
updateRealTime();
exitAtStop.reset();
startTimeInput.reset();
showModelBuilder.reset();
showObjectSelector.reset();
showInputEditor.reset();
showOutputViewer.reset();
showPropertyViewer.reset();
showLogViewer.reset();
// Initialize basic model information
startTime = 0.0;
endTime = 8760.0*3600.0;
myInstance = null;
// close warning/error trace file
InputAgent.closeLogFile();
// Kill all entities except simulation
while(Entity.getAll().size() > 0) {
Entity ent = Entity.getAll().get(Entity.getAll().size()-1);
ent.kill();
}
}
/**
* Initializes and starts the model
* 1) Initializes EventManager to accept events.
* 2) calls startModel() to allow the model to add its starting events to EventManager
* 3) start EventManager processing events
*/
public static void start(EventManager evt) {
// Validate each entity based on inputs only
for (int i = 0; i < Entity.getAll().size(); i++) {
try {
Entity.getAll().get(i).validate();
}
catch (Throwable e) {
LogBox.format("%s: Validation error- %s", Entity.getAll().get(i).getName(), e.getMessage());
GUIFrame.showErrorDialog("Input Error Detected During Validation",
"%s: %-70s",
Entity.getAll().get(i).getName(), e.getMessage());
GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED);
return;
}
}
InputAgent.prepareReportDirectory();
evt.clear();
evt.setTraceListener(null);
if( Simulation.traceEvents() ) {
String evtName = InputAgent.getConfigFile().getParentFile() + File.separator + InputAgent.getRunName() + ".evt";
EventRecorder rec = new EventRecorder(evtName);
evt.setTraceListener(rec);
}
else if( Simulation.verifyEvents() ) {
String evtName = InputAgent.getConfigFile().getParentFile() + File.separator + InputAgent.getRunName() + ".evt";
EventTracer trc = new EventTracer(evtName);
evt.setTraceListener(trc);
}
evt.setTickLength(tickLengthInput.getValue());
setSimTimeScale(evt.secondsToNearestTick(3600.0d));
FrameBox.setSecondsPerTick(tickLengthInput.getValue());
startTime = startTimeInput.getValue();
endTime = startTime + Simulation.getInitializationTime() + Simulation.getRunDuration();
evt.scheduleProcessExternal(0, 0, false, new InitModelTarget(), null);
evt.resume(evt.secondsToNearestTick(Simulation.getPauseTime()));
}
public static int getSubstreamNumber() {
return globalSeedInput.getValue();
}
public static boolean getPrintReport() {
return printReport.getValue();
}
public static boolean traceEvents() {
return traceEventsInput.getValue();
}
public static boolean verifyEvents() {
return verifyEventsInput.getValue();
}
static void setSimTimeScale(double scale) {
timeScale = scale;
}
public static double getSimTimeFactor() {
return timeScale;
}
public static double getEventTolerance() {
return (1.0d / getSimTimeFactor());
}
public static double getTickLength() {
return tickLengthInput.getValue();
}
public static double getPauseTime() {
return pauseTime.getValue();
}
/**
* Returns the start time of the run.
* @return - simulation time in seconds for the start of the run.
*/
public static double getStartTime() {
return startTime;
}
/**
* Returns the end time of the run.
* @return - simulation time in seconds when the current run will stop.
*/
public static double getEndTime() {
return endTime;
}
/**
* Returns the duration of the run (not including intialization)
*/
public static double getRunDuration() {
return runDuration.getValue();
}
/**
* Returns the duration of the initialization period
*/
public static double getInitializationTime() {
return initializationTime.getValue();
}
public static double getIncrementSize() {
return incrementSize.getValue();
}
public static boolean isSnapToGrid() {
return snapToGrid.getValue();
}
public static double getSnapGridSpacing() {
return snapGridSpacing.getValue();
}
/**
* Returns the nearest point on the snap grid to the given coordinate.
* To avoid dithering, the new position must be at least one grid space
* from the old position.
* @param newPos - new coordinate for the object
* @param oldPos - present coordinate for the object
* @return newest snap grid point.
*/
public static Vec3d getSnapGridPosition(Vec3d newPos, Vec3d oldPos) {
double spacing = snapGridSpacing.getValue();
Vec3d ret = new Vec3d(newPos);
if (Math.abs(newPos.x - oldPos.x) < spacing)
ret.x = oldPos.x;
if (Math.abs(newPos.y - oldPos.y) < spacing)
ret.y = oldPos.y;
if (Math.abs(newPos.z - oldPos.z) < spacing)
ret.z = oldPos.z;
return Simulation.getSnapGridPosition(ret);
}
/**
* Returns the nearest point on the snap grid to the given coordinate.
* @param pos - position to be adjusted
* @return nearest snap grid point.
*/
public static Vec3d getSnapGridPosition(Vec3d pos) {
double spacing = snapGridSpacing.getValue();
Vec3d ret = new Vec3d(pos);
ret.x = spacing*Math.rint(ret.x/spacing);
ret.y = spacing*Math.rint(ret.y/spacing);
ret.z = spacing*Math.rint(ret.z/spacing);
return ret;
}
static void updateRealTime() {
GUIFrame.instance().updateForRealTime(realTime.getValue(), realTimeFactor.getValue());
}
static void updatePauseTime() {
GUIFrame.instance().updateForPauseTime(pauseTime.getValueString());
}
public static void setModelName(String newModelName) {
modelName = newModelName;
}
public static String getModelName() {
return modelName;
}
public static boolean getExitAtStop() {
return exitAtStop.getValue();
}
public static boolean getPrintInputReport() {
return printInputReport.getValue();
}
public static void setWindowVisible(JFrame f, boolean visible) {
f.setVisible(visible);
if (visible)
f.toFront();
}
/**
* Re-open any Tools windows that have been closed temporarily.
*/
public static void showActiveTools() {
setWindowVisible(EntityPallet.getInstance(), showModelBuilder.getValue());
setWindowVisible(ObjectSelector.getInstance(), showObjectSelector.getValue());
setWindowVisible(EditBox.getInstance(), showInputEditor.getValue());
setWindowVisible(OutputBox.getInstance(), showOutputViewer.getValue());
setWindowVisible(PropertyBox.getInstance(), showPropertyViewer.getValue());
setWindowVisible(LogBox.getInstance(), showLogViewer.getValue());
}
/**
* Closes all the Tools windows temporarily.
*/
public static void closeAllTools() {
setWindowVisible(EntityPallet.getInstance(), false);
setWindowVisible(ObjectSelector.getInstance(), false);
setWindowVisible(EditBox.getInstance(), false);
setWindowVisible(OutputBox.getInstance(), false);
setWindowVisible(PropertyBox.getInstance(), false);
setWindowVisible(LogBox.getInstance(), false);
}
@Output(name = "Configuration File",
description = "The present configuration file.")
public String getConfigFileName(double simTime) {
return InputAgent.getConfigFile().getPath();
}
}
| src/main/java/com/jaamsim/basicsim/Simulation.java | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2002-2011 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.jaamsim.basicsim;
import java.io.File;
import javax.swing.JFrame;
import com.jaamsim.events.EventManager;
import com.jaamsim.input.BooleanInput;
import com.jaamsim.input.DirInput;
import com.jaamsim.input.EntityListInput;
import com.jaamsim.input.Input;
import com.jaamsim.input.InputAgent;
import com.jaamsim.input.IntegerInput;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.Output;
import com.jaamsim.input.ValueInput;
import com.jaamsim.math.Vec3d;
import com.jaamsim.ui.EditBox;
import com.jaamsim.ui.EntityPallet;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.ui.GUIFrame;
import com.jaamsim.ui.LogBox;
import com.jaamsim.ui.ObjectSelector;
import com.jaamsim.ui.OutputBox;
import com.jaamsim.ui.PropertyBox;
import com.jaamsim.units.DistanceUnit;
import com.jaamsim.units.TimeUnit;
import com.jaamsim.units.Unit;
/**
* Simulation provides the basic structure for the Entity model lifetime of earlyInit,
* startUp and doEndAt. The initial processtargets required to start the model are
* added to the eventmanager here. This class also acts as a bridge to the UI by
* providing controls for the various windows.
*/
public class Simulation extends Entity {
// Key Inputs tab
@Keyword(description = "The duration of the simulation run in which all statistics will be recorded.",
example = "Simulation Duration { 8760 h }")
private static final ValueInput runDuration;
@Keyword(description = "The initialization interval for the simulation run. The model will run "
+ "for the InitializationDuration interval and then clear the statistics and execute for the "
+ "specified RunDuration interval. The total length of the simulation run will be the sum of "
+ "the InitializationDuration and RunDuration inputs.",
example = "Simulation Initialization { 720 h }")
private static final ValueInput initializationTime;
@Keyword(description = "Indicates whether an output report will be printed at the end of the simulation run.",
example = "Simulation PrintReport { TRUE }")
private static final BooleanInput printReport;
@Keyword(description = "The directory in which to place the output report. Defaults to the "
+ "directory containing the configuration file for the run.",
example = "Simulation ReportDirectory { 'c:\reports\' }")
private static final DirInput reportDirectory;
@Keyword(description = "The length of time represented by one simulation tick.",
example = "Simulation TickLength { 1e-6 s }")
private static final ValueInput tickLengthInput;
@Keyword(description = "Indicates whether to close the program on completion of the simulation run.",
example = "Simulation ExitAtStop { TRUE }")
private static final BooleanInput exitAtStop;
@Keyword(description = "Global seed that sets the substream for each probability distribution. "
+ "Must be an integer >= 0. GlobalSubstreamSeed works together with each probability "
+ "distribution's RandomSeed keyword to determine its random sequence. It allows the "
+ "user to change all the random sequences in a model with a single input.",
example = "Simulation GlobalSubstreamSeed { 5 }")
private static final IntegerInput globalSeedInput;
// GUI tab
@Keyword(description = "An optional list of units to be used for displaying model outputs.",
example = "Simulation DisplayedUnits { h kt }")
private static final EntityListInput<? extends Unit> displayedUnits;
@Keyword(description = "If TRUE, a dragged object will be positioned to the nearest grid point.",
example = "Simulation SnapToGrid { TRUE }")
private static final BooleanInput snapToGrid;
@Keyword(description = "The distance between snap grid points.",
example = "Simulation SnapGridSpacing { 1 m }")
private static final ValueInput snapGridSpacing;
@Keyword(description = "The distance moved by the selected entity when the an arrow key is pressed.",
example = "Simulation IncrementSize { 1 cm }")
private static final ValueInput incrementSize;
@Keyword(description = "A Boolean to turn on or off real time in the simulation run",
example = "Simulation RealTime { TRUE }")
private static final BooleanInput realTime;
@Keyword(description = "The real time speed up factor",
example = "Simulation RealTimeFactor { 1200 }")
private static final IntegerInput realTimeFactor;
public static final int DEFAULT_REAL_TIME_FACTOR = 1;
public static final int MIN_REAL_TIME_FACTOR = 1;
public static final int MAX_REAL_TIME_FACTOR= 1000000;
@Keyword(description = "The time at which the simulation will be paused.",
example = "Simulation PauseTime { 200 h }")
private static final ValueInput pauseTime;
@Keyword(description = "Indicates whether the Model Builder tool should be shown on startup.",
example = "Simulation ShowModelBuilder { TRUE }")
private static final BooleanInput showModelBuilder;
@Keyword(description = "Indicates whether the Object Selector tool should be shown on startup.",
example = "Simulation ShowObjectSelector { TRUE }")
private static final BooleanInput showObjectSelector;
@Keyword(description = "Indicates whether the Input Editor tool should be shown on startup.",
example = "Simulation ShowInputEditor { TRUE }")
private static final BooleanInput showInputEditor;
@Keyword(description = "Indicates whether the Output Viewer tool should be shown on startup.",
example = "Simulation ShowOutputViewer { TRUE }")
private static final BooleanInput showOutputViewer;
@Keyword(description = "Indicates whether the Output Viewer tool should be shown on startup.",
example = "Simulation ShowPropertyViewer { TRUE }")
private static final BooleanInput showPropertyViewer;
@Keyword(description = "Indicates whether the Log Viewer tool should be shown on startup.",
example = "Simulation ShowLogViewer { TRUE }")
private static final BooleanInput showLogViewer;
@Keyword(description = "Time at which the simulation run is started (hh:mm).",
example = "Simulation StartTime { 2160 h }")
private static final ValueInput startTimeInput;
// Hidden keywords
@Keyword(description = "If the value is TRUE, then the input report file will be printed after "
+ "loading the configuration file. The input report can always be generated when "
+ "needed by selecting \"Print Input Report\" under the File menu.",
example = "Simulation PrintInputReport { TRUE }")
private static final BooleanInput printInputReport;
@Keyword(description = "This is placeholder description text",
example = "This is placeholder example text")
private static final BooleanInput traceEventsInput;
@Keyword(description = "This is placeholder description text",
example = "This is placeholder example text")
private static final BooleanInput verifyEventsInput;
private static double timeScale; // the scale from discrete to continuous time
private static double startTime; // simulation time (seconds) for the start of the run (not necessarily zero)
private static double endTime; // simulation time (seconds) for the end of the run
private static Simulation myInstance;
private static String modelName = "JaamSim";
static {
// Key Inputs tab
runDuration = new ValueInput("RunDuration", "Key Inputs", 31536000.0d);
runDuration.setUnitType(TimeUnit.class);
runDuration.setValidRange(1e-15d, Double.POSITIVE_INFINITY);
initializationTime = new ValueInput("InitializationDuration", "Key Inputs", 0.0);
initializationTime.setUnitType(TimeUnit.class);
initializationTime.setValidRange(0.0d, Double.POSITIVE_INFINITY);
printReport = new BooleanInput("PrintReport", "Key Inputs", false);
reportDirectory = new DirInput("ReportDirectory", "Key Inputs", null);
tickLengthInput = new ValueInput("TickLength", "Key Inputs", 1e-6d);
tickLengthInput.setUnitType(TimeUnit.class);
tickLengthInput.setValidRange(1e-9d, 5.0d);
exitAtStop = new BooleanInput("ExitAtStop", "Key Inputs", false);
globalSeedInput = new IntegerInput("GlobalSubstreamSeed", "Key Inputs", 0);
globalSeedInput.setValidRange(0, Integer.MAX_VALUE);
// GUI tab
displayedUnits = new EntityListInput<>(Unit.class, "DisplayedUnits", "GUI", null);
displayedUnits.setDefaultText("SI Units");
displayedUnits.setPromptReqd(false);
realTime = new BooleanInput("RealTime", "GUI", false);
realTime.setPromptReqd(false);
snapToGrid = new BooleanInput("SnapToGrid", "GUI", false);
snapToGrid.setPromptReqd(false);
snapGridSpacing = new ValueInput("SnapGridSpacing", "GUI", 0.1d);
snapGridSpacing.setUnitType(DistanceUnit.class);
snapGridSpacing.setValidRange(1.0e-6, Double.POSITIVE_INFINITY);
snapGridSpacing.setPromptReqd(false);
incrementSize = new ValueInput("IncrementSize", "GUI", 0.1d);
incrementSize.setUnitType(DistanceUnit.class);
incrementSize.setValidRange(1.0e-6, Double.POSITIVE_INFINITY);
incrementSize.setPromptReqd(false);
realTimeFactor = new IntegerInput("RealTimeFactor", "GUI", DEFAULT_REAL_TIME_FACTOR);
realTimeFactor.setValidRange(MIN_REAL_TIME_FACTOR, MAX_REAL_TIME_FACTOR);
realTimeFactor.setPromptReqd(false);
pauseTime = new ValueInput("PauseTime", "GUI", Double.POSITIVE_INFINITY);
pauseTime.setUnitType(TimeUnit.class);
pauseTime.setValidRange(0.0d, Double.POSITIVE_INFINITY);
pauseTime.setPromptReqd(false);
showModelBuilder = new BooleanInput("ShowModelBuilder", "GUI", false);
showModelBuilder.setPromptReqd(false);
showObjectSelector = new BooleanInput("ShowObjectSelector", "GUI", false);
showObjectSelector.setPromptReqd(false);
showInputEditor = new BooleanInput("ShowInputEditor", "GUI", false);
showInputEditor.setPromptReqd(false);
showOutputViewer = new BooleanInput("ShowOutputViewer", "GUI", false);
showOutputViewer.setPromptReqd(false);
showPropertyViewer = new BooleanInput("ShowPropertyViewer", "GUI", false);
showPropertyViewer.setPromptReqd(false);
showLogViewer = new BooleanInput("ShowLogViewer", "GUI", false);
showLogViewer.setPromptReqd(false);
// Hidden keywords
startTimeInput = new ValueInput("StartTime", "Key Inputs", 0.0d);
startTimeInput.setUnitType(TimeUnit.class);
startTimeInput.setValidRange(0.0d, Double.POSITIVE_INFINITY);
traceEventsInput = new BooleanInput("TraceEvents", "Key Inputs", false);
verifyEventsInput = new BooleanInput("VerifyEvents", "Key Inputs", false);
printInputReport = new BooleanInput("PrintInputReport", "Key Inputs", false);
// Initialize basic model information
startTime = 0.0;
endTime = 8760.0*3600.0;
}
{
// Key Inputs tab
this.addInput(runDuration);
this.addInput(initializationTime);
this.addInput(printReport);
this.addInput(reportDirectory);
this.addInput(tickLengthInput);
this.addInput(exitAtStop);
this.addInput(globalSeedInput);
// GUI tab
this.addInput(displayedUnits);
this.addInput(snapToGrid);
this.addInput(snapGridSpacing);
this.addInput(incrementSize);
this.addInput(realTime);
this.addInput(realTimeFactor);
this.addInput(pauseTime);
this.addInput(showModelBuilder);
this.addInput(showObjectSelector);
this.addInput(showInputEditor);
this.addInput(showOutputViewer);
this.addInput(showPropertyViewer);
this.addInput(showLogViewer);
// Hidden keywords
this.addInput(startTimeInput);
this.addInput(traceEventsInput);
this.addInput(verifyEventsInput);
this.addInput(printInputReport);
// Hide various keywords
startTimeInput.setHidden(true);
traceEventsInput.setHidden(true);
verifyEventsInput.setHidden(true);
printInputReport.setHidden(true);
}
public Simulation() {}
public static Simulation getInstance() {
if (myInstance == null) {
for (Entity ent : Entity.getAll()) {
if (ent instanceof Simulation ) {
myInstance = (Simulation) ent;
break;
}
}
}
return myInstance;
}
@Override
public void updateForInput( Input<?> in ) {
super.updateForInput( in );
if(in == realTimeFactor || in == realTime) {
updateRealTime();
return;
}
if (in == pauseTime) {
updatePauseTime();
return;
}
if (in == reportDirectory) {
InputAgent.setReportDirectory(reportDirectory.getDir());
return;
}
if (in == displayedUnits) {
if (displayedUnits.getValue() == null)
return;
for (Unit u : displayedUnits.getValue()) {
Unit.setPreferredUnit(u.getClass(), u);
}
return;
}
if (in == showModelBuilder) {
setWindowVisible(EntityPallet.getInstance(), showModelBuilder.getValue());
return;
}
if (in == showObjectSelector) {
setWindowVisible(ObjectSelector.getInstance(), showObjectSelector.getValue());
return;
}
if (in == showInputEditor) {
setWindowVisible(EditBox.getInstance(), showInputEditor.getValue());
FrameBox.reSelectEntity();
return;
}
if (in == showOutputViewer) {
setWindowVisible(OutputBox.getInstance(), showOutputViewer.getValue());
FrameBox.reSelectEntity();
return;
}
if (in == showPropertyViewer) {
setWindowVisible(PropertyBox.getInstance(), showPropertyViewer.getValue());
FrameBox.reSelectEntity();
return;
}
if (in == showLogViewer) {
setWindowVisible(LogBox.getInstance(), showLogViewer.getValue());
FrameBox.reSelectEntity();
return;
}
}
public static void clear() {
initializationTime.reset();
runDuration.reset();
pauseTime.reset();
tickLengthInput.reset();
traceEventsInput.reset();
verifyEventsInput.reset();
printInputReport.reset();
realTimeFactor.reset();
realTime.reset();
updateRealTime();
exitAtStop.reset();
startTimeInput.reset();
showModelBuilder.reset();
showObjectSelector.reset();
showInputEditor.reset();
showOutputViewer.reset();
showPropertyViewer.reset();
showLogViewer.reset();
// Initialize basic model information
startTime = 0.0;
endTime = 8760.0*3600.0;
myInstance = null;
// close warning/error trace file
InputAgent.closeLogFile();
// Kill all entities except simulation
while(Entity.getAll().size() > 0) {
Entity ent = Entity.getAll().get(Entity.getAll().size()-1);
ent.kill();
}
}
/**
* Initializes and starts the model
* 1) Initializes EventManager to accept events.
* 2) calls startModel() to allow the model to add its starting events to EventManager
* 3) start EventManager processing events
*/
public static void start(EventManager evt) {
// Validate each entity based on inputs only
for (int i = 0; i < Entity.getAll().size(); i++) {
try {
Entity.getAll().get(i).validate();
}
catch (Throwable e) {
LogBox.format("%s: Validation error- %s", Entity.getAll().get(i).getName(), e.getMessage());
GUIFrame.showErrorDialog("Input Error Detected During Validation",
"%s: %-70s",
Entity.getAll().get(i).getName(), e.getMessage());
GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED);
return;
}
}
InputAgent.prepareReportDirectory();
evt.clear();
evt.setTraceListener(null);
if( Simulation.traceEvents() ) {
String evtName = InputAgent.getConfigFile().getParentFile() + File.separator + InputAgent.getRunName() + ".evt";
EventRecorder rec = new EventRecorder(evtName);
evt.setTraceListener(rec);
}
else if( Simulation.verifyEvents() ) {
String evtName = InputAgent.getConfigFile().getParentFile() + File.separator + InputAgent.getRunName() + ".evt";
EventTracer trc = new EventTracer(evtName);
evt.setTraceListener(trc);
}
evt.setTickLength(tickLengthInput.getValue());
setSimTimeScale(evt.secondsToNearestTick(3600.0d));
FrameBox.setSecondsPerTick(tickLengthInput.getValue());
startTime = startTimeInput.getValue();
endTime = startTime + Simulation.getInitializationTime() + Simulation.getRunDuration();
evt.scheduleProcessExternal(0, 0, false, new InitModelTarget(), null);
evt.resume(evt.secondsToNearestTick(Simulation.getPauseTime()));
}
public static int getSubstreamNumber() {
return globalSeedInput.getValue();
}
public static boolean getPrintReport() {
return printReport.getValue();
}
public static boolean traceEvents() {
return traceEventsInput.getValue();
}
public static boolean verifyEvents() {
return verifyEventsInput.getValue();
}
static void setSimTimeScale(double scale) {
timeScale = scale;
}
public static double getSimTimeFactor() {
return timeScale;
}
public static double getEventTolerance() {
return (1.0d / getSimTimeFactor());
}
public static double getTickLength() {
return tickLengthInput.getValue();
}
public static double getPauseTime() {
return pauseTime.getValue();
}
/**
* Returns the start time of the run.
* @return - simulation time in seconds for the start of the run.
*/
public static double getStartTime() {
return startTime;
}
/**
* Returns the end time of the run.
* @return - simulation time in seconds when the current run will stop.
*/
public static double getEndTime() {
return endTime;
}
/**
* Returns the duration of the run (not including intialization)
*/
public static double getRunDuration() {
return runDuration.getValue();
}
/**
* Returns the duration of the initialization period
*/
public static double getInitializationTime() {
return initializationTime.getValue();
}
public static double getIncrementSize() {
return incrementSize.getValue();
}
public static boolean isSnapToGrid() {
return snapToGrid.getValue();
}
public static double getSnapGridSpacing() {
return snapGridSpacing.getValue();
}
/**
* Returns the nearest point on the snap grid to the given coordinate.
* To avoid dithering, the new position must be at least one grid space
* from the old position.
* @param newPos - new coordinate for the object
* @param oldPos - present coordinate for the object
* @return newest snap grid point.
*/
public static Vec3d getSnapGridPosition(Vec3d newPos, Vec3d oldPos) {
double spacing = snapGridSpacing.getValue();
Vec3d ret = new Vec3d(newPos);
if (Math.abs(newPos.x - oldPos.x) < spacing)
ret.x = oldPos.x;
if (Math.abs(newPos.y - oldPos.y) < spacing)
ret.y = oldPos.y;
if (Math.abs(newPos.z - oldPos.z) < spacing)
ret.z = oldPos.z;
return Simulation.getSnapGridPosition(ret);
}
/**
* Returns the nearest point on the snap grid to the given coordinate.
* @param pos - position to be adjusted
* @return nearest snap grid point.
*/
public static Vec3d getSnapGridPosition(Vec3d pos) {
double spacing = snapGridSpacing.getValue();
Vec3d ret = new Vec3d(pos);
ret.x = spacing*Math.rint(ret.x/spacing);
ret.y = spacing*Math.rint(ret.y/spacing);
ret.z = spacing*Math.rint(ret.z/spacing);
return ret;
}
static void updateRealTime() {
GUIFrame.instance().updateForRealTime(realTime.getValue(), realTimeFactor.getValue());
}
static void updatePauseTime() {
GUIFrame.instance().updateForPauseTime(pauseTime.getValueString());
}
public static void setModelName(String newModelName) {
modelName = newModelName;
}
public static String getModelName() {
return modelName;
}
public static boolean getExitAtStop() {
return exitAtStop.getValue();
}
public static boolean getPrintInputReport() {
return printInputReport.getValue();
}
public static void setWindowVisible(JFrame f, boolean visible) {
f.setVisible(visible);
if (visible)
f.toFront();
}
/**
* Re-open any Tools windows that have been closed temporarily.
*/
public static void showActiveTools() {
setWindowVisible(EntityPallet.getInstance(), showModelBuilder.getValue());
setWindowVisible(ObjectSelector.getInstance(), showObjectSelector.getValue());
setWindowVisible(EditBox.getInstance(), showInputEditor.getValue());
setWindowVisible(OutputBox.getInstance(), showOutputViewer.getValue());
setWindowVisible(PropertyBox.getInstance(), showPropertyViewer.getValue());
setWindowVisible(LogBox.getInstance(), showLogViewer.getValue());
}
/**
* Closes all the Tools windows temporarily.
*/
public static void closeAllTools() {
setWindowVisible(EntityPallet.getInstance(), false);
setWindowVisible(ObjectSelector.getInstance(), false);
setWindowVisible(EditBox.getInstance(), false);
setWindowVisible(OutputBox.getInstance(), false);
setWindowVisible(PropertyBox.getInstance(), false);
setWindowVisible(LogBox.getInstance(), false);
}
@Output(name = "Configuration File",
description = "The present configuration file.")
public String getConfigFileName(double simTime) {
return InputAgent.getConfigFile().getPath();
}
}
| JS: Set default text for Simulation ReportDirectory to Configuration File Directory
Signed-off-by: Stephen Wong <[email protected]>
| src/main/java/com/jaamsim/basicsim/Simulation.java | JS: Set default text for Simulation ReportDirectory to Configuration File Directory | <ide><path>rc/main/java/com/jaamsim/basicsim/Simulation.java
<ide> printReport = new BooleanInput("PrintReport", "Key Inputs", false);
<ide>
<ide> reportDirectory = new DirInput("ReportDirectory", "Key Inputs", null);
<add> reportDirectory.setDefaultText("Configuration File Directory");
<ide>
<ide> tickLengthInput = new ValueInput("TickLength", "Key Inputs", 1e-6d);
<ide> tickLengthInput.setUnitType(TimeUnit.class); |
|
Java | mit | 6dbccf315b38612defbc1cea99de0a54528f357f | 0 | GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus,GlowstonePlusPlus/GlowstonePlusPlus | package net.glowstone.util.linkstone;
import java.io.File;
import net.glowstone.linkstone.runtime.LinkstoneRuntimeData;
import net.glowstone.linkstone.runtime.boxing.BoxPatchVisitor;
import net.glowstone.linkstone.runtime.direct.DirectFieldAccessReplaceVisitor;
import net.glowstone.linkstone.runtime.inithook.ClassInitInvokeVisitor;
import net.glowstone.linkstone.runtime.reflectionredirect.field.FieldAccessorUtility;
import net.glowstone.linkstone.runtime.reflectionredirect.method.MethodAccessorUtility;
import net.glowstone.linkstone.runtime.reflectionreplace.ReflectionReplaceVisitor;
import org.bukkit.Server;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.plugin.java.PluginClassLoader;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
public class LinkstonePluginLoader extends JavaPluginLoader {
/**
* Bukkit will invoke this constructor via reflection.
* Its signature should therefore not be changed!
*
* @param instance the server instance
*/
public LinkstonePluginLoader(Server instance) {
super(instance);
LinkstoneRuntimeData.setPluginClassLoader(new ClassLoader() {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
return loadClass(name);
}
});
}
@Override
protected PluginClassLoader newPluginLoader(JavaPluginLoader loader, ClassLoader parent, PluginDescriptionFile description, File dataFolder, File file, ClassLoader libraryLoader) throws Exception {
return new PluginClassLoader(loader, parent, description, dataFolder, file, libraryLoader) {
@Override
protected byte[] transformBytecode(byte[] bytecode) {
if (LinkstoneRuntimeData.getFields().isEmpty()
&& LinkstoneRuntimeData.getBoxes().isEmpty()) {
// There are no plugins installed that use a @LField or @LBox annotation
// so there's no need for runtime support
return bytecode;
}
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassVisitor cv = cw;
cv = new DirectFieldAccessReplaceVisitor(LinkstoneRuntimeData.getFields(), cv);
if (!FieldAccessorUtility.isSupported() || !MethodAccessorUtility.isSupported()) {
cv = new ReflectionReplaceVisitor(cv);
}
cv = new ClassInitInvokeVisitor(cv);
cv = new BoxPatchVisitor(LinkstoneRuntimeData.getBoxes(), cv);
new ClassReader(bytecode).accept(cv, 0);
return cw.toByteArray();
}
};
}
}
| src/main/java/net/glowstone/util/linkstone/LinkstonePluginLoader.java | package net.glowstone.util.linkstone;
import java.io.File;
import net.glowstone.linkstone.runtime.LinkstoneRuntimeData;
import net.glowstone.linkstone.runtime.boxing.BoxPatchVisitor;
import net.glowstone.linkstone.runtime.direct.DirectFieldAccessReplaceVisitor;
import net.glowstone.linkstone.runtime.inithook.ClassInitInvokeVisitor;
import net.glowstone.linkstone.runtime.reflectionredirect.field.FieldAccessorUtility;
import net.glowstone.linkstone.runtime.reflectionredirect.method.MethodAccessorUtility;
import net.glowstone.linkstone.runtime.reflectionreplace.ReflectionReplaceVisitor;
import org.bukkit.Server;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.plugin.java.PluginClassLoader;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
public class LinkstonePluginLoader extends JavaPluginLoader {
/**
* Bukkit will invoke this constructor via reflection.
* Its signature should therefore not be changed!
*
* @param instance the server instance
*/
public LinkstonePluginLoader(Server instance) {
super(instance);
LinkstoneRuntimeData.setPluginClassLoader(new ClassLoader() {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
return getClassByName(name);
}
});
}
@Override
protected PluginClassLoader newPluginLoader(JavaPluginLoader loader, ClassLoader parent,
PluginDescriptionFile description, File dataFolder, File file) throws Exception {
return new PluginClassLoader(loader, parent, description, dataFolder, file) {
@Override
protected byte[] transformBytecode(byte[] bytecode) {
if (LinkstoneRuntimeData.getFields().isEmpty()
&& LinkstoneRuntimeData.getBoxes().isEmpty()) {
// There are no plugins installed that use a @LField or @LBox annotation
// so there's no need for runtime support
return bytecode;
}
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassVisitor cv = cw;
cv = new DirectFieldAccessReplaceVisitor(LinkstoneRuntimeData.getFields(), cv);
if (!FieldAccessorUtility.isSupported() || !MethodAccessorUtility.isSupported()) {
cv = new ReflectionReplaceVisitor(cv);
}
cv = new ClassInitInvokeVisitor(cv);
cv = new BoxPatchVisitor(LinkstoneRuntimeData.getBoxes(), cv);
new ClassReader(bytecode).accept(cv, 0);
return cw.toByteArray();
}
};
}
}
| possibly fix Linkstone error
| src/main/java/net/glowstone/util/linkstone/LinkstonePluginLoader.java | possibly fix Linkstone error | <ide><path>rc/main/java/net/glowstone/util/linkstone/LinkstonePluginLoader.java
<ide> LinkstoneRuntimeData.setPluginClassLoader(new ClassLoader() {
<ide> @Override
<ide> protected Class<?> findClass(String name) throws ClassNotFoundException {
<del> return getClassByName(name);
<add> return loadClass(name);
<ide> }
<ide> });
<ide> }
<ide>
<ide> @Override
<del> protected PluginClassLoader newPluginLoader(JavaPluginLoader loader, ClassLoader parent,
<del> PluginDescriptionFile description, File dataFolder, File file) throws Exception {
<del> return new PluginClassLoader(loader, parent, description, dataFolder, file) {
<add> protected PluginClassLoader newPluginLoader(JavaPluginLoader loader, ClassLoader parent, PluginDescriptionFile description, File dataFolder, File file, ClassLoader libraryLoader) throws Exception {
<add> return new PluginClassLoader(loader, parent, description, dataFolder, file, libraryLoader) {
<ide> @Override
<ide> protected byte[] transformBytecode(byte[] bytecode) {
<ide> if (LinkstoneRuntimeData.getFields().isEmpty() |
|
Java | epl-1.0 | e784d8963f468975a8f75bbc5e262d2d062771fa | 0 | stzilli/kapua,LeoNerdoG/kapua,LeoNerdoG/kapua,LeoNerdoG/kapua,stzilli/kapua,stzilli/kapua,stzilli/kapua,LeoNerdoG/kapua,stzilli/kapua,LeoNerdoG/kapua | /*******************************************************************************
* Copyright (c) 2011, 2016 Eurotech and/or its affiliates 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:
* Eurotech - initial API and implementation
*
*******************************************************************************/
package org.eclipse.kapua.app.console.servlet;
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.FileCleanerCleanup;
import org.apache.commons.io.FileCleaningTracker;
import org.eclipse.kapua.app.console.ConsoleJAXBContextProvider;
import org.eclipse.kapua.app.console.setting.ConsoleSetting;
import org.eclipse.kapua.app.console.setting.ConsoleSettingKeys;
import org.eclipse.kapua.app.console.shared.model.KapuaFormFields;
import org.eclipse.kapua.commons.util.xml.JAXBContextProvider;
import org.eclipse.kapua.commons.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KapuaHttpServlet extends HttpServlet {
private static final long serialVersionUID = 8120495078076069807L;
private static final Logger logger = LoggerFactory.getLogger(KapuaHttpServlet.class);
protected DiskFileItemFactory diskFileItemFactory;
protected FileCleaningTracker fileCleaningTracker;
@Override
public void init() throws ServletException {
super.init();
logger.info("Servlet {} initialized", getServletName());
ServletContext ctx = getServletContext();
fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(ctx);
int sizeThreshold = ConsoleSetting.getInstance().getInt(ConsoleSettingKeys.FILE_UPLOAD_INMEMORY_SIZE_THRESHOLD);
File repository = new File(System.getProperty("java.io.tmpdir"));
logger.info("DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD: {}", DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
logger.info("DiskFileItemFactory: using size threshold of: {}", sizeThreshold);
diskFileItemFactory = new DiskFileItemFactory(sizeThreshold, repository);
diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker);
JAXBContextProvider consoleProvider = new ConsoleJAXBContextProvider();
XmlUtil.setContextProvider(consoleProvider);
}
@Override
public void destroy() {
super.destroy();
logger.info("Servlet {} destroyed", getServletName());
if (fileCleaningTracker != null) {
logger.info("Number of temporary files tracked: " + fileCleaningTracker.getTrackCount());
}
}
public KapuaFormFields getFormFields(HttpServletRequest req)
throws ServletException {
UploadRequest upload = new UploadRequest(diskFileItemFactory);
try {
upload.parse(req);
} catch (FileUploadException e) {
logger.error("Error parsing the provision request", e);
throw new ServletException("Error parsing the provision request", e);
}
return new KapuaFormFields(upload.getFormFields(), upload.getFileItems());
}
}
| console/src/main/java/org/eclipse/kapua/app/console/servlet/KapuaHttpServlet.java | /*******************************************************************************
* Copyright (c) 2011, 2016 Eurotech and/or its affiliates 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:
* Eurotech - initial API and implementation
*
*******************************************************************************/
package org.eclipse.kapua.app.console.servlet;
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.FileCleanerCleanup;
import org.apache.commons.io.FileCleaningTracker;
import org.eclipse.kapua.app.console.ConsoleJAXBContextProvider;
import org.eclipse.kapua.app.console.setting.ConsoleSetting;
import org.eclipse.kapua.app.console.setting.ConsoleSettingKeys;
import org.eclipse.kapua.app.console.shared.model.KapuaFormFields;
import org.eclipse.kapua.commons.util.xml.JAXBContextProvider;
import org.eclipse.kapua.commons.util.xml.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KapuaHttpServlet extends HttpServlet
{
private static final long serialVersionUID = 8120495078076069807L;
private static Logger s_logger = LoggerFactory.getLogger(KapuaHttpServlet.class);
protected DiskFileItemFactory m_diskFileItemFactory;
protected FileCleaningTracker m_fileCleaningTracker;
@Override
public void init()
throws ServletException
{
super.init();
s_logger.info("Servlet {} initialized", getServletName());
ServletContext ctx = getServletContext();
m_fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(ctx);
int sizeThreshold = ConsoleSetting.getInstance().getInt(ConsoleSettingKeys.FILE_UPLOAD_INMEMORY_SIZE_THRESHOLD);
File repository = new File(System.getProperty("java.io.tmpdir"));
s_logger.info("DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD: {}", DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
s_logger.info("DiskFileItemFactory: using size threshold of: {}", sizeThreshold);
m_diskFileItemFactory = new DiskFileItemFactory(sizeThreshold, repository);
m_diskFileItemFactory.setFileCleaningTracker(m_fileCleaningTracker);
JAXBContextProvider consoleProvider = new ConsoleJAXBContextProvider();
XmlUtil.setContextProvider(consoleProvider);
}
@Override
public void destroy()
{
super.destroy();
s_logger.info("Servlet {} destroyed", getServletName());
if (m_fileCleaningTracker != null) {
s_logger.info("Number of temporary files tracked: " + m_fileCleaningTracker.getTrackCount());
}
}
public KapuaFormFields getFormFields(HttpServletRequest req)
throws ServletException
{
UploadRequest upload = new UploadRequest(m_diskFileItemFactory);
try {
upload.parse(req);
}
catch (FileUploadException e) {
s_logger.error("Error parsing the provision request", e);
throw new ServletException("Error parsing the provision request", e);
}
return new KapuaFormFields(upload.getFormFields(), upload.getFileItems());
}
}
| Apply code formatter and cleanup profile, clean up | console/src/main/java/org/eclipse/kapua/app/console/servlet/KapuaHttpServlet.java | Apply code formatter and cleanup profile, clean up | <ide><path>onsole/src/main/java/org/eclipse/kapua/app/console/servlet/KapuaHttpServlet.java
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide>
<del>public class KapuaHttpServlet extends HttpServlet
<del>{
<del> private static final long serialVersionUID = 8120495078076069807L;
<del> private static Logger s_logger = LoggerFactory.getLogger(KapuaHttpServlet.class);
<add>public class KapuaHttpServlet extends HttpServlet {
<ide>
<del> protected DiskFileItemFactory m_diskFileItemFactory;
<del> protected FileCleaningTracker m_fileCleaningTracker;
<add> private static final long serialVersionUID = 8120495078076069807L;
<add> private static final Logger logger = LoggerFactory.getLogger(KapuaHttpServlet.class);
<add>
<add> protected DiskFileItemFactory diskFileItemFactory;
<add> protected FileCleaningTracker fileCleaningTracker;
<ide>
<ide> @Override
<del> public void init()
<del> throws ServletException
<del> {
<add> public void init() throws ServletException {
<ide> super.init();
<ide>
<del> s_logger.info("Servlet {} initialized", getServletName());
<add> logger.info("Servlet {} initialized", getServletName());
<ide>
<ide> ServletContext ctx = getServletContext();
<del> m_fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(ctx);
<add> fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(ctx);
<ide>
<ide> int sizeThreshold = ConsoleSetting.getInstance().getInt(ConsoleSettingKeys.FILE_UPLOAD_INMEMORY_SIZE_THRESHOLD);
<ide> File repository = new File(System.getProperty("java.io.tmpdir"));
<ide>
<del> s_logger.info("DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD: {}", DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
<del> s_logger.info("DiskFileItemFactory: using size threshold of: {}", sizeThreshold);
<add> logger.info("DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD: {}", DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
<add> logger.info("DiskFileItemFactory: using size threshold of: {}", sizeThreshold);
<ide>
<del> m_diskFileItemFactory = new DiskFileItemFactory(sizeThreshold, repository);
<del> m_diskFileItemFactory.setFileCleaningTracker(m_fileCleaningTracker);
<add> diskFileItemFactory = new DiskFileItemFactory(sizeThreshold, repository);
<add> diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker);
<ide>
<ide> JAXBContextProvider consoleProvider = new ConsoleJAXBContextProvider();
<ide> XmlUtil.setContextProvider(consoleProvider);
<ide> }
<ide>
<ide> @Override
<del> public void destroy()
<del> {
<add> public void destroy() {
<ide> super.destroy();
<del> s_logger.info("Servlet {} destroyed", getServletName());
<add> logger.info("Servlet {} destroyed", getServletName());
<ide>
<del> if (m_fileCleaningTracker != null) {
<del> s_logger.info("Number of temporary files tracked: " + m_fileCleaningTracker.getTrackCount());
<add> if (fileCleaningTracker != null) {
<add> logger.info("Number of temporary files tracked: " + fileCleaningTracker.getTrackCount());
<ide> }
<ide> }
<ide>
<ide> public KapuaFormFields getFormFields(HttpServletRequest req)
<del> throws ServletException
<del> {
<del> UploadRequest upload = new UploadRequest(m_diskFileItemFactory);
<add> throws ServletException {
<add> UploadRequest upload = new UploadRequest(diskFileItemFactory);
<ide>
<ide> try {
<ide> upload.parse(req);
<del> }
<del> catch (FileUploadException e) {
<del> s_logger.error("Error parsing the provision request", e);
<add> } catch (FileUploadException e) {
<add> logger.error("Error parsing the provision request", e);
<ide> throw new ServletException("Error parsing the provision request", e);
<ide> }
<ide> |
|
Java | agpl-3.0 | 50f181877a76472a32fc0b9e0dffc7b02d936823 | 0 | elki-project/elki,elki-project/elki,elki-project/elki | package de.lmu.ifi.dbs.algorithm.clustering;
import de.lmu.ifi.dbs.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.algorithm.Algorithm;
import de.lmu.ifi.dbs.algorithm.result.clustering.ClustersPlusNoise;
import de.lmu.ifi.dbs.data.RealVector;
import de.lmu.ifi.dbs.database.AssociationID;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.distance.DoubleDistance;
import de.lmu.ifi.dbs.distance.LocallyWeightedDistanceFunction;
import de.lmu.ifi.dbs.logging.ProgressLogRecord;
import de.lmu.ifi.dbs.logging.LoggingConfiguration;
import de.lmu.ifi.dbs.preprocessing.ProjectedDBSCANPreprocessor;
import de.lmu.ifi.dbs.utilities.Progress;
import de.lmu.ifi.dbs.utilities.QueryResult;
import de.lmu.ifi.dbs.utilities.Util;
import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings;
import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler;
import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.utilities.optionhandling.WrongParameterValueException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Provides an abstract algorithm requiring a VarianceAnalysisPreprocessor.
*
* @author Arthur Zimek (<a href="mailto:[email protected]">[email protected]</a>)
*/
public abstract class ProjectedDBSCAN<P extends ProjectedDBSCANPreprocessor> extends AbstractAlgorithm<RealVector> implements Clustering<RealVector> {
/**
* Holds the class specific debug status.
*/
@SuppressWarnings({"UNUSED_SYMBOL"})
private static final boolean DEBUG = LoggingConfiguration.DEBUG;
// private static final boolean DEBUG = true;
/**
* The logger of this class.
*/
private Logger logger = Logger.getLogger(this.getClass().getName());
/**
* Parameter for epsilon.
*/
public static final String EPSILON_P = DBSCAN.EPSILON_P;
/**
* Description for parameter epsilon.
*/
public static final String EPSILON_D = "<epsilon>the maximum radius of the neighborhood to be considered, must be suitable to " + LocallyWeightedDistanceFunction.class.getName();
/**
* Parameter minimum points.
*/
public static final String MINPTS_P = DBSCAN.MINPTS_P;
/**
* Description for parameter minimum points.
*/
public static final String MINPTS_D = DBSCAN.MINPTS_D;
/**
* Epsilon.
*/
protected String epsilon;
/**
* Minimum points.
*/
protected int minpts;
/**
* Parameter lambda.
*/
public static final String LAMBDA_P = "lambda";
/**
* Description for parameter lambda.
*/
public static final String LAMBDA_D = "<int>a positive integer specifiying the intrinsic dimensionality of clusters to be found.";
/**
* Keeps lambda.
*/
private int lambda;
/**
* Holds a list of clusters found.
*/
private List<List<Integer>> resultList;
/**
* Provides the result of the algorithm.
*/
private ClustersPlusNoise<RealVector> result;
/**
* Holds a set of noise.
*/
private Set<Integer> noise;
/**
* Holds a set of processed ids.
*/
private Set<Integer> processedIDs;
/**
* The distance function.
*/
private LocallyWeightedDistanceFunction distanceFunction = new LocallyWeightedDistanceFunction();
/**
* Provides the abstract algorithm for variance analysis based DBSCAN.
*/
protected ProjectedDBSCAN() {
super();
parameterToDescription.put(EPSILON_P + OptionHandler.EXPECTS_VALUE, EPSILON_D);
parameterToDescription.put(MINPTS_P + OptionHandler.EXPECTS_VALUE, MINPTS_D);
parameterToDescription.put(LAMBDA_P + OptionHandler.EXPECTS_VALUE, LAMBDA_D);
optionHandler = new OptionHandler(parameterToDescription, this.getClass().getName());
}
/**
* @see AbstractAlgorithm#runInTime(Database)
*/
protected void runInTime(Database<RealVector> database) throws IllegalStateException {
if (isVerbose()) {
logger.info("\n");
}
try {
Progress progress = new Progress("Clustering", database.size());
resultList = new ArrayList<List<Integer>>();
noise = new HashSet<Integer>();
processedIDs = new HashSet<Integer>(database.size());
distanceFunction.setDatabase(database, isVerbose(), isTime());
if (isVerbose()) {
logger.info("\nClustering:\n");
}
if (database.size() >= minpts) {
for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
Integer id = iter.next();
if (!processedIDs.contains(id)) {
expandCluster(database, id, progress);
if (processedIDs.size() == database.size() && noise.size() == 0) {
break;
}
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
}
else {
for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
Integer id = iter.next();
noise.add(id);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
Integer[][] resultArray = new Integer[resultList.size() + 1][];
int i = 0;
for (Iterator<List<Integer>> resultListIter = resultList.iterator(); resultListIter.hasNext(); i++) {
resultArray[i] = resultListIter.next().toArray(new Integer[0]);
}
resultArray[resultArray.length - 1] = noise.toArray(new Integer[0]);
result = new ClustersPlusNoise<RealVector>(resultArray, database);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
catch (Exception e) {
throw new IllegalStateException(e);
}
}
/**
* ExpandCluster function of DBSCAN.
*/
protected void expandCluster(Database<RealVector> database, Integer startObjectID, Progress progress) {
List<QueryResult<DoubleDistance>> seeds = database.rangeQuery(startObjectID, epsilon, distanceFunction);
if (DEBUG) {
logger.fine("\nseeds of " + startObjectID + " " +
database.getAssociation(AssociationID.LABEL, startObjectID) + " " + seeds.size());
}
// neighbors < minPts OR local dimensionality > lambda -> noise
if (seeds.size() < minpts ||
(Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, startObjectID) > lambda) {
noise.add(startObjectID);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
return;
}
// try to expand the cluster
List<Integer> currentCluster = new ArrayList<Integer>();
for (QueryResult<DoubleDistance> nextSeed : seeds) {
Integer nextID = nextSeed.getID();
if (!processedIDs.contains(nextID)) {
currentCluster.add(nextID);
processedIDs.add(nextID);
}
else if (noise.contains(nextID)) {
currentCluster.add(nextID);
noise.remove(nextID);
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
seeds.remove(0);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
while (seeds.size() > 0) {
Integer o = seeds.remove(0).getID();
List<QueryResult<DoubleDistance>> neighborhood = database.rangeQuery(o, epsilon, distanceFunction);
if (neighborhood.size() >= minpts &&
(Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, o) <= lambda) {
for (QueryResult<DoubleDistance> neighbor : neighborhood) {
Integer p = neighbor.getID();
boolean inNoise = noise.contains(p);
boolean unclassified = !processedIDs.contains(p);
if (inNoise || unclassified) {
if (unclassified) {
seeds.add(neighbor);
}
currentCluster.add(p);
processedIDs.add(p);
if (inNoise) {
noise.remove(p);
}
}
}
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
int numClusters = currentCluster.size() > minpts ? resultList.size() + 1 : resultList.size();
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, numClusters), progress.getTask(), progress.status()));
}
if (processedIDs.size() == database.size() && noise.size() == 0) {
break;
}
}
if (currentCluster.size() >= minpts) {
resultList.add(currentCluster);
}
else {
for (Integer id : currentCluster) {
noise.add(id);
}
noise.add(startObjectID);
processedIDs.add(startObjectID);
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
public String[] setParameters
(String[] args) throws ParameterException {
String[] remainingParameters = super.setParameters(args);
epsilon = optionHandler.getOptionValue(EPSILON_P);
try {
// test whether epsilon is compatible with distance function
distanceFunction.valueOf(epsilon);
}
catch (IllegalArgumentException e) {
throw new WrongParameterValueException(EPSILON_P, epsilon, EPSILON_D);
}
// minpts
String minptsString = optionHandler.getOptionValue(MINPTS_P);
try {
minpts = Integer.parseInt(minptsString);
if (minpts <= 0) {
throw new WrongParameterValueException(MINPTS_P, minptsString, MINPTS_D);
}
}
catch (NumberFormatException e) {
throw new WrongParameterValueException(MINPTS_P, minptsString, MINPTS_D, e);
}
// lambda
String lambdaString = optionHandler.getOptionValue(LAMBDA_P);
try {
lambda = Integer.parseInt(lambdaString);
if (lambda <= 0) {
throw new WrongParameterValueException(LAMBDA_P, lambdaString, LAMBDA_D);
}
}
catch (NumberFormatException e) {
throw new WrongParameterValueException(LAMBDA_P, lambdaString, LAMBDA_D, e);
}
// parameters for the distance function
String[] distanceFunctionParameters = new String[remainingParameters.length + 5];
System.arraycopy(remainingParameters, 0, distanceFunctionParameters, 5, remainingParameters.length);
// omit preprocessing flag
distanceFunctionParameters[0] = OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.OMIT_PREPROCESSING_F;
// preprocessor
distanceFunctionParameters[1] = OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.PREPROCESSOR_CLASS_P;
distanceFunctionParameters[2] = preprocessorClass().getName();
// preprocessor epsilon
distanceFunctionParameters[3] = OptionHandler.OPTION_PREFIX + ProjectedDBSCANPreprocessor.EPSILON_P;
distanceFunctionParameters[4] = epsilon;
distanceFunction.setParameters(distanceFunctionParameters);
setParameters(args, remainingParameters);
return remainingParameters;
}
/**
* @see Algorithm#getAttributeSettings()
*/
@Override
public List<AttributeSettings> getAttributeSettings
() {
List<AttributeSettings> attributeSettings = super.getAttributeSettings();
AttributeSettings mySettings = attributeSettings.get(0);
mySettings.addSetting(LAMBDA_P, Integer.toString(lambda));
mySettings.addSetting(EPSILON_P, epsilon);
mySettings.addSetting(MINPTS_P, Integer.toString(minpts));
attributeSettings.addAll(distanceFunction.getAttributeSettings());
return attributeSettings;
}
/**
* Returns the class actually used as
* {@link ProjectedDBSCANPreprocessor VarianceAnalysisPreprocessor}.
*
* @return the class actually used as
* {@link ProjectedDBSCANPreprocessor VarianceAnalysisPreprocessor}
*/
public abstract Class<P> preprocessorClass
();
/**
* @see de.lmu.ifi.dbs.algorithm.Algorithm#getResult()
*/
public ClustersPlusNoise<RealVector> getResult
() {
return result;
}
}
| src/de/lmu/ifi/dbs/algorithm/clustering/ProjectedDBSCAN.java | package de.lmu.ifi.dbs.algorithm.clustering;
import de.lmu.ifi.dbs.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.algorithm.Algorithm;
import de.lmu.ifi.dbs.algorithm.result.clustering.ClustersPlusNoise;
import de.lmu.ifi.dbs.data.RealVector;
import de.lmu.ifi.dbs.database.AssociationID;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.distance.DoubleDistance;
import de.lmu.ifi.dbs.distance.LocallyWeightedDistanceFunction;
import de.lmu.ifi.dbs.logging.LoggingConfiguration;
import de.lmu.ifi.dbs.logging.ProgressLogRecord;
import de.lmu.ifi.dbs.preprocessing.ProjectedDBSCANPreprocessor;
import de.lmu.ifi.dbs.utilities.Progress;
import de.lmu.ifi.dbs.utilities.QueryResult;
import de.lmu.ifi.dbs.utilities.Util;
import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings;
import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler;
import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.utilities.optionhandling.WrongParameterValueException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Provides an abstract algorithm requiring a VarianceAnalysisPreprocessor.
*
* @author Arthur Zimek (<a href="mailto:[email protected]">[email protected]</a>)
*/
public abstract class ProjectedDBSCAN<P extends ProjectedDBSCANPreprocessor> extends AbstractAlgorithm<RealVector> implements Clustering<RealVector> {
/**
* Holds the class specific debug status.
*/
@SuppressWarnings({"UNUSED_SYMBOL"})
private static final boolean DEBUG = LoggingConfiguration.DEBUG;
/**
* The logger of this class.
*/
private Logger logger = Logger.getLogger(this.getClass().getName());
/**
* Parameter for epsilon.
*/
public static final String EPSILON_P = DBSCAN.EPSILON_P;
/**
* Description for parameter epsilon.
*/
public static final String EPSILON_D = "<epsilon>the maximum radius of the neighborhood to be considered, must be suitable to " + LocallyWeightedDistanceFunction.class.getName();
/**
* Parameter minimum points.
*/
public static final String MINPTS_P = DBSCAN.MINPTS_P;
/**
* Description for parameter minimum points.
*/
public static final String MINPTS_D = DBSCAN.MINPTS_D;
/**
* Epsilon.
*/
protected String epsilon;
/**
* Minimum points.
*/
protected int minpts;
/**
* Parameter lambda.
*/
public static final String LAMBDA_P = "lambda";
/**
* Description for parameter lambda.
*/
public static final String LAMBDA_D = "<int>a positive integer specifiying the intrinsic dimensionality of clusters to be found.";
/**
* Keeps lambda.
*/
private int lambda;
/**
* Holds a list of clusters found.
*/
private List<List<Integer>> resultList;
/**
* Provides the result of the algorithm.
*/
private ClustersPlusNoise<RealVector> result;
/**
* Holds a set of noise.
*/
private Set<Integer> noise;
/**
* Holds a set of processed ids.
*/
private Set<Integer> processedIDs;
/**
* The distance function.
*/
private LocallyWeightedDistanceFunction distanceFunction = new LocallyWeightedDistanceFunction();
/**
* Provides the abstract algorithm for variance analysis based DBSCAN.
*/
protected ProjectedDBSCAN() {
super();
parameterToDescription.put(EPSILON_P + OptionHandler.EXPECTS_VALUE, EPSILON_D);
parameterToDescription.put(MINPTS_P + OptionHandler.EXPECTS_VALUE, MINPTS_D);
parameterToDescription.put(LAMBDA_P + OptionHandler.EXPECTS_VALUE, LAMBDA_D);
optionHandler = new OptionHandler(parameterToDescription, this.getClass().getName());
}
/**
* @see AbstractAlgorithm#runInTime(Database)
*/
protected void runInTime(Database<RealVector> database) throws IllegalStateException {
if (isVerbose()) {
logger.info("\n");
}
try {
Progress progress = new Progress("Clustering", database.size());
resultList = new ArrayList<List<Integer>>();
noise = new HashSet<Integer>();
processedIDs = new HashSet<Integer>(database.size());
distanceFunction.setDatabase(database, isVerbose(), isTime());
if (isVerbose()) {
logger.info("\nClustering:\n");
}
if (database.size() >= minpts) {
for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
Integer id = iter.next();
if (!processedIDs.contains(id)) {
expandCluster(database, id, progress);
if (processedIDs.size() == database.size() && noise.size() == 0) {
break;
}
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
}
else {
for (Iterator<Integer> iter = database.iterator(); iter.hasNext();) {
Integer id = iter.next();
noise.add(id);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
Integer[][] resultArray = new Integer[resultList.size() + 1][];
int i = 0;
for (Iterator<List<Integer>> resultListIter = resultList.iterator(); resultListIter.hasNext(); i++) {
resultArray[i] = resultListIter.next().toArray(new Integer[0]);
}
resultArray[resultArray.length - 1] = noise.toArray(new Integer[0]);
result = new ClustersPlusNoise<RealVector>(resultArray, database);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
catch (Exception e) {
throw new IllegalStateException(e);
}
}
/**
* ExpandCluster function of DBSCAN.
*/
protected void expandCluster(Database<RealVector> database, Integer startObjectID, Progress progress) {
List<QueryResult<DoubleDistance>> neighborhoodIDs = database.rangeQuery(startObjectID, epsilon, distanceFunction);
if (neighborhoodIDs.size() < minpts) {
noise.add(startObjectID);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
else {
List<Integer> currentCluster = new ArrayList<Integer>();
if ((Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, startObjectID) > lambda) {
noise.add(startObjectID);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
else {
List<QueryResult<DoubleDistance>> seeds = database.rangeQuery(startObjectID, epsilon, distanceFunction);
if (seeds.size() < minpts) {
noise.add(startObjectID);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
else {
for (QueryResult<DoubleDistance> nextSeed : seeds) {
Integer nextID = nextSeed.getID();
if (!processedIDs.contains(nextID)) {
currentCluster.add(nextID);
processedIDs.add(nextID);
}
else if (noise.contains(nextID)) {
currentCluster.add(nextID);
noise.remove(nextID);
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
seeds.remove(0);
processedIDs.add(startObjectID);
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
while (seeds.size() > 0) {
Integer seedID = seeds.remove(0).getID();
List<QueryResult<DoubleDistance>> seedNeighborhoodIDs = database.rangeQuery(seedID, epsilon, distanceFunction);
if (seedNeighborhoodIDs.size() >= minpts) {
if ((Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, seedID) <= lambda) {
List<QueryResult<DoubleDistance>> reachables = database.rangeQuery(seedID, epsilon, distanceFunction);
if (reachables.size() >= minpts) {
for (QueryResult<DoubleDistance> reachable : reachables) {
boolean inNoise = noise.contains(reachable.getID());
boolean unclassified = !processedIDs.contains(reachable.getID());
if (inNoise || unclassified) {
if (unclassified) {
seeds.add(reachable);
}
currentCluster.add(reachable.getID());
processedIDs.add(reachable.getID());
if (inNoise) {
noise.remove(reachable.getID());
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
}
}
}
}
}
if (currentCluster.size() >= minpts) {
resultList.add(currentCluster);
}
else {
for (Integer id : currentCluster) {
noise.add(id);
}
noise.add(startObjectID);
processedIDs.add(startObjectID);
}
if (isVerbose()) {
progress.setProcessed(processedIDs.size());
logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
}
}
}
}
}
/**
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
public String[] setParameters(String[] args) throws ParameterException {
String[] remainingParameters = super.setParameters(args);
epsilon = optionHandler.getOptionValue(EPSILON_P);
try {
// test whether epsilon is compatible with distance function
distanceFunction.valueOf(epsilon);
}
catch (IllegalArgumentException e) {
throw new WrongParameterValueException(EPSILON_P, epsilon, EPSILON_D);
}
// minpts
String minptsString = optionHandler.getOptionValue(MINPTS_P);
try {
minpts = Integer.parseInt(minptsString);
if (minpts <= 0) {
throw new WrongParameterValueException(MINPTS_P, minptsString, MINPTS_D);
}
}
catch (NumberFormatException e) {
throw new WrongParameterValueException(MINPTS_P, minptsString, MINPTS_D, e);
}
// lambda
String lambdaString = optionHandler.getOptionValue(LAMBDA_P);
try {
lambda = Integer.parseInt(lambdaString);
if (lambda <= 0) {
throw new WrongParameterValueException(LAMBDA_P, lambdaString, LAMBDA_D);
}
}
catch (NumberFormatException e) {
throw new WrongParameterValueException(LAMBDA_P, lambdaString, LAMBDA_D, e);
}
// parameters for the distance function
List<String> distanceFunctionParameters = new ArrayList<String>();
// omit preprocessing flag
distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.OMIT_PREPROCESSING_F);
// preprocessor
distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.PREPROCESSOR_CLASS_P);
distanceFunctionParameters.add(preprocessorClass().getName());
// preprocessor epsilon
distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + ProjectedDBSCANPreprocessor.EPSILON_P);
distanceFunctionParameters.add(epsilon);
distanceFunction.setParameters(distanceFunctionParameters.toArray(new String[distanceFunctionParameters.size()]));
setParameters(args, remainingParameters);
return remainingParameters;
}
/**
* @see Algorithm#getAttributeSettings()
*/
@Override
public List<AttributeSettings> getAttributeSettings() {
List<AttributeSettings> attributeSettings = super.getAttributeSettings();
AttributeSettings mySettings = attributeSettings.get(0);
mySettings.addSetting(LAMBDA_P, Integer.toString(lambda));
mySettings.addSetting(EPSILON_P, epsilon);
mySettings.addSetting(MINPTS_P, Integer.toString(minpts));
attributeSettings.addAll(distanceFunction.getAttributeSettings());
return attributeSettings;
}
/**
* Returns the class actually used as
* {@link ProjectedDBSCANPreprocessor VarianceAnalysisPreprocessor}.
*
* @return the class actually used as
* {@link ProjectedDBSCANPreprocessor VarianceAnalysisPreprocessor}
*/
public abstract Class<P> preprocessorClass();
/**
* @see de.lmu.ifi.dbs.algorithm.Algorithm#getResult()
*/
public ClustersPlusNoise<RealVector> getResult() {
return result;
}
}
| bugfixing GRMPF
| src/de/lmu/ifi/dbs/algorithm/clustering/ProjectedDBSCAN.java | bugfixing GRMPF | <ide><path>rc/de/lmu/ifi/dbs/algorithm/clustering/ProjectedDBSCAN.java
<ide> import de.lmu.ifi.dbs.database.Database;
<ide> import de.lmu.ifi.dbs.distance.DoubleDistance;
<ide> import de.lmu.ifi.dbs.distance.LocallyWeightedDistanceFunction;
<add>import de.lmu.ifi.dbs.logging.ProgressLogRecord;
<ide> import de.lmu.ifi.dbs.logging.LoggingConfiguration;
<del>import de.lmu.ifi.dbs.logging.ProgressLogRecord;
<ide> import de.lmu.ifi.dbs.preprocessing.ProjectedDBSCANPreprocessor;
<ide> import de.lmu.ifi.dbs.utilities.Progress;
<ide> import de.lmu.ifi.dbs.utilities.QueryResult;
<ide> */
<ide> @SuppressWarnings({"UNUSED_SYMBOL"})
<ide> private static final boolean DEBUG = LoggingConfiguration.DEBUG;
<add>// private static final boolean DEBUG = true;
<ide>
<ide> /**
<ide> * The logger of this class.
<ide> * ExpandCluster function of DBSCAN.
<ide> */
<ide> protected void expandCluster(Database<RealVector> database, Integer startObjectID, Progress progress) {
<del> List<QueryResult<DoubleDistance>> neighborhoodIDs = database.rangeQuery(startObjectID, epsilon, distanceFunction);
<del> if (neighborhoodIDs.size() < minpts) {
<add> List<QueryResult<DoubleDistance>> seeds = database.rangeQuery(startObjectID, epsilon, distanceFunction);
<add> if (DEBUG) {
<add> logger.fine("\nseeds of " + startObjectID + " " +
<add> database.getAssociation(AssociationID.LABEL, startObjectID) + " " + seeds.size());
<add> }
<add>
<add> // neighbors < minPts OR local dimensionality > lambda -> noise
<add> if (seeds.size() < minpts ||
<add> (Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, startObjectID) > lambda) {
<ide> noise.add(startObjectID);
<ide> processedIDs.add(startObjectID);
<ide> if (isVerbose()) {
<ide> progress.setProcessed(processedIDs.size());
<ide> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
<ide> }
<del> }
<del> else {
<del> List<Integer> currentCluster = new ArrayList<Integer>();
<del> if ((Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, startObjectID) > lambda) {
<del> noise.add(startObjectID);
<del> processedIDs.add(startObjectID);
<del> if (isVerbose()) {
<del> progress.setProcessed(processedIDs.size());
<del> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
<del> }
<del> }
<del> else {
<del> List<QueryResult<DoubleDistance>> seeds = database.rangeQuery(startObjectID, epsilon, distanceFunction);
<del> if (seeds.size() < minpts) {
<del> noise.add(startObjectID);
<del> processedIDs.add(startObjectID);
<del> if (isVerbose()) {
<del> progress.setProcessed(processedIDs.size());
<del> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
<add> return;
<add> }
<add>
<add> // try to expand the cluster
<add> List<Integer> currentCluster = new ArrayList<Integer>();
<add> for (QueryResult<DoubleDistance> nextSeed : seeds) {
<add> Integer nextID = nextSeed.getID();
<add> if (!processedIDs.contains(nextID)) {
<add> currentCluster.add(nextID);
<add> processedIDs.add(nextID);
<add> }
<add> else if (noise.contains(nextID)) {
<add> currentCluster.add(nextID);
<add> noise.remove(nextID);
<add> }
<add> if (isVerbose()) {
<add> progress.setProcessed(processedIDs.size());
<add> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
<add> }
<add> }
<add> seeds.remove(0);
<add> processedIDs.add(startObjectID);
<add> if (isVerbose()) {
<add> progress.setProcessed(processedIDs.size());
<add> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
<add> }
<add>
<add> while (seeds.size() > 0) {
<add> Integer o = seeds.remove(0).getID();
<add> List<QueryResult<DoubleDistance>> neighborhood = database.rangeQuery(o, epsilon, distanceFunction);
<add> if (neighborhood.size() >= minpts &&
<add> (Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, o) <= lambda) {
<add> for (QueryResult<DoubleDistance> neighbor : neighborhood) {
<add> Integer p = neighbor.getID();
<add> boolean inNoise = noise.contains(p);
<add> boolean unclassified = !processedIDs.contains(p);
<add> if (inNoise || unclassified) {
<add> if (unclassified) {
<add> seeds.add(neighbor);
<add> }
<add> currentCluster.add(p);
<add> processedIDs.add(p);
<add> if (inNoise) {
<add> noise.remove(p);
<add> }
<ide> }
<ide> }
<del> else {
<del> for (QueryResult<DoubleDistance> nextSeed : seeds) {
<del> Integer nextID = nextSeed.getID();
<del> if (!processedIDs.contains(nextID)) {
<del> currentCluster.add(nextID);
<del> processedIDs.add(nextID);
<del> }
<del> else if (noise.contains(nextID)) {
<del> currentCluster.add(nextID);
<del> noise.remove(nextID);
<del> }
<del> if (isVerbose()) {
<del> progress.setProcessed(processedIDs.size());
<del> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
<del> }
<del> }
<del> seeds.remove(0);
<del> processedIDs.add(startObjectID);
<del> if (isVerbose()) {
<del> progress.setProcessed(processedIDs.size());
<del> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
<del> }
<del>
<del> while (seeds.size() > 0) {
<del> Integer seedID = seeds.remove(0).getID();
<del> List<QueryResult<DoubleDistance>> seedNeighborhoodIDs = database.rangeQuery(seedID, epsilon, distanceFunction);
<del> if (seedNeighborhoodIDs.size() >= minpts) {
<del> if ((Integer) database.getAssociation(AssociationID.LOCAL_DIMENSIONALITY, seedID) <= lambda) {
<del> List<QueryResult<DoubleDistance>> reachables = database.rangeQuery(seedID, epsilon, distanceFunction);
<del> if (reachables.size() >= minpts) {
<del> for (QueryResult<DoubleDistance> reachable : reachables) {
<del> boolean inNoise = noise.contains(reachable.getID());
<del> boolean unclassified = !processedIDs.contains(reachable.getID());
<del> if (inNoise || unclassified) {
<del> if (unclassified) {
<del> seeds.add(reachable);
<del> }
<del> currentCluster.add(reachable.getID());
<del> processedIDs.add(reachable.getID());
<del> if (inNoise) {
<del> noise.remove(reachable.getID());
<del> }
<del> if (isVerbose()) {
<del> progress.setProcessed(processedIDs.size());
<del> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
<del> }
<del> }
<del> }
<del> }
<del> }
<del> }
<del> }
<del> if (currentCluster.size() >= minpts) {
<del> resultList.add(currentCluster);
<del> }
<del> else {
<del> for (Integer id : currentCluster) {
<del> noise.add(id);
<del> }
<del> noise.add(startObjectID);
<del> processedIDs.add(startObjectID);
<del> }
<del> if (isVerbose()) {
<del> progress.setProcessed(processedIDs.size());
<del> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
<del> }
<del> }
<del> }
<add> }
<add>
<add> if (isVerbose()) {
<add> progress.setProcessed(processedIDs.size());
<add> int numClusters = currentCluster.size() > minpts ? resultList.size() + 1 : resultList.size();
<add> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, numClusters), progress.getTask(), progress.status()));
<add> }
<add>
<add> if (processedIDs.size() == database.size() && noise.size() == 0) {
<add> break;
<add> }
<add> }
<add> if (currentCluster.size() >= minpts) {
<add> resultList.add(currentCluster);
<add> }
<add> else {
<add> for (Integer id : currentCluster) {
<add> noise.add(id);
<add> }
<add> noise.add(startObjectID);
<add> processedIDs.add(startObjectID);
<add> }
<add>
<add> if (isVerbose()) {
<add> progress.setProcessed(processedIDs.size());
<add> logger.log(new ProgressLogRecord(Level.INFO, Util.status(progress, resultList.size()), progress.getTask(), progress.status()));
<ide> }
<ide> }
<ide>
<ide> /**
<ide> * @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
<ide> */
<del> public String[] setParameters(String[] args) throws ParameterException {
<add> public String[] setParameters
<add> (String[] args) throws ParameterException {
<ide> String[] remainingParameters = super.setParameters(args);
<ide>
<ide> epsilon = optionHandler.getOptionValue(EPSILON_P);
<ide> }
<ide>
<ide> // parameters for the distance function
<del> List<String> distanceFunctionParameters = new ArrayList<String>();
<add> String[] distanceFunctionParameters = new String[remainingParameters.length + 5];
<add> System.arraycopy(remainingParameters, 0, distanceFunctionParameters, 5, remainingParameters.length);
<add>
<ide> // omit preprocessing flag
<del> distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.OMIT_PREPROCESSING_F);
<add> distanceFunctionParameters[0] = OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.OMIT_PREPROCESSING_F;
<ide> // preprocessor
<del> distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.PREPROCESSOR_CLASS_P);
<del> distanceFunctionParameters.add(preprocessorClass().getName());
<add> distanceFunctionParameters[1] = OptionHandler.OPTION_PREFIX + LocallyWeightedDistanceFunction.PREPROCESSOR_CLASS_P;
<add> distanceFunctionParameters[2] = preprocessorClass().getName();
<ide> // preprocessor epsilon
<del> distanceFunctionParameters.add(OptionHandler.OPTION_PREFIX + ProjectedDBSCANPreprocessor.EPSILON_P);
<del> distanceFunctionParameters.add(epsilon);
<del>
<del> distanceFunction.setParameters(distanceFunctionParameters.toArray(new String[distanceFunctionParameters.size()]));
<add> distanceFunctionParameters[3] = OptionHandler.OPTION_PREFIX + ProjectedDBSCANPreprocessor.EPSILON_P;
<add> distanceFunctionParameters[4] = epsilon;
<add>
<add> distanceFunction.setParameters(distanceFunctionParameters);
<ide>
<ide> setParameters(args, remainingParameters);
<ide> return remainingParameters;
<ide> * @see Algorithm#getAttributeSettings()
<ide> */
<ide> @Override
<del> public List<AttributeSettings> getAttributeSettings() {
<add> public List<AttributeSettings> getAttributeSettings
<add> () {
<ide> List<AttributeSettings> attributeSettings = super.getAttributeSettings();
<ide>
<ide> AttributeSettings mySettings = attributeSettings.get(0);
<ide> * @return the class actually used as
<ide> * {@link ProjectedDBSCANPreprocessor VarianceAnalysisPreprocessor}
<ide> */
<del> public abstract Class<P> preprocessorClass();
<add> public abstract Class<P> preprocessorClass
<add> ();
<ide>
<ide> /**
<ide> * @see de.lmu.ifi.dbs.algorithm.Algorithm#getResult()
<ide> */
<del> public ClustersPlusNoise<RealVector> getResult() {
<add> public ClustersPlusNoise<RealVector> getResult
<add> () {
<ide> return result;
<ide> }
<ide> |
|
Java | apache-2.0 | c4d9a4c82b926c7795b0b21b0d7558f005434a20 | 0 | resmo/cloudstack,mufaddalq/cloudstack-datera-driver,wido/cloudstack,GabrielBrascher/cloudstack,argv0/cloudstack,argv0/cloudstack,GabrielBrascher/cloudstack,cinderella/incubator-cloudstack,resmo/cloudstack,wido/cloudstack,resmo/cloudstack,resmo/cloudstack,cinderella/incubator-cloudstack,jcshen007/cloudstack,wido/cloudstack,mufaddalq/cloudstack-datera-driver,jcshen007/cloudstack,argv0/cloudstack,DaanHoogland/cloudstack,cinderella/incubator-cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,mufaddalq/cloudstack-datera-driver,cinderella/incubator-cloudstack,argv0/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,jcshen007/cloudstack,wido/cloudstack,cinderella/incubator-cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,mufaddalq/cloudstack-datera-driver,jcshen007/cloudstack,mufaddalq/cloudstack-datera-driver,GabrielBrascher/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,mufaddalq/cloudstack-datera-driver,argv0/cloudstack,argv0/cloudstack | /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.cluster.agentlb;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.SearchCriteria2;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.SearchCriteriaService;
@Local(value=AgentLoadBalancerPlanner.class)
public class ClusterBasedAgentLoadBalancerPlanner implements AgentLoadBalancerPlanner{
private static final Logger s_logger = Logger.getLogger(AgentLoadBalancerPlanner.class);
private String _name;
@Inject HostDao _hostDao = null;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public List<HostVO> getHostsToRebalance(long msId, int avLoad) {
SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2.create(HostVO.class);
sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing);
sc.addAnd(sc.getEntity().getManagementServerId(), Op.EQ, msId);
List<HostVO> allHosts = sc.list();
if (allHosts.size() <= avLoad) {
s_logger.debug("Agent load = " + allHosts.size() + " for management server " + msId + " doesn't exceed average system agent load = " + avLoad + "; so it doesn't participate in agent rebalancing process");
return null;
}
sc = SearchCriteria2.create(HostVO.class);
sc.addAnd(sc.getEntity().getManagementServerId(), Op.EQ, msId);
sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up);
List<HostVO> directHosts = sc.list();
if (directHosts.isEmpty()) {
s_logger.debug("No direct agents in status " + Status.Up + " exist for the management server " + msId + "; so it doesn't participate in agent rebalancing process");
return null;
}
Map<Long, List<HostVO>> hostToClusterMap = new HashMap<Long, List<HostVO>>();
for (HostVO directHost : directHosts) {
Long clusterId = directHost.getClusterId();
List<HostVO> directHostsPerCluster = null;
if (!hostToClusterMap.containsKey(clusterId)) {
directHostsPerCluster = new ArrayList<HostVO>();
} else {
directHostsPerCluster = hostToClusterMap.get(clusterId);
}
directHostsPerCluster.add(directHost);
hostToClusterMap.put(clusterId, directHostsPerCluster);
}
hostToClusterMap = sortByClusterSize(hostToClusterMap);
int hostsToGive = allHosts.size() - avLoad;
int hostsLeftToGive = hostsToGive;
int hostsLeft = directHosts.size();
List<HostVO> hostsToReturn = new ArrayList<HostVO>();
s_logger.debug("Management server " + msId + " can give away " + hostsToGive + " as it currently owns " + allHosts.size() +
" and the average agent load in the system is " + avLoad + "; finalyzing list of hosts to give away...");
for (Long cluster : hostToClusterMap.keySet()) {
List<HostVO> hostsInCluster = hostToClusterMap.get(cluster);
hostsLeft = hostsLeft - hostsInCluster.size();
if (hostsToReturn.size() < hostsToGive) {
s_logger.debug("Trying cluster id=" + cluster);
if (hostsInCluster.size() > hostsLeftToGive) {
s_logger.debug("Skipping cluster id=" + cluster + " as it has more hosts than we need: " + hostsInCluster.size() + " vs " + hostsLeftToGive);
if (hostsLeft >= hostsLeftToGive) {
continue;
} else {
break;
}
} else {
s_logger.debug("Taking all " + hostsInCluster.size() + " hosts: " + hostsInCluster + " from cluster id=" + cluster);
hostsToReturn.addAll(hostsInCluster);
hostsLeftToGive = hostsLeftToGive - hostsInCluster.size();
}
} else {
break;
}
}
s_logger.debug("Management server " + msId + " is ready to give away " + hostsToReturn.size() + " hosts");
return hostsToReturn;
}
public static LinkedHashMap<Long, List<HostVO>> sortByClusterSize(final Map<Long, List<HostVO>> hostToClusterMap) {
List<Long> keys = new ArrayList<Long>();
keys.addAll(hostToClusterMap.keySet());
Collections.sort(keys, new Comparator<Long>() {
@Override
public int compare(Long o1, Long o2) {
List<HostVO> v1 = hostToClusterMap.get(o1);
List<HostVO> v2 = hostToClusterMap.get(o2);
if (v1 == null) {
return (v2 == null) ? 0 : 1;
}
if (v1.size() < v2.size()) {
return 1;
} else {
return 0;
}
}
});
LinkedHashMap<Long, List<HostVO>> sortedMap = new LinkedHashMap<Long, List<HostVO>>();
for (Long key : keys) {
sortedMap.put(key, hostToClusterMap.get(key));
}
return sortedMap;
}
}
| server/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java | /**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.cluster.agentlb;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.SearchCriteria2;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.SearchCriteriaService;
@Local(value=AgentLoadBalancerPlanner.class)
public class ClusterBasedAgentLoadBalancerPlanner implements AgentLoadBalancerPlanner{
private static final Logger s_logger = Logger.getLogger(AgentLoadBalancerPlanner.class);
private String _name;
@Inject HostDao _hostDao = null;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public List<HostVO> getHostsToRebalance(long msId, int avLoad) {
SearchCriteriaService<HostVO, HostVO> sc = SearchCriteria2.create(HostVO.class);
sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing);
sc.addAnd(sc.getEntity().getManagementServerId(), Op.EQ, msId);
List<HostVO> allHosts = sc.list();
if (allHosts.size() <= avLoad) {
s_logger.debug("Agent load = " + allHosts.size() + " for management server " + msId + " doesn't exceed average system agent load = " + avLoad + "; so it doesn't participate in agent rebalancing process");
return null;
}
sc = SearchCriteria2.create(HostVO.class);
sc.addAnd(sc.getEntity().getManagementServerId(), Op.EQ, msId);
sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up);
List<HostVO> directHosts = sc.list();
if (directHosts.isEmpty()) {
s_logger.debug("No direct agents in status " + Status.Up + " exist for the management server " + msId + "; so it doesn't participate in agent rebalancing process");
return null;
}
Map<Long, List<HostVO>> hostToClusterMap = new HashMap<Long, List<HostVO>>();
for (HostVO directHost : directHosts) {
Long clusterId = directHost.getClusterId();
List<HostVO> directHostsPerCluster = null;
if (!hostToClusterMap.containsKey(clusterId)) {
directHostsPerCluster = new ArrayList<HostVO>();
} else {
directHostsPerCluster = hostToClusterMap.get(clusterId);
}
directHostsPerCluster.add(directHost);
hostToClusterMap.put(clusterId, directHostsPerCluster);
}
hostToClusterMap = sortByClusterSize(hostToClusterMap);
int hostsToGive = allHosts.size() - avLoad;
int hostsLeftToGive = hostsToGive;
int hostsLeft = directHosts.size();
List<HostVO> hostsToReturn = new ArrayList<HostVO>();
s_logger.debug("Management server " + msId + " can give away " + hostsToGive + " as it currently owns " + allHosts.size() + " and the average agent load in the system is " + avLoad + "; finalyzing list of hosts to give away...");
for (Long cluster : hostToClusterMap.keySet()) {
List<HostVO> hostsInCluster = hostToClusterMap.get(cluster);
hostsLeft = hostsLeft - hostsInCluster.size();
if (hostsToReturn.size() < hostsToGive) {
s_logger.debug("Trying cluster id=" + cluster);
if (hostsInCluster.size() > hostsLeftToGive) {
if (hostsLeft >= hostsLeftToGive) {
s_logger.debug("Skipping cluster id=" + cluster + " as it has more hosts that we need: " + hostsInCluster.size() + " vs " + hostsLeftToGive);
continue;
} else {
//get all hosts that are needed from the cluster
s_logger.debug("Taking " + hostsLeftToGive + " from cluster " + cluster);
for (int i=0; i < hostsLeftToGive; i++) {
s_logger.trace("Taking host id=" + hostsInCluster.get(i) + " from cluster " + cluster);
hostsToReturn.add(hostsInCluster.get(i));
}
break;
}
} else {
s_logger.debug("Taking all " + hostsInCluster.size() + " hosts: " + hostsInCluster + " from cluster id=" + cluster);
hostsToReturn.addAll(hostsInCluster);
hostsLeftToGive = hostsLeftToGive - hostsInCluster.size();
}
} else {
break;
}
}
s_logger.debug("Management server " + msId + " is ready to give away " + hostsToReturn.size() + " hosts");
return hostsToReturn;
}
public static LinkedHashMap<Long, List<HostVO>> sortByClusterSize(final Map<Long, List<HostVO>> hostToClusterMap) {
List<Long> keys = new ArrayList<Long>();
keys.addAll(hostToClusterMap.keySet());
Collections.sort(keys, new Comparator<Long>() {
@Override
public int compare(Long o1, Long o2) {
List<HostVO> v1 = hostToClusterMap.get(o1);
List<HostVO> v2 = hostToClusterMap.get(o2);
if (v1 == null) {
return (v2 == null) ? 0 : 1;
}
if (v1.size() < v2.size()) {
return 1;
} else {
return 0;
}
}
});
LinkedHashMap<Long, List<HostVO>> sortedMap = new LinkedHashMap<Long, List<HostVO>>();
for (Long key : keys) {
sortedMap.put(key, hostToClusterMap.get(key));
}
return sortedMap;
}
}
| Agent LB: never get a part of the hosts from the xen cluster; skip the cluster if it has more hosts than we need
Reviewed-by: Alex Huang
| server/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java | Agent LB: never get a part of the hosts from the xen cluster; skip the cluster if it has more hosts than we need Reviewed-by: Alex Huang | <ide><path>erver/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java
<ide> int hostsLeft = directHosts.size();
<ide> List<HostVO> hostsToReturn = new ArrayList<HostVO>();
<ide>
<del> s_logger.debug("Management server " + msId + " can give away " + hostsToGive + " as it currently owns " + allHosts.size() + " and the average agent load in the system is " + avLoad + "; finalyzing list of hosts to give away...");
<add> s_logger.debug("Management server " + msId + " can give away " + hostsToGive + " as it currently owns " + allHosts.size() +
<add> " and the average agent load in the system is " + avLoad + "; finalyzing list of hosts to give away...");
<ide> for (Long cluster : hostToClusterMap.keySet()) {
<ide> List<HostVO> hostsInCluster = hostToClusterMap.get(cluster);
<ide> hostsLeft = hostsLeft - hostsInCluster.size();
<ide> s_logger.debug("Trying cluster id=" + cluster);
<ide>
<ide> if (hostsInCluster.size() > hostsLeftToGive) {
<add> s_logger.debug("Skipping cluster id=" + cluster + " as it has more hosts than we need: " + hostsInCluster.size() + " vs " + hostsLeftToGive);
<ide> if (hostsLeft >= hostsLeftToGive) {
<del> s_logger.debug("Skipping cluster id=" + cluster + " as it has more hosts that we need: " + hostsInCluster.size() + " vs " + hostsLeftToGive);
<ide> continue;
<ide> } else {
<del> //get all hosts that are needed from the cluster
<del> s_logger.debug("Taking " + hostsLeftToGive + " from cluster " + cluster);
<del> for (int i=0; i < hostsLeftToGive; i++) {
<del> s_logger.trace("Taking host id=" + hostsInCluster.get(i) + " from cluster " + cluster);
<del> hostsToReturn.add(hostsInCluster.get(i));
<del> }
<del>
<ide> break;
<ide> }
<ide> } else { |
|
Java | lgpl-2.1 | e3c0cb3caec5c688f87c63f2e9e7c94f80bb587b | 0 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine |
/*
* jETeL/Clover - Java based ETL application framework.
* Copyright (C) 2002-04 David Pavlis <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
// FILE: c:/projects/jetel/org/jetel/metadata/DataRecordMetadataReaderWriter.java
package org.jetel.metadata;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.Defaults;
import org.jetel.graph.TransformationGraph;
import org.jetel.util.property.PropertyRefResolver;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Helper class for reading/writing DataRecordMetadata (record structure)
* from/to XML format <br>
*
* <i>Note: If for record or some field Node are defined more attributes than
* those recognized, they are transferred to Java Properties object and assigned
* to either record or field. </i>
*
* The XML DTD describing the internal structure is as follows:
*
* <pre>
*
* <!ELEMENT Record (FIELD+)>
* <!ATTLIST Record
* name ID #REQUIRED
* id ID #REQUIRED
* name CDATA #REQUIRED
* type NMTOKEN (delimited | fixed | mixed) #REQUIRED
* locale CDATA #IMPLIED
* recordDelimiter CDATA #IMPLIED
*
*
* <!ELEMENT Field (#PCDATA) EMPTY>
* <!ATTLIST Field
* name ID #REQUIRED
* type NMTOKEN #REQUIRED
* delimiter NMTOKEN #IMPLIED ","
* size NMTOKEN #IMPLIED "0"
* shift NMTOKEN #IMPLIED "0"
* format CDATA #IMPLIED
* locale CDATA #IMPLIED
* nullable NMTOKEN (true | false) #IMPLIED "true"
* compressed NMTOKEN (true | false) #IMPLIED "false"
* default CDATA #IMPLIED >
*
* </pre>
*
* Example:
*
* <pre>
*
* <Record name="TestRecord" type="delimited">
* <Field name="Field1" type="numeric" delimiter=";" />
* <Field name="Field2" type="numeric" delimiter=";" locale="de" />
* <Field name="Field3" type="string" delimiter=";" />
* <Field name="Field4" type="string" delimiter="\n"/>
* </Record>
*
* </pre>
*
* If you specify your own attributes, they will be accessible through
* getFieldProperties() method of DataFieldMetadata class. <br>
* Example:
*
* <pre>
*
* <Field name="Field1" type="numeric" delimiter=";" mySpec1="1" mySpec2="xyz"/>
*
* </pre>
*
* @author D.Pavlis
* @since May 6, 2002
* @see javax.xml.parsers
*/
public class DataRecordMetadataXMLReaderWriter extends DefaultHandler {
// Attributes
private DocumentBuilder db;
private DocumentBuilderFactory dbf;
private PropertyRefResolver refResolver;
// not needed private final static String DEFAULT_PARSER_NAME = "";
private static final boolean validation = false;
private static final boolean ignoreComments = true;
private static final boolean ignoreWhitespaces = true;
private static final boolean putCDATAIntoText = false;
private static final boolean createEntityRefs = false;
//private static boolean setLoadExternalDTD = true;
//private static boolean setSchemaSupport = true;
//private static boolean setSchemaFullSupport = false;
private static final String METADATA_ELEMENT = "Metadata";
private static final String ID = "id";
private static final String RECORD_ELEMENT = "Record";
private static final String FIELD_ELEMENT = "Field";
private static final String CODE_ELEMENT = "Code";
private static final String NAME_ATTR = "name";
private static final String TYPE_ATTR = "type";
private static final String RECORD_SIZE_ATTR = "recordSize";
public static final String RECORD_DELIMITER_ATTR = "recordDelimiter";
private static final String DELIMITER_ATTR = "delimiter";
private static final String EOF_AS_DELIMITER_ATTR = "eofAsDelimiter";
private static final String FORMAT_ATTR = "format";
private static final String DEFAULT_ATTR = "default";
private static final String LOCALE_ATTR = "locale";
private static final String NULLABLE_ATTR = "nullable";
private static final String COMPRESSED_ATTR = "compressed";
private static final String SHIFT_ATTR = "shift";
private static final String SIZE_ATTR = "size";
private static final String AUTO_FILLING_ATTR = "auto_filling";
private static final String DEFAULT_CHARACTER_ENCODING = "UTF-8";
private static final String XSL_FORMATER
= "<?xml version='1.0' encoding='"+DEFAULT_CHARACTER_ENCODING+"'?>"
+ "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>"
+ "<xsl:output encoding='"+DEFAULT_CHARACTER_ENCODING+"' indent='yes' method='xml'/>"
+ "<xsl:template match='/'><xsl:copy-of select='*'/></xsl:template>"
+ "</xsl:stylesheet>";
private static Log logger = LogFactory.getLog(DataRecordMetadata.class);
/**
* Constructor with graph to property resolving.
* @param graph
*/
public DataRecordMetadataXMLReaderWriter() {
this((Properties) null);
}
/**
* Constructor with graph to property resolving.
* @param graph
*/
public DataRecordMetadataXMLReaderWriter(TransformationGraph graph) {
this(graph.getGraphProperties());
}
/**
* Constructor with properties for resolving.
* @param properties
*/
public DataRecordMetadataXMLReaderWriter(Properties properties) {
refResolver = new PropertyRefResolver(properties);
}
// Associations
// Operations
/**
* An operation that reads DataRecord format definition from XML data
*
* @param in
* InputStream with XML data describing DataRecord
* @return DataRecordMetadata object
* @since May 6, 2002
*/
public DataRecordMetadata read(InputStream in) {
return read(in, null);
}
public DataRecordMetadata read(InputStream in, String metadataId) {
Document document;
try {
// construct XML parser (if it is needed)
if ((dbf == null) || (db == null)) {
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setCoalescing(true);
// Optional: set various configuration options
dbf.setValidating(validation);
dbf.setIgnoringComments(ignoreComments);
dbf.setIgnoringElementContentWhitespace(ignoreWhitespaces);
dbf.setCoalescing(putCDATAIntoText);
dbf.setExpandEntityReferences(!createEntityRefs);
db = dbf.newDocumentBuilder();
}
document = db.parse(new BufferedInputStream(in));
document.normalize();
} catch (SAXParseException ex) {
logger.fatal("SAX Exception on line "
+ ex.getLineNumber() + " row " + ex.getColumnNumber(), ex);
return null;
} catch (ParserConfigurationException ex) {
logger.fatal(ex.getMessage());
return null;
} catch (Exception ex) {
logger.fatal(ex.getMessage());
return null;
}
try {
return parseRecordMetadata(document, metadataId);
} catch (DOMException ex) {
logger.fatal(ex.getMessage());
return null;
} catch (Exception ex) {
logger.fatal("parseRecordMetadata method call: "
+ ex.getMessage());
return null;
}
}
/**
* An operation that writes DataRecord format definition into XML format
*
* @param record
* Metadata describing data record
* @param outStream
* OutputStream into which XML data is written
* @since May 6, 2002
*/
public static void write(DataRecordMetadata record, OutputStream outStream) {
DocumentBuilder db = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element rootElement = doc.createElement(RECORD_ELEMENT);
doc.appendChild(rootElement);
write(record, rootElement);
StreamSource formSrc = new StreamSource(new StringReader(XSL_FORMATER));
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer(formSrc);
t.transform(new DOMSource(doc), new StreamResult(outStream));
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public static void write(DataRecordMetadata record, Element metadataElement) {
String rt;
DataFieldMetadata field;
metadataElement.setAttribute(NAME_ATTR, record.getName());
if(record.getRecType() == DataRecordMetadata.DELIMITED_RECORD) rt = "delimited";
else if(record.getRecType() == DataRecordMetadata.FIXEDLEN_RECORD) rt = "fixed";
else rt = "mixed";
metadataElement.setAttribute(TYPE_ATTR, rt);
if(!StringUtils.isEmpty(record.getRecordDelimiter())) {
metadataElement.setAttribute(RECORD_DELIMITER_ATTR, StringUtils.specCharToString(record.getRecordDelimiter()));
}
if (record.getRecordSize() != 0) {
metadataElement.setAttribute(RECORD_SIZE_ATTR, String.valueOf(record.getRecordSize()));
}
Properties prop = record.getRecordProperties();
if (prop != null) {
Enumeration enumeration = prop.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
metadataElement.setAttribute(key, prop.getProperty(key));
}
}
// OUTPUT FIELDS
// MessageFormat fieldForm = new MessageFormat(
// "\t<Field name=\"{0}\" type=\"{1}\" ");
char[] fieldTypeLimits = { DataFieldMetadata.STRING_FIELD,
DataFieldMetadata.DATE_FIELD,
DataFieldMetadata.DATETIME_FIELD,
DataFieldMetadata.NUMERIC_FIELD,
DataFieldMetadata.INTEGER_FIELD,
DataFieldMetadata.LONG_FIELD,
DataFieldMetadata.DECIMAL_FIELD,
DataFieldMetadata.BYTE_FIELD,
DataFieldMetadata.BYTE_FIELD_COMPRESSED };
String[] fieldTypeParts = { "string", "date", "datetime", "numeric",
"integer", "long", "decimal", "byte", "cbyte" };
Document doc = metadataElement.getOwnerDocument();
for (int i = 0; i < record.getNumFields(); i++) {
field = record.getField(i);
if (field != null) {
Element fieldElement = doc.createElement(FIELD_ELEMENT);
metadataElement.appendChild(fieldElement);
fieldElement.setAttribute(NAME_ATTR, field.getName());
fieldElement.setAttribute(TYPE_ATTR,
fieldTypeFormat(field.getType(), fieldTypeLimits,
fieldTypeParts));
fieldElement.setAttribute(SHIFT_ATTR, String.valueOf(field.getShift()));
if (record.getRecType() == DataRecordMetadata.DELIMITED_RECORD) {
fieldElement.setAttribute(DELIMITER_ATTR,
StringUtils.specCharToString(field.getDelimiter()));
} else {
fieldElement.setAttribute(SIZE_ATTR, String.valueOf(field.getSize()));
}
if (field.getFormatStr() != null) {
fieldElement.setAttribute(FORMAT_ATTR, field.getFormatStr());
}
if (field.getDefaultValueStr() != null) {
fieldElement.setAttribute(DEFAULT_ATTR, field.getDefaultValueStr());
}
if (field.getLocaleStr() != null) {
fieldElement.setAttribute(LOCALE_ATTR, field.getLocaleStr());
}
if (field.getAutoFilling() != null) {
fieldElement.setAttribute(AUTO_FILLING_ATTR, field.getAutoFilling());
}
fieldElement.setAttribute(NULLABLE_ATTR,
String.valueOf(field.isNullable()));
// output field properties - if anything defined
prop = field.getFieldProperties();
if (prop != null) {
Enumeration enumeration = prop.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
fieldElement.setAttribute(key, prop.getProperty(key));
}
}
// if (field.getCodeStr() != null) {
// Element codeElement = doc.createElement(CODE_ELEMENT);
// fieldElement.appendChild(codeElement);
// Text codeText = doc.createTextNode(field.getCodeStr());
// codeElement.appendChild(codeText);
// }
}
}
}
public DataRecordMetadata parseRecordMetadata(Document document)
throws DOMException {
return parseRecordMetadata(document, null);
}
public DataRecordMetadata parseRecordMetadata(Document document, String metadataId) throws DOMException {
org.w3c.dom.NodeList nodes;
if (metadataId != null) {
nodes = document.getElementsByTagName(METADATA_ELEMENT);
int lenght = nodes.getLength();
org.w3c.dom.Node node = null;
for (int i=0; i<lenght; i++) {
node = nodes.item(i);
if (node.getAttributes().getNamedItem(ID).getNodeValue().equals(metadataId)) {
return parseRecordMetadata(node.getChildNodes().item(1));
}
}
return null;
} else {
nodes = document.getElementsByTagName(RECORD_ELEMENT);
if (nodes.getLength() == 0) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"No Record element has been found ! ");
}
return parseRecordMetadata(nodes.item(0));
}
}
public DataRecordMetadata parseRecordMetadata(org.w3c.dom.Node topNode)
throws DOMException {
org.w3c.dom.NamedNodeMap attributes;
DataRecordMetadata recordMetadata;
String recordName = null;
String recordType = null;
String recordDelimiter = null;
String sizeStr = null;
String recLocaleStr = null;
String itemName;
String itemValue;
Properties recordProperties = null;
if (topNode.getNodeName() != RECORD_ELEMENT) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Root Node is not of type " + RECORD_ELEMENT);
}
/*
* get Record level metadata
*/
attributes = topNode.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
itemName = attributes.item(i).getNodeName();
itemValue = refResolver.resolveRef(attributes.item(i)
.getNodeValue());
if (itemName.equalsIgnoreCase("name")) {
recordName = itemValue;
} else if (itemName.equalsIgnoreCase("type")) {
recordType = itemValue;
} else if (itemName.equalsIgnoreCase("locale")) {
recLocaleStr = itemValue;
} else if (itemName.equalsIgnoreCase(RECORD_DELIMITER_ATTR)) {
recordDelimiter = itemValue;
} else if (itemName.equalsIgnoreCase(RECORD_SIZE_ATTR)) {
sizeStr = itemValue;
} else {
if (recordProperties == null) {
recordProperties = new Properties();
}
recordProperties.setProperty(itemName, itemValue);
}
}
if (recordType == null || recordName == null) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Attribute \"name\" or \"type\" not defined within Record !");
}
char rt;
if(recordType.equalsIgnoreCase("delimited")) rt = DataRecordMetadata.DELIMITED_RECORD;
else if(recordType.equalsIgnoreCase("fixed")) rt = DataRecordMetadata.FIXEDLEN_RECORD;
else rt = DataRecordMetadata.MIXED_RECORD;
recordMetadata = new DataRecordMetadata(recordName, rt);
if (recLocaleStr != null) {
recordMetadata.setLocaleStr(recLocaleStr);
}
recordMetadata.setRecordProperties(recordProperties);
if(!StringUtils.isEmpty(recordDelimiter)) {
recordMetadata.setRecordDelimiter(recordDelimiter.split(Defaults.DataFormatter.DELIMITER_DELIMITERS_REGEX));
}
short recSize = 0;
try {
recSize = Short.parseShort(sizeStr);
} catch (NumberFormatException e) {
// ignore
}
recordMetadata.setRecordSize(recSize);
/*
* parse metadata of FIELDs
*/
NodeList fieldElements = topNode.getChildNodes();
for (int i = 0; i < fieldElements.getLength(); i++) {
if (!fieldElements.item(i).getNodeName().equals(FIELD_ELEMENT)) {
continue;
}
attributes = fieldElements.item(i).getAttributes();
DataFieldMetadata field;
String format = null;
String defaultValue = null;
String name = null;
String size = null;
String shift = null;
String delimiter = null;
String eofAsDelimiter = null;
String nullable = null;
String localeStr = null;
String compressed = null;
String autoFilling = null;
String trim = null;
char fieldType = ' ';
Properties fieldProperties = new Properties();
for (int j = 0; j < attributes.getLength(); j++) {
itemName = attributes.item(j).getNodeName();
itemValue = refResolver.resolveRef(attributes.item(j)
.getNodeValue());
if (itemName.equalsIgnoreCase("type")) {
fieldType = getFieldType(itemValue);
} else if (itemName.equalsIgnoreCase("name")) {
name = itemValue;
} else if (itemName.equalsIgnoreCase("size")) {
size = itemValue;
} else if (itemName.equalsIgnoreCase(SHIFT_ATTR)) {
shift = itemValue;
} else if (itemName.equalsIgnoreCase("delimiter")) {
delimiter = itemValue;
} else if (itemName.equalsIgnoreCase(this.EOF_AS_DELIMITER_ATTR)) {
eofAsDelimiter = itemValue;
} else if (itemName.equalsIgnoreCase("format")) {
format = itemValue;
} else if (itemName.equalsIgnoreCase("default")) {
defaultValue = itemValue;
} else if (itemName.equalsIgnoreCase("nullable")) {
nullable = itemValue;
} else if (itemName.equalsIgnoreCase("locale")) {
localeStr = itemValue;
}else if (itemName.equalsIgnoreCase("trim")) {
trim = itemValue;
} else if (itemName.equalsIgnoreCase(COMPRESSED_ATTR)) {
compressed = itemValue;
} else if (itemName.equalsIgnoreCase(AUTO_FILLING_ATTR)) {
autoFilling = itemValue;
} else {
if (fieldProperties == null) {
fieldProperties = new Properties();
}
fieldProperties.setProperty(itemName, itemValue);
}
}
if (fieldType == DataFieldMetadata.BYTE_FIELD && Boolean.valueOf(compressed)) {
fieldType = DataFieldMetadata.BYTE_FIELD_COMPRESSED;
}
if ((fieldType == ' ') || (name == null)) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Attribute \"name\" or \"type\" not defined for field #"
+ i);
}
short shiftVal = 0;
try {
shiftVal = Short.parseShort(shift);
} catch (NumberFormatException e) {
// ignore
}
// create FixLength field or Delimited base on Record Type
if (recordMetadata.getRecType() == DataRecordMetadata.FIXEDLEN_RECORD) {
if (size == null) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Attribute \"size\" not defined for field #" + i);
}
field = new DataFieldMetadata(name, fieldType,
getFieldSize(size));
field.setShift(shiftVal);
} else if (recordMetadata.getRecType() == DataRecordMetadata.DELIMITED_RECORD) {
if (delimiter == null) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Attribute \"delimiter\" not defined for field #"
+ i);
}
field = new DataFieldMetadata(name, fieldType, delimiter);
field.setShift(shiftVal);
} else { //mixed dataRecord type
if (delimiter == null && size == null) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Attribute \"delimiter\" either \"size\" not defined for field #"
+ i);
}
if(delimiter != null) {
field = new DataFieldMetadata(name, fieldType, delimiter);
field.setShift(shiftVal);
} else {
field = new DataFieldMetadata(name, fieldType, getFieldSize(size));
field.setShift(shiftVal);
}
}
field.setEofAsDelimiter( Boolean.valueOf( eofAsDelimiter ).booleanValue() );
// set properties
field.setFieldProperties(fieldProperties);
// set format string if defined
if (format != null) {
field.setFormatStr(format);
}
if (defaultValue != null) {
field.setDefaultValueStr(defaultValue);
}
// set nullable if defined
if (nullable != null) {
field.setNullable(nullable.matches("^[tTyY].*"));
}
// set localeStr if defined
if (localeStr != null) {
field.setLocaleStr(localeStr);
}
if (autoFilling != null) {
field.setAutoFilling(autoFilling);
}
if (trim != null) {
field.setTrim(nullable.matches("^[tTyY].*"));
}
recordMetadata.addField(field);
}
// check that at least one valid field definition has been found
if (recordMetadata.getNumFields() == 0) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"No Field elements have been found ! ");
}
return recordMetadata;
}
/**
* Gets the FieldType attribute of the DataRecordMetadataXMLReaderWriter
* object
*
* @param fieldType
* Description of Parameter
* @return The FieldType value
* @since May 6, 2002
*/
private char getFieldType(String fieldType) {
if (fieldType.equalsIgnoreCase("string")) {
return DataFieldMetadata.STRING_FIELD;
}
if (fieldType.equalsIgnoreCase("date")) {
return DataFieldMetadata.DATE_FIELD;
}
if (fieldType.equalsIgnoreCase("datetime")) {
return DataFieldMetadata.DATETIME_FIELD;
}
if (fieldType.equalsIgnoreCase("numeric")) {
return DataFieldMetadata.NUMERIC_FIELD;
}
if (fieldType.equalsIgnoreCase("integer")) {
return DataFieldMetadata.INTEGER_FIELD;
}
if (fieldType.equalsIgnoreCase("long")) {
return DataFieldMetadata.LONG_FIELD;
}
if (fieldType.equalsIgnoreCase("decimal")) {
return DataFieldMetadata.DECIMAL_FIELD;
}
if (fieldType.equalsIgnoreCase("byte")) {
return DataFieldMetadata.BYTE_FIELD;
}
if (fieldType.equalsIgnoreCase("cbyte")) {
return DataFieldMetadata.BYTE_FIELD_COMPRESSED;
}
if (fieldType.equalsIgnoreCase("boolean")) {
return DataFieldMetadata.BOOLEAN_FIELD;
}
throw new RuntimeException("Unrecognized field type specified!");
}
/**
* Gets the FieldSize attribute of the DataRecordMetadataXMLReaderWriter
* object
*
* @param fieldSizeStr
* Description of Parameter
* @return The FieldSize value
* @exception SAXException
* Description of Exception
* @since May 6, 2002
*/
private short getFieldSize(String fieldSizeStr) {
return Short.parseShort(fieldSizeStr);
}
/**
* Description of the Method
*
* @param fieldType
* Description of Parameter
* @param fieldTypeOptions
* Description of Parameter
* @param fieldTypeStrings
* Description of Parameter
* @return Description of the Returned Value
* @since May 6, 2002
*/
private final static String fieldTypeFormat(char fieldType,
char[] fieldTypeOptions, String[] fieldTypeStrings) {
for (int i = 0; i < fieldTypeOptions.length; i++) {
if (fieldTypeOptions[i] == fieldType) {
return fieldTypeStrings[i];
}
}
return "";
}
}
/*
* end class DataRecordMetadataXMLReaderWriter
*/
| cloveretl.engine/src/org/jetel/metadata/DataRecordMetadataXMLReaderWriter.java |
/*
* jETeL/Clover - Java based ETL application framework.
* Copyright (C) 2002-04 David Pavlis <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
// FILE: c:/projects/jetel/org/jetel/metadata/DataRecordMetadataReaderWriter.java
package org.jetel.metadata;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.Defaults;
import org.jetel.graph.TransformationGraph;
import org.jetel.util.property.PropertyRefResolver;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Helper class for reading/writing DataRecordMetadata (record structure)
* from/to XML format <br>
*
* <i>Note: If for record or some field Node are defined more attributes than
* those recognized, they are transferred to Java Properties object and assigned
* to either record or field. </i>
*
* The XML DTD describing the internal structure is as follows:
*
* <pre>
*
* <!ELEMENT Record (FIELD+)>
* <!ATTLIST Record
* name ID #REQUIRED
* id ID #REQUIRED
* name CDATA #REQUIRED
* type NMTOKEN (delimited | fixed | mixed) #REQUIRED
* locale CDATA #IMPLIED
* recordDelimiter CDATA #IMPLIED
*
*
* <!ELEMENT Field (#PCDATA) EMPTY>
* <!ATTLIST Field
* name ID #REQUIRED
* type NMTOKEN #REQUIRED
* delimiter NMTOKEN #IMPLIED ","
* size NMTOKEN #IMPLIED "0"
* shift NMTOKEN #IMPLIED "0"
* format CDATA #IMPLIED
* locale CDATA #IMPLIED
* nullable NMTOKEN (true | false) #IMPLIED "true"
* compressed NMTOKEN (true | false) #IMPLIED "false"
* default CDATA #IMPLIED >
*
* </pre>
*
* Example:
*
* <pre>
*
* <Record name="TestRecord" type="delimited">
* <Field name="Field1" type="numeric" delimiter=";" />
* <Field name="Field2" type="numeric" delimiter=";" locale="de" />
* <Field name="Field3" type="string" delimiter=";" />
* <Field name="Field4" type="string" delimiter="\n"/>
* </Record>
*
* </pre>
*
* If you specify your own attributes, they will be accessible through
* getFieldProperties() method of DataFieldMetadata class. <br>
* Example:
*
* <pre>
*
* <Field name="Field1" type="numeric" delimiter=";" mySpec1="1" mySpec2="xyz"/>
*
* </pre>
*
* @author D.Pavlis
* @since May 6, 2002
* @see javax.xml.parsers
*/
public class DataRecordMetadataXMLReaderWriter extends DefaultHandler {
// Attributes
private DocumentBuilder db;
private DocumentBuilderFactory dbf;
private PropertyRefResolver refResolver;
// not needed private final static String DEFAULT_PARSER_NAME = "";
private static final boolean validation = false;
private static final boolean ignoreComments = true;
private static final boolean ignoreWhitespaces = true;
private static final boolean putCDATAIntoText = false;
private static final boolean createEntityRefs = false;
//private static boolean setLoadExternalDTD = true;
//private static boolean setSchemaSupport = true;
//private static boolean setSchemaFullSupport = false;
private static final String METADATA_ELEMENT = "Metadata";
private static final String ID = "id";
private static final String RECORD_ELEMENT = "Record";
private static final String FIELD_ELEMENT = "Field";
private static final String CODE_ELEMENT = "Code";
private static final String NAME_ATTR = "name";
private static final String TYPE_ATTR = "type";
private static final String RECORD_SIZE_ATTR = "recordSize";
public static final String RECORD_DELIMITER_ATTR = "recordDelimiter";
private static final String DELIMITER_ATTR = "delimiter";
private static final String FORMAT_ATTR = "format";
private static final String DEFAULT_ATTR = "default";
private static final String LOCALE_ATTR = "locale";
private static final String NULLABLE_ATTR = "nullable";
private static final String COMPRESSED_ATTR = "compressed";
private static final String SHIFT_ATTR = "shift";
private static final String SIZE_ATTR = "size";
private static final String AUTO_FILLING_ATTR = "auto_filling";
private static final String DEFAULT_CHARACTER_ENCODING = "UTF-8";
private static final String XSL_FORMATER
= "<?xml version='1.0' encoding='"+DEFAULT_CHARACTER_ENCODING+"'?>"
+ "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>"
+ "<xsl:output encoding='"+DEFAULT_CHARACTER_ENCODING+"' indent='yes' method='xml'/>"
+ "<xsl:template match='/'><xsl:copy-of select='*'/></xsl:template>"
+ "</xsl:stylesheet>";
private static Log logger = LogFactory.getLog(DataRecordMetadata.class);
/**
* Constructor with graph to property resolving.
* @param graph
*/
public DataRecordMetadataXMLReaderWriter() {
this((Properties) null);
}
/**
* Constructor with graph to property resolving.
* @param graph
*/
public DataRecordMetadataXMLReaderWriter(TransformationGraph graph) {
this(graph.getGraphProperties());
}
/**
* Constructor with properties for resolving.
* @param properties
*/
public DataRecordMetadataXMLReaderWriter(Properties properties) {
refResolver = new PropertyRefResolver(properties);
}
// Associations
// Operations
/**
* An operation that reads DataRecord format definition from XML data
*
* @param in
* InputStream with XML data describing DataRecord
* @return DataRecordMetadata object
* @since May 6, 2002
*/
public DataRecordMetadata read(InputStream in) {
return read(in, null);
}
public DataRecordMetadata read(InputStream in, String metadataId) {
Document document;
try {
// construct XML parser (if it is needed)
if ((dbf == null) || (db == null)) {
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setCoalescing(true);
// Optional: set various configuration options
dbf.setValidating(validation);
dbf.setIgnoringComments(ignoreComments);
dbf.setIgnoringElementContentWhitespace(ignoreWhitespaces);
dbf.setCoalescing(putCDATAIntoText);
dbf.setExpandEntityReferences(!createEntityRefs);
db = dbf.newDocumentBuilder();
}
document = db.parse(new BufferedInputStream(in));
document.normalize();
} catch (SAXParseException ex) {
logger.fatal("SAX Exception on line "
+ ex.getLineNumber() + " row " + ex.getColumnNumber(), ex);
return null;
} catch (ParserConfigurationException ex) {
logger.fatal(ex.getMessage());
return null;
} catch (Exception ex) {
logger.fatal(ex.getMessage());
return null;
}
try {
return parseRecordMetadata(document, metadataId);
} catch (DOMException ex) {
logger.fatal(ex.getMessage());
return null;
} catch (Exception ex) {
logger.fatal("parseRecordMetadata method call: "
+ ex.getMessage());
return null;
}
}
/**
* An operation that writes DataRecord format definition into XML format
*
* @param record
* Metadata describing data record
* @param outStream
* OutputStream into which XML data is written
* @since May 6, 2002
*/
public static void write(DataRecordMetadata record, OutputStream outStream) {
DocumentBuilder db = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element rootElement = doc.createElement(RECORD_ELEMENT);
doc.appendChild(rootElement);
write(record, rootElement);
StreamSource formSrc = new StreamSource(new StringReader(XSL_FORMATER));
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer(formSrc);
t.transform(new DOMSource(doc), new StreamResult(outStream));
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public static void write(DataRecordMetadata record, Element metadataElement) {
String rt;
DataFieldMetadata field;
metadataElement.setAttribute(NAME_ATTR, record.getName());
if(record.getRecType() == DataRecordMetadata.DELIMITED_RECORD) rt = "delimited";
else if(record.getRecType() == DataRecordMetadata.FIXEDLEN_RECORD) rt = "fixed";
else rt = "mixed";
metadataElement.setAttribute(TYPE_ATTR, rt);
if(!StringUtils.isEmpty(record.getRecordDelimiter())) {
metadataElement.setAttribute(RECORD_DELIMITER_ATTR, StringUtils.specCharToString(record.getRecordDelimiter()));
}
if (record.getRecordSize() != 0) {
metadataElement.setAttribute(RECORD_SIZE_ATTR, String.valueOf(record.getRecordSize()));
}
Properties prop = record.getRecordProperties();
if (prop != null) {
Enumeration enumeration = prop.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
metadataElement.setAttribute(key, prop.getProperty(key));
}
}
// OUTPUT FIELDS
// MessageFormat fieldForm = new MessageFormat(
// "\t<Field name=\"{0}\" type=\"{1}\" ");
char[] fieldTypeLimits = { DataFieldMetadata.STRING_FIELD,
DataFieldMetadata.DATE_FIELD,
DataFieldMetadata.DATETIME_FIELD,
DataFieldMetadata.NUMERIC_FIELD,
DataFieldMetadata.INTEGER_FIELD,
DataFieldMetadata.LONG_FIELD,
DataFieldMetadata.DECIMAL_FIELD,
DataFieldMetadata.BYTE_FIELD,
DataFieldMetadata.BYTE_FIELD_COMPRESSED };
String[] fieldTypeParts = { "string", "date", "datetime", "numeric",
"integer", "long", "decimal", "byte", "cbyte" };
Document doc = metadataElement.getOwnerDocument();
for (int i = 0; i < record.getNumFields(); i++) {
field = record.getField(i);
if (field != null) {
Element fieldElement = doc.createElement(FIELD_ELEMENT);
metadataElement.appendChild(fieldElement);
fieldElement.setAttribute(NAME_ATTR, field.getName());
fieldElement.setAttribute(TYPE_ATTR,
fieldTypeFormat(field.getType(), fieldTypeLimits,
fieldTypeParts));
fieldElement.setAttribute(SHIFT_ATTR, String.valueOf(field.getShift()));
if (record.getRecType() == DataRecordMetadata.DELIMITED_RECORD) {
fieldElement.setAttribute(DELIMITER_ATTR,
StringUtils.specCharToString(field.getDelimiter()));
} else {
fieldElement.setAttribute(SIZE_ATTR, String.valueOf(field.getSize()));
}
if (field.getFormatStr() != null) {
fieldElement.setAttribute(FORMAT_ATTR, field.getFormatStr());
}
if (field.getDefaultValueStr() != null) {
fieldElement.setAttribute(DEFAULT_ATTR, field.getDefaultValueStr());
}
if (field.getLocaleStr() != null) {
fieldElement.setAttribute(LOCALE_ATTR, field.getLocaleStr());
}
if (field.getAutoFilling() != null) {
fieldElement.setAttribute(AUTO_FILLING_ATTR, field.getAutoFilling());
}
fieldElement.setAttribute(NULLABLE_ATTR,
String.valueOf(field.isNullable()));
// output field properties - if anything defined
prop = field.getFieldProperties();
if (prop != null) {
Enumeration enumeration = prop.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
fieldElement.setAttribute(key, prop.getProperty(key));
}
}
// if (field.getCodeStr() != null) {
// Element codeElement = doc.createElement(CODE_ELEMENT);
// fieldElement.appendChild(codeElement);
// Text codeText = doc.createTextNode(field.getCodeStr());
// codeElement.appendChild(codeText);
// }
}
}
}
public DataRecordMetadata parseRecordMetadata(Document document)
throws DOMException {
return parseRecordMetadata(document, null);
}
public DataRecordMetadata parseRecordMetadata(Document document, String metadataId) throws DOMException {
org.w3c.dom.NodeList nodes;
if (metadataId != null) {
nodes = document.getElementsByTagName(METADATA_ELEMENT);
int lenght = nodes.getLength();
org.w3c.dom.Node node = null;
for (int i=0; i<lenght; i++) {
node = nodes.item(i);
if (node.getAttributes().getNamedItem(ID).getNodeValue().equals(metadataId)) {
return parseRecordMetadata(node.getChildNodes().item(1));
}
}
return null;
} else {
nodes = document.getElementsByTagName(RECORD_ELEMENT);
if (nodes.getLength() == 0) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"No Record element has been found ! ");
}
return parseRecordMetadata(nodes.item(0));
}
}
public DataRecordMetadata parseRecordMetadata(org.w3c.dom.Node topNode)
throws DOMException {
org.w3c.dom.NamedNodeMap attributes;
DataRecordMetadata recordMetadata;
String recordName = null;
String recordType = null;
String recordDelimiter = null;
String sizeStr = null;
String recLocaleStr = null;
String itemName;
String itemValue;
Properties recordProperties = null;
if (topNode.getNodeName() != RECORD_ELEMENT) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Root Node is not of type " + RECORD_ELEMENT);
}
/*
* get Record level metadata
*/
attributes = topNode.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
itemName = attributes.item(i).getNodeName();
itemValue = refResolver.resolveRef(attributes.item(i)
.getNodeValue());
if (itemName.equalsIgnoreCase("name")) {
recordName = itemValue;
} else if (itemName.equalsIgnoreCase("type")) {
recordType = itemValue;
} else if (itemName.equalsIgnoreCase("locale")) {
recLocaleStr = itemValue;
} else if (itemName.equalsIgnoreCase(RECORD_DELIMITER_ATTR)) {
recordDelimiter = itemValue;
} else if (itemName.equalsIgnoreCase(RECORD_SIZE_ATTR)) {
sizeStr = itemValue;
} else {
if (recordProperties == null) {
recordProperties = new Properties();
}
recordProperties.setProperty(itemName, itemValue);
}
}
if (recordType == null || recordName == null) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Attribute \"name\" or \"type\" not defined within Record !");
}
char rt;
if(recordType.equalsIgnoreCase("delimited")) rt = DataRecordMetadata.DELIMITED_RECORD;
else if(recordType.equalsIgnoreCase("fixed")) rt = DataRecordMetadata.FIXEDLEN_RECORD;
else rt = DataRecordMetadata.MIXED_RECORD;
recordMetadata = new DataRecordMetadata(recordName, rt);
if (recLocaleStr != null) {
recordMetadata.setLocaleStr(recLocaleStr);
}
recordMetadata.setRecordProperties(recordProperties);
if(!StringUtils.isEmpty(recordDelimiter)) {
recordMetadata.setRecordDelimiter(recordDelimiter.split(Defaults.DataFormatter.DELIMITER_DELIMITERS_REGEX));
}
short recSize = 0;
try {
recSize = Short.parseShort(sizeStr);
} catch (NumberFormatException e) {
// ignore
}
recordMetadata.setRecordSize(recSize);
/*
* parse metadata of FIELDs
*/
NodeList fieldElements = topNode.getChildNodes();
for (int i = 0; i < fieldElements.getLength(); i++) {
if (!fieldElements.item(i).getNodeName().equals(FIELD_ELEMENT)) {
continue;
}
attributes = fieldElements.item(i).getAttributes();
DataFieldMetadata field;
String format = null;
String defaultValue = null;
String name = null;
String size = null;
String shift = null;
String delimiter = null;
String nullable = null;
String localeStr = null;
String compressed = null;
String autoFilling = null;
String trim = null;
char fieldType = ' ';
Properties fieldProperties = new Properties();
for (int j = 0; j < attributes.getLength(); j++) {
itemName = attributes.item(j).getNodeName();
itemValue = refResolver.resolveRef(attributes.item(j)
.getNodeValue());
if (itemName.equalsIgnoreCase("type")) {
fieldType = getFieldType(itemValue);
} else if (itemName.equalsIgnoreCase("name")) {
name = itemValue;
} else if (itemName.equalsIgnoreCase("size")) {
size = itemValue;
} else if (itemName.equalsIgnoreCase(SHIFT_ATTR)) {
shift = itemValue;
} else if (itemName.equalsIgnoreCase("delimiter")) {
delimiter = itemValue;
} else if (itemName.equalsIgnoreCase("format")) {
format = itemValue;
} else if (itemName.equalsIgnoreCase("default")) {
defaultValue = itemValue;
} else if (itemName.equalsIgnoreCase("nullable")) {
nullable = itemValue;
} else if (itemName.equalsIgnoreCase("locale")) {
localeStr = itemValue;
}else if (itemName.equalsIgnoreCase("trim")) {
trim = itemValue;
} else if (itemName.equalsIgnoreCase(COMPRESSED_ATTR)) {
compressed = itemValue;
} else if (itemName.equalsIgnoreCase(AUTO_FILLING_ATTR)) {
autoFilling = itemValue;
} else {
if (fieldProperties == null) {
fieldProperties = new Properties();
}
fieldProperties.setProperty(itemName, itemValue);
}
}
if (fieldType == DataFieldMetadata.BYTE_FIELD && Boolean.valueOf(compressed)) {
fieldType = DataFieldMetadata.BYTE_FIELD_COMPRESSED;
}
if ((fieldType == ' ') || (name == null)) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Attribute \"name\" or \"type\" not defined for field #"
+ i);
}
short shiftVal = 0;
try {
shiftVal = Short.parseShort(shift);
} catch (NumberFormatException e) {
// ignore
}
// create FixLength field or Delimited base on Record Type
if (recordMetadata.getRecType() == DataRecordMetadata.FIXEDLEN_RECORD) {
if (size == null) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Attribute \"size\" not defined for field #" + i);
}
field = new DataFieldMetadata(name, fieldType,
getFieldSize(size));
field.setShift(shiftVal);
} else if (recordMetadata.getRecType() == DataRecordMetadata.DELIMITED_RECORD) {
if (delimiter == null) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Attribute \"delimiter\" not defined for field #"
+ i);
}
field = new DataFieldMetadata(name, fieldType, delimiter);
field.setShift(shiftVal);
} else { //mixed dataRecord type
if (delimiter == null && size == null) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"Attribute \"delimiter\" either \"size\" not defined for field #"
+ i);
}
if(delimiter != null) {
field = new DataFieldMetadata(name, fieldType, delimiter);
field.setShift(shiftVal);
} else {
field = new DataFieldMetadata(name, fieldType, getFieldSize(size));
field.setShift(shiftVal);
}
}
// set properties
field.setFieldProperties(fieldProperties);
// set format string if defined
if (format != null) {
field.setFormatStr(format);
}
if (defaultValue != null) {
field.setDefaultValueStr(defaultValue);
}
// set nullable if defined
if (nullable != null) {
field.setNullable(nullable.matches("^[tTyY].*"));
}
// set localeStr if defined
if (localeStr != null) {
field.setLocaleStr(localeStr);
}
if (autoFilling != null) {
field.setAutoFilling(autoFilling);
}
if (trim != null) {
field.setTrim(nullable.matches("^[tTyY].*"));
}
recordMetadata.addField(field);
}
// check that at least one valid field definition has been found
if (recordMetadata.getNumFields() == 0) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
"No Field elements have been found ! ");
}
return recordMetadata;
}
/**
* Gets the FieldType attribute of the DataRecordMetadataXMLReaderWriter
* object
*
* @param fieldType
* Description of Parameter
* @return The FieldType value
* @since May 6, 2002
*/
private char getFieldType(String fieldType) {
if (fieldType.equalsIgnoreCase("string")) {
return DataFieldMetadata.STRING_FIELD;
}
if (fieldType.equalsIgnoreCase("date")) {
return DataFieldMetadata.DATE_FIELD;
}
if (fieldType.equalsIgnoreCase("datetime")) {
return DataFieldMetadata.DATETIME_FIELD;
}
if (fieldType.equalsIgnoreCase("numeric")) {
return DataFieldMetadata.NUMERIC_FIELD;
}
if (fieldType.equalsIgnoreCase("integer")) {
return DataFieldMetadata.INTEGER_FIELD;
}
if (fieldType.equalsIgnoreCase("long")) {
return DataFieldMetadata.LONG_FIELD;
}
if (fieldType.equalsIgnoreCase("decimal")) {
return DataFieldMetadata.DECIMAL_FIELD;
}
if (fieldType.equalsIgnoreCase("byte")) {
return DataFieldMetadata.BYTE_FIELD;
}
if (fieldType.equalsIgnoreCase("cbyte")) {
return DataFieldMetadata.BYTE_FIELD_COMPRESSED;
}
if (fieldType.equalsIgnoreCase("boolean")) {
return DataFieldMetadata.BOOLEAN_FIELD;
}
throw new RuntimeException("Unrecognized field type specified!");
}
/**
* Gets the FieldSize attribute of the DataRecordMetadataXMLReaderWriter
* object
*
* @param fieldSizeStr
* Description of Parameter
* @return The FieldSize value
* @exception SAXException
* Description of Exception
* @since May 6, 2002
*/
private short getFieldSize(String fieldSizeStr) {
return Short.parseShort(fieldSizeStr);
}
/**
* Description of the Method
*
* @param fieldType
* Description of Parameter
* @param fieldTypeOptions
* Description of Parameter
* @param fieldTypeStrings
* Description of Parameter
* @return Description of the Returned Value
* @since May 6, 2002
*/
private final static String fieldTypeFormat(char fieldType,
char[] fieldTypeOptions, String[] fieldTypeStrings) {
for (int i = 0; i < fieldTypeOptions.length; i++) {
if (fieldTypeOptions[i] == fieldType) {
return fieldTypeStrings[i];
}
}
return "";
}
}
/*
* end class DataRecordMetadataXMLReaderWriter
*/
| EOF delimiter
git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@3832 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.engine/src/org/jetel/metadata/DataRecordMetadataXMLReaderWriter.java | EOF delimiter | <ide><path>loveretl.engine/src/org/jetel/metadata/DataRecordMetadataXMLReaderWriter.java
<ide> private static final String RECORD_SIZE_ATTR = "recordSize";
<ide> public static final String RECORD_DELIMITER_ATTR = "recordDelimiter";
<ide> private static final String DELIMITER_ATTR = "delimiter";
<add> private static final String EOF_AS_DELIMITER_ATTR = "eofAsDelimiter";
<ide> private static final String FORMAT_ATTR = "format";
<ide> private static final String DEFAULT_ATTR = "default";
<ide> private static final String LOCALE_ATTR = "locale";
<ide> String size = null;
<ide> String shift = null;
<ide> String delimiter = null;
<add> String eofAsDelimiter = null;
<ide> String nullable = null;
<ide> String localeStr = null;
<ide> String compressed = null;
<ide> shift = itemValue;
<ide> } else if (itemName.equalsIgnoreCase("delimiter")) {
<ide> delimiter = itemValue;
<add> } else if (itemName.equalsIgnoreCase(this.EOF_AS_DELIMITER_ATTR)) {
<add> eofAsDelimiter = itemValue;
<ide> } else if (itemName.equalsIgnoreCase("format")) {
<ide> format = itemValue;
<ide> } else if (itemName.equalsIgnoreCase("default")) {
<ide> }
<ide> }
<ide>
<add> field.setEofAsDelimiter( Boolean.valueOf( eofAsDelimiter ).booleanValue() );
<ide> // set properties
<ide> field.setFieldProperties(fieldProperties);
<ide> |
|
JavaScript | bsd-3-clause | 60146cd243bb09a6127631f0dba699f6ca051fdd | 0 | scsibug/read52,scsibug/read52 | /*
* jQuery Plugin : jConfirmAction
*
* by Hidayat Sagita
* http://www.webstuffshare.com
* Licensed Under GPL version 2 license.
*
*/
/**
* Modifications to support more advanced 'onclick'-like handlers passed in through yesFunction.
* Greg Heartsfield <[email protected]> 12-29-10
*/
(function($){
jQuery.fn.jConfirmAction = function (options) {
// Some jConfirmAction options (limited to customize language) :
// question : a text for your question.
// yesAnswer : a text for Yes answer.
// cancelAnswer : a text for Cancel/No answer.
var theOptions = jQuery.extend ({
question: "Are You Sure ?",
yesAnswer: "Yes",
cancelAnswer: "Cancel",
yesFunction: null,
cancelFunction: null
}, options);
return this.each (function () {
$(this).bind('click', function(e) {
e.preventDefault();
thisHref = $(this).attr('href');
if($(this).next('.question').length <= 0)
$(this).after('<div class="question">'+theOptions.question+'<br/> <span class="yes">'+theOptions.yesAnswer+'</span><span class="cancel">'+theOptions.cancelAnswer+'</span></div>');
$(this).next('.question').animate({opacity: 1}, 300);
$('.yes').bind('click', function(){
window.location = thisHref;
if (theOptions.yesFunction)
theOptions.yesFunction();
});
$('.cancel').bind('click', function(){
$(this).parents('.question').fadeOut(300, function() {
if (theOptions.cancelFunction)
theOptions.cancelFunction();
$(this).remove();
});
});
});
});
}
})(jQuery); | static/js/jconfirmaction.jquery.js | /*
* jQuery Plugin : jConfirmAction
*
* by Hidayat Sagita
* http://www.webstuffshare.com
* Licensed Under GPL version 2 license.
*
*/
(function($){
jQuery.fn.jConfirmAction = function (options) {
// Some jConfirmAction options (limited to customize language) :
// question : a text for your question.
// yesAnswer : a text for Yes answer.
// cancelAnswer : a text for Cancel/No answer.
var theOptions = jQuery.extend ({
question: "Are You Sure ?",
yesAnswer: "Yes",
cancelAnswer: "Cancel"
}, options);
return this.each (function () {
$(this).bind('click', function(e) {
e.preventDefault();
thisHref = $(this).attr('href');
if($(this).next('.question').length <= 0)
$(this).after('<div class="question">'+theOptions.question+'<br/> <span class="yes">'+theOptions.yesAnswer+'</span><span class="cancel">'+theOptions.cancelAnswer+'</span></div>');
$(this).next('.question').animate({opacity: 1}, 300);
$('.yes').bind('click', function(){
window.location = thisHref;
});
$('.cancel').bind('click', function(){
$(this).parents('.question').fadeOut(300, function() {
$(this).remove();
});
});
});
});
}
})(jQuery); | Modified jConfirmAction to support onclick-like handlers.
| static/js/jconfirmaction.jquery.js | Modified jConfirmAction to support onclick-like handlers. | <ide><path>tatic/js/jconfirmaction.jquery.js
<ide> * Licensed Under GPL version 2 license.
<ide> *
<ide> */
<add>
<add>/**
<add> * Modifications to support more advanced 'onclick'-like handlers passed in through yesFunction.
<add> * Greg Heartsfield <[email protected]> 12-29-10
<add> */
<add>
<ide> (function($){
<ide>
<ide> jQuery.fn.jConfirmAction = function (options) {
<ide> // yesAnswer : a text for Yes answer.
<ide> // cancelAnswer : a text for Cancel/No answer.
<ide> var theOptions = jQuery.extend ({
<del> question: "Are You Sure ?",
<del> yesAnswer: "Yes",
<del> cancelAnswer: "Cancel"
<add> question: "Are You Sure ?",
<add> yesAnswer: "Yes",
<add> cancelAnswer: "Cancel",
<add> yesFunction: null,
<add> cancelFunction: null
<ide> }, options);
<ide>
<ide> return this.each (function () {
<ide>
<ide> e.preventDefault();
<ide> thisHref = $(this).attr('href');
<del>
<add>
<ide> if($(this).next('.question').length <= 0)
<ide> $(this).after('<div class="question">'+theOptions.question+'<br/> <span class="yes">'+theOptions.yesAnswer+'</span><span class="cancel">'+theOptions.cancelAnswer+'</span></div>');
<ide>
<ide>
<ide> $('.yes').bind('click', function(){
<ide> window.location = thisHref;
<add> if (theOptions.yesFunction)
<add> theOptions.yesFunction();
<ide> });
<ide>
<ide> $('.cancel').bind('click', function(){
<ide> $(this).parents('.question').fadeOut(300, function() {
<del> $(this).remove();
<add> if (theOptions.cancelFunction)
<add> theOptions.cancelFunction();
<add> $(this).remove();
<ide> });
<ide> });
<ide> |
|
Java | apache-2.0 | 3ec8de700f5e637ae368c44099ae636cf7788755 | 0 | WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules | /*
* Copyright (c) 2012-2014 LabKey Corporation
*
* 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.labkey.wnprc_ehr.table;
import org.apache.log4j.Logger;
import org.labkey.api.data.AbstractTableInfo;
import org.labkey.api.data.BaseColumnInfo;
import org.labkey.api.data.ColumnInfo;
import org.labkey.api.data.CompareType;
import org.labkey.api.data.Container;
import org.labkey.api.data.DataColumn;
import org.labkey.api.data.DbSchema;
import org.labkey.api.data.DbSchemaType;
import org.labkey.api.data.DisplayColumn;
import org.labkey.api.data.DisplayColumnFactory;
import org.labkey.api.data.JdbcType;
import org.labkey.api.data.RenderContext;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.data.TableInfo;
import org.labkey.api.data.TableSelector;
import org.labkey.api.data.WrappedColumn;
import org.labkey.api.ehr.EHRService;
import org.labkey.api.exp.api.StorageProvisioner;
import org.labkey.api.ldk.table.AbstractTableCustomizer;
import org.labkey.api.query.ExprColumn;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.QueryForeignKey;
import org.labkey.api.query.QueryService;
import org.labkey.api.query.UserSchema;
import org.labkey.api.security.User;
import org.labkey.api.security.permissions.AdminPermission;
import org.labkey.api.study.Dataset;
import org.labkey.api.study.Study;
import org.labkey.api.study.StudyService;
import org.labkey.api.util.GUID;
import org.labkey.api.util.HtmlString;
import org.labkey.api.util.HtmlStringBuilder;
import org.labkey.api.util.PageFlowUtil;
import org.labkey.api.util.StringExpressionFactory;
import org.labkey.api.view.ActionURL;
import org.labkey.dbutils.api.SimplerFilter;
import org.labkey.wnprc_ehr.security.permissions.WNPRCAnimalRequestsEditPermission;
import org.labkey.wnprc_ehr.security.permissions.WNPRCAnimalRequestsViewPermission;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
* User: bimber
* Date: 12/7/12
* Time: 2:22 PM
*/
public class WNPRC_EHRCustomizer extends AbstractTableCustomizer
{
protected static final Logger _log = Logger.getLogger(WNPRC_EHRCustomizer.class);
public WNPRC_EHRCustomizer()
{
}
@Override
public void customize(TableInfo table)
{
if (table instanceof AbstractTableInfo)
{
customizeColumns((AbstractTableInfo)table);
if (table.getName().equalsIgnoreCase("Animal") && table.getSchema().getName().equalsIgnoreCase("study"))
customizeAnimalTable((AbstractTableInfo) table);
else if (table.getName().equalsIgnoreCase("Birth") && table.getSchema().getName().equalsIgnoreCase("study"))
customizeBirthTable((AbstractTableInfo) table);
else if (table.getName().equalsIgnoreCase("protocol") && table.getSchema().getName().equalsIgnoreCase("ehr"))
customizeProtocolTable((AbstractTableInfo)table);
else if (table.getName().equalsIgnoreCase("breeding_encounters") && table.getSchema().getName().equalsIgnoreCase("study")) {
customizeBreedingEncountersTable((AbstractTableInfo) table);
} else if (table.getName().equalsIgnoreCase("pregnancies") && table.getSchema().getName().equalsIgnoreCase("study")) {
customizePregnanciesTable((AbstractTableInfo) table);
} else if (table.getName().equalsIgnoreCase("housing") && table.getSchema().getName().equalsIgnoreCase("study")) {
customizeHousingTable((AbstractTableInfo) table);
} else if (matches(table, "ehr", "project")) {
customizeProjectTable((AbstractTableInfo) table);
} else if (matches(table, "study", "feeding")) {
customizeFeedingTable((AbstractTableInfo) table);
} else if (matches(table, "study", "demographics")) {
customizeDemographicsTable((AbstractTableInfo) table);
} else if (matches(table, "ehr", "tasks")) {
customizeTasksTable((AbstractTableInfo) table);
} else if (matches(table, "wnprc", "animal_requests")) {
customizeAnimalRequestsTable((AbstractTableInfo) table);
}
}
}
private void customizeColumns(AbstractTableInfo ti)
{
var project = ti.getMutableColumn("project");
if (project != null)
{
project.setFormat("00000000");
}
customizeRoomCol(ti, "room");
customizeRoomCol(ti, "room1");
customizeRoomCol(ti, "room2");
}
private void customizeRoomCol(AbstractTableInfo ti, String columnName)
{
var room = ti.getMutableColumn(columnName);
if (room != null)
{
if (!ti.getName().equalsIgnoreCase("rooms"))
{
// Configure the FK to show the raw value to improve performance, since the database can avoid
// doing the join in many cases
Container ehrContainer = EHRService.get().getEHRStudyContainer(ti.getUserSchema().getContainer());
if (ehrContainer != null)
{
UserSchema us = getUserSchema(ti, "ehr_lookups", ehrContainer);
if (us != null)
{
room.setFk(QueryForeignKey.from(us, ti.getContainerFilter())
.container(ehrContainer)
.table("rooms")
.key("room")
.display("room")
.raw(true));
}
}
}
}
}
private void customizeTasksTable(AbstractTableInfo ti)
{
UserSchema us = ti.getUserSchema();
BaseColumnInfo rowIdCol = (BaseColumnInfo) ti.getColumn("rowid");
if (rowIdCol != null && us != null)
{
rowIdCol.setDisplayColumnFactory(colInfo -> new DataColumn(colInfo)
{
@Override
public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException
{
Integer rowId = (Integer) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "rowid"));
String taskId = (String) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "taskid"));
String formType = (String) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "formtype"));
if (isExt4Form("form", formType))
{
ActionURL url = new ActionURL("ehr", "dataEntryFormDetails.view", us.getContainer());
if ("Research Ultrasounds".equalsIgnoreCase(formType)) {
formType = "Research Ultrasounds Task";
}
url.addParameter("formtype", formType);
url.addParameter("taskid", taskId);
StringBuilder urlString = new StringBuilder();
urlString.append("<a href=\"" + PageFlowUtil.filter(url) + "\">");
urlString.append(PageFlowUtil.filter(rowId));
urlString.append("</a>");
out.write(urlString.toString());
} else {
super.renderGridCellContents(ctx, out);
}
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
return ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "rowid"));
}
});
BaseColumnInfo updateTitleCol = (BaseColumnInfo) ti.getColumn("updateTitle");
if (updateTitleCol != null && us != null)
{
updateTitleCol.setDisplayColumnFactory(colInfo -> new DataColumn(colInfo)
{
@Override
public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException
{
String updateTitle = (String) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "updateTitle"));
String taskId = (String) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "taskid"));
String formType = (String) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "formtype"));
if (isExt4Form("form", formType))
{
ActionURL url = new ActionURL("ehr", "dataEntryForm.view", us.getContainer());
if ("Research Ultrasounds".equalsIgnoreCase(formType))
{
formType = "Research Ultrasounds Review";
}
url.addParameter("formType", formType);
url.addParameter("taskid", taskId);
StringBuilder urlString = new StringBuilder();
urlString.append("<a href=\"" + PageFlowUtil.filter(url) + "\">");
urlString.append(PageFlowUtil.filter(updateTitle));
urlString.append("</a>");
out.write(urlString.toString());
}
else
{
super.renderGridCellContents(ctx, out);
}
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
return ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "rowid"));
}
});
}
}
}
private void customizeProjectTable(AbstractTableInfo ti)
{
String investigatorName = "investigatorName";
SQLFragment sql = new SQLFragment("COALESCE((SELECT " +
"(CASE WHEN lastName IS NOT NULL AND firstName IS NOT NULL " +
"THEN (lastName ||', '|| firstName) " +
"WHEN lastName IS NOT NULL AND firstName IS NULL " +
"THEN lastName " +
"ELSE " +
"firstName " +
"END) AS investigatorWithName " +
"from ehr.investigators where rowid = " + ExprColumn.STR_TABLE_ALIAS + ".investigatorId), " + ExprColumn.STR_TABLE_ALIAS + ".inves)");
ExprColumn newCol = new ExprColumn(ti, investigatorName, sql, JdbcType.VARCHAR);
newCol.setLabel("Investigator");
newCol.setDescription("This column shows the name of the investigator on the project. It first checks if there is an investigatorId, and if not defaults to the old inves column.");
ti.addColumn(newCol);
}
private void customizeFeedingTable(AbstractTableInfo ti)
{
// this number is representative of 12/17 ratio
Double d = new Double(.705882);
Double conv = d;
Double invconv = 1/d;
String chowConversion = "chowConversion";
Container ehrContainer = EHRService.get().getEHRStudyContainer(ti.getUserSchema().getContainer());
GUID ehrEntityId = ehrContainer.getEntityId();
ehrEntityId.toString();
SQLFragment sql = new SQLFragment("(SELECT " +
" (CASE WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'log' and container ='"+ ehrEntityId.toString() + "')" +
"THEN (ROUND(amount*"+ conv.toString() + ") || ' flower')" +
"WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'log (gluten-free)' and container ='"+ ehrEntityId.toString() + "')" +
"THEN (ROUND(amount*"+ conv.toString() + ") || ' flower')" +
"WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'flower' and container ='" + ehrEntityId.toString() + "')" +
"THEN (ROUND(amount*" + invconv.toString() + ") || ' log')" +
"ELSE " +
" 'bad data'" +
"END) as ChowConversion)");
ExprColumn newCol = new ExprColumn(ti, chowConversion, sql, JdbcType.VARCHAR);
newCol.setLabel("Chow Conversion");
newCol.setDescription("This column shows the calculated conversion amount between log and flower chows. The current conversion is 12g log <=> 17g flower.");
ti.addColumn(newCol);
String chowLookup = "chowLookup";
SQLFragment sql2 = new SQLFragment("(SELECT " +
" (CASE WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'log' and container ='"+ ehrEntityId.toString() + "')" +
"THEN (CAST (amount as text) || ' log')" +
"WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'log (gluten-free)' and container ='"+ ehrEntityId.toString() + "')" +
"THEN (CAST (amount as text) || ' log (gluten-free)')" +
"WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'flower' and container ='"+ ehrEntityId.toString() + "')" +
"THEN (CAST (amount as text) || ' flower')" +
"ELSE " +
" 'bad data'" +
"END) as ChowLookup)");
ExprColumn newCol2 = new ExprColumn(ti, chowLookup, sql2, JdbcType.VARCHAR);
newCol2.setLabel("Chow Lookup");
ti.addColumn(newCol2);
}
private void customizeBirthTable(AbstractTableInfo ti)
{
var cond = ti.getMutableColumn("cond");
if (cond != null)
{
cond.setLabel("Housing Condition");
UserSchema us = getUserSchema(ti, "ehr_lookups");
if (us != null)
{
cond.setFk(QueryForeignKey.from(us, ti.getContainerFilter())
.table("housing_condition_codes")
.key("value")
.display("title"));
}
}
}
private void customizeAnimalTable(AbstractTableInfo ds)
{
if (ds.getColumn("MHCtyping") != null)
return;
UserSchema us = getStudyUserSchema(ds);
if (us == null){
return;
}
if (ds.getColumn("demographicsMHC") == null)
{
BaseColumnInfo col = getWrappedIdCol(us, ds, "MHCtyping", "demographicsMHC");
col.setLabel("MHC SSP Typing");
col.setDescription("Summarizes MHC SSP typing results for the common alleles");
ds.addColumn(col);
BaseColumnInfo col2 = getWrappedIdCol(us, ds, "ViralLoad", "demographicsVL");
col2.setLabel("Viral Loads");
col2.setDescription("This field calculates the most recent viral load for this animal");
ds.addColumn(col2);
BaseColumnInfo col3 = getWrappedIdCol(us, ds, "ViralStatus", "demographicsViralStatus");
col3.setLabel("Viral Status");
col3.setDescription("This calculates the viral status of the animal based on tracking project assignments");
ds.addColumn(col3);
BaseColumnInfo col18 = getWrappedIdCol(us, ds, "Virology", "demographicsVirology");
col18.setLabel("Virology");
col18.setDescription("This calculates the distinct pathogens listed as positive for this animal from the virology table");
ds.addColumn(col18);
BaseColumnInfo col4 = getWrappedIdCol(us, ds, "IrregularObs", "demographicsObs");
col4.setLabel("Irregular Obs");
col4.setDescription("Shows any irregular observations from each animal today or yesterday.");
ds.addColumn(col4);
BaseColumnInfo col7 = getWrappedIdCol(us, ds, "activeAssignments", "demographicsAssignments");
col7.setLabel("Assignments - Active");
col7.setDescription("Contains summaries of the assignments for each animal, including the project numbers, availability codes and a count");
ds.addColumn(col7);
BaseColumnInfo col6 = getWrappedIdCol(us, ds, "totalAssignments", "demographicsAssignmentHistory");
col6.setLabel("Assignments - Total");
col6.setDescription("Contains summaries of the total assignments this animal has ever had, including the project numbers and a count");
ds.addColumn(col6);
BaseColumnInfo col5 = getWrappedIdCol(us, ds, "assignmentSummary", "demographicsAssignmentSummary");
col5.setLabel("Assignments - Detailed");
col5.setDescription("Contains more detailed summaries of the active assignments for each animal, including a breakdown between research, breeding, training, etc.");
ds.addColumn(col5);
BaseColumnInfo col10 = getWrappedIdCol(us, ds, "DaysAlone", "demographicsDaysAlone");
col10.setLabel("Days Alone");
col10.setDescription("Calculates the total number of days each animal has been single housed, if applicable.");
ds.addColumn(col10);
BaseColumnInfo bloodCol = getWrappedIdCol(us, ds, "AvailBlood", "demographicsBloodSummary");
bloodCol.setLabel("Blood Remaining");
bloodCol.setDescription("Calculates the total blood draw and remaining, which is determine by weight and blood drawn in the past 30 days.");
ds.addColumn(bloodCol);
BaseColumnInfo col17 = getWrappedIdCol(us, ds, "MostRecentTB", "demographicsMostRecentTBDate");
col17.setLabel("TB Tests");
col17.setDescription("Calculates the most recent TB date for this animal, time since TB and the last eye TB tested");
ds.addColumn(col17);
BaseColumnInfo col16 = getWrappedIdCol(us, ds, "Surgery", "demographicsSurgery");
col16.setLabel("Surgical History");
col16.setDescription("Calculates whether this animal has ever had any surgery or a surgery flagged as major");
ds.addColumn(col16);
BaseColumnInfo col19 = getWrappedIdCol(us, ds, "CurrentBehavior", "CurrentBehaviorNotes");
col19.setLabel("Behavior - Current");
col19.setDescription("This calculates the current behavior(s) for the animal, based on the behavior abstract table");
ds.addColumn(col19);
BaseColumnInfo col20 = getWrappedIdCol(us, ds, "PrimateId", "demographicsPrimateId");
col20.setLabel("PrimateId");
col20.setDescription("Unique PrimateID column to be shared across all datasets");
ds.addColumn(col20);
}
if (ds.getColumn("totalOffspring") == null)
{
BaseColumnInfo col15 = getWrappedIdCol(us, ds, "totalOffspring", "demographicsTotalOffspring");
col15.setLabel("Number of Offspring");
col15.setDescription("Shows the total offspring of each animal");
ds.addColumn(col15);
}
}
private void customizeDemographicsTable(AbstractTableInfo table)
{
UserSchema us = getStudyUserSchema(table);
if (us == null){
return;
}
if (table.getColumn("Feeding") == null)
{
BaseColumnInfo col = getWrappedIdCol(us, table, "Feeding", "demographicsMostRecentFeeding");
col.setLabel("Feeding");
col.setDescription("Shows most recent feeding type and chow conversion.");
table.addColumn(col);
}
if (table.getColumn("mostRecentAlopeciaScore") == null)
{
String mostRecentAlopeciaScore = "mostRecentAlopeciaScore";
TableInfo alopecia = getRealTableForDataset(table, "alopecia");
String theQuery = "( " +
"(SELECT " +
"a.score as score " +
"FROM studydataset." +alopecia.getName() + " a " +
"WHERE a.score is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid ORDER by a.date DESC LIMIT 1) " +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, mostRecentAlopeciaScore, sql, JdbcType.VARCHAR);
newCol.setLabel("Alopecia Score");
newCol.setDescription("Calculates the most recent alopecia score for each animal");
newCol.setURL(StringExpressionFactory.create("query-executeQuery.view?schemaName=ehr_lookups&query.queryName=alopecia_scores"));
table.addColumn(newCol);
}
if (table.getColumn("mostRecentBodyConditionScore") == null)
{
String mostRecentBodyConditionScore = "mostRecentBodyConditionScore";
TableInfo bcs = getRealTableForDataset(table, "bcs");
String theQuery = "( " +
"(SELECT " +
"a.score as score " +
"FROM studydataset." +bcs.getName() + " a " +
"WHERE a.score is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid ORDER by a.date DESC LIMIT 1) " +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, mostRecentBodyConditionScore, sql, JdbcType.VARCHAR);
newCol.setURL(StringExpressionFactory.create("query-executeQuery.view?schemaName=ehr_lookups&query.queryName=body_condition_scores"));
newCol.setLabel("Most Recent BCS");
newCol.setDescription("Returns the participant's most recent body condition score");
table.addColumn(newCol);
}
if (table.getColumn("necropsyAbstractNotes") == null)
{
BaseColumnInfo col = getWrappedIdCol(us, table, "necropsyAbstractNotes", "demographicsNecropsyAbstractNotes");
col.setLabel("Necropsy Abstract Notes");
col.setDescription("Returns the participant's necropsy abstract remarks and projects");
table.addColumn(col);
}
if (table.getColumn("origin") == null)
{
String origin = "origin";
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo arrival = getRealTableForDataset(table, "arrival");
// Here we want a union of the birth and arrival tables to get the origin of the animal
String arrivalAndBirthUnion = "( " +
"SELECT " +
"a.source as source, " +
"a.date as date," +
"a.participantid as participantid " +
"FROM studydataset." +arrival.getName() + " a " +
"WHERE a.source is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"UNION ALL " +
"SELECT " +
"b.origin as source," +
"b.date as date," +
"b.participantid as participantid " +
"FROM studydataset." + birth.getName() + " b " +
"WHERE b.origin is not null and b.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
")";
String theQuery = "(" +
"SELECT source FROM " + arrivalAndBirthUnion + " w ORDER BY w.date DESC LIMIT 1" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, origin, sql, JdbcType.VARCHAR);
//String url = "query-detailsQueryRow.view?schemaName=ehr_lookups&query.queryName=source&code=${origin}";
//newCol.setURL(StringExpressionFactory.createURL(url));
newCol.setLabel("Source/Vendor");
newCol.setDescription("Returns the animal's original source from an arrival or birth record.");
UserSchema ehrLookupsSchema = getUserSchema(table, "ehr_lookups");
newCol.setFk(new QueryForeignKey(ehrLookupsSchema, null, "source", "code", "meaning"));
newCol.setURL(StringExpressionFactory.create("query-detailsQueryRow.view?schemaName=ehr_lookups&query.queryName=source&code=${origin}"));
table.addColumn(newCol);
}
// Here we want a custom query since the getWrappedIdCol model did not work for us for the following requirements:
// 1. Show the geographic origin if the query is able to calculate it.
// 2. Show blank (and not the broken lookup with the id inside of <angle brackets>) if we don't have the info.
// 3. Have the text be a link when we have a value to show.
if (table.getColumn("geographic_origin") == null)
{
String geographicOrigin = "geographic_origin";
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo arrival = getRealTableForDataset(table, "arrival");
// Here we want a union of the birth and arrival tables to get the geographic origin of the animal
String arrivalAndBirthUnion = "( " +
"SELECT " +
"a.geographic_origin as origin, " +
"a.date as date," +
"a.participantid as participantid " +
"FROM studydataset." +arrival.getName() + " a " +
"WHERE a.geographic_origin is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"UNION ALL " +
"SELECT " +
"b.origin as origin," +
"b.date as date," +
"b.participantid as participantid " +
"FROM studydataset." + birth.getName() + " b " +
"WHERE b.origin is not null and b.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
")";
String theQuery = "(" +
"SELECT " +
"CASE WHEN origin = 'cen'" +
"THEN 'domestic' " +
"ELSE origin " +
"END AS geographic_origin " +
"FROM " + arrivalAndBirthUnion + " w ORDER BY w.date ASC LIMIT 1" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, geographicOrigin, sql, JdbcType.VARCHAR);
String url = "query-detailsQueryRow.view?schemaName=ehr_lookups&query.queryName=geographic_origins&meaning=${geographic_origin}";
newCol.setURL(StringExpressionFactory.createURL(url));
newCol.setLabel("Geographic Origin");
newCol.setDescription("This column is the geographic origin");
table.addColumn(newCol);
}
if (table.getColumn("ancestry") == null)
{
String ancestry = "ancestry";
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo arrival = getRealTableForDataset(table, "arrival");
// Here we want a union of the birth and arrival tables to get the ancestry of the animal
String arrivalAndBirthUnion = "( " +
"SELECT " +
"a.ancestry as ancestry, " +
"a.date as date," +
"a.participantid as participantid " +
"FROM studydataset." + arrival.getName() + " a " +
"WHERE a.ancestry is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"UNION ALL " +
"SELECT " +
"b.ancestry as ancestry," +
"b.date as date," +
"b.participantid as participantid " +
"FROM studydataset." + birth.getName() + " b " +
"WHERE b.ancestry is not null and b.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
")";
String theQuery = "(" +
"SELECT ancestry FROM " + arrivalAndBirthUnion + " w ORDER BY w.date ASC LIMIT 1" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, ancestry, sql, JdbcType.VARCHAR);
newCol.setLabel("Ancestry");
newCol.setDescription("Returns the animal's ancestry.");
UserSchema ehrLookupsSchema = getUserSchema(table, "ehr_lookups");
newCol.setFk(new QueryForeignKey(ehrLookupsSchema, null, "ancestry", "rowid", "value"));
newCol.setURL(StringExpressionFactory.create("query-detailsQueryRow.view?schemaName=ehr_lookups&query.queryName=source&code=${ancestry}"));
table.addColumn(newCol);
}
if (table.getColumn("birth") == null)
{
String birthColumn = "birth";
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo arrival = getRealTableForDataset(table, "arrival");
// Here we want a union of the birth and arrival tables to get the ancestry of the animal
String arrivalAndBirthUnion = "( " +
"SELECT " +
"a.birth as birth, " +
"a.participantid as participantid, " +
"a.modified as modified " +
"FROM studydataset." + arrival.getName() + " a " +
"WHERE a.birth is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"UNION ALL " +
"SELECT " +
"b.date as birth," +
"b.participantid as participantid, " +
"b.modified as modified " +
"FROM studydataset." + birth.getName() + " b " +
"WHERE b.date is not null and b.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
")";
String theQuery = "(" +
"SELECT birth FROM " + arrivalAndBirthUnion + " w ORDER BY w.modified DESC LIMIT 1" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, birthColumn, sql, JdbcType.DATE);
newCol.setLabel("Birth");
newCol.setDescription("Returns the animal's birth date.");
//newCol.setURL(StringExpressionFactory.create("query-executeQuery.view?schemaName=study&query.queryName=Birth&query.Id~eq={id}"));
table.addColumn(newCol);
}
if (table.getColumn("vendor_id") == null)
{
String vendorIdColumn = "vendor_id";
TableInfo arrival = getRealTableForDataset(table, "arrival");
String theQuery = "(" +
"SELECT vendor_id FROM studydataset." + arrival.getName() + " w where w.participantid="
+ ExprColumn.STR_TABLE_ALIAS + ".participantid and w.vendor_id is not null LIMIT 1" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, vendorIdColumn, sql, JdbcType.VARCHAR);
newCol.setLabel("Vendor ID");
newCol.setDescription("Returns the animal's original vendor id.");
table.addColumn(newCol);
}
if (table.getColumn("sire") == null)
{
String sire_new = "sire";
TableInfo arrival = getRealTableForDataset(table, "arrival");
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo demographics = getRealTableForDataset(table, "demographics");
// Here we want a union of the birth and arrival tables to get the sire of the animal,
// if none found, we fall back on the "old" data in the demographic table
String arrivalAndBirthQuery = "( " +
"SELECT " +
"COALESCE ( " +
"(SELECT " +
"a.participantid as sire " +
"FROM " +
"studydataset." + arrival.getName() + " a, studydataset." + arrival.getName() + " b " +
" WHERE " +
" b.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND lower(a.vendor_id) = lower(b.sire) AND lower(a.vendor_id) != lower(a.participantid) " +
"ORDER BY " +
"b.modified DESC " +
"LIMIT 1), " +
"(SELECT " +
"sire " +
"FROM " +
"studydataset." + arrival.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"ORDER BY " +
"modified DESC " +
"LIMIT 1), " +
"(SELECT " +
"sire " +
"FROM " +
"studydataset." + birth.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"ORDER BY " +
"modified DESC" +
" LIMIT 1), " +
"(SELECT " +
"sire_old " +
"FROM " +
"studydataset." + demographics.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
" LIMIT 1) " +
") AS sire " +
")";
SQLFragment sql = new SQLFragment(arrivalAndBirthQuery);
ExprColumn newCol = new ExprColumn(table, sire_new, sql, JdbcType.VARCHAR);
newCol.setLabel("Sire");
newCol.setDescription("Returns the animal's updated sire id");
table.addColumn(newCol);
}
if (table.getColumn("dam") == null)
{
String dam_new = "dam";
TableInfo arrival = getRealTableForDataset(table, "arrival");
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo demographics = getRealTableForDataset(table, "demographics");
// Here we want a union of the birth and arrival tables to get the dam of the animal
// if none found, we fall back on the "old" data in the demographic table
String arrivalAndBirthQuery = "( " +
"SELECT " +
"COALESCE ( " +
"(SELECT " +
"a.participantid as dam " +
"FROM " +
"studydataset." + arrival.getName() + " a, studydataset." + arrival.getName() + " b " +
" WHERE " +
" b.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND lower(a.vendor_id) = lower(b.dam) AND lower(a.vendor_id) != lower(a.participantid) " +
"ORDER BY " +
"b.modified DESC " +
"LIMIT 1), " +
"(SELECT " +
"dam " +
"FROM " +
"studydataset." + arrival.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"ORDER BY " +
"modified DESC " +
"LIMIT 1), " +
"(SELECT " +
"dam " +
"FROM " +
"studydataset." + birth.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"ORDER BY " +
"modified DESC" +
" LIMIT 1), " +
"(SELECT " +
"dam_old " +
"FROM " +
"studydataset." + demographics.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
" LIMIT 1) " +
") AS dam " +
")";
SQLFragment sql = new SQLFragment(arrivalAndBirthQuery);
ExprColumn newCol = new ExprColumn(table, dam_new, sql, JdbcType.VARCHAR);
newCol.setLabel("Dam");
newCol.setDescription("Returns the animal's updated dam id");
table.addColumn(newCol);
}
}
private TableInfo getRealTableForDataset(AbstractTableInfo ti, String name)
{
Container ehrContainer = EHRService.get().getEHRStudyContainer(ti.getUserSchema().getContainer());
if (ehrContainer == null)
return null;
Dataset ds;
Study s = StudyService.get().getStudy(ehrContainer);
if (s == null)
return null;
ds = s.getDatasetByName(name);
if (ds == null)
{
// NOTE: this seems to happen during study import on TeamCity. It does not seem to happen during normal operation
_log.info("A dataset was requested that does not exist: " + name + " in container: " + ehrContainer.getPath());
StringBuilder sb = new StringBuilder();
for (Dataset d : s.getDatasets())
{
sb.append(d.getName() + ", ");
}
_log.info("datasets present: " + sb.toString());
return null;
}
else
{
return StorageProvisioner.createTableInfo(ds.getDomain());
}
}
private void customizeProtocolTable(AbstractTableInfo table)
{
BaseColumnInfo protocolCol = (BaseColumnInfo) table.getColumn("protocol");
if (protocolCol != null && table.getColumn("pdf") == null)
{
var col = table.addColumn(new WrappedColumn(protocolCol, "pdf"));
col.setLabel("PDF");
col.setURL(StringExpressionFactory.create("/query/WNPRC/WNPRC_Units/Animal_Services/Compliance_Training/Private/Protocol_PDFs/executeQuery.view?schemaName=lists&query.queryName=ProtocolPDFs&query.protocol~eq=${pdf}", true));
}
if (table.getColumn("totalProjects") == null)
{
UserSchema us = getUserSchema(table, "ehr");
if (us != null)
{
var col2 = table.addColumn(new WrappedColumn(protocolCol, "totalProjects"));
col2.setLabel("Total Projects");
col2.setUserEditable(false);
col2.setIsUnselectable(true);
col2.setFk(QueryForeignKey.from(us, table.getContainerFilter())
.table("protocolTotalProjects")
.key("protocol")
.display("protocol"));
}
}
//TODO: Make this work with an Ext UI that does not over write the values
/* ColumnInfo contactsColumn = table.getColumn("contacts");
contactsColumn.setDisplayColumnFactory(new DisplayColumnFactory()
{
@Override
public DisplayColumn createRenderer(ColumnInfo colInfo)
{
return new ContactsColumn(colInfo);
}
});*/
if (table.getColumn("expirationDate") == null)
{
UserSchema us = getUserSchema(table, "ehr");
if (us != null)
{
BaseColumnInfo col2 = (BaseColumnInfo) table.addColumn(new WrappedColumn(protocolCol, "expirationDate"));
col2.setLabel("Expiration Date");
col2.setUserEditable(false);
col2.setIsUnselectable(true);
col2.setFk(new QueryForeignKey(us, null, "protocolExpirationDate", "protocol", "protocol"));
}
}
if (table.getColumn("countsBySpecies") == null)
{
UserSchema us = getUserSchema(table, "ehr");
if (us != null)
{
BaseColumnInfo col2 = (BaseColumnInfo) table.addColumn(new WrappedColumn(protocolCol, "countsBySpecies"));
col2.setLabel("Max Animals Per Species");
col2.setUserEditable(false);
col2.setIsUnselectable(true);
col2.setFk(new QueryForeignKey(us, null, "protocolCountsBySpecies", "protocol", "protocol"));
}
}
}
private void customizeBreedingEncountersTable(AbstractTableInfo ti)
{
customizeSireIdColumn(ti);
}
private void customizePregnanciesTable(AbstractTableInfo ti) {
customizeSireIdColumn(ti);
}
private void customizeHousingTable(AbstractTableInfo ti) {
customizeReasonForMoveColumn(ti);
}
private void customizeSireIdColumn(AbstractTableInfo ti) {
BaseColumnInfo sireid = (BaseColumnInfo) ti.getColumn("sireid");
if (sireid != null)
{
UserSchema us = getUserSchema(ti, "study");
if (us != null)
{
sireid.setDisplayColumnFactory(colInfo -> new DataColumn(colInfo){
@Override
public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException
{
ActionURL url = new ActionURL("ehr", "participantView.view", us.getContainer());
String joinedIds = (String)ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "sireid"));
if (joinedIds != null)
{
String[] ids = joinedIds.split(",");
String urlString = "";
for (int i = 0; i < ids.length; i++)
{
String id = ids[i];
url.replaceParameter("participantId", id);
urlString += "<a href=\"" + PageFlowUtil.filter(url) + "\">";
urlString += PageFlowUtil.filter(id);
urlString += "</a>";
if (i + 1 < ids.length)
{
urlString += ", ";
}
}
out.write(urlString);
}
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
return ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "sireid"));
}
});
}
}
}
private void customizeReasonForMoveColumn(AbstractTableInfo ti) {
BaseColumnInfo reason = (BaseColumnInfo)ti.getColumn("reason");
if (reason != null)
{
UserSchema us = getUserSchema(ti, "study");
if (us != null)
{
reason.setDisplayColumnFactory(colInfo -> new DataColumn(colInfo){
@Override
public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException
{
ActionURL url = new ActionURL("query", "recordDetails.view", us.getContainer());
String joinedReasons = (String)ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "reason"));
if (joinedReasons != null)
{
String[] reasons = joinedReasons.split(",");
url.addParameter("schemaName", "ehr_lookups");
url.addParameter("query.queryName", "housing_reason");
url.addParameter("keyField", "value");
StringBuilder urlString = new StringBuilder();
for (int i = 0; i < reasons.length; i++)
{
String reasonForMoveValue = reasons[i];
SimplerFilter filter = new SimplerFilter("set_name", CompareType.EQUAL, "housing_reason").addCondition("value", CompareType.EQUAL, reasonForMoveValue);
DbSchema schema = DbSchema.get("ehr_lookups", DbSchemaType.Module);
TableInfo ti = schema.getTable("lookups");
TableSelector ts = new TableSelector(ti, filter, null);
String reasonForMoveTitle;
if (ts.getMap() != null && ts.getMap().get("title") != null)
{
reasonForMoveTitle = (String) ts.getMap().get("title");
url.replaceParameter("key", reasonForMoveValue);
urlString.append("<a href=\"").append(PageFlowUtil.filter(url)).append("\">");
urlString.append(PageFlowUtil.filter(reasonForMoveTitle));
urlString.append("</a>");
}
else
{
urlString.append(PageFlowUtil.filter("<" + reasonForMoveValue + ">"));
}
if (i + 1 < reasons.length)
{
urlString.append(", ");
}
}
out.write(urlString.toString());
}
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
return ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "reason"));
}
});
}
}
}
public static class AnimalIdsToOfferColumn extends DataColumn {
public AnimalIdsToOfferColumn(ColumnInfo colInfo) {
super(colInfo);
}
@Override
public Object getValue(RenderContext ctx) {
return super.getValue(ctx);
}
}
public static class AnimalIdsToOfferColumnQCStateConditional extends DataColumn {
private User _currentUser;
public AnimalIdsToOfferColumnQCStateConditional(ColumnInfo colInfo, User currentUser) {
super(colInfo);
_currentUser = currentUser;
}
@Override
public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException
{
if ("Request: Pending".equals(ctx.get("QCState$Label")))
{
out.write("");
}
else if (_currentUser.getUserId() == (Integer) ctx.get("createdBy"))
{
super.renderGridCellContents(ctx, out);
}
else
{
out.write("");
}
}
}
public static class AnimalRequestsEditLinkConditional extends DataColumn
{
private User _currentUser;
public AnimalRequestsEditLinkConditional(ColumnInfo colInfo, User currentUser)
{
super(colInfo);
_currentUser = currentUser;
}
@Override
public HtmlString getFormattedHtml(RenderContext ctx)
{
String edit;
if (_currentUser.getUserId() == (Integer) ctx.get("createdBy"))
{
edit = "<a class='fa fa-pencil lk-dr-action-icon' style='opacity: 1' href='" +
ctx.getViewContext().getContextPath() +
"/ehr/WNPRC/EHR/manageRecord.view?schemaName=wnprc&queryName=animal_requests&title=Animal%20Request&keyField=rowid&key=" +
ctx.get("rowid").toString() +
"&update=1&returnUrl=" +
ctx.getViewContext().getContextPath() +
"%2Fwnprc_ehr%2FWNPRC%2FEHR%2FdataEntry.view%3F'></a>";
}
else {
edit = "";
}
return HtmlString.unsafe(edit);
}
}
public static class AnimalRequestsEditLinkShow extends DataColumn {
public AnimalRequestsEditLinkShow(ColumnInfo colInfo) {
super(colInfo);
}
@Override
public HtmlString getFormattedHtml(RenderContext ctx)
{
String edit;
edit = "<a class='fa fa-pencil lk-dr-action-icon' style='opacity: 1' href='" +
ctx.getViewContext().getContextPath() +
"/ehr/WNPRC/EHR/manageRecord.view?schemaName=wnprc&queryName=animal_requests&title=Animal%20Request&keyField=rowid&key=" +
ctx.get("rowid").toString() +
"&update=1&returnUrl=" +
ctx.getViewContext().getContextPath() +
"%2Fwnprc_ehr%2FWNPRC%2FEHR%2FdataEntry.view%3F'></a>";
return HtmlString.unsafe(edit);
}
}
public static class AnimalReportLink extends DataColumn {
public AnimalReportLink(ColumnInfo colInfo) {
super(colInfo);
}
@Override
public Object getValue(RenderContext ctx) {
return super.getValue(ctx);
}
}
public static class AnimalReportLinkQCStateConditional extends DataColumn {
private User _currentUser;
public AnimalReportLinkQCStateConditional(ColumnInfo colInfo, User currentUser) {
super(colInfo);
_currentUser = currentUser;
}
@Override
public Object getValue(RenderContext ctx)
{
if ("Request: Pending".equals(ctx.get("QCState$Label")))
{
return "";
}
else if (_currentUser.getUserId() == (Integer) ctx.get("createdBy"))
{
return super.getValue(ctx);
}
else
{
return "";
}
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
if ("Request: Pending".equals(ctx.get("QCState$Label")))
{
return "";
}
else if (_currentUser.getUserId() == (Integer) ctx.get("createdBy"))
{
return super.getDisplayValue(ctx);
}
else
{
return "";
}
}
@Override
public HtmlString getFormattedHtml(RenderContext ctx)
{
HtmlStringBuilder emptyString = HtmlStringBuilder.of();
if ("Request: Pending".equals(ctx.get("QCState$Label")))
{
return emptyString.getHtmlString();
}
else if (_currentUser.getUserId() == (Integer) ctx.get("createdBy"))
{
return super.getFormattedHtml(ctx);
}
else
{
return emptyString.getHtmlString();
}
}
}
private void customizeAnimalRequestsTable(AbstractTableInfo table)
{
UserSchema us = getStudyUserSchema(table);
if (us == null)
{
return;
}
User currentUser = us.getUser();
//Nail down individual fields for editing, unless user has permission
List<String> readOnlyFields = new ArrayList<>();
readOnlyFields.add("QCState");
readOnlyFields.add("dateapprovedordenied");
readOnlyFields.add("animalsorigin");
readOnlyFields.add("dateordered");
readOnlyFields.add("datearrival");
for (String item : readOnlyFields)
{
if (table.getColumn(item) != null)
{
BaseColumnInfo col = (BaseColumnInfo) table.getColumn(item);
if (!us.getContainer().hasPermission(currentUser, WNPRCAnimalRequestsEditPermission.class) && !us.getContainer().hasPermission(currentUser, AdminPermission.class))
{
col.setReadOnly(true);
}
}
}
if (table.getColumn("edit") == null){
String edit = "edit";
String theQuery = "( " +
"(SELECT 'edit')" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, edit, sql, JdbcType.VARCHAR);
table.addColumn(newCol);
newCol.setDisplayColumnFactory(new DisplayColumnFactory()
{
@Override
public DisplayColumn createRenderer(ColumnInfo colInfo)
{
if (us.getContainer().hasPermission(currentUser, WNPRCAnimalRequestsEditPermission.class) || us.getContainer().hasPermission(currentUser, AdminPermission.class))
{
return new AnimalRequestsEditLinkShow(colInfo);
}
else
{
return new AnimalRequestsEditLinkConditional(colInfo, currentUser);
}
}
});
}
//re-render animalidsoffer column
if (table.getColumn("animalidstooffer") != null)
{
BaseColumnInfo col = (BaseColumnInfo) table.getColumn("animalidstooffer");
col.setLabel("Animal Ids");
if (us.getContainer().hasPermission(currentUser, WNPRCAnimalRequestsViewPermission.class) || us.getContainer().hasPermission(currentUser, AdminPermission.class)){
col.setDisplayColumnFactory(colInfo -> new AnimalIdsToOfferColumn(colInfo));
}
else{
col.setHidden(true);
col.setDisplayColumnFactory(colInfo -> new AnimalIdsToOfferColumnQCStateConditional(colInfo, currentUser));
}
}
//create animal history report link from a set of animal ids
if (table.getColumn("animal_history_link") == null)
{
String animal_history_link = "animal_history_link";
String theQuery = "( " +
"(SELECT " +
" CASE WHEN a.animalidstooffer is not null " +
"THEN 'Report Link' " +
"ELSE '' " +
" END AS animal_history_link " +
" FROM wnprc.animal_requests a " +
"WHERE a.rowid=" + ExprColumn.STR_TABLE_ALIAS + ".rowid LIMIT 1) " +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, animal_history_link, sql, JdbcType.VARCHAR);
newCol.setLabel("Animal History Link");
newCol.setDescription("Provides a link to the animal history records given the animal ids that were selected.");
newCol.setURL(StringExpressionFactory.create("ehr-animalHistory.view?#subjects:${animalidstooffer}&inputType:multiSubject&showReport:0&activeReport:abstractReport"));
table.addColumn(newCol);
newCol.setDisplayColumnFactory(new DisplayColumnFactory()
{
@Override
public DisplayColumn createRenderer(ColumnInfo colInfo)
{
if (us.getContainer().hasPermission(currentUser, WNPRCAnimalRequestsViewPermission.class) || us.getContainer().hasPermission(currentUser, AdminPermission.class))
{
return new AnimalReportLink(colInfo);
}
else
{
return new AnimalReportLinkQCStateConditional(colInfo, currentUser);
}
}
});
}
}
private BaseColumnInfo getWrappedIdCol(UserSchema us, AbstractTableInfo ds, String name, String queryName)
{
String ID_COL = "Id";
WrappedColumn col = new WrappedColumn(ds.getColumn(ID_COL), name);
col.setReadOnly(true);
col.setIsUnselectable(true);
col.setUserEditable(false);
col.setFk(QueryForeignKey.from(us, ds.getContainerFilter())
.table(queryName)
.key(ID_COL)
.display(ID_COL));
return col;
}
private UserSchema getStudyUserSchema(AbstractTableInfo ds)
{
return getUserSchema(ds, "study");
}
@Override
public UserSchema getUserSchema(AbstractTableInfo ds, String name)
{
UserSchema us = ds.getUserSchema();
if (us != null)
{
if (name.equalsIgnoreCase(us.getName()))
return us;
return QueryService.get().getUserSchema(us.getUser(), us.getContainer(), name);
}
return null;
}
//TODO: Look how to use another UI to allow for better support for virtual columns
/* public static class ContactsColumn extends DataColumn
{
public ContactsColumn(ColumnInfo colInfo)
{
super(colInfo);
}
@Override
public Object getValue(RenderContext ctx)
{
Object value = super.getValue(ctx);
StringBuffer readableContacts = new StringBuffer();
if(value != null)
{
//TODO:parse the value into integers to display users
String contacts = value.toString();
if (contacts.contains(","))
{
List<String> contactList = new ArrayList<>(Arrays.asList(contacts.split(",")));
Iterator<String> contactsIterator = contactList.iterator();
while (contactsIterator.hasNext())
{
User singleContact = UserManager.getUser(Integer.parseInt(contactsIterator.next()));
readableContacts.append(singleContact.getDisplayName(singleContact));
readableContacts.append(" ");
System.out.println("readable contact "+readableContacts);
}
return readableContacts;
}
if (NumberUtils.isNumber(contacts)){
User singleContact = UserManager.getUser(Integer.parseInt(contacts));
readableContacts.append(singleContact.getDisplayName(singleContact));
return readableContacts;
}
}
return readableContacts;
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
return getValue(ctx);
}
@Override
public String getFormattedValue(RenderContext ctx)
{
return h(getValue(ctx));
}
}*/
private boolean isExt4Form(String schemaName, String queryName)
{
boolean isExt4Form = false;
SimplerFilter filter = new SimplerFilter("schemaname", CompareType.EQUAL, schemaName).addCondition("queryname", CompareType.EQUAL, queryName);
//TableInfo ti = DbSchema.get("ehr", DbSchemaType.Module).getTable(EHRSchema.TABLE_FORM_FRAMEWORK_TYPES);
TableInfo ti = DbSchema.get("ehr", DbSchemaType.Module).getTable("form_framework_types");
TableSelector ts = new TableSelector(ti, filter, null);
String framework;
if (ts.getMap() != null && ts.getMap().get("framework") != null)
{
framework = (String) ts.getMap().get("framework");
if ("extjs4".equalsIgnoreCase(framework)) {
isExt4Form = true;
}
}
return isExt4Form;
}
}
| WNPRC_EHR/src/org/labkey/wnprc_ehr/table/WNPRC_EHRCustomizer.java | /*
* Copyright (c) 2012-2014 LabKey Corporation
*
* 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.labkey.wnprc_ehr.table;
import org.apache.log4j.Logger;
import org.labkey.api.data.AbstractTableInfo;
import org.labkey.api.data.BaseColumnInfo;
import org.labkey.api.data.ColumnInfo;
import org.labkey.api.data.CompareType;
import org.labkey.api.data.Container;
import org.labkey.api.data.DataColumn;
import org.labkey.api.data.DbSchema;
import org.labkey.api.data.DbSchemaType;
import org.labkey.api.data.DisplayColumn;
import org.labkey.api.data.DisplayColumnFactory;
import org.labkey.api.data.JdbcType;
import org.labkey.api.data.RenderContext;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.data.TableInfo;
import org.labkey.api.data.TableSelector;
import org.labkey.api.data.WrappedColumn;
import org.labkey.api.ehr.EHRService;
import org.labkey.api.exp.api.StorageProvisioner;
import org.labkey.api.ldk.table.AbstractTableCustomizer;
import org.labkey.api.query.ExprColumn;
import org.labkey.api.query.FieldKey;
import org.labkey.api.query.QueryForeignKey;
import org.labkey.api.query.QueryService;
import org.labkey.api.query.UserSchema;
import org.labkey.api.security.User;
import org.labkey.api.security.permissions.AdminPermission;
import org.labkey.api.study.Dataset;
import org.labkey.api.study.Study;
import org.labkey.api.study.StudyService;
import org.labkey.api.util.GUID;
import org.labkey.api.util.HtmlString;
import org.labkey.api.util.HtmlStringBuilder;
import org.labkey.api.util.PageFlowUtil;
import org.labkey.api.util.StringExpressionFactory;
import org.labkey.api.view.ActionURL;
import org.labkey.dbutils.api.SimplerFilter;
import org.labkey.wnprc_ehr.security.permissions.WNPRCAnimalRequestsEditPermission;
import org.labkey.wnprc_ehr.security.permissions.WNPRCAnimalRequestsViewPermission;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
* User: bimber
* Date: 12/7/12
* Time: 2:22 PM
*/
public class WNPRC_EHRCustomizer extends AbstractTableCustomizer
{
protected static final Logger _log = Logger.getLogger(WNPRC_EHRCustomizer.class);
public WNPRC_EHRCustomizer()
{
}
@Override
public void customize(TableInfo table)
{
if (table instanceof AbstractTableInfo)
{
customizeColumns((AbstractTableInfo)table);
if (table.getName().equalsIgnoreCase("Animal") && table.getSchema().getName().equalsIgnoreCase("study"))
customizeAnimalTable((AbstractTableInfo) table);
else if (table.getName().equalsIgnoreCase("Birth") && table.getSchema().getName().equalsIgnoreCase("study"))
customizeBirthTable((AbstractTableInfo) table);
else if (table.getName().equalsIgnoreCase("protocol") && table.getSchema().getName().equalsIgnoreCase("ehr"))
customizeProtocolTable((AbstractTableInfo)table);
else if (table.getName().equalsIgnoreCase("breeding_encounters") && table.getSchema().getName().equalsIgnoreCase("study")) {
customizeBreedingEncountersTable((AbstractTableInfo) table);
} else if (table.getName().equalsIgnoreCase("pregnancies") && table.getSchema().getName().equalsIgnoreCase("study")) {
customizePregnanciesTable((AbstractTableInfo) table);
} else if (table.getName().equalsIgnoreCase("housing") && table.getSchema().getName().equalsIgnoreCase("study")) {
customizeHousingTable((AbstractTableInfo) table);
} else if (matches(table, "ehr", "project")) {
customizeProjectTable((AbstractTableInfo) table);
} else if (matches(table, "study", "feeding")) {
customizeFeedingTable((AbstractTableInfo) table);
} else if (matches(table, "study", "demographics")) {
customizeDemographicsTable((AbstractTableInfo) table);
} else if (matches(table, "ehr", "tasks")) {
customizeTasksTable((AbstractTableInfo) table);
} else if (matches(table, "wnprc", "animal_requests")) {
customizeAnimalRequestsTable((AbstractTableInfo) table);
}
}
}
private void customizeColumns(AbstractTableInfo ti)
{
var project = ti.getMutableColumn("project");
if (project != null)
{
project.setFormat("00000000");
}
customizeRoomCol(ti, "room");
customizeRoomCol(ti, "room1");
customizeRoomCol(ti, "room2");
}
private void customizeRoomCol(AbstractTableInfo ti, String columnName)
{
var room = ti.getMutableColumn(columnName);
if (room != null)
{
if (!ti.getName().equalsIgnoreCase("rooms"))
{
// Configure the FK to show the raw value to improve performance, since the database can avoid
// doing the join in many cases
Container ehrContainer = EHRService.get().getEHRStudyContainer(ti.getUserSchema().getContainer());
if (ehrContainer != null)
{
UserSchema us = getUserSchema(ti, "ehr_lookups", ehrContainer);
if (us != null)
{
room.setFk(QueryForeignKey.from(us, ti.getContainerFilter())
.container(ehrContainer)
.table("rooms")
.key("room")
.display("room")
.raw(true));
}
}
}
}
}
private void customizeTasksTable(AbstractTableInfo ti)
{
UserSchema us = ti.getUserSchema();
BaseColumnInfo rowIdCol = (BaseColumnInfo) ti.getColumn("rowid");
if (rowIdCol != null && us != null)
{
rowIdCol.setDisplayColumnFactory(colInfo -> new DataColumn(colInfo)
{
@Override
public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException
{
Integer rowId = (Integer) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "rowid"));
String taskId = (String) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "taskid"));
String formType = (String) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "formtype"));
if (isExt4Form("form", formType))
{
ActionURL url = new ActionURL("ehr", "dataEntryFormDetails.view", us.getContainer());
if ("Research Ultrasounds".equalsIgnoreCase(formType)) {
formType = "Research Ultrasounds Task";
}
url.addParameter("formtype", formType);
url.addParameter("taskid", taskId);
StringBuilder urlString = new StringBuilder();
urlString.append("<a href=\"" + PageFlowUtil.filter(url) + "\">");
urlString.append(PageFlowUtil.filter(rowId));
urlString.append("</a>");
out.write(urlString.toString());
} else {
super.renderGridCellContents(ctx, out);
}
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
return ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "rowid"));
}
});
BaseColumnInfo updateTitleCol = (BaseColumnInfo) ti.getColumn("updateTitle");
if (updateTitleCol != null && us != null)
{
updateTitleCol.setDisplayColumnFactory(colInfo -> new DataColumn(colInfo)
{
@Override
public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException
{
String updateTitle = (String) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "updateTitle"));
String taskId = (String) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "taskid"));
String formType = (String) ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "formtype"));
if (isExt4Form("form", formType))
{
ActionURL url = new ActionURL("ehr", "dataEntryForm.view", us.getContainer());
if ("Research Ultrasounds".equalsIgnoreCase(formType))
{
formType = "Research Ultrasounds Review";
}
url.addParameter("formType", formType);
url.addParameter("taskid", taskId);
StringBuilder urlString = new StringBuilder();
urlString.append("<a href=\"" + PageFlowUtil.filter(url) + "\">");
urlString.append(PageFlowUtil.filter(updateTitle));
urlString.append("</a>");
out.write(urlString.toString());
}
else
{
super.renderGridCellContents(ctx, out);
}
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
return ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "rowid"));
}
});
}
}
}
private void customizeProjectTable(AbstractTableInfo ti)
{
String investigatorName = "investigatorName";
SQLFragment sql = new SQLFragment("COALESCE((SELECT " +
"(CASE WHEN lastName IS NOT NULL AND firstName IS NOT NULL " +
"THEN (lastName ||', '|| firstName) " +
"WHEN lastName IS NOT NULL AND firstName IS NULL " +
"THEN lastName " +
"ELSE " +
"firstName " +
"END) AS investigatorWithName " +
"from ehr.investigators where rowid = " + ExprColumn.STR_TABLE_ALIAS + ".investigatorId), " + ExprColumn.STR_TABLE_ALIAS + ".inves)");
ExprColumn newCol = new ExprColumn(ti, investigatorName, sql, JdbcType.VARCHAR);
newCol.setLabel("Investigator");
newCol.setDescription("This column shows the name of the investigator on the project. It first checks if there is an investigatorId, and if not defaults to the old inves column.");
ti.addColumn(newCol);
}
private void customizeFeedingTable(AbstractTableInfo ti)
{
// this number is representative of 12/17 ratio
Double d = new Double(.705882);
Double conv = d;
Double invconv = 1/d;
String chowConversion = "chowConversion";
Container ehrContainer = EHRService.get().getEHRStudyContainer(ti.getUserSchema().getContainer());
GUID ehrEntityId = ehrContainer.getEntityId();
ehrEntityId.toString();
SQLFragment sql = new SQLFragment("(SELECT " +
" (CASE WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'log' and container ='"+ ehrEntityId.toString() + "')" +
"THEN (ROUND(amount*"+ conv.toString() + ") || ' flower')" +
"WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'log (gluten-free)' and container ='"+ ehrEntityId.toString() + "')" +
"THEN (ROUND(amount*"+ conv.toString() + ") || ' flower')" +
"WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'flower' and container ='" + ehrEntityId.toString() + "')" +
"THEN (ROUND(amount*" + invconv.toString() + ") || ' log')" +
"ELSE " +
" 'bad data'" +
"END) as ChowConversion)");
ExprColumn newCol = new ExprColumn(ti, chowConversion, sql, JdbcType.VARCHAR);
newCol.setLabel("Chow Conversion");
newCol.setDescription("This column shows the calculated conversion amount between log and flower chows. The current conversion is 12g log <=> 17g flower.");
ti.addColumn(newCol);
String chowLookup = "chowLookup";
SQLFragment sql2 = new SQLFragment("(SELECT " +
" (CASE WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'log' and container ='"+ ehrEntityId.toString() + "')" +
"THEN (CAST (amount as text) || ' log')" +
"WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'log (gluten-free)' and container ='"+ ehrEntityId.toString() + "')" +
"THEN (CAST (amount as text) || ' log (gluten-free)')" +
"WHEN " + ExprColumn.STR_TABLE_ALIAS + ".type = (SELECT Rowid from ehr_lookups.lookups where set_name = 'feeding_types' and value = 'flower' and container ='"+ ehrEntityId.toString() + "')" +
"THEN (CAST (amount as text) || ' flower')" +
"ELSE " +
" 'bad data'" +
"END) as ChowLookup)");
ExprColumn newCol2 = new ExprColumn(ti, chowLookup, sql2, JdbcType.VARCHAR);
newCol2.setLabel("Chow Lookup");
ti.addColumn(newCol2);
}
private void customizeBirthTable(AbstractTableInfo ti)
{
var cond = ti.getMutableColumn("cond");
if (cond != null)
{
cond.setLabel("Housing Condition");
UserSchema us = getUserSchema(ti, "ehr_lookups");
if (us != null)
{
cond.setFk(QueryForeignKey.from(us, ti.getContainerFilter())
.table("housing_condition_codes")
.key("value")
.display("title"));
}
}
}
private void customizeAnimalTable(AbstractTableInfo ds)
{
if (ds.getColumn("MHCtyping") != null)
return;
UserSchema us = getStudyUserSchema(ds);
if (us == null){
return;
}
if (ds.getColumn("demographicsMHC") == null)
{
BaseColumnInfo col = getWrappedIdCol(us, ds, "MHCtyping", "demographicsMHC");
col.setLabel("MHC SSP Typing");
col.setDescription("Summarizes MHC SSP typing results for the common alleles");
ds.addColumn(col);
BaseColumnInfo col2 = getWrappedIdCol(us, ds, "ViralLoad", "demographicsVL");
col2.setLabel("Viral Loads");
col2.setDescription("This field calculates the most recent viral load for this animal");
ds.addColumn(col2);
BaseColumnInfo col3 = getWrappedIdCol(us, ds, "ViralStatus", "demographicsViralStatus");
col3.setLabel("Viral Status");
col3.setDescription("This calculates the viral status of the animal based on tracking project assignments");
ds.addColumn(col3);
BaseColumnInfo col18 = getWrappedIdCol(us, ds, "Virology", "demographicsVirology");
col18.setLabel("Virology");
col18.setDescription("This calculates the distinct pathogens listed as positive for this animal from the virology table");
ds.addColumn(col18);
BaseColumnInfo col4 = getWrappedIdCol(us, ds, "IrregularObs", "demographicsObs");
col4.setLabel("Irregular Obs");
col4.setDescription("Shows any irregular observations from each animal today or yesterday.");
ds.addColumn(col4);
BaseColumnInfo col7 = getWrappedIdCol(us, ds, "activeAssignments", "demographicsAssignments");
col7.setLabel("Assignments - Active");
col7.setDescription("Contains summaries of the assignments for each animal, including the project numbers, availability codes and a count");
ds.addColumn(col7);
BaseColumnInfo col6 = getWrappedIdCol(us, ds, "totalAssignments", "demographicsAssignmentHistory");
col6.setLabel("Assignments - Total");
col6.setDescription("Contains summaries of the total assignments this animal has ever had, including the project numbers and a count");
ds.addColumn(col6);
BaseColumnInfo col5 = getWrappedIdCol(us, ds, "assignmentSummary", "demographicsAssignmentSummary");
col5.setLabel("Assignments - Detailed");
col5.setDescription("Contains more detailed summaries of the active assignments for each animal, including a breakdown between research, breeding, training, etc.");
ds.addColumn(col5);
BaseColumnInfo col10 = getWrappedIdCol(us, ds, "DaysAlone", "demographicsDaysAlone");
col10.setLabel("Days Alone");
col10.setDescription("Calculates the total number of days each animal has been single housed, if applicable.");
ds.addColumn(col10);
BaseColumnInfo bloodCol = getWrappedIdCol(us, ds, "AvailBlood", "demographicsBloodSummary");
bloodCol.setLabel("Blood Remaining");
bloodCol.setDescription("Calculates the total blood draw and remaining, which is determine by weight and blood drawn in the past 30 days.");
ds.addColumn(bloodCol);
BaseColumnInfo col17 = getWrappedIdCol(us, ds, "MostRecentTB", "demographicsMostRecentTBDate");
col17.setLabel("TB Tests");
col17.setDescription("Calculates the most recent TB date for this animal, time since TB and the last eye TB tested");
ds.addColumn(col17);
BaseColumnInfo col16 = getWrappedIdCol(us, ds, "Surgery", "demographicsSurgery");
col16.setLabel("Surgical History");
col16.setDescription("Calculates whether this animal has ever had any surgery or a surgery flagged as major");
ds.addColumn(col16);
BaseColumnInfo col19 = getWrappedIdCol(us, ds, "CurrentBehavior", "CurrentBehaviorNotes");
col19.setLabel("Behavior - Current");
col19.setDescription("This calculates the current behavior(s) for the animal, based on the behavior abstract table");
ds.addColumn(col19);
BaseColumnInfo col20 = getWrappedIdCol(us, ds, "PrimateId", "demographicsPrimateId");
col20.setLabel("PrimateId");
col20.setDescription("Unique PrimateID column to be shared across all datasets");
ds.addColumn(col20);
}
if (ds.getColumn("totalOffspring") == null)
{
BaseColumnInfo col15 = getWrappedIdCol(us, ds, "totalOffspring", "demographicsTotalOffspring");
col15.setLabel("Number of Offspring");
col15.setDescription("Shows the total offspring of each animal");
ds.addColumn(col15);
}
}
private void customizeDemographicsTable(AbstractTableInfo table)
{
UserSchema us = getStudyUserSchema(table);
if (us == null){
return;
}
if (table.getColumn("Feeding") == null)
{
BaseColumnInfo col = getWrappedIdCol(us, table, "Feeding", "demographicsMostRecentFeeding");
col.setLabel("Feeding");
col.setDescription("Shows most recent feeding type and chow conversion.");
table.addColumn(col);
}
if (table.getColumn("mostRecentAlopeciaScore") == null)
{
String mostRecentAlopeciaScore = "mostRecentAlopeciaScore";
TableInfo alopecia = getRealTableForDataset(table, "alopecia");
String theQuery = "( " +
"(SELECT " +
"a.score as score " +
"FROM studydataset." +alopecia.getName() + " a " +
"WHERE a.score is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid ORDER by a.date DESC LIMIT 1) " +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, mostRecentAlopeciaScore, sql, JdbcType.VARCHAR);
newCol.setLabel("Alopecia Score");
newCol.setDescription("Calculates the most recent alopecia score for each animal");
newCol.setURL(StringExpressionFactory.create("query-executeQuery.view?schemaName=ehr_lookups&query.queryName=alopecia_scores"));
table.addColumn(newCol);
}
if (table.getColumn("mostRecentBodyConditionScore") == null)
{
String mostRecentBodyConditionScore = "mostRecentBodyConditionScore";
TableInfo bcs = getRealTableForDataset(table, "bcs");
String theQuery = "( " +
"(SELECT " +
"a.score as score " +
"FROM studydataset." +bcs.getName() + " a " +
"WHERE a.score is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid ORDER by a.date DESC LIMIT 1) " +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, mostRecentBodyConditionScore, sql, JdbcType.VARCHAR);
newCol.setURL(StringExpressionFactory.create("query-executeQuery.view?schemaName=ehr_lookups&query.queryName=body_condition_scores"));
newCol.setLabel("Most Recent BCS");
newCol.setDescription("Returns the participant's most recent body condition score");
table.addColumn(newCol);
}
if (table.getColumn("necropsyAbstractNotes") == null)
{
BaseColumnInfo col = getWrappedIdCol(us, table, "necropsyAbstractNotes", "demographicsNecropsyAbstractNotes");
col.setLabel("Necropsy Abstract Notes");
col.setDescription("Returns the participant's necropsy abstract remarks and projects");
table.addColumn(col);
}
if (table.getColumn("origin") == null)
{
String origin = "origin";
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo arrival = getRealTableForDataset(table, "arrival");
// Here we want a union of the birth and arrival tables to get the origin of the animal
String arrivalAndBirthUnion = "( " +
"SELECT " +
"a.source as source, " +
"a.date as date," +
"a.participantid as participantid " +
"FROM studydataset." +arrival.getName() + " a " +
"WHERE a.source is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"UNION ALL " +
"SELECT " +
"b.origin as source," +
"b.date as date," +
"b.participantid as participantid " +
"FROM studydataset." + birth.getName() + " b " +
"WHERE b.origin is not null and b.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
")";
String theQuery = "(" +
"SELECT source FROM " + arrivalAndBirthUnion + " w ORDER BY w.date DESC LIMIT 1" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, origin, sql, JdbcType.VARCHAR);
//String url = "query-detailsQueryRow.view?schemaName=ehr_lookups&query.queryName=source&code=${origin}";
//newCol.setURL(StringExpressionFactory.createURL(url));
newCol.setLabel("Source/Vendor");
newCol.setDescription("Returns the animal's original source from an arrival or birth record.");
UserSchema ehrLookupsSchema = getUserSchema(table, "ehr_lookups");
newCol.setFk(new QueryForeignKey(ehrLookupsSchema, null, "source", "code", "meaning"));
newCol.setURL(StringExpressionFactory.create("query-detailsQueryRow.view?schemaName=ehr_lookups&query.queryName=source&code=${origin}"));
table.addColumn(newCol);
}
// Here we want a custom query since the getWrappedIdCol model did not work for us for the following requirements:
// 1. Show the geographic origin if the query is able to calculate it.
// 2. Show blank (and not the broken lookup with the id inside of <angle brackets>) if we don't have the info.
// 3. Have the text be a link when we have a value to show.
if (table.getColumn("geographic_origin") == null)
{
String geographicOrigin = "geographic_origin";
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo arrival = getRealTableForDataset(table, "arrival");
// Here we want a union of the birth and arrival tables to get the geographic origin of the animal
String arrivalAndBirthUnion = "( " +
"SELECT " +
"a.geographic_origin as origin, " +
"a.date as date," +
"a.participantid as participantid " +
"FROM studydataset." +arrival.getName() + " a " +
"WHERE a.geographic_origin is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"UNION ALL " +
"SELECT " +
"b.origin as origin," +
"b.date as date," +
"b.participantid as participantid " +
"FROM studydataset." + birth.getName() + " b " +
"WHERE b.origin is not null and b.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
")";
String theQuery = "(" +
"SELECT " +
"CASE WHEN origin = 'cen'" +
"THEN 'domestic' " +
"ELSE origin " +
"END AS geographic_origin " +
"FROM " + arrivalAndBirthUnion + " w ORDER BY w.date ASC LIMIT 1" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, geographicOrigin, sql, JdbcType.VARCHAR);
String url = "query-detailsQueryRow.view?schemaName=ehr_lookups&query.queryName=geographic_origins&meaning=${geographic_origin}";
newCol.setURL(StringExpressionFactory.createURL(url));
newCol.setLabel("Geographic Origin");
newCol.setDescription("This column is the geographic origin");
table.addColumn(newCol);
}
if (table.getColumn("ancestry") == null)
{
String ancestry = "ancestry";
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo arrival = getRealTableForDataset(table, "arrival");
// Here we want a union of the birth and arrival tables to get the ancestry of the animal
String arrivalAndBirthUnion = "( " +
"SELECT " +
"a.ancestry as ancestry, " +
"a.date as date," +
"a.participantid as participantid " +
"FROM studydataset." + arrival.getName() + " a " +
"WHERE a.ancestry is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"UNION ALL " +
"SELECT " +
"b.ancestry as ancestry," +
"b.date as date," +
"b.participantid as participantid " +
"FROM studydataset." + birth.getName() + " b " +
"WHERE b.ancestry is not null and b.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
")";
String theQuery = "(" +
"SELECT ancestry FROM " + arrivalAndBirthUnion + " w ORDER BY w.date ASC LIMIT 1" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, ancestry, sql, JdbcType.VARCHAR);
newCol.setLabel("Ancestry");
newCol.setDescription("Returns the animal's ancestry.");
UserSchema ehrLookupsSchema = getUserSchema(table, "ehr_lookups");
newCol.setFk(new QueryForeignKey(ehrLookupsSchema, null, "ancestry", "rowid", "value"));
newCol.setURL(StringExpressionFactory.create("query-detailsQueryRow.view?schemaName=ehr_lookups&query.queryName=source&code=${ancestry}"));
table.addColumn(newCol);
}
if (table.getColumn("birth") == null)
{
String birthColumn = "birth";
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo arrival = getRealTableForDataset(table, "arrival");
// Here we want a union of the birth and arrival tables to get the ancestry of the animal
String arrivalAndBirthUnion = "( " +
"SELECT " +
"a.birth as birth, " +
"a.participantid as participantid, " +
"a.modified as modified " +
"FROM studydataset." + arrival.getName() + " a " +
"WHERE a.birth is not null and a.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"UNION ALL " +
"SELECT " +
"b.date as birth," +
"b.participantid as participantid, " +
"b.modified as modified " +
"FROM studydataset." + birth.getName() + " b " +
"WHERE b.date is not null and b.participantid=" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
")";
String theQuery = "(" +
"SELECT birth FROM " + arrivalAndBirthUnion + " w ORDER BY w.modified DESC LIMIT 1" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, birthColumn, sql, JdbcType.DATE);
newCol.setLabel("Birth");
newCol.setDescription("Returns the animal's birth date.");
//newCol.setURL(StringExpressionFactory.create("query-executeQuery.view?schemaName=study&query.queryName=Birth&query.Id~eq={id}"));
table.addColumn(newCol);
}
if (table.getColumn("vendor_id") == null)
{
String vendorIdColumn = "vendor_id";
TableInfo arrival = getRealTableForDataset(table, "arrival");
String theQuery = "(" +
"SELECT vendor_id FROM studydataset." + arrival.getName() + " w where w.participantid="
+ ExprColumn.STR_TABLE_ALIAS + ".participantid and w.vendor_id is not null LIMIT 1" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, vendorIdColumn, sql, JdbcType.VARCHAR);
newCol.setLabel("Vendor ID");
newCol.setDescription("Returns the animal's original vendor id.");
table.addColumn(newCol);
}
if (table.getColumn("sire") == null)
{
String sire_new = "sire";
TableInfo arrival = getRealTableForDataset(table, "arrival");
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo demographics = getRealTableForDataset(table, "demographics");
// Here we want a union of the birth and arrival tables to get the sire of the animal,
// if none found, we fall back on the "old" data in the demographic table
String arrivalAndBirthQuery = "( " +
"SELECT " +
"COALESCE ( " +
"(SELECT " +
"a.participantid as sire " +
"FROM " +
"studydataset." + arrival.getName() + " a, studydataset." + arrival.getName() + " b " +
" WHERE " +
" b.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND a.vendor_id = b.sire AND a.vendor_id != a.participantid " +
"ORDER BY " +
"b.modified DESC " +
"LIMIT 1), " +
"(SELECT " +
"sire " +
"FROM " +
"studydataset." + arrival.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"ORDER BY " +
"modified DESC " +
"LIMIT 1), " +
"(SELECT " +
"sire " +
"FROM " +
"studydataset." + birth.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"ORDER BY " +
"modified DESC" +
" LIMIT 1), " +
"(SELECT " +
"sire_old " +
"FROM " +
"studydataset." + demographics.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
" LIMIT 1) " +
") AS sire " +
")";
SQLFragment sql = new SQLFragment(arrivalAndBirthQuery);
ExprColumn newCol = new ExprColumn(table, sire_new, sql, JdbcType.VARCHAR);
newCol.setLabel("Sire");
newCol.setDescription("Returns the animal's updated sire id");
table.addColumn(newCol);
}
if (table.getColumn("dam") == null)
{
String dam_new = "dam";
TableInfo arrival = getRealTableForDataset(table, "arrival");
TableInfo birth = getRealTableForDataset(table, "birth");
TableInfo demographics = getRealTableForDataset(table, "demographics");
// Here we want a union of the birth and arrival tables to get the dam of the animal
// if none found, we fall back on the "old" data in the demographic table
String arrivalAndBirthQuery = "( " +
"SELECT " +
"COALESCE ( " +
"(SELECT " +
"a.participantid as dam " +
"FROM " +
"studydataset." + arrival.getName() + " a, studydataset." + arrival.getName() + " b " +
" WHERE " +
" b.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND a.vendor_id = b.dam AND a.vendor_id != a.participantid " +
"ORDER BY " +
"b.modified DESC " +
"LIMIT 1), " +
"(SELECT " +
"dam " +
"FROM " +
"studydataset." + arrival.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"ORDER BY " +
"modified DESC " +
"LIMIT 1), " +
"(SELECT " +
"dam " +
"FROM " +
"studydataset." + birth.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
"ORDER BY " +
"modified DESC" +
" LIMIT 1), " +
"(SELECT " +
"dam_old " +
"FROM " +
"studydataset." + demographics.getName() +
" WHERE " +
"participantid =" + ExprColumn.STR_TABLE_ALIAS + ".participantid " +
" LIMIT 1) " +
") AS dam " +
")";
SQLFragment sql = new SQLFragment(arrivalAndBirthQuery);
ExprColumn newCol = new ExprColumn(table, dam_new, sql, JdbcType.VARCHAR);
newCol.setLabel("Dam");
newCol.setDescription("Returns the animal's updated dam id");
table.addColumn(newCol);
}
}
private TableInfo getRealTableForDataset(AbstractTableInfo ti, String name)
{
Container ehrContainer = EHRService.get().getEHRStudyContainer(ti.getUserSchema().getContainer());
if (ehrContainer == null)
return null;
Dataset ds;
Study s = StudyService.get().getStudy(ehrContainer);
if (s == null)
return null;
ds = s.getDatasetByName(name);
if (ds == null)
{
// NOTE: this seems to happen during study import on TeamCity. It does not seem to happen during normal operation
_log.info("A dataset was requested that does not exist: " + name + " in container: " + ehrContainer.getPath());
StringBuilder sb = new StringBuilder();
for (Dataset d : s.getDatasets())
{
sb.append(d.getName() + ", ");
}
_log.info("datasets present: " + sb.toString());
return null;
}
else
{
return StorageProvisioner.createTableInfo(ds.getDomain());
}
}
private void customizeProtocolTable(AbstractTableInfo table)
{
BaseColumnInfo protocolCol = (BaseColumnInfo) table.getColumn("protocol");
if (protocolCol != null && table.getColumn("pdf") == null)
{
var col = table.addColumn(new WrappedColumn(protocolCol, "pdf"));
col.setLabel("PDF");
col.setURL(StringExpressionFactory.create("/query/WNPRC/WNPRC_Units/Animal_Services/Compliance_Training/Private/Protocol_PDFs/executeQuery.view?schemaName=lists&query.queryName=ProtocolPDFs&query.protocol~eq=${pdf}", true));
}
if (table.getColumn("totalProjects") == null)
{
UserSchema us = getUserSchema(table, "ehr");
if (us != null)
{
var col2 = table.addColumn(new WrappedColumn(protocolCol, "totalProjects"));
col2.setLabel("Total Projects");
col2.setUserEditable(false);
col2.setIsUnselectable(true);
col2.setFk(QueryForeignKey.from(us, table.getContainerFilter())
.table("protocolTotalProjects")
.key("protocol")
.display("protocol"));
}
}
//TODO: Make this work with an Ext UI that does not over write the values
/* ColumnInfo contactsColumn = table.getColumn("contacts");
contactsColumn.setDisplayColumnFactory(new DisplayColumnFactory()
{
@Override
public DisplayColumn createRenderer(ColumnInfo colInfo)
{
return new ContactsColumn(colInfo);
}
});*/
if (table.getColumn("expirationDate") == null)
{
UserSchema us = getUserSchema(table, "ehr");
if (us != null)
{
BaseColumnInfo col2 = (BaseColumnInfo) table.addColumn(new WrappedColumn(protocolCol, "expirationDate"));
col2.setLabel("Expiration Date");
col2.setUserEditable(false);
col2.setIsUnselectable(true);
col2.setFk(new QueryForeignKey(us, null, "protocolExpirationDate", "protocol", "protocol"));
}
}
if (table.getColumn("countsBySpecies") == null)
{
UserSchema us = getUserSchema(table, "ehr");
if (us != null)
{
BaseColumnInfo col2 = (BaseColumnInfo) table.addColumn(new WrappedColumn(protocolCol, "countsBySpecies"));
col2.setLabel("Max Animals Per Species");
col2.setUserEditable(false);
col2.setIsUnselectable(true);
col2.setFk(new QueryForeignKey(us, null, "protocolCountsBySpecies", "protocol", "protocol"));
}
}
}
private void customizeBreedingEncountersTable(AbstractTableInfo ti)
{
customizeSireIdColumn(ti);
}
private void customizePregnanciesTable(AbstractTableInfo ti) {
customizeSireIdColumn(ti);
}
private void customizeHousingTable(AbstractTableInfo ti) {
customizeReasonForMoveColumn(ti);
}
private void customizeSireIdColumn(AbstractTableInfo ti) {
BaseColumnInfo sireid = (BaseColumnInfo) ti.getColumn("sireid");
if (sireid != null)
{
UserSchema us = getUserSchema(ti, "study");
if (us != null)
{
sireid.setDisplayColumnFactory(colInfo -> new DataColumn(colInfo){
@Override
public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException
{
ActionURL url = new ActionURL("ehr", "participantView.view", us.getContainer());
String joinedIds = (String)ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "sireid"));
if (joinedIds != null)
{
String[] ids = joinedIds.split(",");
String urlString = "";
for (int i = 0; i < ids.length; i++)
{
String id = ids[i];
url.replaceParameter("participantId", id);
urlString += "<a href=\"" + PageFlowUtil.filter(url) + "\">";
urlString += PageFlowUtil.filter(id);
urlString += "</a>";
if (i + 1 < ids.length)
{
urlString += ", ";
}
}
out.write(urlString);
}
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
return ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "sireid"));
}
});
}
}
}
private void customizeReasonForMoveColumn(AbstractTableInfo ti) {
BaseColumnInfo reason = (BaseColumnInfo)ti.getColumn("reason");
if (reason != null)
{
UserSchema us = getUserSchema(ti, "study");
if (us != null)
{
reason.setDisplayColumnFactory(colInfo -> new DataColumn(colInfo){
@Override
public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException
{
ActionURL url = new ActionURL("query", "recordDetails.view", us.getContainer());
String joinedReasons = (String)ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "reason"));
if (joinedReasons != null)
{
String[] reasons = joinedReasons.split(",");
url.addParameter("schemaName", "ehr_lookups");
url.addParameter("query.queryName", "housing_reason");
url.addParameter("keyField", "value");
StringBuilder urlString = new StringBuilder();
for (int i = 0; i < reasons.length; i++)
{
String reasonForMoveValue = reasons[i];
SimplerFilter filter = new SimplerFilter("set_name", CompareType.EQUAL, "housing_reason").addCondition("value", CompareType.EQUAL, reasonForMoveValue);
DbSchema schema = DbSchema.get("ehr_lookups", DbSchemaType.Module);
TableInfo ti = schema.getTable("lookups");
TableSelector ts = new TableSelector(ti, filter, null);
String reasonForMoveTitle;
if (ts.getMap() != null && ts.getMap().get("title") != null)
{
reasonForMoveTitle = (String) ts.getMap().get("title");
url.replaceParameter("key", reasonForMoveValue);
urlString.append("<a href=\"").append(PageFlowUtil.filter(url)).append("\">");
urlString.append(PageFlowUtil.filter(reasonForMoveTitle));
urlString.append("</a>");
}
else
{
urlString.append(PageFlowUtil.filter("<" + reasonForMoveValue + ">"));
}
if (i + 1 < reasons.length)
{
urlString.append(", ");
}
}
out.write(urlString.toString());
}
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
return ctx.get(new FieldKey(getBoundColumn().getFieldKey().getParent(), "reason"));
}
});
}
}
}
public static class AnimalIdsToOfferColumn extends DataColumn {
public AnimalIdsToOfferColumn(ColumnInfo colInfo) {
super(colInfo);
}
@Override
public Object getValue(RenderContext ctx) {
return super.getValue(ctx);
}
}
public static class AnimalIdsToOfferColumnQCStateConditional extends DataColumn {
private User _currentUser;
public AnimalIdsToOfferColumnQCStateConditional(ColumnInfo colInfo, User currentUser) {
super(colInfo);
_currentUser = currentUser;
}
@Override
public void renderGridCellContents(RenderContext ctx, Writer out) throws IOException
{
if ("Request: Pending".equals(ctx.get("QCState$Label")))
{
out.write("");
}
else if (_currentUser.getUserId() == (Integer) ctx.get("createdBy"))
{
super.renderGridCellContents(ctx, out);
}
else
{
out.write("");
}
}
}
public static class AnimalRequestsEditLinkConditional extends DataColumn
{
private User _currentUser;
public AnimalRequestsEditLinkConditional(ColumnInfo colInfo, User currentUser)
{
super(colInfo);
_currentUser = currentUser;
}
@Override
public HtmlString getFormattedHtml(RenderContext ctx)
{
String edit;
if (_currentUser.getUserId() == (Integer) ctx.get("createdBy"))
{
edit = "<a class='fa fa-pencil lk-dr-action-icon' style='opacity: 1' href='" +
ctx.getViewContext().getContextPath() +
"/ehr/WNPRC/EHR/manageRecord.view?schemaName=wnprc&queryName=animal_requests&title=Animal%20Request&keyField=rowid&key=" +
ctx.get("rowid").toString() +
"&update=1&returnUrl=" +
ctx.getViewContext().getContextPath() +
"%2Fwnprc_ehr%2FWNPRC%2FEHR%2FdataEntry.view%3F'></a>";
}
else {
edit = "";
}
return HtmlString.unsafe(edit);
}
}
public static class AnimalRequestsEditLinkShow extends DataColumn {
public AnimalRequestsEditLinkShow(ColumnInfo colInfo) {
super(colInfo);
}
@Override
public HtmlString getFormattedHtml(RenderContext ctx)
{
String edit;
edit = "<a class='fa fa-pencil lk-dr-action-icon' style='opacity: 1' href='" +
ctx.getViewContext().getContextPath() +
"/ehr/WNPRC/EHR/manageRecord.view?schemaName=wnprc&queryName=animal_requests&title=Animal%20Request&keyField=rowid&key=" +
ctx.get("rowid").toString() +
"&update=1&returnUrl=" +
ctx.getViewContext().getContextPath() +
"%2Fwnprc_ehr%2FWNPRC%2FEHR%2FdataEntry.view%3F'></a>";
return HtmlString.unsafe(edit);
}
}
public static class AnimalReportLink extends DataColumn {
public AnimalReportLink(ColumnInfo colInfo) {
super(colInfo);
}
@Override
public Object getValue(RenderContext ctx) {
return super.getValue(ctx);
}
}
public static class AnimalReportLinkQCStateConditional extends DataColumn {
private User _currentUser;
public AnimalReportLinkQCStateConditional(ColumnInfo colInfo, User currentUser) {
super(colInfo);
_currentUser = currentUser;
}
@Override
public Object getValue(RenderContext ctx)
{
if ("Request: Pending".equals(ctx.get("QCState$Label")))
{
return "";
}
else if (_currentUser.getUserId() == (Integer) ctx.get("createdBy"))
{
return super.getValue(ctx);
}
else
{
return "";
}
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
if ("Request: Pending".equals(ctx.get("QCState$Label")))
{
return "";
}
else if (_currentUser.getUserId() == (Integer) ctx.get("createdBy"))
{
return super.getDisplayValue(ctx);
}
else
{
return "";
}
}
@Override
public HtmlString getFormattedHtml(RenderContext ctx)
{
HtmlStringBuilder emptyString = HtmlStringBuilder.of();
if ("Request: Pending".equals(ctx.get("QCState$Label")))
{
return emptyString.getHtmlString();
}
else if (_currentUser.getUserId() == (Integer) ctx.get("createdBy"))
{
return super.getFormattedHtml(ctx);
}
else
{
return emptyString.getHtmlString();
}
}
}
private void customizeAnimalRequestsTable(AbstractTableInfo table)
{
UserSchema us = getStudyUserSchema(table);
if (us == null)
{
return;
}
User currentUser = us.getUser();
//Nail down individual fields for editing, unless user has permission
List<String> readOnlyFields = new ArrayList<>();
readOnlyFields.add("QCState");
readOnlyFields.add("dateapprovedordenied");
readOnlyFields.add("animalsorigin");
readOnlyFields.add("dateordered");
readOnlyFields.add("datearrival");
for (String item : readOnlyFields)
{
if (table.getColumn(item) != null)
{
BaseColumnInfo col = (BaseColumnInfo) table.getColumn(item);
if (!us.getContainer().hasPermission(currentUser, WNPRCAnimalRequestsEditPermission.class) && !us.getContainer().hasPermission(currentUser, AdminPermission.class))
{
col.setReadOnly(true);
}
}
}
if (table.getColumn("edit") == null){
String edit = "edit";
String theQuery = "( " +
"(SELECT 'edit')" +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, edit, sql, JdbcType.VARCHAR);
table.addColumn(newCol);
newCol.setDisplayColumnFactory(new DisplayColumnFactory()
{
@Override
public DisplayColumn createRenderer(ColumnInfo colInfo)
{
if (us.getContainer().hasPermission(currentUser, WNPRCAnimalRequestsEditPermission.class) || us.getContainer().hasPermission(currentUser, AdminPermission.class))
{
return new AnimalRequestsEditLinkShow(colInfo);
}
else
{
return new AnimalRequestsEditLinkConditional(colInfo, currentUser);
}
}
});
}
//re-render animalidsoffer column
if (table.getColumn("animalidstooffer") != null)
{
BaseColumnInfo col = (BaseColumnInfo) table.getColumn("animalidstooffer");
col.setLabel("Animal Ids");
if (us.getContainer().hasPermission(currentUser, WNPRCAnimalRequestsViewPermission.class) || us.getContainer().hasPermission(currentUser, AdminPermission.class)){
col.setDisplayColumnFactory(colInfo -> new AnimalIdsToOfferColumn(colInfo));
}
else{
col.setHidden(true);
col.setDisplayColumnFactory(colInfo -> new AnimalIdsToOfferColumnQCStateConditional(colInfo, currentUser));
}
}
//create animal history report link from a set of animal ids
if (table.getColumn("animal_history_link") == null)
{
String animal_history_link = "animal_history_link";
String theQuery = "( " +
"(SELECT " +
" CASE WHEN a.animalidstooffer is not null " +
"THEN 'Report Link' " +
"ELSE '' " +
" END AS animal_history_link " +
" FROM wnprc.animal_requests a " +
"WHERE a.rowid=" + ExprColumn.STR_TABLE_ALIAS + ".rowid LIMIT 1) " +
")";
SQLFragment sql = new SQLFragment(theQuery);
ExprColumn newCol = new ExprColumn(table, animal_history_link, sql, JdbcType.VARCHAR);
newCol.setLabel("Animal History Link");
newCol.setDescription("Provides a link to the animal history records given the animal ids that were selected.");
newCol.setURL(StringExpressionFactory.create("ehr-animalHistory.view?#subjects:${animalidstooffer}&inputType:multiSubject&showReport:0&activeReport:abstractReport"));
table.addColumn(newCol);
newCol.setDisplayColumnFactory(new DisplayColumnFactory()
{
@Override
public DisplayColumn createRenderer(ColumnInfo colInfo)
{
if (us.getContainer().hasPermission(currentUser, WNPRCAnimalRequestsViewPermission.class) || us.getContainer().hasPermission(currentUser, AdminPermission.class))
{
return new AnimalReportLink(colInfo);
}
else
{
return new AnimalReportLinkQCStateConditional(colInfo, currentUser);
}
}
});
}
}
private BaseColumnInfo getWrappedIdCol(UserSchema us, AbstractTableInfo ds, String name, String queryName)
{
String ID_COL = "Id";
WrappedColumn col = new WrappedColumn(ds.getColumn(ID_COL), name);
col.setReadOnly(true);
col.setIsUnselectable(true);
col.setUserEditable(false);
col.setFk(QueryForeignKey.from(us, ds.getContainerFilter())
.table(queryName)
.key(ID_COL)
.display(ID_COL));
return col;
}
private UserSchema getStudyUserSchema(AbstractTableInfo ds)
{
return getUserSchema(ds, "study");
}
@Override
public UserSchema getUserSchema(AbstractTableInfo ds, String name)
{
UserSchema us = ds.getUserSchema();
if (us != null)
{
if (name.equalsIgnoreCase(us.getName()))
return us;
return QueryService.get().getUserSchema(us.getUser(), us.getContainer(), name);
}
return null;
}
//TODO: Look how to use another UI to allow for better support for virtual columns
/* public static class ContactsColumn extends DataColumn
{
public ContactsColumn(ColumnInfo colInfo)
{
super(colInfo);
}
@Override
public Object getValue(RenderContext ctx)
{
Object value = super.getValue(ctx);
StringBuffer readableContacts = new StringBuffer();
if(value != null)
{
//TODO:parse the value into integers to display users
String contacts = value.toString();
if (contacts.contains(","))
{
List<String> contactList = new ArrayList<>(Arrays.asList(contacts.split(",")));
Iterator<String> contactsIterator = contactList.iterator();
while (contactsIterator.hasNext())
{
User singleContact = UserManager.getUser(Integer.parseInt(contactsIterator.next()));
readableContacts.append(singleContact.getDisplayName(singleContact));
readableContacts.append(" ");
System.out.println("readable contact "+readableContacts);
}
return readableContacts;
}
if (NumberUtils.isNumber(contacts)){
User singleContact = UserManager.getUser(Integer.parseInt(contacts));
readableContacts.append(singleContact.getDisplayName(singleContact));
return readableContacts;
}
}
return readableContacts;
}
@Override
public Object getDisplayValue(RenderContext ctx)
{
return getValue(ctx);
}
@Override
public String getFormattedValue(RenderContext ctx)
{
return h(getValue(ctx));
}
}*/
private boolean isExt4Form(String schemaName, String queryName)
{
boolean isExt4Form = false;
SimplerFilter filter = new SimplerFilter("schemaname", CompareType.EQUAL, schemaName).addCondition("queryname", CompareType.EQUAL, queryName);
//TableInfo ti = DbSchema.get("ehr", DbSchemaType.Module).getTable(EHRSchema.TABLE_FORM_FRAMEWORK_TYPES);
TableInfo ti = DbSchema.get("ehr", DbSchemaType.Module).getTable("form_framework_types");
TableSelector ts = new TableSelector(ti, filter, null);
String framework;
if (ts.getMap() != null && ts.getMap().get("framework") != null)
{
framework = (String) ts.getMap().get("framework");
if ("extjs4".equalsIgnoreCase(framework)) {
isExt4Form = true;
}
}
return isExt4Form;
}
}
| Make the vendor id swap case insensitive
| WNPRC_EHR/src/org/labkey/wnprc_ehr/table/WNPRC_EHRCustomizer.java | Make the vendor id swap case insensitive | <ide><path>NPRC_EHR/src/org/labkey/wnprc_ehr/table/WNPRC_EHRCustomizer.java
<ide> "FROM " +
<ide> "studydataset." + arrival.getName() + " a, studydataset." + arrival.getName() + " b " +
<ide> " WHERE " +
<del> " b.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND a.vendor_id = b.sire AND a.vendor_id != a.participantid " +
<add> " b.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND lower(a.vendor_id) = lower(b.sire) AND lower(a.vendor_id) != lower(a.participantid) " +
<ide> "ORDER BY " +
<ide> "b.modified DESC " +
<ide> "LIMIT 1), " +
<ide> "FROM " +
<ide> "studydataset." + arrival.getName() + " a, studydataset." + arrival.getName() + " b " +
<ide> " WHERE " +
<del> " b.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND a.vendor_id = b.dam AND a.vendor_id != a.participantid " +
<add> " b.participantid = " + ExprColumn.STR_TABLE_ALIAS + ".participantid AND lower(a.vendor_id) = lower(b.dam) AND lower(a.vendor_id) != lower(a.participantid) " +
<ide> "ORDER BY " +
<ide> "b.modified DESC " +
<ide> "LIMIT 1), " + |
|
Java | apache-2.0 | 26ccbc49beea5bc3b07232fcb432d91ea5e733fa | 0 | HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.rsgroup;
import static org.apache.hadoop.hbase.AuthUtil.toGroupEntry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.security.access.AccessControlClient;
import org.apache.hadoop.hbase.security.access.AccessControlLists;
import org.apache.hadoop.hbase.security.access.Permission;
import org.apache.hadoop.hbase.security.access.SecureTestUtil;
import org.apache.hadoop.hbase.security.access.TableAuthManager;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.testclassification.SecurityTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Performs authorization checks for rsgroup operations, according to different
* levels of authorized users.
*/
@Category({SecurityTests.class, MediumTests.class})
public class TestRSGroupsWithACL extends SecureTestUtil{
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestRSGroupsWithACL.class);
private static final Logger LOG = LoggerFactory.getLogger(TestRSGroupsWithACL.class);
private static TableName TEST_TABLE = TableName.valueOf("testtable1");
private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private static Configuration conf;
private static Connection systemUserConnection;
// user with all permissions
private static User SUPERUSER;
// user granted with all global permission
private static User USER_ADMIN;
// user with rw permissions on column family.
private static User USER_RW;
// user with read-only permissions
private static User USER_RO;
// user is table owner. will have all permissions on table
private static User USER_OWNER;
// user with create table permissions alone
private static User USER_CREATE;
// user with no permissions
private static User USER_NONE;
private static final String GROUP_ADMIN = "group_admin";
private static final String GROUP_CREATE = "group_create";
private static final String GROUP_READ = "group_read";
private static final String GROUP_WRITE = "group_write";
private static User USER_GROUP_ADMIN;
private static User USER_GROUP_CREATE;
private static User USER_GROUP_READ;
private static User USER_GROUP_WRITE;
private static byte[] TEST_FAMILY = Bytes.toBytes("f1");
private static RSGroupAdminEndpoint rsGroupAdminEndpoint;
@BeforeClass
public static void setupBeforeClass() throws Exception {
// setup configuration
conf = TEST_UTIL.getConfiguration();
conf.set(HConstants.HBASE_MASTER_LOADBALANCER_CLASS,
RSGroupBasedLoadBalancer.class.getName());
// Enable security
enableSecurity(conf);
// Verify enableSecurity sets up what we require
verifyConfiguration(conf);
// Enable rsgroup
configureRSGroupAdminEndpoint(conf);
TEST_UTIL.startMiniCluster();
rsGroupAdminEndpoint = (RSGroupAdminEndpoint) TEST_UTIL.getMiniHBaseCluster().getMaster().
getMasterCoprocessorHost().findCoprocessor(RSGroupAdminEndpoint.class.getName());
// Wait for the ACL table to become available
TEST_UTIL.waitUntilAllRegionsAssigned(AccessControlLists.ACL_TABLE_NAME);
// create a set of test users
SUPERUSER = User.createUserForTesting(conf, "admin", new String[] { "supergroup" });
USER_ADMIN = User.createUserForTesting(conf, "admin2", new String[0]);
USER_RW = User.createUserForTesting(conf, "rwuser", new String[0]);
USER_RO = User.createUserForTesting(conf, "rouser", new String[0]);
USER_OWNER = User.createUserForTesting(conf, "owner", new String[0]);
USER_CREATE = User.createUserForTesting(conf, "tbl_create", new String[0]);
USER_NONE = User.createUserForTesting(conf, "nouser", new String[0]);
USER_GROUP_ADMIN =
User.createUserForTesting(conf, "user_group_admin", new String[] { GROUP_ADMIN });
USER_GROUP_CREATE =
User.createUserForTesting(conf, "user_group_create", new String[] { GROUP_CREATE });
USER_GROUP_READ =
User.createUserForTesting(conf, "user_group_read", new String[] { GROUP_READ });
USER_GROUP_WRITE =
User.createUserForTesting(conf, "user_group_write", new String[] { GROUP_WRITE });
systemUserConnection = TEST_UTIL.getConnection();
setUpTableAndUserPermissions();
}
private static void setUpTableAndUserPermissions() throws Exception {
TableDescriptorBuilder tableBuilder = TableDescriptorBuilder.newBuilder(TEST_TABLE);
ColumnFamilyDescriptorBuilder cfd = ColumnFamilyDescriptorBuilder.newBuilder(TEST_FAMILY);
cfd.setMaxVersions(100);
tableBuilder.addColumnFamily(cfd.build());
tableBuilder.setValue(TableDescriptorBuilder.OWNER, USER_OWNER.getShortName());
createTable(TEST_UTIL, tableBuilder.build(),
new byte[][] { Bytes.toBytes("s") });
// Set up initial grants
grantGlobal(TEST_UTIL, USER_ADMIN.getShortName(),
Permission.Action.ADMIN,
Permission.Action.CREATE,
Permission.Action.READ,
Permission.Action.WRITE);
grantOnTable(TEST_UTIL, USER_RW.getShortName(),
TEST_TABLE, TEST_FAMILY, null,
Permission.Action.READ,
Permission.Action.WRITE);
// USER_CREATE is USER_RW plus CREATE permissions
grantOnTable(TEST_UTIL, USER_CREATE.getShortName(),
TEST_TABLE, null, null,
Permission.Action.CREATE,
Permission.Action.READ,
Permission.Action.WRITE);
grantOnTable(TEST_UTIL, USER_RO.getShortName(),
TEST_TABLE, TEST_FAMILY, null,
Permission.Action.READ);
grantGlobal(TEST_UTIL, toGroupEntry(GROUP_ADMIN), Permission.Action.ADMIN);
grantGlobal(TEST_UTIL, toGroupEntry(GROUP_CREATE), Permission.Action.CREATE);
grantGlobal(TEST_UTIL, toGroupEntry(GROUP_READ), Permission.Action.READ);
grantGlobal(TEST_UTIL, toGroupEntry(GROUP_WRITE), Permission.Action.WRITE);
assertEquals(4, AccessControlLists.getTablePermissions(conf, TEST_TABLE).size());
try {
assertEquals(4, AccessControlClient.getUserPermissions(systemUserConnection,
TEST_TABLE.toString()).size());
} catch (Throwable e) {
LOG.error("error during call of AccessControlClient.getUserPermissions. ", e);
fail("error during call of AccessControlClient.getUserPermissions.");
}
}
private static void cleanUp() throws Exception {
// Clean the _acl_ table
try {
deleteTable(TEST_UTIL, TEST_TABLE);
} catch (TableNotFoundException ex) {
// Test deleted the table, no problem
LOG.info("Test deleted table " + TEST_TABLE);
}
// Verify all table/namespace permissions are erased
assertEquals(0, AccessControlLists.getTablePermissions(conf, TEST_TABLE).size());
assertEquals(0, AccessControlLists.getNamespacePermissions(conf,
TEST_TABLE.getNamespaceAsString()).size());
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
cleanUp();
TEST_UTIL.shutdownMiniCluster();
int total = TableAuthManager.getTotalRefCount();
assertTrue("Unexpected reference count: " + total, total == 0);
}
private static void configureRSGroupAdminEndpoint(Configuration conf) {
String currentCoprocessors = conf.get(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY);
String coprocessors = RSGroupAdminEndpoint.class.getName();
if (currentCoprocessors != null) {
coprocessors += "," + currentCoprocessors;
}
conf.set(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, coprocessors);
conf.set(HConstants.HBASE_MASTER_LOADBALANCER_CLASS,
RSGroupBasedLoadBalancer.class.getName());
}
@Test
public void testGetRSGroupInfo() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("getRSGroupInfo");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testGetRSGroupInfoOfTable() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("getRSGroupInfoOfTable");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testMoveServers() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("moveServers");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testMoveTables() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("moveTables");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testAddRSGroup() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("addRSGroup");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testRemoveRSGroup() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("removeRSGroup");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testBalanceRSGroup() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("balanceRSGroup");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testListRSGroup() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("listRSGroup");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testGetRSGroupInfoOfServer() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("getRSGroupInfoOfServer");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testMoveServersAndTables() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("moveServersAndTables");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
}
| hbase-rsgroup/src/test/java/org/apache/hadoop/hbase/rsgroup/TestRSGroupsWithACL.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.hadoop.hbase.rsgroup;
import static org.apache.hadoop.hbase.AuthUtil.toGroupEntry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.security.access.AccessControlClient;
import org.apache.hadoop.hbase.security.access.AccessControlLists;
import org.apache.hadoop.hbase.security.access.Permission;
import org.apache.hadoop.hbase.security.access.SecureTestUtil;
import org.apache.hadoop.hbase.security.access.TableAuthManager;
import org.apache.hadoop.hbase.testclassification.SecurityTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Performs authorization checks for rsgroup operations, according to different
* levels of authorized users.
*/
@Category({SecurityTests.class})
public class TestRSGroupsWithACL extends SecureTestUtil{
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestRSGroupsWithACL.class);
private static final Logger LOG = LoggerFactory.getLogger(TestRSGroupsWithACL.class);
private static TableName TEST_TABLE = TableName.valueOf("testtable1");
private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private static Configuration conf;
private static Connection systemUserConnection;
// user with all permissions
private static User SUPERUSER;
// user granted with all global permission
private static User USER_ADMIN;
// user with rw permissions on column family.
private static User USER_RW;
// user with read-only permissions
private static User USER_RO;
// user is table owner. will have all permissions on table
private static User USER_OWNER;
// user with create table permissions alone
private static User USER_CREATE;
// user with no permissions
private static User USER_NONE;
private static final String GROUP_ADMIN = "group_admin";
private static final String GROUP_CREATE = "group_create";
private static final String GROUP_READ = "group_read";
private static final String GROUP_WRITE = "group_write";
private static User USER_GROUP_ADMIN;
private static User USER_GROUP_CREATE;
private static User USER_GROUP_READ;
private static User USER_GROUP_WRITE;
private static byte[] TEST_FAMILY = Bytes.toBytes("f1");
private static RSGroupAdminEndpoint rsGroupAdminEndpoint;
@BeforeClass
public static void setupBeforeClass() throws Exception {
// setup configuration
conf = TEST_UTIL.getConfiguration();
conf.set(HConstants.HBASE_MASTER_LOADBALANCER_CLASS,
RSGroupBasedLoadBalancer.class.getName());
// Enable security
enableSecurity(conf);
// Verify enableSecurity sets up what we require
verifyConfiguration(conf);
// Enable rsgroup
configureRSGroupAdminEndpoint(conf);
TEST_UTIL.startMiniCluster();
rsGroupAdminEndpoint = (RSGroupAdminEndpoint) TEST_UTIL.getMiniHBaseCluster().getMaster().
getMasterCoprocessorHost().findCoprocessor(RSGroupAdminEndpoint.class.getName());
// Wait for the ACL table to become available
TEST_UTIL.waitUntilAllRegionsAssigned(AccessControlLists.ACL_TABLE_NAME);
// create a set of test users
SUPERUSER = User.createUserForTesting(conf, "admin", new String[] { "supergroup" });
USER_ADMIN = User.createUserForTesting(conf, "admin2", new String[0]);
USER_RW = User.createUserForTesting(conf, "rwuser", new String[0]);
USER_RO = User.createUserForTesting(conf, "rouser", new String[0]);
USER_OWNER = User.createUserForTesting(conf, "owner", new String[0]);
USER_CREATE = User.createUserForTesting(conf, "tbl_create", new String[0]);
USER_NONE = User.createUserForTesting(conf, "nouser", new String[0]);
USER_GROUP_ADMIN =
User.createUserForTesting(conf, "user_group_admin", new String[] { GROUP_ADMIN });
USER_GROUP_CREATE =
User.createUserForTesting(conf, "user_group_create", new String[] { GROUP_CREATE });
USER_GROUP_READ =
User.createUserForTesting(conf, "user_group_read", new String[] { GROUP_READ });
USER_GROUP_WRITE =
User.createUserForTesting(conf, "user_group_write", new String[] { GROUP_WRITE });
systemUserConnection = TEST_UTIL.getConnection();
setUpTableAndUserPermissions();
}
private static void setUpTableAndUserPermissions() throws Exception {
TableDescriptorBuilder tableBuilder = TableDescriptorBuilder.newBuilder(TEST_TABLE);
ColumnFamilyDescriptorBuilder cfd = ColumnFamilyDescriptorBuilder.newBuilder(TEST_FAMILY);
cfd.setMaxVersions(100);
tableBuilder.addColumnFamily(cfd.build());
tableBuilder.setValue(TableDescriptorBuilder.OWNER, USER_OWNER.getShortName());
createTable(TEST_UTIL, tableBuilder.build(),
new byte[][] { Bytes.toBytes("s") });
// Set up initial grants
grantGlobal(TEST_UTIL, USER_ADMIN.getShortName(),
Permission.Action.ADMIN,
Permission.Action.CREATE,
Permission.Action.READ,
Permission.Action.WRITE);
grantOnTable(TEST_UTIL, USER_RW.getShortName(),
TEST_TABLE, TEST_FAMILY, null,
Permission.Action.READ,
Permission.Action.WRITE);
// USER_CREATE is USER_RW plus CREATE permissions
grantOnTable(TEST_UTIL, USER_CREATE.getShortName(),
TEST_TABLE, null, null,
Permission.Action.CREATE,
Permission.Action.READ,
Permission.Action.WRITE);
grantOnTable(TEST_UTIL, USER_RO.getShortName(),
TEST_TABLE, TEST_FAMILY, null,
Permission.Action.READ);
grantGlobal(TEST_UTIL, toGroupEntry(GROUP_ADMIN), Permission.Action.ADMIN);
grantGlobal(TEST_UTIL, toGroupEntry(GROUP_CREATE), Permission.Action.CREATE);
grantGlobal(TEST_UTIL, toGroupEntry(GROUP_READ), Permission.Action.READ);
grantGlobal(TEST_UTIL, toGroupEntry(GROUP_WRITE), Permission.Action.WRITE);
assertEquals(4, AccessControlLists.getTablePermissions(conf, TEST_TABLE).size());
try {
assertEquals(4, AccessControlClient.getUserPermissions(systemUserConnection,
TEST_TABLE.toString()).size());
} catch (Throwable e) {
LOG.error("error during call of AccessControlClient.getUserPermissions. ", e);
fail("error during call of AccessControlClient.getUserPermissions.");
}
}
private static void cleanUp() throws Exception {
// Clean the _acl_ table
try {
deleteTable(TEST_UTIL, TEST_TABLE);
} catch (TableNotFoundException ex) {
// Test deleted the table, no problem
LOG.info("Test deleted table " + TEST_TABLE);
}
// Verify all table/namespace permissions are erased
assertEquals(0, AccessControlLists.getTablePermissions(conf, TEST_TABLE).size());
assertEquals(0, AccessControlLists.getNamespacePermissions(conf,
TEST_TABLE.getNamespaceAsString()).size());
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
cleanUp();
TEST_UTIL.shutdownMiniCluster();
int total = TableAuthManager.getTotalRefCount();
assertTrue("Unexpected reference count: " + total, total == 0);
}
private static void configureRSGroupAdminEndpoint(Configuration conf) {
String currentCoprocessors = conf.get(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY);
String coprocessors = RSGroupAdminEndpoint.class.getName();
if (currentCoprocessors != null) {
coprocessors += "," + currentCoprocessors;
}
conf.set(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, coprocessors);
conf.set(HConstants.HBASE_MASTER_LOADBALANCER_CLASS,
RSGroupBasedLoadBalancer.class.getName());
}
@Test
public void testGetRSGroupInfo() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("getRSGroupInfo");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testGetRSGroupInfoOfTable() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("getRSGroupInfoOfTable");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testMoveServers() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("moveServers");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testMoveTables() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("moveTables");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testAddRSGroup() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("addRSGroup");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testRemoveRSGroup() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("removeRSGroup");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testBalanceRSGroup() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("balanceRSGroup");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testListRSGroup() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("listRSGroup");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testGetRSGroupInfoOfServer() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("getRSGroupInfoOfServer");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
@Test
public void testMoveServersAndTables() throws Exception {
AccessTestAction action = () -> {
rsGroupAdminEndpoint.checkPermission("moveServersAndTables");
return null;
};
verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP_ADMIN);
verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO,
USER_NONE, USER_GROUP_READ, USER_GROUP_WRITE, USER_GROUP_CREATE);
}
}
| HBASE-19949 TestRSGroupsWithACL fails with ExceptionInInitializerError
| hbase-rsgroup/src/test/java/org/apache/hadoop/hbase/rsgroup/TestRSGroupsWithACL.java | HBASE-19949 TestRSGroupsWithACL fails with ExceptionInInitializerError | <ide><path>base-rsgroup/src/test/java/org/apache/hadoop/hbase/rsgroup/TestRSGroupsWithACL.java
<ide> import org.apache.hadoop.hbase.security.access.Permission;
<ide> import org.apache.hadoop.hbase.security.access.SecureTestUtil;
<ide> import org.apache.hadoop.hbase.security.access.TableAuthManager;
<add>import org.apache.hadoop.hbase.testclassification.MediumTests;
<ide> import org.apache.hadoop.hbase.testclassification.SecurityTests;
<ide> import org.apache.hadoop.hbase.util.Bytes;
<ide> import org.junit.AfterClass;
<ide> * Performs authorization checks for rsgroup operations, according to different
<ide> * levels of authorized users.
<ide> */
<del>@Category({SecurityTests.class})
<add>@Category({SecurityTests.class, MediumTests.class})
<ide> public class TestRSGroupsWithACL extends SecureTestUtil{
<ide>
<ide> @ClassRule |
|
Java | mit | b2b8d737a2b184afe0b14d9ce293a967f036698d | 0 | nrinaudo/scala-csv,nrinaudo/tabulate | /*
* Copyright 2016 Nicolas Rinaudo
*
* 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 kantan.csv.engine.jackson;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.SequenceWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import java.io.Reader;
import java.io.Writer;
public class JacksonCsv {
private static final CsvMapper MAPPER;
static {
MAPPER = new CsvMapper();
MAPPER.enable(com.fasterxml.jackson.dataformat.csv.CsvParser.Feature.WRAP_AS_ARRAY);
MAPPER.enable(com.fasterxml.jackson.dataformat.csv.CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING);
}
public static MappingIterator<String[]> parse(Reader reader, char separator) throws java.io.IOException {
return MAPPER.readerFor(String[].class)
.with(MAPPER.schemaFor(String[].class).withColumnSeparator(separator))
.readValues(reader);
}
public static SequenceWriter write(Writer writer, char separator) throws java.io.IOException {
return MAPPER.writer()
.with(MAPPER.schemaFor(String[].class).withColumnSeparator(separator).withLineSeparator("\r\n").withoutComments())
.writeValues(writer);
}
} | jackson/src/main/java/kantan/csv/engine/jackson/JacksonCsv.java | /*
* Copyright 2016 Nicolas Rinaudo
*
* 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 kantan.csv.engine.jackson;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.SequenceWriter;
import com.fasterxml.jackson.dataformat.csv.CsvGenerator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvParser;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
public class JacksonCsv {
private static final CsvMapper MAPPER;
static {
MAPPER = new CsvMapper();
MAPPER.enable(CsvParser.Feature.WRAP_AS_ARRAY);
MAPPER.enable(CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING);
}
public static MappingIterator<String[]> parse(Reader reader, char separator) throws IOException {
return MAPPER.readerFor(String[].class)
.with(MAPPER.schemaFor(String[].class).withColumnSeparator(separator))
.readValues(reader);
}
public static SequenceWriter write(Writer writer, char separator) throws IOException {
return MAPPER.writer()
.with(MAPPER.schemaFor(String[].class).withColumnSeparator(separator).withLineSeparator("\r\n").withoutComments())
.writeValues(writer);
}
} | Appease unidoc by using complete class names rather than relying on imports to bring them in scope.
| jackson/src/main/java/kantan/csv/engine/jackson/JacksonCsv.java | Appease unidoc by using complete class names rather than relying on imports to bring them in scope. | <ide><path>ackson/src/main/java/kantan/csv/engine/jackson/JacksonCsv.java
<ide>
<ide> import com.fasterxml.jackson.databind.MappingIterator;
<ide> import com.fasterxml.jackson.databind.SequenceWriter;
<del>import com.fasterxml.jackson.dataformat.csv.CsvGenerator;
<ide> import com.fasterxml.jackson.dataformat.csv.CsvMapper;
<del>import com.fasterxml.jackson.dataformat.csv.CsvParser;
<ide>
<del>import java.io.IOException;
<ide> import java.io.Reader;
<ide> import java.io.Writer;
<ide>
<ide>
<ide> static {
<ide> MAPPER = new CsvMapper();
<del> MAPPER.enable(CsvParser.Feature.WRAP_AS_ARRAY);
<del> MAPPER.enable(CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING);
<add> MAPPER.enable(com.fasterxml.jackson.dataformat.csv.CsvParser.Feature.WRAP_AS_ARRAY);
<add> MAPPER.enable(com.fasterxml.jackson.dataformat.csv.CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING);
<ide> }
<ide>
<del> public static MappingIterator<String[]> parse(Reader reader, char separator) throws IOException {
<add> public static MappingIterator<String[]> parse(Reader reader, char separator) throws java.io.IOException {
<ide> return MAPPER.readerFor(String[].class)
<ide> .with(MAPPER.schemaFor(String[].class).withColumnSeparator(separator))
<ide> .readValues(reader);
<ide> }
<ide>
<del> public static SequenceWriter write(Writer writer, char separator) throws IOException {
<add> public static SequenceWriter write(Writer writer, char separator) throws java.io.IOException {
<ide> return MAPPER.writer()
<ide> .with(MAPPER.schemaFor(String[].class).withColumnSeparator(separator).withLineSeparator("\r\n").withoutComments())
<ide> .writeValues(writer); |
|
Java | apache-2.0 | 37c1d067436f03347ccc7a69eada0bc5fd6a8558 | 0 | amithadke/drill,parthchandra/incubator-drill,vkorukanti/drill,norrislee/incubator-drill,yufeldman/incubator-drill,Serhii-Harnyk/drill,activitystream/drill,adeneche/incubator-drill,cwestin/incubator-drill,akumarb2010/incubator-drill,caijieming-baidu/drill,puneetjaiswal/drill,vvysotskyi/drill,mapr-demos/drill-pcap-format,rchallapalli/drill,bbevens/drill,sudheeshkatkam/drill,abhipol/drill,parthchandra/drill,bbevens/drill,jackyxhb/drill,adityakishore/drill,jaltekruse/incubator-drill,AdamPD/drill,tgrall/drill,ketfos/testdrill,sudheeshkatkam/drill,julienledem/drill,cchang738/drill,weijietong/drill,StevenMPhillips/drill,yssharma/drill,maryannxue/drill,julienledem/drill,vvysotskyi/drill,ppadma/drill,julienledem/drill,mehant/drill,homosepian/drill,maryannxue/drill,akumarb2010/incubator-drill,ssriniva123/drill,jinfengni/incubator-drill,johanwitters/drill,mehant/drill,puneetjaiswal/drill,norrislee/incubator-drill,apache/drill,caijieming-baidu/drill,abhipol/drill,vvysotskyi/drill,tshiran/drill,mapr/incubator-drill,hsuanyi/incubator-drill,adityakishore/drill,Serhii-Harnyk/drill,bitblender/drill,homosepian/drill,apache/drill,kkhatua/drill,xiaom/drill,jdownton/drill,parthchandra/drill,rchallapalli/drill,cchang738/drill,arina-ielchiieva/drill,pwong-mapr/incubator-drill,activitystream/drill,ketfos/testdrill,kingmesal/drill,tgrall/drill,squidsolutions/drill,apache/drill,yufeldman/incubator-drill,mapr-demos/drill-pcap-format,tshiran/drill,mapr/incubator-drill,cwestin/incubator-drill,sindhurirayavaram/drill,parthchandra/drill,kkhatua/drill,superbstreak/drill,kristinehahn/drill,jacques-n/drill,mapr/incubator-drill,paul-rogers/drill,Agirish/drill,cocosli/drill,tshiran/drill,tgrall/drill,bitblender/drill,ketfos/testdrill,dsbos/incubator-drill,AdamPD/drill,activitystream/drill,vdiravka/drill,cchang738/drill,vvysotskyi/drill,bbevens/drill,yssharma/drill,weijietong/drill,jinfengni/incubator-drill,Serhii-Harnyk/drill,Ben-Zvi/drill,mapr-demos/drill-pcap-format,ppadma/drill,myroch/drill,kingmesal/drill,adityakishore/drill,tshiran/drill,xiaom/drill,sohami/drill,superbstreak/drill,cchang738/drill,rchallapalli/drill,parthchandra/incubator-drill,bitblender/drill,rchallapalli/drill,mapr-demos/drill-pcap-format,paul-rogers/drill,pwong-mapr/incubator-drill,johanwitters/drill,mapr-demos/drill-pcap-format,yssharma/drill,norrislee/incubator-drill,squidsolutions/drill,parthchandra/incubator-drill,jacques-n/drill,StevenMPhillips/drill,bbevens/drill,julianhyde/drill,superbstreak/drill,jdownton/drill,ebegoli/drill,yssharma/pig-on-drill,caijieming-baidu/drill,maryannxue/drill,Serhii-Harnyk/drill,StevenMPhillips/drill,Serhii-Harnyk/drill,santoshsahoo/drill,vvysotskyi/drill,akumarb2010/incubator-drill,weijietong/drill,santoshsahoo/drill,paul-rogers/drill,hnfgns/incubator-drill,Agirish/drill,amithadke/drill,xiaom/drill,zzy6395/drill,sindhurirayavaram/drill,johnnywale/drill,yssharma/drill,julienledem/drill,cwestin/incubator-drill,StevenMPhillips/drill,myroch/drill,puneetjaiswal/drill,santoshsahoo/drill,bitblender/drill,weijietong/drill,tgrall/drill,ppadma/drill,ppadma/drill,nagix/drill,vkorukanti/drill,apache/drill,vdiravka/drill,yssharma/pig-on-drill,jinfengni/incubator-drill,tgrall/drill,julianhyde/drill,johnnywale/drill,arina-ielchiieva/drill,nagix/drill,pwong-mapr/incubator-drill,abhipol/drill,ebegoli/drill,ketfos/testdrill,Ben-Zvi/drill,arina-ielchiieva/drill,jaltekruse/incubator-drill,cchang738/drill,jhsbeat/drill,zzy6395/drill,johanwitters/drill,yufeldman/incubator-drill,ssriniva123/drill,StevenMPhillips/drill,homosepian/drill,tshiran/drill,ketfos/testdrill,AdamPD/drill,vvysotskyi/drill,sohami/drill,parthchandra/drill,pwong-mapr/incubator-drill,yssharma/pig-on-drill,paul-rogers/drill,jhsbeat/drill,Agirish/drill,zzy6395/drill,cocosli/drill,jaltekruse/incubator-drill,nagix/drill,jaltekruse/incubator-drill,ebegoli/drill,dsbos/incubator-drill,KulykRoman/drill,xiaom/drill,kristinehahn/drill,pwong-mapr/incubator-drill,kingmesal/drill,hsuanyi/incubator-drill,sindhurirayavaram/drill,puneetjaiswal/drill,santoshsahoo/drill,vdiravka/drill,mehant/drill,kristinehahn/drill,johnnywale/drill,adityakishore/drill,ebegoli/drill,amithadke/drill,myroch/drill,maryannxue/drill,kkhatua/drill,cwestin/incubator-drill,paul-rogers/drill,jinfengni/incubator-drill,julianhyde/drill,mapr/incubator-drill,cocosli/drill,norrislee/incubator-drill,kkhatua/drill,kkhatua/drill,maryannxue/drill,hsuanyi/incubator-drill,superbstreak/drill,Agirish/drill,adeneche/incubator-drill,pwong-mapr/incubator-drill,dsbos/incubator-drill,tshiran/drill,parthchandra/drill,zzy6395/drill,mapr/incubator-drill,parthchandra/incubator-drill,arina-ielchiieva/drill,akumarb2010/incubator-drill,kingmesal/drill,jdownton/drill,nagix/drill,yssharma/pig-on-drill,vdiravka/drill,sohami/drill,julianhyde/drill,hsuanyi/incubator-drill,norrislee/incubator-drill,ssriniva123/drill,paul-rogers/drill,jackyxhb/drill,zzy6395/drill,jhsbeat/drill,jdownton/drill,AdamPD/drill,hnfgns/incubator-drill,xiaom/drill,activitystream/drill,adityakishore/drill,squidsolutions/drill,dsbos/incubator-drill,puneetjaiswal/drill,nagix/drill,ssriniva123/drill,ppadma/drill,mapr/incubator-drill,KulykRoman/drill,dsbos/incubator-drill,KulykRoman/drill,bitblender/drill,nagix/drill,yssharma/pig-on-drill,jacques-n/drill,homosepian/drill,yssharma/pig-on-drill,akumarb2010/incubator-drill,rchallapalli/drill,mehant/drill,jaltekruse/incubator-drill,hnfgns/incubator-drill,sindhurirayavaram/drill,adeneche/incubator-drill,johnnywale/drill,Ben-Zvi/drill,sudheeshkatkam/drill,sindhurirayavaram/drill,squidsolutions/drill,yufeldman/incubator-drill,sudheeshkatkam/drill,johanwitters/drill,cocosli/drill,jackyxhb/drill,arina-ielchiieva/drill,vkorukanti/drill,superbstreak/drill,apache/drill,yufeldman/incubator-drill,myroch/drill,jaltekruse/incubator-drill,weijietong/drill,KulykRoman/drill,mehant/drill,kkhatua/drill,kristinehahn/drill,apache/drill,bbevens/drill,amithadke/drill,xiaom/drill,julienledem/drill,jhsbeat/drill,hnfgns/incubator-drill,vkorukanti/drill,ssriniva123/drill,jinfengni/incubator-drill,caijieming-baidu/drill,Agirish/drill,hsuanyi/incubator-drill,jhsbeat/drill,johanwitters/drill,cchang738/drill,kristinehahn/drill,jackyxhb/drill,mapr-demos/drill-pcap-format,sudheeshkatkam/drill,superbstreak/drill,hnfgns/incubator-drill,Ben-Zvi/drill,ebegoli/drill,jdownton/drill,cwestin/incubator-drill,julianhyde/drill,KulykRoman/drill,jacques-n/drill,myroch/drill,sohami/drill,sohami/drill,yssharma/drill,abhipol/drill,jackyxhb/drill,amithadke/drill,homosepian/drill,ppadma/drill,Ben-Zvi/drill,AdamPD/drill,abhipol/drill,KulykRoman/drill,parthchandra/incubator-drill,adeneche/incubator-drill,activitystream/drill,arina-ielchiieva/drill,caijieming-baidu/drill,jacques-n/drill,cocosli/drill,vkorukanti/drill,squidsolutions/drill,Agirish/drill,santoshsahoo/drill,adeneche/incubator-drill,vdiravka/drill,Ben-Zvi/drill,parthchandra/drill,johnnywale/drill,sohami/drill,kingmesal/drill | /**
* 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.drill.exec.planner.physical;
import java.util.BitSet;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import net.hydromatic.linq4j.Ord;
import net.hydromatic.optiq.util.BitSets;
import org.eigenbase.rel.AggregateCall;
import org.eigenbase.rel.AggregateRelBase;
import org.eigenbase.rel.Aggregation;
import org.eigenbase.rel.InvalidRelException;
import org.eigenbase.rel.RelNode;
import org.eigenbase.relopt.RelOptCluster;
import org.eigenbase.relopt.RelTraitSet;
import org.eigenbase.reltype.RelDataType;
import org.eigenbase.reltype.RelDataTypeFactory;
import org.eigenbase.sql.SqlAggFunction;
import org.eigenbase.sql.SqlFunctionCategory;
import org.eigenbase.sql.SqlKind;
import org.eigenbase.sql.type.OperandTypes;
import org.eigenbase.sql.type.ReturnTypes;
import org.apache.drill.common.expression.ExpressionPosition;
import org.apache.drill.common.expression.FieldReference;
import org.apache.drill.common.expression.FunctionCall;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.ValueExpressions;
import org.apache.drill.common.logical.data.NamedExpression;
import org.apache.drill.exec.planner.logical.DrillParseContext;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.ImmutableList;
public abstract class AggPrelBase extends AggregateRelBase implements Prel{
protected static enum OperatorPhase {PHASE_1of1, PHASE_1of2, PHASE_2of2};
protected OperatorPhase operPhase = OperatorPhase.PHASE_1of1 ; // default phase
protected List<NamedExpression> keys = Lists.newArrayList();
protected List<NamedExpression> aggExprs = Lists.newArrayList();
protected List<AggregateCall> phase2AggCallList = Lists.newArrayList();
/**
* Specialized aggregate function for SUMing the COUNTs. Since return type of
* COUNT is non-nullable and return type of SUM is nullable, this class enables
* creating a SUM whose return type is non-nullable.
*
*/
public class SqlSumCountAggFunction extends SqlAggFunction {
private final RelDataType type;
public SqlSumCountAggFunction(RelDataType type) {
super("SUM",
SqlKind.OTHER_FUNCTION,
ReturnTypes.BIGINT, // use the inferred return type of SqlCountAggFunction
null,
OperandTypes.NUMERIC,
SqlFunctionCategory.NUMERIC);
this.type = type;
}
public List<RelDataType> getParameterTypes(RelDataTypeFactory typeFactory) {
return ImmutableList.of(type);
}
public RelDataType getType() {
return type;
}
public RelDataType getReturnType(RelDataTypeFactory typeFactory) {
return type;
}
}
public AggPrelBase(RelOptCluster cluster, RelTraitSet traits, RelNode child, BitSet groupSet,
List<AggregateCall> aggCalls, OperatorPhase phase) throws InvalidRelException {
super(cluster, traits, child, groupSet, aggCalls);
this.operPhase = phase;
createKeysAndExprs();
}
public OperatorPhase getOperatorPhase() {
return operPhase;
}
public List<NamedExpression> getKeys() {
return keys;
}
public List<NamedExpression> getAggExprs() {
return aggExprs;
}
public List<AggregateCall> getPhase2AggCalls() {
return phase2AggCallList;
}
protected void createKeysAndExprs() {
final List<String> childFields = getChild().getRowType().getFieldNames();
final List<String> fields = getRowType().getFieldNames();
for (int group : BitSets.toIter(groupSet)) {
FieldReference fr = new FieldReference(childFields.get(group), ExpressionPosition.UNKNOWN);
keys.add(new NamedExpression(fr, fr));
}
for (Ord<AggregateCall> aggCall : Ord.zip(aggCalls)) {
int aggExprOrdinal = groupSet.cardinality() + aggCall.i;
FieldReference ref = new FieldReference(fields.get(aggExprOrdinal));
LogicalExpression expr = toDrill(aggCall.e, childFields, new DrillParseContext());
NamedExpression ne = new NamedExpression(expr, ref);
aggExprs.add(ne);
if (getOperatorPhase() == OperatorPhase.PHASE_1of2) {
if (aggCall.e.getAggregation().getName().equals("COUNT")) {
// If we are doing a COUNT aggregate in Phase1of2, then in Phase2of2 we should SUM the COUNTs,
Aggregation sumAggFun = new SqlSumCountAggFunction(aggCall.e.getType());
AggregateCall newAggCall =
new AggregateCall(
sumAggFun,
aggCall.e.isDistinct(),
Collections.singletonList(aggExprOrdinal),
aggCall.e.getType(),
aggCall.e.getName());
phase2AggCallList.add(newAggCall);
} else {
AggregateCall newAggCall =
new AggregateCall(
aggCall.e.getAggregation(),
aggCall.e.isDistinct(),
Collections.singletonList(aggExprOrdinal),
aggCall.e.getType(),
aggCall.e.getName());
phase2AggCallList.add(newAggCall);
}
}
}
}
protected LogicalExpression toDrill(AggregateCall call, List<String> fn, DrillParseContext pContext) {
List<LogicalExpression> args = Lists.newArrayList();
for(Integer i : call.getArgList()){
args.add(new FieldReference(fn.get(i)));
}
// for count(1).
if(args.isEmpty()) args.add(new ValueExpressions.LongExpression(1l));
LogicalExpression expr = new FunctionCall(call.getAggregation().getName().toLowerCase(), args, ExpressionPosition.UNKNOWN );
return expr;
}
@Override
public Iterator<Prel> iterator() {
return PrelUtil.iter(getChild());
}
@Override
public <T, X, E extends Throwable> T accept(PrelVisitor<T, X, E> logicalVisitor, X value) throws E {
return logicalVisitor.visitPrel(this, value);
}
}
| exec/java-exec/src/main/java/org/apache/drill/exec/planner/physical/AggPrelBase.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.drill.exec.planner.physical;
import java.util.BitSet;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import net.hydromatic.linq4j.Ord;
import net.hydromatic.optiq.util.BitSets;
import org.eigenbase.rel.AggregateCall;
import org.eigenbase.rel.AggregateRelBase;
import org.eigenbase.rel.Aggregation;
import org.eigenbase.rel.InvalidRelException;
import org.eigenbase.rel.RelNode;
import org.eigenbase.relopt.RelOptCluster;
import org.eigenbase.relopt.RelTraitSet;
import org.eigenbase.reltype.RelDataType;
import org.eigenbase.reltype.RelDataTypeFactory;
import org.eigenbase.sql.SqlAggFunction;
import org.eigenbase.sql.SqlFunctionCategory;
import org.eigenbase.sql.SqlKind;
import org.eigenbase.sql.type.OperandTypes;
import org.eigenbase.sql.type.ReturnTypes;
import org.apache.drill.common.expression.ExpressionPosition;
import org.apache.drill.common.expression.FieldReference;
import org.apache.drill.common.expression.FunctionCall;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.ValueExpressions;
import org.apache.drill.common.logical.data.NamedExpression;
import org.apache.drill.exec.planner.logical.DrillParseContext;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.ImmutableList;
public abstract class AggPrelBase extends AggregateRelBase implements Prel{
protected static enum OperatorPhase {PHASE_1of1, PHASE_1of2, PHASE_2of2};
protected OperatorPhase operPhase = OperatorPhase.PHASE_1of1 ; // default phase
protected List<NamedExpression> keys = Lists.newArrayList();
protected List<NamedExpression> aggExprs = Lists.newArrayList();
protected List<AggregateCall> phase2AggCallList = Lists.newArrayList();
/**
* Specialized aggregate function for SUMing the COUNTs. Since return type of
* COUNT is non-nullable and return type of SUM is nullable, this class enables
* creating a SUM whose return type is non-nullable.
*
*/
public class SqlSumCountAggFunction extends SqlAggFunction {
private final RelDataType type;
public SqlSumCountAggFunction(RelDataType type) {
super("SUM",
SqlKind.OTHER_FUNCTION,
ReturnTypes.BIGINT, // use the inferred return type of SqlCountAggFunction
null,
OperandTypes.NUMERIC,
SqlFunctionCategory.NUMERIC);
this.type = type;
}
public List<RelDataType> getParameterTypes(RelDataTypeFactory typeFactory) {
return ImmutableList.of(type);
}
public RelDataType getType() {
return type;
}
public RelDataType getReturnType(RelDataTypeFactory typeFactory) {
return type;
}
}
public AggPrelBase(RelOptCluster cluster, RelTraitSet traits, RelNode child, BitSet groupSet,
List<AggregateCall> aggCalls, OperatorPhase phase) throws InvalidRelException {
super(cluster, traits, child, groupSet, aggCalls);
this.operPhase = phase;
createKeysAndExprs();
}
public OperatorPhase getOperatorPhase() {
return operPhase;
}
public List<NamedExpression> getKeys() {
return keys;
}
public List<NamedExpression> getAggExprs() {
return aggExprs;
}
public List<AggregateCall> getPhase2AggCalls() {
return phase2AggCallList;
}
protected void createKeysAndExprs() {
final List<String> childFields = getChild().getRowType().getFieldNames();
final List<String> fields = getRowType().getFieldNames();
for (int group : BitSets.toIter(groupSet)) {
FieldReference fr = new FieldReference(childFields.get(group), ExpressionPosition.UNKNOWN);
keys.add(new NamedExpression(fr, fr));
}
for (Ord<AggregateCall> aggCall : Ord.zip(aggCalls)) {
int aggExprOrdinal = groupSet.cardinality() + aggCall.i;
FieldReference ref = new FieldReference(fields.get(aggExprOrdinal));
LogicalExpression expr = toDrill(aggCall.e, childFields, new DrillParseContext());
NamedExpression ne = new NamedExpression(expr, ref);
aggExprs.add(ne);
if (getOperatorPhase() == OperatorPhase.PHASE_1of2) {
if (aggCall.e.getAggregation().getName().equals("COUNT")) {
// If we are doing a COUNT aggregate in Phase1of2, then in Phase2of2 we should SUM the COUNTs,
Aggregation sumAggFun = new SqlSumCountAggFunction(aggCall.e.getType());
AggregateCall newAggCall =
new AggregateCall(
sumAggFun,
aggCall.e.isDistinct(),
Collections.singletonList(aggExprOrdinal),
aggCall.e.getType(),
aggCall.e.getName());
phase2AggCallList.add(newAggCall);
} else {
phase2AggCallList.add(aggCall.e);
}
}
}
}
protected LogicalExpression toDrill(AggregateCall call, List<String> fn, DrillParseContext pContext) {
List<LogicalExpression> args = Lists.newArrayList();
for(Integer i : call.getArgList()){
args.add(new FieldReference(fn.get(i)));
}
// for count(1).
if(args.isEmpty()) args.add(new ValueExpressions.LongExpression(1l));
LogicalExpression expr = new FunctionCall(call.getAggregation().getName().toLowerCase(), args, ExpressionPosition.UNKNOWN );
return expr;
}
@Override
public Iterator<Prel> iterator() {
return PrelUtil.iter(getChild());
}
@Override
public <T, X, E extends Throwable> T accept(PrelVisitor<T, X, E> logicalVisitor, X value) throws E {
return logicalVisitor.visitPrel(this, value);
}
}
| Fix DRILL-791: In Phase 1of2 use the agg expr ordinal and create new AggregateCall for non-COUNT functions.
| exec/java-exec/src/main/java/org/apache/drill/exec/planner/physical/AggPrelBase.java | Fix DRILL-791: In Phase 1of2 use the agg expr ordinal and create new AggregateCall for non-COUNT functions. | <ide><path>xec/java-exec/src/main/java/org/apache/drill/exec/planner/physical/AggPrelBase.java
<ide>
<ide> phase2AggCallList.add(newAggCall);
<ide> } else {
<del> phase2AggCallList.add(aggCall.e);
<add> AggregateCall newAggCall =
<add> new AggregateCall(
<add> aggCall.e.getAggregation(),
<add> aggCall.e.isDistinct(),
<add> Collections.singletonList(aggExprOrdinal),
<add> aggCall.e.getType(),
<add> aggCall.e.getName());
<add>
<add> phase2AggCallList.add(newAggCall);
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 75b197017f5445d71a91d1613c69180e2499b973 | 0 | pex-gl/pex-renderer,pex-gl/pex-renderer | const Signal = require('signals')
const vec3 = require('pex-math/vec3')
const vec4 = require('pex-math/vec4')
const mat4 = require('pex-math/mat4')
const aabb = require('pex-geom/aabb')
function vec4set4 (v, x, y, z, w) {
v[0] = x
v[1] = y
v[2] = z
v[3] = w
return v
}
// TODO remove, should in AABB
function emptyAABB (a) {
a[0][0] = Infinity
a[0][1] = Infinity
a[0][2] = Infinity
a[1][0] = -Infinity
a[1][1] = -Infinity
a[1][2] = -Infinity
}
// TODO remove, should in AABB
function aabbToPoints (points, box) {
vec4set4(points[0], box[0][0], box[0][1], box[0][2], 1)
vec4set4(points[1], box[1][0], box[0][1], box[0][2], 1)
vec4set4(points[2], box[1][0], box[0][1], box[1][2], 1)
vec4set4(points[3], box[0][0], box[0][1], box[1][2], 1)
vec4set4(points[4], box[0][0], box[1][1], box[0][2], 1)
vec4set4(points[5], box[1][0], box[1][1], box[0][2], 1)
vec4set4(points[6], box[1][0], box[1][1], box[1][2], 1)
vec4set4(points[7], box[0][0], box[1][1], box[1][2], 1)
return points
}
function aabbFromPoints (aabb, points) {
var min = aabb[0]
var max = aabb[1]
for (var i = 0, len = points.length; i < len; i++) {
var p = points[i]
min[0] = Math.min(min[0], p[0])
min[1] = Math.min(min[1], p[1])
min[2] = Math.min(min[2], p[2])
max[0] = Math.max(max[0], p[0])
max[1] = Math.max(max[1], p[1])
max[2] = Math.max(max[2], p[2])
}
return aabb
}
function Transform (opts) {
this.type = 'Transform'
this.entity = null
this.changed = new Signal()
this.position = [0, 0, 0]
this.worldPosition = [0, 0, 0]
this.rotation = [0, 0, 0, 1]
this.scale = [1, 1, 1]
this.parent = null
this.children = []
this.enabled = true
// bounds of this node and it's children
this.bounds = aabb.create()
this._boundsPoints = new Array(8).fill(0).map(() => vec4.create())
// bounds of this node and it's children in the world space
this.worldBounds = aabb.create()
this.localModelMatrix = mat4.create()
this.modelMatrix = mat4.create()
this.geometry = null
this.set(opts)
}
Transform.prototype.init = function (entity) {
this.entity = entity
}
Transform.prototype.set = function (opts) {
if (opts.parent !== undefined) {
if (this.parent) {
this.parent.children.splice(this.parent.children.indexOf(this), 1)
}
if (opts.parent) {
opts.parent.children.push(this)
}
}
Object.assign(this, opts)
Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))
}
Transform.prototype.update = function () {
mat4.identity(this.localModelMatrix)
mat4.translate(this.localModelMatrix, this.position)
mat4.mult(this.localModelMatrix, mat4.fromQuat(mat4.create(), this.rotation))
mat4.scale(this.localModelMatrix, this.scale)
if (this.matrix) mat4.mult(this.localModelMatrix, this.matrix)
mat4.identity(this.modelMatrix)
var parents = []
var parent = this
while (parent) {
parents.unshift(parent) // TODO: GC
parent = parent.parent
}
parents.forEach((p) => { // TODO: forEach
mat4.mult(this.modelMatrix, p.localModelMatrix)
})
emptyAABB(this.bounds)
const geom = this.entity.getComponent('Geometry')
if (geom) {
aabb.set(this.bounds, geom.bounds)
}
}
Transform.prototype.afterUpdate = function () {
if (!aabb.isEmpty(this.bounds)) {
aabbToPoints(this._boundsPoints, this.bounds)
for (var i = 0; i < this._boundsPoints.length; i++) {
vec3.multMat4(this._boundsPoints[i], this.modelMatrix)
}
aabbFromPoints(this.worldBounds, this._boundsPoints)
} else {
emptyAABB(this.worldBounds)
}
this.children.forEach((child) => {
if (!aabb.isEmpty(child.worldBounds)) {
aabb.includeAABB(this.worldBounds, child.worldBounds)
}
})
vec3.scale(this.worldPosition, 0)
vec3.multMat4(this.worldPosition, this.modelMatrix)
}
module.exports = function createTransform (opts) {
return new Transform(opts)
}
| transform.js | const Signal = require('signals')
const vec3 = require('pex-math/vec3')
const mat4 = require('pex-math/mat4')
const aabb = require('pex-geom/aabb')
// TODO remove, should in AABB
function emptyAABB (a) {
a[0][0] = Infinity
a[0][1] = Infinity
a[0][2] = Infinity
a[1][0] = -Infinity
a[1][1] = -Infinity
a[1][2] = -Infinity
}
// TODO remove, should in AABB
function aabbToPoints (box) {
if (aabb.isEmpty(box)) return []
return [
[box[0][0], box[0][1], box[0][2], 1],
[box[1][0], box[0][1], box[0][2], 1],
[box[1][0], box[0][1], box[1][2], 1],
[box[0][0], box[0][1], box[1][2], 1],
[box[0][0], box[1][1], box[0][2], 1],
[box[1][0], box[1][1], box[0][2], 1],
[box[1][0], box[1][1], box[1][2], 1],
[box[0][0], box[1][1], box[1][2], 1]
]
}
function Transform (opts) {
this.type = 'Transform'
this.entity = null
this.changed = new Signal()
this.position = [0, 0, 0]
this.worldPosition = [0, 0, 0]
this.rotation = [0, 0, 0, 1]
this.scale = [1, 1, 1]
this.parent = null
this.children = []
this.enabled = true
// bounds of this node and it's children
this.bounds = aabb.create()
// bounds of this node and it's children in the world space
this.worldBounds = aabb.create()
this.localModelMatrix = mat4.create()
this.modelMatrix = mat4.create()
this.geometry = null
this.set(opts)
}
Transform.prototype.init = function (entity) {
this.entity = entity
}
Transform.prototype.set = function (opts) {
if (opts.parent !== undefined) {
if (this.parent) {
this.parent.children.splice(this.parent.children.indexOf(this), 1)
}
if (opts.parent) {
opts.parent.children.push(this)
}
}
Object.assign(this, opts)
Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))
}
Transform.prototype.update = function () {
mat4.identity(this.localModelMatrix)
mat4.translate(this.localModelMatrix, this.position)
mat4.mult(this.localModelMatrix, mat4.fromQuat(mat4.create(), this.rotation))
mat4.scale(this.localModelMatrix, this.scale)
if (this.matrix) mat4.mult(this.localModelMatrix, this.matrix)
mat4.identity(this.modelMatrix)
var parents = []
var parent = this
while (parent) {
parents.unshift(parent) // TODO: GC
parent = parent.parent
}
parents.forEach((p) => { // TODO: forEach
mat4.mult(this.modelMatrix, p.localModelMatrix)
})
emptyAABB(this.bounds)
const geom = this.entity.getComponent('Geometry')
if (geom) {
aabb.set(this.bounds, geom.bounds)
}
}
Transform.prototype.afterUpdate = function () {
if (!aabb.isEmpty(this.bounds)) {
const points = aabbToPoints(this.bounds)
const pointsInWorldSpace = points.map((p) => vec3.multMat4(vec3.copy(p), this.modelMatrix))
this.worldBounds = aabb.fromPoints(pointsInWorldSpace)
} else {
emptyAABB(this.worldBounds)
}
this.children.forEach((child) => {
if (!aabb.isEmpty(child.worldBounds)) {
aabb.includeAABB(this.worldBounds, child.worldBounds)
}
})
vec3.scale(this.worldPosition, 0)
vec3.multMat4(this.worldPosition, this.modelMatrix)
}
module.exports = function createTransform (opts) {
return new Transform(opts)
}
| Reuse data for bounding box calculation | transform.js | Reuse data for bounding box calculation | <ide><path>ransform.js
<ide> const Signal = require('signals')
<ide> const vec3 = require('pex-math/vec3')
<add>const vec4 = require('pex-math/vec4')
<ide> const mat4 = require('pex-math/mat4')
<ide> const aabb = require('pex-geom/aabb')
<add>
<add>function vec4set4 (v, x, y, z, w) {
<add> v[0] = x
<add> v[1] = y
<add> v[2] = z
<add> v[3] = w
<add> return v
<add>}
<ide>
<ide> // TODO remove, should in AABB
<ide> function emptyAABB (a) {
<ide> }
<ide>
<ide> // TODO remove, should in AABB
<del>function aabbToPoints (box) {
<del> if (aabb.isEmpty(box)) return []
<del> return [
<del> [box[0][0], box[0][1], box[0][2], 1],
<del> [box[1][0], box[0][1], box[0][2], 1],
<del> [box[1][0], box[0][1], box[1][2], 1],
<del> [box[0][0], box[0][1], box[1][2], 1],
<del> [box[0][0], box[1][1], box[0][2], 1],
<del> [box[1][0], box[1][1], box[0][2], 1],
<del> [box[1][0], box[1][1], box[1][2], 1],
<del> [box[0][0], box[1][1], box[1][2], 1]
<del> ]
<add>function aabbToPoints (points, box) {
<add> vec4set4(points[0], box[0][0], box[0][1], box[0][2], 1)
<add> vec4set4(points[1], box[1][0], box[0][1], box[0][2], 1)
<add> vec4set4(points[2], box[1][0], box[0][1], box[1][2], 1)
<add> vec4set4(points[3], box[0][0], box[0][1], box[1][2], 1)
<add> vec4set4(points[4], box[0][0], box[1][1], box[0][2], 1)
<add> vec4set4(points[5], box[1][0], box[1][1], box[0][2], 1)
<add> vec4set4(points[6], box[1][0], box[1][1], box[1][2], 1)
<add> vec4set4(points[7], box[0][0], box[1][1], box[1][2], 1)
<add> return points
<add>}
<add>
<add>function aabbFromPoints (aabb, points) {
<add> var min = aabb[0]
<add> var max = aabb[1]
<add>
<add> for (var i = 0, len = points.length; i < len; i++) {
<add> var p = points[i]
<add> min[0] = Math.min(min[0], p[0])
<add> min[1] = Math.min(min[1], p[1])
<add> min[2] = Math.min(min[2], p[2])
<add> max[0] = Math.max(max[0], p[0])
<add> max[1] = Math.max(max[1], p[1])
<add> max[2] = Math.max(max[2], p[2])
<add> }
<add>
<add> return aabb
<ide> }
<ide>
<ide> function Transform (opts) {
<ide> this.enabled = true
<ide> // bounds of this node and it's children
<ide> this.bounds = aabb.create()
<add> this._boundsPoints = new Array(8).fill(0).map(() => vec4.create())
<ide> // bounds of this node and it's children in the world space
<ide> this.worldBounds = aabb.create()
<ide> this.localModelMatrix = mat4.create()
<ide>
<ide> Transform.prototype.afterUpdate = function () {
<ide> if (!aabb.isEmpty(this.bounds)) {
<del> const points = aabbToPoints(this.bounds)
<del> const pointsInWorldSpace = points.map((p) => vec3.multMat4(vec3.copy(p), this.modelMatrix))
<del> this.worldBounds = aabb.fromPoints(pointsInWorldSpace)
<add> aabbToPoints(this._boundsPoints, this.bounds)
<add> for (var i = 0; i < this._boundsPoints.length; i++) {
<add> vec3.multMat4(this._boundsPoints[i], this.modelMatrix)
<add> }
<add> aabbFromPoints(this.worldBounds, this._boundsPoints)
<ide> } else {
<ide> emptyAABB(this.worldBounds)
<ide> } |
|
Java | apache-2.0 | 4be2a6d5781a91a8ca59d40325024fdf03bcfe74 | 0 | dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android | package org.commcare.dalvik.activities;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import org.commcare.android.adapters.EntityListAdapter;
import org.commcare.android.fragments.ContainerFragment;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.framework.SaveSessionCommCareActivity;
import org.commcare.android.logic.DetailCalloutListenerDefaultImpl;
import org.commcare.android.models.AndroidSessionWrapper;
import org.commcare.android.models.Entity;
import org.commcare.android.models.NodeEntityFactory;
import org.commcare.android.tasks.EntityLoaderListener;
import org.commcare.android.tasks.EntityLoaderTask;
import org.commcare.android.util.AndroidInstanceInitializer;
import org.commcare.android.util.DetailCalloutListener;
import org.commcare.android.util.SerializationUtil;
import org.commcare.android.view.EntityView;
import org.commcare.android.view.TabbedDetailView;
import org.commcare.android.view.ViewUtil;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.dialogs.DialogChoiceItem;
import org.commcare.dalvik.dialogs.PaneledChoiceDialog;
import org.commcare.dalvik.geo.HereFunctionHandler;
import org.commcare.dalvik.preferences.CommCarePreferences;
import org.commcare.dalvik.preferences.DeveloperPreferences;
import org.commcare.session.CommCareSession;
import org.commcare.session.SessionFrame;
import org.commcare.suite.model.Action;
import org.commcare.suite.model.Callout;
import org.commcare.suite.model.CalloutData;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.DetailField;
import org.commcare.suite.model.SessionDatum;
import org.javarosa.core.model.data.GeoPointData;
import org.javarosa.core.model.data.UncastData;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.activities.GeoPointActivity;
import org.odk.collect.android.views.media.AudioController;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
/**
* TODO: Lots of locking and state-based cleanup
*
* @author ctsims
*/
public class EntitySelectActivity extends SaveSessionCommCareActivity
implements TextWatcher,
EntityLoaderListener,
OnItemClickListener,
TextToSpeech.OnInitListener,
DetailCalloutListener {
private static final String TAG = EntitySelectActivity.class.getSimpleName();
private CommCareSession session;
private AndroidSessionWrapper asw;
public static final String EXTRA_ENTITY_KEY = "esa_entity_key";
private static final String EXTRA_IS_MAP = "is_map";
private static final int CONFIRM_SELECT = 0;
private static final int MAP_SELECT = 2;
private static final int BARCODE_FETCH = 1;
private static final int CALLOUT = 3;
private static final int LOCATION_REQUEST = 4;
private static final int MENU_SORT = Menu.FIRST + 1;
private static final int MENU_MAP = Menu.FIRST + 2;
private static final int MENU_ACTION = Menu.FIRST + 3;
private EditText searchbox;
private TextView searchResultStatus;
private EntityListAdapter adapter;
private LinearLayout header;
private ImageButton barcodeButton;
private SearchView searchView;
private MenuItem searchItem;
private TextToSpeech tts;
private SessionDatum selectDatum;
private boolean mResultIsMap = false;
private boolean mMappingEnabled = false;
// Is the detail screen for showing entities, without option for moving
// forward on to form manipulation?
private boolean mViewMode = false;
// No detail confirm screen is defined for this entity select
private boolean mNoDetailMode = false;
private EntityLoaderTask loader;
private boolean inAwesomeMode = false;
private FrameLayout rightFrame;
private TabbedDetailView detailView;
private Intent selectedIntent = null;
private String filterString = "";
private Detail shortSelect;
private DataSetObserver mListStateObserver;
private OnClickListener barcodeScanOnClickListener;
private boolean resuming = false;
private boolean startOther = false;
private boolean rightFrameSetup = false;
private NodeEntityFactory factory;
private Timer myTimer;
private final Object timerLock = new Object();
private boolean cancelled;
private ContainerFragment<EntityListAdapter> containerFragment;
// Singleton HereFunctionHandler used by entities.
// The location inside is not calculated until GeoPointActivity returns.
public static final HereFunctionHandler hereFunctionHandler = new HereFunctionHandler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.createDataSetObserver();
if (savedInstanceState != null) {
mResultIsMap = savedInstanceState.getBoolean(EXTRA_IS_MAP, false);
}
asw = CommCareApplication._().getCurrentSessionWrapper();
session = asw.getSession();
if (session.getCommand() == null) {
// session ended, avoid (session dependent) setup because session
// management will exit the activity in onResume
return;
}
selectDatum = session.getNeededDatum();
shortSelect = session.getDetail(selectDatum.getShortDetail());
mNoDetailMode = selectDatum.getLongDetail() == null;
if (this.getString(R.string.panes).equals("two") && !mNoDetailMode) {
//See if we're on a big 'ol screen.
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//If we're in landscape mode, we can display this with the awesome UI.
//Inflate and set up the normal view for now.
setContentView(R.layout.screen_compound_select);
View.inflate(this, R.layout.entity_select_layout, (ViewGroup)findViewById(R.id.screen_compound_select_left_pane));
inAwesomeMode = true;
rightFrame = (FrameLayout)findViewById(R.id.screen_compound_select_right_pane);
TextView message = (TextView)findViewById(R.id.screen_compound_select_prompt);
//use the old method here because some Android versions don't like Spannables for titles
message.setText(Localization.get("select.placeholder.message", new String[]{Localization.get("cchq.case")}));
} else {
setContentView(R.layout.entity_select_layout);
//So we're not in landscape mode anymore, but were before. If we had something selected, we
//need to go to the detail screen instead.
if (savedInstanceState != null) {
Intent intent = this.getIntent();
TreeReference selectedRef = SerializationUtil.deserializeFromIntent(intent,
EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class);
if (selectedRef != null) {
// remove the reference from this intent, ensuring we
// don't re-launch the detail for an entity even after
// it being de-selected.
intent.removeExtra(EntityDetailActivity.CONTEXT_REFERENCE);
// attach the selected entity to the new detail intent
// we're launching
Intent detailIntent = getDetailIntent(selectedRef, null);
startOther = true;
startActivityForResult(detailIntent, CONFIRM_SELECT);
}
}
}
} else {
setContentView(R.layout.entity_select_layout);
}
ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list));
view.setOnItemClickListener(this);
setupDivider(view);
TextView searchLabel = (TextView)findViewById(R.id.screen_entity_select_search_label);
//use the old method here because some Android versions don't like Spannables for titles
searchLabel.setText(Localization.get("select.search.label"));
searchLabel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// get the focus on the edittext by performing click
searchbox.performClick();
// then force the keyboard up since performClick() apparently isn't enough on some devices
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// only will trigger it if no physical keyboard is open
inputMethodManager.showSoftInput(searchbox, InputMethodManager.SHOW_IMPLICIT);
}
});
searchbox = (EditText)findViewById(R.id.searchbox);
searchbox.setMaxLines(3);
searchbox.setHorizontallyScrolling(false);
searchResultStatus = (TextView)findViewById(R.id.no_search_results);
header = (LinearLayout)findViewById(R.id.entity_select_header);
mViewMode = session.isViewCommand(session.getCommand());
barcodeButton = (ImageButton)findViewById(R.id.barcodeButton);
Callout callout = shortSelect.getCallout();
if (callout == null) {
barcodeScanOnClickListener = makeBarcodeClickListener();
} else {
barcodeScanOnClickListener = makeCalloutClickListener(callout);
}
barcodeButton.setOnClickListener(barcodeScanOnClickListener);
searchbox.addTextChangedListener(this);
searchbox.requestFocus();
persistAdapterState(view);
//cts: disabling for non-demo purposes
//tts = new TextToSpeech(this, this);
restoreLastQueryString();
if (!isUsingActionBar()) {
searchbox.setText(lastQueryString);
}
}
private void persistAdapterState(ListView view) {
FragmentManager fm = this.getSupportFragmentManager();
containerFragment = (ContainerFragment)fm.findFragmentByTag("entity-adapter");
// stateHolder and its previous state aren't null if the activity is
// being created due to an orientation change.
if (containerFragment == null) {
containerFragment = new ContainerFragment<>();
fm.beginTransaction().add(containerFragment, "entity-adapter").commit();
} else {
adapter = containerFragment.getData();
// on orientation change
if (adapter != null) {
view.setAdapter(adapter);
setupDivider(view);
findViewById(R.id.entity_select_loading).setVisibility(View.GONE);
}
}
}
/**
* @return A click listener that launches QR code scanner
*/
private View.OnClickListener makeBarcodeClickListener() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent("com.google.zxing.client.android.SCAN");
try {
EntitySelectActivity.this.startActivityForResult(i, BARCODE_FETCH);
} catch (ActivityNotFoundException anfe) {
Toast.makeText(EntitySelectActivity.this,
"No barcode reader available! You can install one " +
"from the android market.",
Toast.LENGTH_LONG).show();
}
}
};
}
/**
* Build click listener from callout: set button's image, get intent action,
* and copy extras into intent.
*
* @param callout contains intent action and extras, and sometimes button image
* @return click listener that launches the callout's activity with the
* associated callout extras
*/
private View.OnClickListener makeCalloutClickListener(Callout callout) {
final CalloutData calloutData = callout.getRawCalloutData();
if (calloutData.getImage() != null) {
setupImageLayout(barcodeButton, calloutData.getImage());
}
final Intent i = new Intent(calloutData.getActionName());
for (Map.Entry<String, String> keyValue : calloutData.getExtras().entrySet()) {
i.putExtra(keyValue.getKey(), keyValue.getValue());
}
return new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
EntitySelectActivity.this.startActivityForResult(i, CALLOUT);
} catch (ActivityNotFoundException anfe) {
Toast.makeText(EntitySelectActivity.this,
"No application found for action: " + i.getAction(),
Toast.LENGTH_LONG).show();
}
}
};
}
/**
* Updates the ImageView layout that is passed in, based on the
* new id and source
*/
private void setupImageLayout(View layout, final String imagePath) {
ImageView iv = (ImageView)layout;
Bitmap b;
if (!imagePath.equals("")) {
try {
b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(imagePath).getStream());
if (b == null) {
// Input stream could not be used to derive bitmap, so
// showing error-indicating image
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive));
} else {
iv.setImageBitmap(b);
}
} catch (IOException | InvalidReferenceException ex) {
ex.printStackTrace();
// Error loading image, default to folder button
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive));
}
} else {
// no image passed in, draw a white background
iv.setImageDrawable(getResources().getDrawable(R.color.white));
}
}
private void createDataSetObserver() {
mListStateObserver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
//update the search results box
String query = getSearchText().toString();
if (!"".equals(query)) {
searchResultStatus.setText(Localization.get("select.search.status", new String[]{
"" + adapter.getCount(true, false),
"" + adapter.getCount(true, true),
query
}));
searchResultStatus.setVisibility(View.VISIBLE);
} else {
searchResultStatus.setVisibility(View.GONE);
}
}
};
}
@Override
protected boolean isTopNavEnabled() {
return true;
}
@Override
public String getActivityTitle() {
return null;
}
@Override
protected void onResume() {
super.onResume();
//Don't go through making the whole thing if we're finishing anyway.
if (this.isFinishing() || startOther) {
return;
}
if (adapter != null) {
adapter.registerDataSetObserver(mListStateObserver);
}
if (!resuming && !mNoDetailMode && this.getIntent().hasExtra(EXTRA_ENTITY_KEY)) {
TreeReference entity =
selectDatum.getEntityFromID(asw.getEvaluationContext(),
this.getIntent().getStringExtra(EXTRA_ENTITY_KEY));
if (entity != null) {
if (inAwesomeMode) {
if (adapter != null) {
displayReferenceAwesome(entity, adapter.getPosition(entity));
updateSelectedItem(entity, true);
}
} else {
//Once we've done the initial dispatch, we don't want to end up triggering it later.
this.getIntent().removeExtra(EXTRA_ENTITY_KEY);
Intent i = getDetailIntent(entity, null);
if (adapter != null) {
i.putExtra("entity_detail_index", adapter.getPosition(entity));
i.putExtra(EntityDetailActivity.DETAIL_PERSISTENT_ID,
selectDatum.getShortDetail());
}
startActivityForResult(i, CONFIRM_SELECT);
return;
}
}
}
refreshView();
}
/**
* Get form list from database and insert into view.
*/
private void refreshView() {
try {
//TODO: Get ec into these text's
String[] headers = new String[shortSelect.getFields().length];
for (int i = 0; i < headers.length; ++i) {
headers[i] = shortSelect.getFields()[i].getHeader().evaluate();
if ("address".equals(shortSelect.getFields()[i].getTemplateForm())) {
this.mMappingEnabled = true;
}
}
header.removeAllViews();
// only add headers if we're not using grid mode
if (!shortSelect.usesGridView()) {
//Hm, sadly we possibly need to rebuild this each time.
EntityView v = new EntityView(this, shortSelect, headers);
header.addView(v);
}
if (adapter == null &&
loader == null &&
!EntityLoaderTask.attachToActivity(this)) {
EntityLoaderTask theloader =
new EntityLoaderTask(shortSelect, asw.getEvaluationContext());
theloader.attachListener(this);
theloader.execute(selectDatum.getNodeset());
} else {
startTimer();
}
} catch (RuntimeException re) {
createErrorDialog(re.getMessage(), true);
}
}
@Override
protected void onPause() {
super.onPause();
stopTimer();
if (adapter != null) {
adapter.unregisterDataSetObserver(mListStateObserver);
}
}
@Override
protected void onStop() {
super.onStop();
stopTimer();
saveLastQueryString();
}
/**
* Get an intent for displaying the confirm detail screen for an element (either just populates
* the given intent with the necessary information, or creates a new one if it is null)
*
* @param contextRef reference to the selected element for which to display
* detailed view
* @return The intent argument, or a newly created one, with element
* selection information attached.
*/
private Intent getDetailIntent(TreeReference contextRef, Intent detailIntent) {
if (detailIntent == null) {
detailIntent = new Intent(getApplicationContext(), EntityDetailActivity.class);
}
return populateDetailIntent(detailIntent, contextRef, this.selectDatum, this.asw);
}
/**
* Attach all element selection information to the intent argument and return the resulting
* intent
*/
protected static Intent populateDetailIntent(Intent detailIntent,
TreeReference contextRef,
SessionDatum selectDatum,
AndroidSessionWrapper asw) {
String caseId = SessionDatum.getCaseIdFromReference(
contextRef, selectDatum, asw.getEvaluationContext());
detailIntent.putExtra(SessionFrame.STATE_DATUM_VAL, caseId);
// Include long datum info if present
if (selectDatum.getLongDetail() != null) {
detailIntent.putExtra(EntityDetailActivity.DETAIL_ID,
selectDatum.getLongDetail());
detailIntent.putExtra(EntityDetailActivity.DETAIL_PERSISTENT_ID,
selectDatum.getPersistentDetail());
}
SerializationUtil.serializeToIntent(detailIntent,
EntityDetailActivity.CONTEXT_REFERENCE, contextRef);
return detailIntent;
}
@Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
if (id == EntityListAdapter.SPECIAL_ACTION) {
triggerDetailAction();
return;
}
TreeReference selection = adapter.getItem(position);
if (CommCarePreferences.isEntityDetailLoggingEnabled()) {
Logger.log(EntityDetailActivity.class.getSimpleName(), selectDatum.getLongDetail());
}
if (inAwesomeMode) {
displayReferenceAwesome(selection, position);
updateSelectedItem(selection, false);
} else {
Intent i = getDetailIntent(selection, null);
i.putExtra("entity_detail_index", position);
if (mNoDetailMode) {
// Not actually launching detail intent because there's no confirm detail available
returnWithResult(i);
} else {
startActivityForResult(i, CONFIRM_SELECT);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case BARCODE_FETCH:
processBarcodeFetch(resultCode, intent);
break;
case CALLOUT:
processCalloutResult(resultCode, intent);
break;
case CONFIRM_SELECT:
resuming = true;
if (resultCode == RESULT_OK && !mViewMode) {
// create intent for return and store path
returnWithResult(intent);
return;
} else {
//Did we enter the detail from mapping mode? If so, go back to that
if (mResultIsMap) {
mResultIsMap = false;
Intent i = new Intent(this, EntityMapActivity.class);
this.startActivityForResult(i, MAP_SELECT);
return;
}
if (inAwesomeMode) {
// Retain original element selection
TreeReference r =
SerializationUtil.deserializeFromIntent(intent,
EntityDetailActivity.CONTEXT_REFERENCE,
TreeReference.class);
if (r != null && adapter != null) {
// TODO: added 'adapter != null' due to a
// NullPointerException, we need to figure out how to
// make sure adapter is never null -- PLM
this.displayReferenceAwesome(r, adapter.getPosition(r));
updateSelectedItem(r, true);
}
AudioController.INSTANCE.releaseCurrentMediaEntity();
}
return;
}
case MAP_SELECT:
if (resultCode == RESULT_OK) {
TreeReference r =
SerializationUtil.deserializeFromIntent(intent,
EntityDetailActivity.CONTEXT_REFERENCE,
TreeReference.class);
if (inAwesomeMode) {
this.displayReferenceAwesome(r, adapter.getPosition(r));
} else {
Intent i = this.getDetailIntent(r, null);
if (mNoDetailMode) {
returnWithResult(i);
} else {
//To go back to map mode if confirm is false
mResultIsMap = true;
i.putExtra("entity_detail_index", adapter.getPosition(r));
startActivityForResult(i, CONFIRM_SELECT);
}
return;
}
} else {
refreshView();
return;
}
case LOCATION_REQUEST:
if (resultCode == RESULT_OK) {
hereFunctionHandler.setLocationString(
intent.getStringExtra(FormEntryActivity.LOCATION_RESULT));
}
default:
super.onActivityResult(requestCode, resultCode, intent);
}
}
private void processBarcodeFetch(int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK) {
String result = intent.getStringExtra("SCAN_RESULT");
if (result != null) {
result = result.trim();
}
setSearchText(result);
}
}
private void processCalloutResult(int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK) {
String result = intent.getStringExtra("odk_intent_data");
if (result != null){
setSearchText(result.trim());
} else {
for (String key : shortSelect.getCallout().getResponses()) {
result = intent.getExtras().getString(key);
if (result != null) {
setSearchText(result);
return;
}
}
}
}
}
/**
* Finish this activity, including all extras from the given intent in the finishing intent
*/
private void returnWithResult(Intent intent) {
Intent i = new Intent(this.getIntent());
i.putExtras(intent.getExtras());
setResult(RESULT_OK, i);
finish();
}
@Override
public void afterTextChanged(Editable incomingEditable) {
final String incomingString = incomingEditable.toString();
final String currentSearchText = getSearchText().toString();
if (incomingString.equals(currentSearchText)) {
filterString = currentSearchText;
if (adapter != null) {
adapter.applyFilter(filterString);
}
}
if (!isUsingActionBar()) {
lastQueryString = filterString;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//use the old method here because some Android versions don't like Spannables for titles
menu.add(0, MENU_SORT, MENU_SORT, Localization.get("select.menu.sort")).setIcon(
android.R.drawable.ic_menu_sort_alphabetically);
if (mMappingEnabled) {
menu.add(0, MENU_MAP, MENU_MAP, Localization.get("select.menu.map")).setIcon(
android.R.drawable.ic_menu_mapmode);
}
if (shortSelect != null) {
Action action = shortSelect.getCustomAction();
if (action != null) {
ViewUtil.addDisplayToMenu(this, menu, MENU_ACTION,
action.getDisplay().evaluate());
}
}
tryToAddActionSearchBar(this, menu, new ActionBarInstantiator() {
// again, this should be unnecessary...
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onActionBarFound(MenuItem searchItem, SearchView searchView) {
EntitySelectActivity.this.searchItem = searchItem;
EntitySelectActivity.this.searchView = searchView;
// restore last query string in the searchView if there is one
if (lastQueryString != null && lastQueryString.length() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
searchItem.expandActionView();
}
searchView.setQuery(lastQueryString, false);
if (BuildConfig.DEBUG) {
Log.v(TAG, "Setting lastQueryString in searchView: (" + lastQueryString + ")");
}
if (adapter != null) {
adapter.applyFilter(lastQueryString == null ? "" : lastQueryString);
}
}
EntitySelectActivity.this.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
lastQueryString = newText;
filterString = newText;
if (adapter != null) {
adapter.applyFilter(newText);
}
return false;
}
});
}
});
return true;
}
/**
* Checks if this activity uses the ActionBar
*/
private boolean isUsingActionBar() {
return searchView != null;
}
@SuppressWarnings("NewApi")
private CharSequence getSearchText() {
if (isUsingActionBar()) {
return searchView.getQuery();
}
return searchbox.getText();
}
@SuppressWarnings("NewApi")
private void setSearchText(CharSequence text) {
if (isUsingActionBar()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
searchItem.expandActionView();
}
searchView.setQuery(text, false);
}
searchbox.setText(text);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// only enable sorting once entity loading is complete
menu.findItem(MENU_SORT).setEnabled(adapter != null);
// hide sorting menu when using async loading strategy
menu.findItem(MENU_SORT).setVisible((shortSelect == null || !shortSelect.useAsyncStrategy()));
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SORT:
createSortMenu();
return true;
case MENU_MAP:
Intent i = new Intent(this, EntityMapActivity.class);
this.startActivityForResult(i, MAP_SELECT);
return true;
case MENU_ACTION:
triggerDetailAction();
return true;
// handling click on the barcode scanner's actionbar
// trying to set the onclicklistener in its view in the onCreateOptionsMenu method does not work because it returns null
case R.id.barcode_scan_action_bar:
barcodeScanOnClickListener.onClick(null);
return true;
// this is needed because superclasses do not implement the menu_settings click
case R.id.menu_settings:
CommCareHomeActivity.createPreferencesMenu(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private void triggerDetailAction() {
Action action = shortSelect.getCustomAction();
try {
asw.executeStackActions(action.getStackOperations());
} catch (XPathTypeMismatchException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), true);
return;
}
this.setResult(CommCareHomeActivity.RESULT_RESTART);
this.finish();
}
private void createSortMenu() {
final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, Localization.get("select.menu.sort"));
dialog.setChoiceItems(getSortOptionsList(dialog));
dialog.show();
}
private DialogChoiceItem[] getSortOptionsList(final PaneledChoiceDialog dialog) {
SessionDatum datum = session.getNeededDatum();
DetailField[] fields = session.getDetail(datum.getShortDetail()).getFields();
List<String> namesList = new ArrayList<>();
final int[] keyArray = new int[fields.length];
int[] sorts = adapter.getCurrentSort();
int currentSort = sorts.length == 1 ? sorts[0] : -1;
boolean reversed = adapter.isCurrentSortReversed();
int added = 0;
for (int i = 0; i < fields.length; ++i) {
String result = fields[i].getHeader().evaluate();
if (!"".equals(result)) {
String prepend = "";
if (currentSort == -1) {
for (int j = 0; j < sorts.length; ++j) {
if (sorts[j] == i) {
prepend = (j + 1) + " " + (fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) ");
}
}
} else if (currentSort == i) {
prepend = reversed ^ fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) ";
}
namesList.add(prepend + result);
keyArray[added] = i;
added++;
}
}
DialogChoiceItem[] choiceItems = new DialogChoiceItem[namesList.size()];
for (int i = 0; i < namesList.size(); i++) {
final int index = i;
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(EntitySelectActivity.this, GeoPointActivity.class);
startActivityForResult(i, LOCATION_REQUEST);
adapter.sortEntities(new int[]{keyArray[index]});
adapter.applyFilter(getSearchText().toString());
dialog.dismiss();
}
};
DialogChoiceItem item = new DialogChoiceItem(namesList.get(i), -1, listener);
choiceItems[i] = item;
}
return choiceItems;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (loader != null) {
if (isFinishing()) {
loader.cancel(false);
} else {
loader.detachActivity();
}
}
if (adapter != null) {
adapter.signalKilled();
}
if (tts != null) {
tts.stop();
tts.shutdown();
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
//using the default speech engine for now.
} else {
}
}
@Override
public void deliverResult(List<Entity<TreeReference>> entities,
List<TreeReference> references,
NodeEntityFactory factory) {
loader = null;
Detail detail = session.getDetail(selectDatum.getShortDetail());
int[] order = detail.getSortOrder();
for (int i = 0; i < detail.getFields().length; ++i) {
String header = detail.getFields()[i].getHeader().evaluate();
if (order.length == 0 && !"".equals(header)) {
order = new int[]{i};
}
}
ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list));
setupDivider(view);
adapter = new EntityListAdapter(EntitySelectActivity.this, detail, references, entities, order, tts, factory);
view.setAdapter(adapter);
adapter.registerDataSetObserver(this.mListStateObserver);
containerFragment.setData(adapter);
// Pre-select entity if one was provided in original intent
if (!resuming && !mNoDetailMode && inAwesomeMode && this.getIntent().hasExtra(EXTRA_ENTITY_KEY)) {
TreeReference entity =
selectDatum.getEntityFromID(asw.getEvaluationContext(),
this.getIntent().getStringExtra(EXTRA_ENTITY_KEY));
if (entity != null) {
displayReferenceAwesome(entity, adapter.getPosition(entity));
updateSelectedItem(entity, true);
}
}
findViewById(R.id.entity_select_loading).setVisibility(View.GONE);
if (adapter != null && filterString != null && !"".equals(filterString)) {
adapter.applyFilter(filterString);
}
//In landscape we want to select something now. Either the top item, or the most recently selected one
if (inAwesomeMode) {
updateSelectedItem(true);
}
this.startTimer();
}
private void setupDivider(ListView view) {
boolean useNewDivider = shortSelect.usesGridView();
if (useNewDivider) {
int viewWidth = view.getWidth();
float density = getResources().getDisplayMetrics().density;
int viewWidthDP = (int)(viewWidth / density);
// sometimes viewWidth is 0, and in this case we default to a reasonable value taken from dimens.xml
int dividerWidth = viewWidth == 0 ? (int)getResources().getDimension(R.dimen.entity_select_divider_left_inset) : (int)(viewWidth / 6.0);
Drawable divider = getResources().getDrawable(R.drawable.divider_case_list_modern);
if (BuildConfig.DEBUG) {
Log.v(TAG, "ListView divider is: " + divider + ", estimated divider width is: " + dividerWidth + ", viewWidth (dp) is: " + viewWidthDP);
}
if (BuildConfig.DEBUG && (divider == null || !(divider instanceof LayerDrawable))) {
throw new AssertionError("Divider should be a LayerDrawable!");
}
LayerDrawable layerDrawable = (LayerDrawable)divider;
dividerWidth += (int)getResources().getDimension(R.dimen.row_padding_horizontal);
layerDrawable.setLayerInset(0, dividerWidth, 0, 0, 0);
view.setDivider(layerDrawable);
} else {
view.setDivider(null);
}
view.setDividerHeight((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()));
}
private void updateSelectedItem(boolean forceMove) {
TreeReference chosen = null;
if (selectedIntent != null) {
chosen = SerializationUtil.deserializeFromIntent(selectedIntent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class);
}
updateSelectedItem(chosen, forceMove);
}
private void updateSelectedItem(TreeReference selected, boolean forceMove) {
if (adapter == null) {
return;
}
if (selected != null) {
adapter.notifyCurrentlyHighlighted(selected);
if (forceMove) {
ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list));
view.setSelection(adapter.getPosition(selected));
}
}
}
@Override
public void attach(EntityLoaderTask task) {
findViewById(R.id.entity_select_loading).setVisibility(View.VISIBLE);
this.loader = task;
}
private void select() {
// create intent for return and store path
Intent i = new Intent(EntitySelectActivity.this.getIntent());
i.putExtra(SessionFrame.STATE_DATUM_VAL, selectedIntent.getStringExtra(SessionFrame.STATE_DATUM_VAL));
setResult(RESULT_OK, i);
finish();
}
@Override
public void callRequested(String phoneNumber) {
DetailCalloutListenerDefaultImpl.callRequested(this, phoneNumber);
}
@Override
public void addressRequested(String address) {
DetailCalloutListenerDefaultImpl.addressRequested(this, address);
}
@Override
public void playVideo(String videoRef) {
DetailCalloutListenerDefaultImpl.playVideo(this, videoRef);
}
@Override
public void performCallout(CalloutData callout, int id) {
DetailCalloutListenerDefaultImpl.performCallout(this, callout, id);
}
private void displayReferenceAwesome(final TreeReference selection, int detailIndex) {
selectedIntent = getDetailIntent(selection, getIntent());
//this should be 100% "fragment" able
if (!rightFrameSetup) {
findViewById(R.id.screen_compound_select_prompt).setVisibility(View.GONE);
View.inflate(this, R.layout.entity_detail, rightFrame);
Button next = (Button)findViewById(R.id.entity_select_button);
//use the old method here because some Android versions don't like Spannables for titles
next.setText(Localization.get("select.detail.confirm"));
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
select();
}
});
if (mViewMode) {
next.setVisibility(View.GONE);
next.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
String passedCommand = selectedIntent.getStringExtra(SessionFrame.STATE_COMMAND_ID);
if (passedCommand != null) {
mViewMode = session.isViewCommand(passedCommand);
} else {
mViewMode = session.isViewCommand(session.getCommand());
}
detailView = (TabbedDetailView)rightFrame.findViewById(R.id.entity_detail_tabs);
detailView.setRoot(detailView);
factory = new NodeEntityFactory(session.getDetail(selectedIntent.getStringExtra(EntityDetailActivity.DETAIL_ID)), session.getEvaluationContext(new AndroidInstanceInitializer(session)));
Detail detail = factory.getDetail();
detailView.setDetail(detail);
if (detail.isCompound()) {
// border around right panel doesn't look right when there are tabs
rightFrame.setBackgroundDrawable(null);
}
rightFrameSetup = true;
}
detailView.refresh(factory.getDetail(), selection, detailIndex);
}
@Override
public void deliverError(Exception e) {
displayException(e);
}
@Override
protected boolean onForwardSwipe() {
// If user has picked an entity, move along to form entry
if (selectedIntent != null) {
if (inAwesomeMode &&
detailView != null &&
detailView.getCurrentTab() < detailView.getTabCount() - 1) {
return false;
}
if (!mViewMode) {
select();
}
}
return true;
}
@Override
protected boolean onBackwardSwipe() {
if (inAwesomeMode && detailView != null && detailView.getCurrentTab() > 0) {
return false;
}
finish();
return true;
}
//Below is helper code for the Refresh Feature.
//this is a dev feature and should get restructured before release in prod.
//If the devloper setting is turned off this code should do nothing.
private void triggerRebuild() {
if (loader == null && !EntityLoaderTask.attachToActivity(this)) {
EntityLoaderTask theloader = new EntityLoaderTask(shortSelect, asw.getEvaluationContext());
theloader.attachListener(this);
theloader.execute(selectDatum.getNodeset());
}
}
private void startTimer() {
if (!DeveloperPreferences.isListRefreshEnabled()) {
return;
}
synchronized (timerLock) {
if (myTimer == null) {
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!cancelled) {
triggerRebuild();
}
}
});
}
}, 15 * 1000, 15 * 1000);
cancelled = false;
}
}
}
private void stopTimer() {
synchronized (timerLock) {
if (myTimer != null) {
myTimer.cancel();
myTimer = null;
cancelled = true;
}
}
}
}
| app/src/org/commcare/dalvik/activities/EntitySelectActivity.java | package org.commcare.dalvik.activities;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import org.commcare.android.adapters.EntityListAdapter;
import org.commcare.android.fragments.ContainerFragment;
import org.commcare.android.framework.CommCareActivity;
import org.commcare.android.framework.SaveSessionCommCareActivity;
import org.commcare.android.logic.DetailCalloutListenerDefaultImpl;
import org.commcare.android.models.AndroidSessionWrapper;
import org.commcare.android.models.Entity;
import org.commcare.android.models.NodeEntityFactory;
import org.commcare.android.tasks.EntityLoaderListener;
import org.commcare.android.tasks.EntityLoaderTask;
import org.commcare.android.util.AndroidInstanceInitializer;
import org.commcare.android.util.DetailCalloutListener;
import org.commcare.android.util.SerializationUtil;
import org.commcare.android.view.EntityView;
import org.commcare.android.view.TabbedDetailView;
import org.commcare.android.view.ViewUtil;
import org.commcare.dalvik.BuildConfig;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.commcare.dalvik.dialogs.DialogChoiceItem;
import org.commcare.dalvik.dialogs.PaneledChoiceDialog;
import org.commcare.dalvik.geo.HereFunctionHandler;
import org.commcare.dalvik.preferences.CommCarePreferences;
import org.commcare.dalvik.preferences.DeveloperPreferences;
import org.commcare.session.CommCareSession;
import org.commcare.session.SessionFrame;
import org.commcare.suite.model.Action;
import org.commcare.suite.model.Callout;
import org.commcare.suite.model.CalloutData;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.DetailField;
import org.commcare.suite.model.SessionDatum;
import org.javarosa.core.model.data.GeoPointData;
import org.javarosa.core.model.data.UncastData;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.activities.GeoPointActivity;
import org.odk.collect.android.views.media.AudioController;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
/**
* TODO: Lots of locking and state-based cleanup
*
* @author ctsims
*/
public class EntitySelectActivity extends SaveSessionCommCareActivity
implements TextWatcher,
EntityLoaderListener,
OnItemClickListener,
TextToSpeech.OnInitListener,
DetailCalloutListener {
private static final String TAG = EntitySelectActivity.class.getSimpleName();
private CommCareSession session;
private AndroidSessionWrapper asw;
public static final String EXTRA_ENTITY_KEY = "esa_entity_key";
private static final String EXTRA_IS_MAP = "is_map";
private static final int CONFIRM_SELECT = 0;
private static final int MAP_SELECT = 2;
private static final int BARCODE_FETCH = 1;
private static final int CALLOUT = 3;
private static final int LOCATION_REQUEST = 4;
private static final int MENU_SORT = Menu.FIRST + 1;
private static final int MENU_MAP = Menu.FIRST + 2;
private static final int MENU_ACTION = Menu.FIRST + 3;
private EditText searchbox;
private TextView searchResultStatus;
private EntityListAdapter adapter;
private LinearLayout header;
private ImageButton barcodeButton;
private SearchView searchView;
private MenuItem searchItem;
private TextToSpeech tts;
private SessionDatum selectDatum;
private boolean mResultIsMap = false;
private boolean mMappingEnabled = false;
// Is the detail screen for showing entities, without option for moving
// forward on to form manipulation?
private boolean mViewMode = false;
// No detail confirm screen is defined for this entity select
private boolean mNoDetailMode = false;
private EntityLoaderTask loader;
private boolean inAwesomeMode = false;
private FrameLayout rightFrame;
private TabbedDetailView detailView;
private Intent selectedIntent = null;
private String filterString = "";
private Detail shortSelect;
private DataSetObserver mListStateObserver;
private OnClickListener barcodeScanOnClickListener;
private boolean resuming = false;
private boolean startOther = false;
private boolean rightFrameSetup = false;
private NodeEntityFactory factory;
private Timer myTimer;
private final Object timerLock = new Object();
private boolean cancelled;
private ContainerFragment<EntityListAdapter> containerFragment;
// Singleton HereFunctionHandler used by entities.
// The location inside is not calculated until GeoPointActivity returns.
public static final HereFunctionHandler hereFunctionHandler = new HereFunctionHandler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.createDataSetObserver();
if (savedInstanceState != null) {
mResultIsMap = savedInstanceState.getBoolean(EXTRA_IS_MAP, false);
}
asw = CommCareApplication._().getCurrentSessionWrapper();
session = asw.getSession();
if (session.getCommand() == null) {
// session ended, avoid (session dependent) setup because session
// management will exit the activity in onResume
return;
}
selectDatum = session.getNeededDatum();
shortSelect = session.getDetail(selectDatum.getShortDetail());
mNoDetailMode = selectDatum.getLongDetail() == null;
if (this.getString(R.string.panes).equals("two") && !mNoDetailMode) {
//See if we're on a big 'ol screen.
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//If we're in landscape mode, we can display this with the awesome UI.
//Inflate and set up the normal view for now.
setContentView(R.layout.screen_compound_select);
View.inflate(this, R.layout.entity_select_layout, (ViewGroup)findViewById(R.id.screen_compound_select_left_pane));
inAwesomeMode = true;
rightFrame = (FrameLayout)findViewById(R.id.screen_compound_select_right_pane);
TextView message = (TextView)findViewById(R.id.screen_compound_select_prompt);
//use the old method here because some Android versions don't like Spannables for titles
message.setText(Localization.get("select.placeholder.message", new String[]{Localization.get("cchq.case")}));
} else {
setContentView(R.layout.entity_select_layout);
//So we're not in landscape mode anymore, but were before. If we had something selected, we
//need to go to the detail screen instead.
if (savedInstanceState != null) {
Intent intent = this.getIntent();
TreeReference selectedRef = SerializationUtil.deserializeFromIntent(intent,
EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class);
if (selectedRef != null) {
// remove the reference from this intent, ensuring we
// don't re-launch the detail for an entity even after
// it being de-selected.
intent.removeExtra(EntityDetailActivity.CONTEXT_REFERENCE);
// attach the selected entity to the new detail intent
// we're launching
Intent detailIntent = getDetailIntent(selectedRef, null);
startOther = true;
startActivityForResult(detailIntent, CONFIRM_SELECT);
}
}
}
} else {
setContentView(R.layout.entity_select_layout);
}
ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list));
view.setOnItemClickListener(this);
setupDivider(view);
TextView searchLabel = (TextView)findViewById(R.id.screen_entity_select_search_label);
//use the old method here because some Android versions don't like Spannables for titles
searchLabel.setText(Localization.get("select.search.label"));
searchLabel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// get the focus on the edittext by performing click
searchbox.performClick();
// then force the keyboard up since performClick() apparently isn't enough on some devices
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// only will trigger it if no physical keyboard is open
inputMethodManager.showSoftInput(searchbox, InputMethodManager.SHOW_IMPLICIT);
}
});
searchbox = (EditText)findViewById(R.id.searchbox);
searchbox.setMaxLines(3);
searchbox.setHorizontallyScrolling(false);
searchResultStatus = (TextView)findViewById(R.id.no_search_results);
header = (LinearLayout)findViewById(R.id.entity_select_header);
mViewMode = session.isViewCommand(session.getCommand());
barcodeButton = (ImageButton)findViewById(R.id.barcodeButton);
Callout callout = shortSelect.getCallout();
if (callout == null) {
barcodeScanOnClickListener = makeBarcodeClickListener();
} else {
barcodeScanOnClickListener = makeCalloutClickListener(callout);
}
barcodeButton.setOnClickListener(barcodeScanOnClickListener);
searchbox.addTextChangedListener(this);
searchbox.requestFocus();
persistAdapterState(view);
//cts: disabling for non-demo purposes
//tts = new TextToSpeech(this, this);
restoreLastQueryString();
if (!isUsingActionBar()) {
searchbox.setText(lastQueryString);
}
}
private void persistAdapterState(ListView view) {
FragmentManager fm = this.getSupportFragmentManager();
containerFragment = (ContainerFragment)fm.findFragmentByTag("entity-adapter");
// stateHolder and its previous state aren't null if the activity is
// being created due to an orientation change.
if (containerFragment == null) {
containerFragment = new ContainerFragment<>();
fm.beginTransaction().add(containerFragment, "entity-adapter").commit();
} else {
adapter = containerFragment.getData();
// on orientation change
if (adapter != null) {
view.setAdapter(adapter);
setupDivider(view);
findViewById(R.id.entity_select_loading).setVisibility(View.GONE);
}
}
}
/**
* @return A click listener that launches QR code scanner
*/
private View.OnClickListener makeBarcodeClickListener() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent("com.google.zxing.client.android.SCAN");
try {
EntitySelectActivity.this.startActivityForResult(i, BARCODE_FETCH);
} catch (ActivityNotFoundException anfe) {
Toast.makeText(EntitySelectActivity.this,
"No barcode reader available! You can install one " +
"from the android market.",
Toast.LENGTH_LONG).show();
}
}
};
}
/**
* Build click listener from callout: set button's image, get intent action,
* and copy extras into intent.
*
* @param callout contains intent action and extras, and sometimes button image
* @return click listener that launches the callout's activity with the
* associated callout extras
*/
private View.OnClickListener makeCalloutClickListener(Callout callout) {
final CalloutData calloutData = callout.getRawCalloutData();
if (calloutData.getImage() != null) {
setupImageLayout(barcodeButton, calloutData.getImage());
}
final Intent i = new Intent(calloutData.getActionName());
for (Map.Entry<String, String> keyValue : calloutData.getExtras().entrySet()) {
i.putExtra(keyValue.getKey(), keyValue.getValue());
}
return new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
EntitySelectActivity.this.startActivityForResult(i, CALLOUT);
} catch (ActivityNotFoundException anfe) {
Toast.makeText(EntitySelectActivity.this,
"No application found for action: " + i.getAction(),
Toast.LENGTH_LONG).show();
}
}
};
}
/**
* Updates the ImageView layout that is passed in, based on the
* new id and source
*/
private void setupImageLayout(View layout, final String imagePath) {
ImageView iv = (ImageView)layout;
Bitmap b;
if (!imagePath.equals("")) {
try {
b = BitmapFactory.decodeStream(ReferenceManager._().DeriveReference(imagePath).getStream());
if (b == null) {
// Input stream could not be used to derive bitmap, so
// showing error-indicating image
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive));
} else {
iv.setImageBitmap(b);
}
} catch (IOException | InvalidReferenceException ex) {
ex.printStackTrace();
// Error loading image, default to folder button
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_archive));
}
} else {
// no image passed in, draw a white background
iv.setImageDrawable(getResources().getDrawable(R.color.white));
}
}
private void createDataSetObserver() {
mListStateObserver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
//update the search results box
String query = getSearchText().toString();
if (!"".equals(query)) {
searchResultStatus.setText(Localization.get("select.search.status", new String[]{
"" + adapter.getCount(true, false),
"" + adapter.getCount(true, true),
query
}));
searchResultStatus.setVisibility(View.VISIBLE);
} else {
searchResultStatus.setVisibility(View.GONE);
}
}
};
}
@Override
protected boolean isTopNavEnabled() {
return true;
}
@Override
public String getActivityTitle() {
return null;
}
@Override
protected void onResume() {
super.onResume();
//Don't go through making the whole thing if we're finishing anyway.
if (this.isFinishing() || startOther) {
return;
}
if (adapter != null) {
adapter.registerDataSetObserver(mListStateObserver);
}
if (!resuming && !mNoDetailMode && this.getIntent().hasExtra(EXTRA_ENTITY_KEY)) {
TreeReference entity =
selectDatum.getEntityFromID(asw.getEvaluationContext(),
this.getIntent().getStringExtra(EXTRA_ENTITY_KEY));
if (entity != null) {
if (inAwesomeMode) {
if (adapter != null) {
displayReferenceAwesome(entity, adapter.getPosition(entity));
updateSelectedItem(entity, true);
}
} else {
//Once we've done the initial dispatch, we don't want to end up triggering it later.
this.getIntent().removeExtra(EXTRA_ENTITY_KEY);
Intent i = getDetailIntent(entity, null);
if (adapter != null) {
i.putExtra("entity_detail_index", adapter.getPosition(entity));
i.putExtra(EntityDetailActivity.DETAIL_PERSISTENT_ID,
selectDatum.getShortDetail());
}
startActivityForResult(i, CONFIRM_SELECT);
return;
}
}
}
refreshView();
}
/**
* Get form list from database and insert into view.
*/
private void refreshView() {
try {
//TODO: Get ec into these text's
String[] headers = new String[shortSelect.getFields().length];
for (int i = 0; i < headers.length; ++i) {
headers[i] = shortSelect.getFields()[i].getHeader().evaluate();
if ("address".equals(shortSelect.getFields()[i].getTemplateForm())) {
this.mMappingEnabled = true;
}
}
header.removeAllViews();
// only add headers if we're not using grid mode
if (!shortSelect.usesGridView()) {
//Hm, sadly we possibly need to rebuild this each time.
EntityView v = new EntityView(this, shortSelect, headers);
header.addView(v);
}
if (adapter == null &&
loader == null &&
!EntityLoaderTask.attachToActivity(this)) {
EntityLoaderTask theloader =
new EntityLoaderTask(shortSelect, asw.getEvaluationContext());
theloader.attachListener(this);
theloader.execute(selectDatum.getNodeset());
} else {
startTimer();
}
} catch (RuntimeException re) {
createErrorDialog(re.getMessage(), true);
}
}
@Override
protected void onPause() {
super.onPause();
stopTimer();
if (adapter != null) {
adapter.unregisterDataSetObserver(mListStateObserver);
}
}
@Override
protected void onStop() {
super.onStop();
stopTimer();
saveLastQueryString();
}
/**
* Get an intent for displaying the confirm detail screen for an element (either just populates
* the given intent with the necessary information, or creates a new one if it is null)
*
* @param contextRef reference to the selected element for which to display
* detailed view
* @return The intent argument, or a newly created one, with element
* selection information attached.
*/
private Intent getDetailIntent(TreeReference contextRef, Intent detailIntent) {
if (detailIntent == null) {
detailIntent = new Intent(getApplicationContext(), EntityDetailActivity.class);
}
return populateDetailIntent(detailIntent, contextRef, this.selectDatum, this.asw);
}
/**
* Attach all element selection information to the intent argument and return the resulting
* intent
*/
protected static Intent populateDetailIntent(Intent detailIntent,
TreeReference contextRef,
SessionDatum selectDatum,
AndroidSessionWrapper asw) {
String caseId = SessionDatum.getCaseIdFromReference(
contextRef, selectDatum, asw.getEvaluationContext());
detailIntent.putExtra(SessionFrame.STATE_DATUM_VAL, caseId);
// Include long datum info if present
if (selectDatum.getLongDetail() != null) {
detailIntent.putExtra(EntityDetailActivity.DETAIL_ID,
selectDatum.getLongDetail());
detailIntent.putExtra(EntityDetailActivity.DETAIL_PERSISTENT_ID,
selectDatum.getPersistentDetail());
}
SerializationUtil.serializeToIntent(detailIntent,
EntityDetailActivity.CONTEXT_REFERENCE, contextRef);
return detailIntent;
}
@Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
if (id == EntityListAdapter.SPECIAL_ACTION) {
triggerDetailAction();
return;
}
TreeReference selection = adapter.getItem(position);
if (CommCarePreferences.isEntityDetailLoggingEnabled()) {
Logger.log(EntityDetailActivity.class.getSimpleName(), selectDatum.getLongDetail());
}
if (inAwesomeMode) {
displayReferenceAwesome(selection, position);
updateSelectedItem(selection, false);
} else {
Intent i = getDetailIntent(selection, null);
i.putExtra("entity_detail_index", position);
if (mNoDetailMode) {
// Not actually launching detail intent because there's no confirm detail available
returnWithResult(i);
} else {
startActivityForResult(i, CONFIRM_SELECT);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case BARCODE_FETCH:
processBarcodeFetch(resultCode, intent);
break;
case CALLOUT:
processCalloutResult(resultCode, intent);
break;
case CONFIRM_SELECT:
resuming = true;
if (resultCode == RESULT_OK && !mViewMode) {
// create intent for return and store path
returnWithResult(intent);
return;
} else {
//Did we enter the detail from mapping mode? If so, go back to that
if (mResultIsMap) {
mResultIsMap = false;
Intent i = new Intent(this, EntityMapActivity.class);
this.startActivityForResult(i, MAP_SELECT);
return;
}
if (inAwesomeMode) {
// Retain original element selection
TreeReference r =
SerializationUtil.deserializeFromIntent(intent,
EntityDetailActivity.CONTEXT_REFERENCE,
TreeReference.class);
if (r != null && adapter != null) {
// TODO: added 'adapter != null' due to a
// NullPointerException, we need to figure out how to
// make sure adapter is never null -- PLM
this.displayReferenceAwesome(r, adapter.getPosition(r));
updateSelectedItem(r, true);
}
AudioController.INSTANCE.releaseCurrentMediaEntity();
}
return;
}
case MAP_SELECT:
if (resultCode == RESULT_OK) {
TreeReference r =
SerializationUtil.deserializeFromIntent(intent,
EntityDetailActivity.CONTEXT_REFERENCE,
TreeReference.class);
if (inAwesomeMode) {
this.displayReferenceAwesome(r, adapter.getPosition(r));
} else {
Intent i = this.getDetailIntent(r, null);
if (mNoDetailMode) {
returnWithResult(i);
} else {
//To go back to map mode if confirm is false
mResultIsMap = true;
i.putExtra("entity_detail_index", adapter.getPosition(r));
startActivityForResult(i, CONFIRM_SELECT);
}
return;
}
} else {
refreshView();
return;
}
case LOCATION_REQUEST:
if (resultCode == RESULT_OK) {
hereFunctionHandler.setLocationString(FormEntryActivity.LOCATION_RESULT);
}
default:
super.onActivityResult(requestCode, resultCode, intent);
}
}
private void processBarcodeFetch(int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK) {
String result = intent.getStringExtra("SCAN_RESULT");
if (result != null) {
result = result.trim();
}
setSearchText(result);
}
}
private void processCalloutResult(int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK) {
String result = intent.getStringExtra("odk_intent_data");
if (result != null){
setSearchText(result.trim());
} else {
for (String key : shortSelect.getCallout().getResponses()) {
result = intent.getExtras().getString(key);
if (result != null) {
setSearchText(result);
return;
}
}
}
}
}
/**
* Finish this activity, including all extras from the given intent in the finishing intent
*/
private void returnWithResult(Intent intent) {
Intent i = new Intent(this.getIntent());
i.putExtras(intent.getExtras());
setResult(RESULT_OK, i);
finish();
}
@Override
public void afterTextChanged(Editable incomingEditable) {
final String incomingString = incomingEditable.toString();
final String currentSearchText = getSearchText().toString();
if (incomingString.equals(currentSearchText)) {
filterString = currentSearchText;
if (adapter != null) {
adapter.applyFilter(filterString);
}
}
if (!isUsingActionBar()) {
lastQueryString = filterString;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//use the old method here because some Android versions don't like Spannables for titles
menu.add(0, MENU_SORT, MENU_SORT, Localization.get("select.menu.sort")).setIcon(
android.R.drawable.ic_menu_sort_alphabetically);
if (mMappingEnabled) {
menu.add(0, MENU_MAP, MENU_MAP, Localization.get("select.menu.map")).setIcon(
android.R.drawable.ic_menu_mapmode);
}
if (shortSelect != null) {
Action action = shortSelect.getCustomAction();
if (action != null) {
ViewUtil.addDisplayToMenu(this, menu, MENU_ACTION,
action.getDisplay().evaluate());
}
}
tryToAddActionSearchBar(this, menu, new ActionBarInstantiator() {
// again, this should be unnecessary...
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onActionBarFound(MenuItem searchItem, SearchView searchView) {
EntitySelectActivity.this.searchItem = searchItem;
EntitySelectActivity.this.searchView = searchView;
// restore last query string in the searchView if there is one
if (lastQueryString != null && lastQueryString.length() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
searchItem.expandActionView();
}
searchView.setQuery(lastQueryString, false);
if (BuildConfig.DEBUG) {
Log.v(TAG, "Setting lastQueryString in searchView: (" + lastQueryString + ")");
}
if (adapter != null) {
adapter.applyFilter(lastQueryString == null ? "" : lastQueryString);
}
}
EntitySelectActivity.this.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
lastQueryString = newText;
filterString = newText;
if (adapter != null) {
adapter.applyFilter(newText);
}
return false;
}
});
}
});
return true;
}
/**
* Checks if this activity uses the ActionBar
*/
private boolean isUsingActionBar() {
return searchView != null;
}
@SuppressWarnings("NewApi")
private CharSequence getSearchText() {
if (isUsingActionBar()) {
return searchView.getQuery();
}
return searchbox.getText();
}
@SuppressWarnings("NewApi")
private void setSearchText(CharSequence text) {
if (isUsingActionBar()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
searchItem.expandActionView();
}
searchView.setQuery(text, false);
}
searchbox.setText(text);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// only enable sorting once entity loading is complete
menu.findItem(MENU_SORT).setEnabled(adapter != null);
// hide sorting menu when using async loading strategy
menu.findItem(MENU_SORT).setVisible((shortSelect == null || !shortSelect.useAsyncStrategy()));
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SORT:
createSortMenu();
return true;
case MENU_MAP:
Intent i = new Intent(this, EntityMapActivity.class);
this.startActivityForResult(i, MAP_SELECT);
return true;
case MENU_ACTION:
triggerDetailAction();
return true;
// handling click on the barcode scanner's actionbar
// trying to set the onclicklistener in its view in the onCreateOptionsMenu method does not work because it returns null
case R.id.barcode_scan_action_bar:
barcodeScanOnClickListener.onClick(null);
return true;
// this is needed because superclasses do not implement the menu_settings click
case R.id.menu_settings:
CommCareHomeActivity.createPreferencesMenu(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private void triggerDetailAction() {
Action action = shortSelect.getCustomAction();
try {
asw.executeStackActions(action.getStackOperations());
} catch (XPathTypeMismatchException e) {
Logger.exception(e);
CommCareActivity.createErrorDialog(this, e.getMessage(), true);
return;
}
this.setResult(CommCareHomeActivity.RESULT_RESTART);
this.finish();
}
private void createSortMenu() {
final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, Localization.get("select.menu.sort"));
dialog.setChoiceItems(getSortOptionsList(dialog));
dialog.show();
}
private DialogChoiceItem[] getSortOptionsList(final PaneledChoiceDialog dialog) {
SessionDatum datum = session.getNeededDatum();
DetailField[] fields = session.getDetail(datum.getShortDetail()).getFields();
List<String> namesList = new ArrayList<>();
final int[] keyArray = new int[fields.length];
int[] sorts = adapter.getCurrentSort();
int currentSort = sorts.length == 1 ? sorts[0] : -1;
boolean reversed = adapter.isCurrentSortReversed();
int added = 0;
for (int i = 0; i < fields.length; ++i) {
String result = fields[i].getHeader().evaluate();
if (!"".equals(result)) {
String prepend = "";
if (currentSort == -1) {
for (int j = 0; j < sorts.length; ++j) {
if (sorts[j] == i) {
prepend = (j + 1) + " " + (fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) ");
}
}
} else if (currentSort == i) {
prepend = reversed ^ fields[i].getSortDirection() == DetailField.DIRECTION_DESCENDING ? "(v) " : "(^) ";
}
namesList.add(prepend + result);
keyArray[added] = i;
added++;
}
}
DialogChoiceItem[] choiceItems = new DialogChoiceItem[namesList.size()];
for (int i = 0; i < namesList.size(); i++) {
final int index = i;
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(EntitySelectActivity.this, GeoPointActivity.class);
startActivityForResult(i, LOCATION_REQUEST);
adapter.sortEntities(new int[]{keyArray[index]});
adapter.applyFilter(getSearchText().toString());
dialog.dismiss();
}
};
DialogChoiceItem item = new DialogChoiceItem(namesList.get(i), -1, listener);
choiceItems[i] = item;
}
return choiceItems;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (loader != null) {
if (isFinishing()) {
loader.cancel(false);
} else {
loader.detachActivity();
}
}
if (adapter != null) {
adapter.signalKilled();
}
if (tts != null) {
tts.stop();
tts.shutdown();
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
//using the default speech engine for now.
} else {
}
}
@Override
public void deliverResult(List<Entity<TreeReference>> entities,
List<TreeReference> references,
NodeEntityFactory factory) {
loader = null;
Detail detail = session.getDetail(selectDatum.getShortDetail());
int[] order = detail.getSortOrder();
for (int i = 0; i < detail.getFields().length; ++i) {
String header = detail.getFields()[i].getHeader().evaluate();
if (order.length == 0 && !"".equals(header)) {
order = new int[]{i};
}
}
ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list));
setupDivider(view);
adapter = new EntityListAdapter(EntitySelectActivity.this, detail, references, entities, order, tts, factory);
view.setAdapter(adapter);
adapter.registerDataSetObserver(this.mListStateObserver);
containerFragment.setData(adapter);
// Pre-select entity if one was provided in original intent
if (!resuming && !mNoDetailMode && inAwesomeMode && this.getIntent().hasExtra(EXTRA_ENTITY_KEY)) {
TreeReference entity =
selectDatum.getEntityFromID(asw.getEvaluationContext(),
this.getIntent().getStringExtra(EXTRA_ENTITY_KEY));
if (entity != null) {
displayReferenceAwesome(entity, adapter.getPosition(entity));
updateSelectedItem(entity, true);
}
}
findViewById(R.id.entity_select_loading).setVisibility(View.GONE);
if (adapter != null && filterString != null && !"".equals(filterString)) {
adapter.applyFilter(filterString);
}
//In landscape we want to select something now. Either the top item, or the most recently selected one
if (inAwesomeMode) {
updateSelectedItem(true);
}
this.startTimer();
}
private void setupDivider(ListView view) {
boolean useNewDivider = shortSelect.usesGridView();
if (useNewDivider) {
int viewWidth = view.getWidth();
float density = getResources().getDisplayMetrics().density;
int viewWidthDP = (int)(viewWidth / density);
// sometimes viewWidth is 0, and in this case we default to a reasonable value taken from dimens.xml
int dividerWidth = viewWidth == 0 ? (int)getResources().getDimension(R.dimen.entity_select_divider_left_inset) : (int)(viewWidth / 6.0);
Drawable divider = getResources().getDrawable(R.drawable.divider_case_list_modern);
if (BuildConfig.DEBUG) {
Log.v(TAG, "ListView divider is: " + divider + ", estimated divider width is: " + dividerWidth + ", viewWidth (dp) is: " + viewWidthDP);
}
if (BuildConfig.DEBUG && (divider == null || !(divider instanceof LayerDrawable))) {
throw new AssertionError("Divider should be a LayerDrawable!");
}
LayerDrawable layerDrawable = (LayerDrawable)divider;
dividerWidth += (int)getResources().getDimension(R.dimen.row_padding_horizontal);
layerDrawable.setLayerInset(0, dividerWidth, 0, 0, 0);
view.setDivider(layerDrawable);
} else {
view.setDivider(null);
}
view.setDividerHeight((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()));
}
private void updateSelectedItem(boolean forceMove) {
TreeReference chosen = null;
if (selectedIntent != null) {
chosen = SerializationUtil.deserializeFromIntent(selectedIntent, EntityDetailActivity.CONTEXT_REFERENCE, TreeReference.class);
}
updateSelectedItem(chosen, forceMove);
}
private void updateSelectedItem(TreeReference selected, boolean forceMove) {
if (adapter == null) {
return;
}
if (selected != null) {
adapter.notifyCurrentlyHighlighted(selected);
if (forceMove) {
ListView view = ((ListView)this.findViewById(R.id.screen_entity_select_list));
view.setSelection(adapter.getPosition(selected));
}
}
}
@Override
public void attach(EntityLoaderTask task) {
findViewById(R.id.entity_select_loading).setVisibility(View.VISIBLE);
this.loader = task;
}
private void select() {
// create intent for return and store path
Intent i = new Intent(EntitySelectActivity.this.getIntent());
i.putExtra(SessionFrame.STATE_DATUM_VAL, selectedIntent.getStringExtra(SessionFrame.STATE_DATUM_VAL));
setResult(RESULT_OK, i);
finish();
}
@Override
public void callRequested(String phoneNumber) {
DetailCalloutListenerDefaultImpl.callRequested(this, phoneNumber);
}
@Override
public void addressRequested(String address) {
DetailCalloutListenerDefaultImpl.addressRequested(this, address);
}
@Override
public void playVideo(String videoRef) {
DetailCalloutListenerDefaultImpl.playVideo(this, videoRef);
}
@Override
public void performCallout(CalloutData callout, int id) {
DetailCalloutListenerDefaultImpl.performCallout(this, callout, id);
}
private void displayReferenceAwesome(final TreeReference selection, int detailIndex) {
selectedIntent = getDetailIntent(selection, getIntent());
//this should be 100% "fragment" able
if (!rightFrameSetup) {
findViewById(R.id.screen_compound_select_prompt).setVisibility(View.GONE);
View.inflate(this, R.layout.entity_detail, rightFrame);
Button next = (Button)findViewById(R.id.entity_select_button);
//use the old method here because some Android versions don't like Spannables for titles
next.setText(Localization.get("select.detail.confirm"));
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
select();
}
});
if (mViewMode) {
next.setVisibility(View.GONE);
next.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
String passedCommand = selectedIntent.getStringExtra(SessionFrame.STATE_COMMAND_ID);
if (passedCommand != null) {
mViewMode = session.isViewCommand(passedCommand);
} else {
mViewMode = session.isViewCommand(session.getCommand());
}
detailView = (TabbedDetailView)rightFrame.findViewById(R.id.entity_detail_tabs);
detailView.setRoot(detailView);
factory = new NodeEntityFactory(session.getDetail(selectedIntent.getStringExtra(EntityDetailActivity.DETAIL_ID)), session.getEvaluationContext(new AndroidInstanceInitializer(session)));
Detail detail = factory.getDetail();
detailView.setDetail(detail);
if (detail.isCompound()) {
// border around right panel doesn't look right when there are tabs
rightFrame.setBackgroundDrawable(null);
}
rightFrameSetup = true;
}
detailView.refresh(factory.getDetail(), selection, detailIndex);
}
@Override
public void deliverError(Exception e) {
displayException(e);
}
@Override
protected boolean onForwardSwipe() {
// If user has picked an entity, move along to form entry
if (selectedIntent != null) {
if (inAwesomeMode &&
detailView != null &&
detailView.getCurrentTab() < detailView.getTabCount() - 1) {
return false;
}
if (!mViewMode) {
select();
}
}
return true;
}
@Override
protected boolean onBackwardSwipe() {
if (inAwesomeMode && detailView != null && detailView.getCurrentTab() > 0) {
return false;
}
finish();
return true;
}
//Below is helper code for the Refresh Feature.
//this is a dev feature and should get restructured before release in prod.
//If the devloper setting is turned off this code should do nothing.
private void triggerRebuild() {
if (loader == null && !EntityLoaderTask.attachToActivity(this)) {
EntityLoaderTask theloader = new EntityLoaderTask(shortSelect, asw.getEvaluationContext());
theloader.attachListener(this);
theloader.execute(selectDatum.getNodeset());
}
}
private void startTimer() {
if (!DeveloperPreferences.isListRefreshEnabled()) {
return;
}
synchronized (timerLock) {
if (myTimer == null) {
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!cancelled) {
triggerRebuild();
}
}
});
}
}, 15 * 1000, 15 * 1000);
cancelled = false;
}
}
}
private void stopTimer() {
synchronized (timerLock) {
if (myTimer != null) {
myTimer.cancel();
myTimer = null;
cancelled = true;
}
}
}
}
| Bug fix: LOCATION_RESULT
| app/src/org/commcare/dalvik/activities/EntitySelectActivity.java | Bug fix: LOCATION_RESULT | <ide><path>pp/src/org/commcare/dalvik/activities/EntitySelectActivity.java
<ide> }
<ide> case LOCATION_REQUEST:
<ide> if (resultCode == RESULT_OK) {
<del> hereFunctionHandler.setLocationString(FormEntryActivity.LOCATION_RESULT);
<add> hereFunctionHandler.setLocationString(
<add> intent.getStringExtra(FormEntryActivity.LOCATION_RESULT));
<ide> }
<ide> default:
<ide> super.onActivityResult(requestCode, resultCode, intent); |
|
Java | apache-2.0 | 3e895c6e9549b48856598a8ea949e1e2d904732c | 0 | chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.camel.component;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import org.apache.activemq.EnhancedConnection;
import org.apache.activemq.advisory.DestinationEvent;
import org.apache.activemq.advisory.DestinationListener;
import org.apache.activemq.advisory.DestinationSource;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Endpoint;
import org.apache.camel.component.jms.JmsEndpoint;
import org.apache.camel.component.jms.JmsQueueEndpoint;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A helper bean which populates a {@link CamelContext} with ActiveMQ Queue endpoints
*
*
* @org.apache.xbean.XBean
*/
public class CamelEndpointLoader implements CamelContextAware {
private static final transient Logger LOG = LoggerFactory.getLogger(CamelEndpointLoader.class);
private CamelContext camelContext;
private EnhancedConnection connection;
private ConnectionFactory connectionFactory;
private ActiveMQComponent component;
public CamelEndpointLoader() {
}
public CamelEndpointLoader(CamelContext camelContext) {
this.camelContext = camelContext;
}
/**
*
* @throws Exception
* @org.apache.xbean.InitMethod
*/
@PostConstruct
public void afterPropertiesSet() throws Exception {
ObjectHelper.notNull(camelContext, "camelContext");
if (connection == null) {
Connection value = getConnectionFactory().createConnection();
if (value instanceof EnhancedConnection) {
connection = (EnhancedConnection) value;
}
else {
throw new IllegalArgumentException("Created JMS Connection is not an EnhancedConnection: " + value);
}
}
connection.start();
DestinationSource source = connection.getDestinationSource();
source.setDestinationListener(new DestinationListener() {
public void onDestinationEvent(DestinationEvent event) {
try {
ActiveMQDestination destination = event.getDestination();
if (destination instanceof ActiveMQQueue) {
ActiveMQQueue queue = (ActiveMQQueue) destination;
if (event.isAddOperation()) {
addQueue(queue);
}
else {
removeQueue(queue);
}
}
else if (destination instanceof ActiveMQTopic) {
ActiveMQTopic topic = (ActiveMQTopic) destination;
if (event.isAddOperation()) {
addTopic(topic);
}
else {
removeTopic(topic);
}
}
}
catch (Exception e) {
LOG.warn("Caught: " + e, e);
}
}
});
Set<ActiveMQQueue> queues = source.getQueues();
for (ActiveMQQueue queue : queues) {
addQueue(queue);
}
Set<ActiveMQTopic> topics = source.getTopics();
for (ActiveMQTopic topic : topics) {
addTopic(topic);
}
}
/**
*
* @throws Exception
* @org.apache.xbean.DestroyMethod
*/
@PreDestroy
public void destroy() throws Exception {
if (connection != null) {
connection.close();
connection = null;
}
}
// Properties
//-------------------------------------------------------------------------
public CamelContext getCamelContext() {
return camelContext;
}
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
public EnhancedConnection getConnection() {
return connection;
}
public ConnectionFactory getConnectionFactory() {
if (connectionFactory == null
&& getComponent().getConfiguration() instanceof ActiveMQConfiguration) {
connectionFactory = ((ActiveMQConfiguration) getComponent()
.getConfiguration()).createConnectionFactory();
}
return connectionFactory;
}
public void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public ActiveMQComponent getComponent() {
if (component == null) {
component = camelContext.getComponent("activemq", ActiveMQComponent.class);
}
return component;
}
public void setComponent(ActiveMQComponent component) {
this.component = component;
}
// Implementation methods
//-------------------------------------------------------------------------
protected void addQueue(ActiveMQQueue queue) throws Exception {
String queueUri = getQueueUri(queue);
ActiveMQComponent jmsComponent = getComponent();
Endpoint endpoint = new JmsQueueEndpoint(queueUri, jmsComponent, queue.getPhysicalName(), jmsComponent.getConfiguration());
camelContext.addEndpoint(queueUri, endpoint);
}
protected String getQueueUri(ActiveMQQueue queue) {
return "activemq:" + queue.getPhysicalName();
}
protected void removeQueue(ActiveMQQueue queue) throws Exception {
String queueUri = getQueueUri(queue);
// lur cache of endpoints so they will disappear in time
// this feature needs a new component api - list available endpoints
camelContext.removeEndpoints(queueUri);
}
protected void addTopic(ActiveMQTopic topic) throws Exception {
String topicUri = getTopicUri(topic);
ActiveMQComponent jmsComponent = getComponent();
Endpoint endpoint = new JmsEndpoint(topicUri, jmsComponent, topic.getPhysicalName(), true, jmsComponent.getConfiguration());
camelContext.addEndpoint(topicUri, endpoint);
}
protected String getTopicUri(ActiveMQTopic topic) {
return "activemq:topic:" + topic.getPhysicalName();
}
protected void removeTopic(ActiveMQTopic topic) throws Exception {
String topicUri = getTopicUri(topic);
// lur cache of endpoints so they will disappear in time
// this feature needs a new component api - list available endpoints
camelContext.removeEndpoints(topicUri);
}
}
| activemq-camel/src/main/java/org/apache/activemq/camel/component/CamelEndpointLoader.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.camel.component;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import org.apache.activemq.EnhancedConnection;
import org.apache.activemq.advisory.DestinationEvent;
import org.apache.activemq.advisory.DestinationListener;
import org.apache.activemq.advisory.DestinationSource;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Endpoint;
import org.apache.camel.component.jms.JmsEndpoint;
import org.apache.camel.component.jms.JmsQueueEndpoint;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A helper bean which populates a {@link CamelContext} with ActiveMQ Queue endpoints
*
*
* @org.apache.xbean.XBean
*/
public class CamelEndpointLoader implements CamelContextAware {
private static final transient Logger LOG = LoggerFactory.getLogger(CamelEndpointLoader.class);
private CamelContext camelContext;
private EnhancedConnection connection;
private ConnectionFactory connectionFactory;
private ActiveMQComponent component;
public CamelEndpointLoader() {
}
public CamelEndpointLoader(CamelContext camelContext) {
this.camelContext = camelContext;
}
/**
*
* @throws Exception
* @org.apache.xbean.InitMethod
*/
@PostConstruct
public void afterPropertiesSet() throws Exception {
ObjectHelper.notNull(camelContext, "camelContext");
if (connection == null) {
Connection value = getConnectionFactory().createConnection();
if (value instanceof EnhancedConnection) {
connection = (EnhancedConnection) value;
}
else {
throw new IllegalArgumentException("Created JMS Connection is not an EnhancedConnection: " + value);
}
}
connection.start();
DestinationSource source = connection.getDestinationSource();
source.setDestinationListener(new DestinationListener() {
public void onDestinationEvent(DestinationEvent event) {
try {
ActiveMQDestination destination = event.getDestination();
if (destination instanceof ActiveMQQueue) {
ActiveMQQueue queue = (ActiveMQQueue) destination;
if (event.isAddOperation()) {
addQueue(queue);
}
else {
removeQueue(queue);
}
}
else if (destination instanceof ActiveMQTopic) {
ActiveMQTopic topic = (ActiveMQTopic) destination;
if (event.isAddOperation()) {
addTopic(topic);
}
else {
removeTopic(topic);
}
}
}
catch (Exception e) {
LOG.warn("Caught: " + e, e);
}
}
});
Set<ActiveMQQueue> queues = source.getQueues();
for (ActiveMQQueue queue : queues) {
addQueue(queue);
}
Set<ActiveMQTopic> topics = source.getTopics();
for (ActiveMQTopic topic : topics) {
addTopic(topic);
}
}
/**
*
* @throws Exception
* @org.apache.xbean.DestroyMethod
*/
@PreDestroy
public void destroy() throws Exception {
if (connection != null) {
connection.close();
connection = null;
}
}
// Properties
//-------------------------------------------------------------------------
public CamelContext getCamelContext() {
return camelContext;
}
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
public EnhancedConnection getConnection() {
return connection;
}
public ConnectionFactory getConnectionFactory() {
if (connectionFactory == null
&& getComponent().getConfiguration() instanceof ActiveMQConfiguration) {
connectionFactory = ((ActiveMQConfiguration) getComponent()
.getConfiguration()).createConnectionFactory();
}
return connectionFactory;
}
public void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public ActiveMQComponent getComponent() {
if (component == null) {
component = camelContext.getComponent("activemq", ActiveMQComponent.class);
}
return component;
}
public void setComponent(ActiveMQComponent component) {
this.component = component;
}
// Implementation methods
//-------------------------------------------------------------------------
protected void addQueue(ActiveMQQueue queue) throws Exception {
String queueUri = getQueueUri(queue);
ActiveMQComponent jmsComponent = getComponent();
Endpoint endpoint = new JmsQueueEndpoint(queueUri, jmsComponent, queue.getPhysicalName(), jmsComponent.getConfiguration());
camelContext.addEndpoint(queueUri, endpoint);
}
protected String getQueueUri(ActiveMQQueue queue) {
return "activemq:" + queue.getPhysicalName();
}
protected void removeQueue(ActiveMQQueue queue) throws Exception {
String queueUri = getQueueUri(queue);
// lur cache of endpoints so they will disappear in time
// this feature needs a new component api - list available endpoints
//camelContext.removeEndpoints(queueUri);
}
protected void addTopic(ActiveMQTopic topic) throws Exception {
String topicUri = getTopicUri(topic);
ActiveMQComponent jmsComponent = getComponent();
Endpoint endpoint = new JmsEndpoint(topicUri, jmsComponent, topic.getPhysicalName(), true, jmsComponent.getConfiguration());
camelContext.addEndpoint(topicUri, endpoint);
}
protected String getTopicUri(ActiveMQTopic topic) {
return "activemq:topic:" + topic.getPhysicalName();
}
protected void removeTopic(ActiveMQTopic topic) throws Exception {
String topicUri = getTopicUri(topic);
// lur cache of endpoints so they will disappear in time
// this feature needs a new component api - list available endpoints
//camelContext.removeEndpoints(topicUri);
}
}
| fix for: https://issues.apache.org/jira/browse/AMQ-3139
git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@1074300 13f79535-47bb-0310-9956-ffa450edef68
| activemq-camel/src/main/java/org/apache/activemq/camel/component/CamelEndpointLoader.java | fix for: https://issues.apache.org/jira/browse/AMQ-3139 | <ide><path>ctivemq-camel/src/main/java/org/apache/activemq/camel/component/CamelEndpointLoader.java
<ide> /**
<ide> * A helper bean which populates a {@link CamelContext} with ActiveMQ Queue endpoints
<ide> *
<del> *
<add> *
<ide> * @org.apache.xbean.XBean
<ide> */
<ide> public class CamelEndpointLoader implements CamelContextAware {
<ide> String queueUri = getQueueUri(queue);
<ide> // lur cache of endpoints so they will disappear in time
<ide> // this feature needs a new component api - list available endpoints
<del> //camelContext.removeEndpoints(queueUri);
<del> }
<del>
<add> camelContext.removeEndpoints(queueUri);
<add> }
<add>
<ide> protected void addTopic(ActiveMQTopic topic) throws Exception {
<ide> String topicUri = getTopicUri(topic);
<ide> ActiveMQComponent jmsComponent = getComponent();
<ide> String topicUri = getTopicUri(topic);
<ide> // lur cache of endpoints so they will disappear in time
<ide> // this feature needs a new component api - list available endpoints
<del> //camelContext.removeEndpoints(topicUri);
<add> camelContext.removeEndpoints(topicUri);
<ide> }
<ide> } |
|
Java | apache-2.0 | 937fccafab996e2769471f5fc23e5f25b2c7513a | 0 | baszero/yanel,wyona/yanel,baszero/yanel,baszero/yanel,wyona/yanel,wyona/yanel,wyona/yanel,wyona/yanel,wyona/yanel,baszero/yanel,baszero/yanel,baszero/yanel | package org.wyona.yanel.servlet.security.impl;
import org.wyona.yanel.core.map.Map;
import org.wyona.yanel.core.map.Realm;
import org.wyona.yanel.servlet.IdentityMap;
import org.wyona.yanel.servlet.YanelServlet;
import org.wyona.yanel.core.api.security.WebAuthenticator;
import org.wyona.security.core.api.AccessManagementException;
import org.wyona.security.core.ExpiredIdentityException;
import org.wyona.security.core.api.Identity;
import org.wyona.security.core.api.User;
import org.wyona.security.core.api.UserManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import java.net.URL;
import org.w3c.dom.Element;
import org.apache.log4j.Category;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.verisign.joid.consumer.OpenIdFilter;
import org.verisign.joid.util.UrlUtils;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.Discovery;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.ParameterList;
/**
*
*/
public class DefaultWebAuthenticatorImpl implements WebAuthenticator {
private static Category log = Category.getInstance(DefaultWebAuthenticatorImpl.class);
private static String OPENID_DISCOVERED_KEY = "openid-discovered";
// NOTE: The OpenID consumer manager needs to be the same instance for redirect to provider and provider verification
private ConsumerManager manager;
/**
*
*/
public void init(org.w3c.dom.Document configuration, javax.xml.transform.URIResolver resolver) throws Exception {
manager = new ConsumerManager();
}
/**
*
*/
public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response, Map map, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort) throws ServletException, IOException {
try {
Realm realm = map.getRealm(request.getServletPath());
String path = map.getPath(realm, request.getServletPath());
//Realm realm = map.getRealm(new Path(request.getServletPath()));
if (log.isDebugEnabled()) log.debug("Generic WebAuthenticator called for realm path " + path);
// HTML Form based authentication
String loginUsername = request.getParameter("yanel.login.username");
String openID = request.getParameter("yanel.login.openid");
String openIDSignature = request.getParameter("openid.sig");
if(loginUsername != null) {
HttpSession session = request.getSession(true);
try {
User user = realm.getIdentityManager().getUserManager().getUser(loginUsername, true);
if (user != null && user.authenticate(request.getParameter("yanel.login.password"))) {
log.debug("Realm: " + realm);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
return null;
} else {
log.warn("Login failed: " + loginUsername);
getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
}
} catch (ExpiredIdentityException e) {
log.warn("Login failed: [" + loginUsername + "] " + e);
getXHTMLAuthenticationForm(request, response, realm, "The account has expired!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
} catch (AccessManagementException e) {
log.warn("Login failed: [" + loginUsername + "] " + e);
getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
}
} else if (openID != null) {
// Append http scheme if missing
if (!openID.startsWith("http://")) {
openID = "http://" + openID;
}
String redirectUrlString = null;
try {
redirectUrlString = getOpenIDRedirectURL(openID, request, map);
response.sendRedirect(redirectUrlString);
} catch (Exception e) {
log.error(e, e);
getXHTMLAuthenticationForm(request, response, realm, "Login failed: " + e.getMessage() + "!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
log.debug("Redirect URL: " + redirectUrlString);
return response;
} else if (openIDSignature != null) {
log.debug("Verify OpenID provider response ...");
if (verifyOpenIDProviderResponse(request)) {
UserManager uManager = realm.getIdentityManager().getUserManager();
String openIdentity = request.getParameter("openid.identity");
if (openIdentity != null) {
if (!uManager.existsUser(openIdentity)) {
uManager.createUser(openIdentity, null, null, null);
log.warn("An OpenID user has been created: " + openIdentity);
}
User user = uManager.getUser(openIdentity);
IdentityMap identityMap = (IdentityMap)request.getSession(true).getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
request.getSession().setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
// OpenID authentication successful, hence return null instead an "exceptional" response
return null;
} else {
log.error("No openid.identity!");
getXHTMLAuthenticationForm(request, response, realm, "OpenID verification successful, but no openid.identity!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
} else {
getXHTMLAuthenticationForm(request, response, realm, "Login failed: OpenID response from provider could not be verified!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
return response;
} else {
if (log.isDebugEnabled()) log.debug("No form based authentication request.");
}
// Check for Neutron-Auth based authentication
String yanelUsecase = request.getParameter("yanel.usecase");
if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) {
log.debug("Neutron Authentication ...");
String username = null;
String password = null;
String originalRequest = null;
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
try {
Configuration config = builder.build(request.getInputStream());
Configuration originalRequestConfig = config.getChild("original-request");
originalRequest = originalRequestConfig.getAttribute("url", null);
Configuration[] paramConfig = config.getChildren("param");
for (int i = 0; i < paramConfig.length; i++) {
String paramName = paramConfig[i].getAttribute("name", null);
if (paramName != null) {
if (paramName.equals("username")) {
username = paramConfig[i].getValue();
} else if (paramName.equals("password")) {
password = paramConfig[i].getValue();
}
}
}
} catch(Exception e) {
log.warn(e);
}
log.debug("Username: " + username);
if (username != null) {
HttpSession session = request.getSession(true);
log.debug("Realm ID: " + realm.getID());
User user = realm.getIdentityManager().getUserManager().getUser(username, true);
if (user != null && user.authenticate(password)) {
log.info("Authentication successful: " + username);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
// TODO: send some XML content, e.g. <authentication-successful/>
response.setContentType("text/plain; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(response.SC_OK);
if (log.isDebugEnabled()) log.debug("Neutron Authentication successful.");
PrintWriter writer = response.getWriter();
writer.print("Neutron Authentication Successful!");
return response;
} else {
log.warn("Neutron Authentication failed: " + username);
// TODO: Refactor this code with the one from doAuthenticate ...
log.debug("Original Request: " + originalRequest);
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
return response;
}
} else {
// TODO: Refactor resp. reuse response from above ...
log.warn("Neutron Authentication failed because username is NULL!");
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed because no username was sent!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter writer = response.getWriter();
writer.print(sb);
return response;
}
} else {
if (log.isDebugEnabled()) log.debug("No Neutron based authentication request.");
}
log.warn("No credentials specified yet!");
// Check if this is a neutron request, a Sunbird/Calendar request or just a common GET request
// Also see e-mail about recognizing a WebDAV request: http://lists.w3.org/Archives/Public/w3c-dist-auth/2006AprJun/0064.html
StringBuffer sb = new StringBuffer("");
String neutronVersions = request.getHeader("Neutron");
String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate");
if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) {
log.debug("Neutron Versions supported by client: " + neutronVersions);
log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme);
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authorization\">");
sb.append("<message>Authorization denied: " + getRequestURLQS(request, null, true, map) + "</message>");
sb.append("<authentication>");
sb.append("<original-request url=\"" + getRequestURLQS(request, null, true, map) + "\"/>");
//TODO: Also support https ...
sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true, map) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
sb.append("<logout url=\"" + getRequestURLQS(request, "yanel.usecase=logout", true, map) + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
} else if (request.getRequestURI().endsWith(".ics")) {
log.warn("Somebody seems to ask for a Calendar (ICS) ...");
response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\"");
response.sendError(response.SC_UNAUTHORIZED);
} else {
getXHTMLAuthenticationForm(request, response, realm, null, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
return response;
/*
if (log.isDebugEnabled()) log.debug("TODO: Was this authentication request really necessary!");
return null;
*/
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
}
/**
* Custom XHTML Form for authentication
*/
public void getXHTMLAuthenticationForm(HttpServletRequest request, HttpServletResponse response, Realm realm, String message, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort, Map map) throws ServletException, IOException {
if(log.isDebugEnabled()) log.debug("Default authentication form implementation!");
String pathRelativeToRealm = request.getServletPath().replaceFirst(realm.getMountPoint(),"/");
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(pathRelativeToRealm);
try {
org.w3c.dom.Document adoc = YanelServlet.getDocument(YanelServlet.NAMESPACE, "yanel-auth-screen");
Element rootElement = adoc.getDocumentElement();
if (message != null) {
Element messageElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "message"));
messageElement.appendChild(adoc.createTextNode(message));
}
Element requestElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "request"));
requestElement.setAttributeNS(YanelServlet.NAMESPACE, "urlqs", getRequestURLQS(request, null, true, map));
if (request.getQueryString() != null) {
requestElement.setAttributeNS(YanelServlet.NAMESPACE, "qs", request.getQueryString().replaceAll("&", "&"));
}
Element realmElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "realm"));
realmElement.setAttributeNS(YanelServlet.NAMESPACE, "name", realm.getName());
realmElement.setAttributeNS(YanelServlet.NAMESPACE, "mount-point", realm.getMountPoint().toString());
Element sslElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "ssl"));
if(sslPort != null) {
sslElement.setAttributeNS(YanelServlet.NAMESPACE, "status", "ON");
} else {
sslElement.setAttributeNS(YanelServlet.NAMESPACE, "status", "OFF");
}
String yanelFormat = request.getParameter("yanel.format");
if(yanelFormat != null && yanelFormat.equals("xml")) {
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
//OutputStream out = response.getOutputStream();
javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(adoc), new javax.xml.transform.stream.StreamResult(response.getOutputStream()));
//out.close();
} else {
String mimeType = YanelServlet.patchMimeType("application/xhtml+xml", request);
response.setContentType(mimeType + "; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
File realmDir = realm.getRootDir();
if (realmDir == null) realmDir = new File(realm.getConfigFile().getParent());
File xsltLoginScreen = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + xsltLoginScreenDefault);
if (!xsltLoginScreen.isFile()) xsltLoginScreen = org.wyona.commons.io.FileUtil.file(servletContextRealPath, xsltLoginScreenDefault);
Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltLoginScreen));
transformer.setParameter("yanel.back2realm", backToRealm);
transformer.setParameter("yanel.reservedPrefix", reservedPrefix);
transformer.transform(new javax.xml.transform.dom.DOMSource(adoc), new javax.xml.transform.stream.StreamResult(response.getWriter()));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage());
}
}
/**
* Patch request with proxy settings re realm configuration
*/
private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml, Map map) {
try {
Realm realm = map.getRealm(request.getServletPath());
// TODO: Handle this exception more gracefully!
if (realm == null) log.error("No realm found for path " +request.getServletPath());
String proxyHostName = realm.getProxyHostName();
int proxyPort = realm.getProxyPort();
String proxyPrefix = realm.getProxyPrefix();
URL url = null;
url = new URL(request.getRequestURL().toString());
//if(proxyHostName != null || proxyPort >= null || proxyPrefix != null) {
if(realm.isProxySet()) {
if (proxyHostName != null) {
url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile());
}
if (proxyPort >= 0) {
url = new URL(url.getProtocol(), url.getHost(), proxyPort, url.getFile());
} else {
url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile());
}
if (proxyPrefix != null) {
url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length()));
}
//log.debug("Proxy enabled for this realm resp. request: " + realm + ", " + url);
} else {
//log.debug("No proxy set for this realm resp. request: " + realm + ", " + url);
}
String urlQS = url.toString();
if (request.getQueryString() != null) {
urlQS = urlQS + "?" + request.getQueryString();
if (addQS != null) urlQS = urlQS + "&" + addQS;
} else {
if (addQS != null) urlQS = urlQS + "?" + addQS;
}
if (xml) urlQS = urlQS.replaceAll("&", "&");
if(log.isDebugEnabled()) log.debug("Request: " + urlQS);
return urlQS;
} catch (Exception e) {
log.error(e);
return null;
}
}
// Using openid4java library
/**
* Get OpenID redirect URL (to the OpenID provider). Also see http://code.google.com/p/openid4java/wiki/Documentation and particularly http://code.google.com/p/openid4java/wiki/SampleConsumer
*/
private String getOpenIDRedirectURL(String openID, HttpServletRequest request, Map map) throws Exception {
String returnToUrlString = getRequestURLQS(request, null, false, map);
Identifier identifier = Discovery.parseIdentifier(openID);
java.util.List discoveries = new Discovery().discover(identifier);
DiscoveryInformation discovered = null;
try {
discovered = manager.associate(discoveries);
} catch(Exception e) {
log.warn(e, e);
}
if (discovered == null) {
throw new Exception("OpenID DiscoverInfo is null");
}
request.getSession(true).setAttribute(OPENID_DISCOVERED_KEY, discovered);
AuthRequest authReq = manager.authenticate(discovered, returnToUrlString);
return authReq.getDestinationUrl(true);
}
// Using JOID library
/*
private String getOpenIDRedirectURL(String openID, HttpServletRequest request, Map map) throws Exception {
String returnToUrlString = UrlUtils.getFullUrl(request);
log.debug("After successful authentication return to: " + returnToUrlString);
String redirectUrlString = OpenIdFilter.joid().getAuthUrl(openID, returnToUrlString, returnToUrlString);
log.debug("OpenID Provider URL: " + redirectUrlString);
return redirectUrlString;
}
*/
/**
* Verify OpenID provider response
*/
private boolean verifyOpenIDProviderResponse (HttpServletRequest request) throws Exception {
ParameterList responseParas = new ParameterList(request.getParameterMap());
DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute(OPENID_DISCOVERED_KEY);
StringBuffer receivingURL = request.getRequestURL();
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
receivingURL.append("?").append(request.getQueryString());
VerificationResult verification = manager.verify(receivingURL.toString(), responseParas, discovered);
Identifier verified = verification.getVerifiedId();
if (verified != null) {
/*
AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
List emails = fetchResp.getAttributeValues("email");
String email = (String) emails.get(0);
}
*/
return true;
}
}
return false;
}
/*
// TODO: src/org/verisign/joid/consumer/JoidConsumer.java
// see AuthenticationResult result = joid.authenticate(convertToStringValueMap(servletRequest.getParameterMap())); (src/org/verisign/joid/consumer/OpenIdFilter.java)
// https://127.0.0.1:8443/yanel/foaf/login.html?openid.sig=2%2FjpOdpJpEMfibrb9v9OHuzm0kg%3D&openid.mode=id_res&openid.return_to=https%3A%2F%2F127.0.0.1%3A8443%2Fyanel%2Ffoaf%2Flogin.html&openid.identity=http%3A%2F%2Fopenid.claimid.com%2Fmichi&openid.signed=identity%2Creturn_to%2Cmode&openid.assoc_handle=%7BHMAC-SHA1%7D%7B47967654%7D%7BB8gYrw%3D%3D%7D
*/
}
| src/webapp/src/java/org/wyona/yanel/servlet/security/impl/DefaultWebAuthenticatorImpl.java | package org.wyona.yanel.servlet.security.impl;
import org.wyona.yanel.core.map.Map;
import org.wyona.yanel.core.map.Realm;
import org.wyona.yanel.servlet.IdentityMap;
import org.wyona.yanel.servlet.YanelServlet;
import org.wyona.yanel.core.api.security.WebAuthenticator;
import org.wyona.security.core.api.AccessManagementException;
import org.wyona.security.core.ExpiredIdentityException;
import org.wyona.security.core.api.Identity;
import org.wyona.security.core.api.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import java.net.URL;
import org.w3c.dom.Element;
import org.apache.log4j.Category;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.verisign.joid.consumer.OpenIdFilter;
import org.verisign.joid.util.UrlUtils;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.Discovery;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.ParameterList;
/**
*
*/
public class DefaultWebAuthenticatorImpl implements WebAuthenticator {
private static Category log = Category.getInstance(DefaultWebAuthenticatorImpl.class);
private static String OPENID_DISCOVERED_KEY = "openid-discovered";
// NOTE: The OpenID consumer manager needs to be the same instance for redirect to provider and provider verification
private ConsumerManager manager;
/**
*
*/
public void init(org.w3c.dom.Document configuration, javax.xml.transform.URIResolver resolver) throws Exception {
manager = new ConsumerManager();
}
/**
*
*/
public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response, Map map, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort) throws ServletException, IOException {
try {
Realm realm = map.getRealm(request.getServletPath());
String path = map.getPath(realm, request.getServletPath());
//Realm realm = map.getRealm(new Path(request.getServletPath()));
if (log.isDebugEnabled()) log.debug("Generic WebAuthenticator called for realm path " + path);
// HTML Form based authentication
String loginUsername = request.getParameter("yanel.login.username");
String openID = request.getParameter("yanel.login.openid");
String openIDSignature = request.getParameter("openid.sig");
if(loginUsername != null) {
HttpSession session = request.getSession(true);
try {
User user = realm.getIdentityManager().getUserManager().getUser(loginUsername, true);
if (user != null && user.authenticate(request.getParameter("yanel.login.password"))) {
log.debug("Realm: " + realm);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
return null;
} else {
log.warn("Login failed: " + loginUsername);
getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
}
} catch (ExpiredIdentityException e) {
log.warn("Login failed: [" + loginUsername + "] " + e);
getXHTMLAuthenticationForm(request, response, realm, "The account has expired!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
} catch (AccessManagementException e) {
log.warn("Login failed: [" + loginUsername + "] " + e);
getXHTMLAuthenticationForm(request, response, realm, "Login failed!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
return response;
}
} else if (openID != null) {
// Append http scheme if missing
if (!openID.startsWith("http://")) {
openID = "http://" + openID;
}
String redirectUrlString = null;
try {
redirectUrlString = getOpenIDRedirectURL(openID, request, map);
response.sendRedirect(redirectUrlString);
} catch (Exception e) {
log.error(e, e);
getXHTMLAuthenticationForm(request, response, realm, "Login failed: " + e.getMessage() + "!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
log.debug("Redirect URL: " + redirectUrlString);
return response;
} else if (openIDSignature != null) {
log.debug("Verify OpenID provider response ...");
if (verifyOpenIDProviderResponse(request)) {
getXHTMLAuthenticationForm(request, response, realm, "OpenID verification successful, but OpenID session implementation is not finished yet!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
// TODO: Add verified OpenID user to the session
/*
log.info("Authentication successful: " + username);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
*/
} else {
getXHTMLAuthenticationForm(request, response, realm, "Login failed: OpenID response from provider could not be verified!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
return response;
} else {
if (log.isDebugEnabled()) log.debug("No form based authentication request.");
}
// Check for Neutron-Auth based authentication
String yanelUsecase = request.getParameter("yanel.usecase");
if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) {
log.debug("Neutron Authentication ...");
String username = null;
String password = null;
String originalRequest = null;
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
try {
Configuration config = builder.build(request.getInputStream());
Configuration originalRequestConfig = config.getChild("original-request");
originalRequest = originalRequestConfig.getAttribute("url", null);
Configuration[] paramConfig = config.getChildren("param");
for (int i = 0; i < paramConfig.length; i++) {
String paramName = paramConfig[i].getAttribute("name", null);
if (paramName != null) {
if (paramName.equals("username")) {
username = paramConfig[i].getValue();
} else if (paramName.equals("password")) {
password = paramConfig[i].getValue();
}
}
}
} catch(Exception e) {
log.warn(e);
}
log.debug("Username: " + username);
if (username != null) {
HttpSession session = request.getSession(true);
log.debug("Realm ID: " + realm.getID());
User user = realm.getIdentityManager().getUserManager().getUser(username, true);
if (user != null && user.authenticate(password)) {
log.info("Authentication successful: " + username);
IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
if (identityMap == null) {
identityMap = new IdentityMap();
session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
}
identityMap.put(realm.getID(), new Identity(user));
// TODO: send some XML content, e.g. <authentication-successful/>
response.setContentType("text/plain; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(response.SC_OK);
if (log.isDebugEnabled()) log.debug("Neutron Authentication successful.");
PrintWriter writer = response.getWriter();
writer.print("Neutron Authentication Successful!");
return response;
} else {
log.warn("Neutron Authentication failed: " + username);
// TODO: Refactor this code with the one from doAuthenticate ...
log.debug("Original Request: " + originalRequest);
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
return response;
}
} else {
// TODO: Refactor resp. reuse response from above ...
log.warn("Neutron Authentication failed because username is NULL!");
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authentication\">");
sb.append("<message>Authentication failed because no username was sent!</message>");
sb.append("<authentication>");
// TODO: ...
sb.append("<original-request url=\"" + YanelServlet.encodeXML(originalRequest) + "\"/>");
//sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>");
//TODO: Also support https ...
// TODO: ...
sb.append("<login url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=neutron-auth" + "\" method=\"POST\">");
//sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
// TODO: ...
sb.append("<logout url=\"" + YanelServlet.encodeXML(originalRequest) + "&yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter writer = response.getWriter();
writer.print(sb);
return response;
}
} else {
if (log.isDebugEnabled()) log.debug("No Neutron based authentication request.");
}
log.warn("No credentials specified yet!");
// Check if this is a neutron request, a Sunbird/Calendar request or just a common GET request
// Also see e-mail about recognizing a WebDAV request: http://lists.w3.org/Archives/Public/w3c-dist-auth/2006AprJun/0064.html
StringBuffer sb = new StringBuffer("");
String neutronVersions = request.getHeader("Neutron");
String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate");
if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) {
log.debug("Neutron Versions supported by client: " + neutronVersions);
log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme);
sb.append("<?xml version=\"1.0\"?>");
sb.append("<exception xmlns=\"http://www.wyona.org/neutron/1.0\" type=\"authorization\">");
sb.append("<message>Authorization denied: " + getRequestURLQS(request, null, true, map) + "</message>");
sb.append("<authentication>");
sb.append("<original-request url=\"" + getRequestURLQS(request, null, true, map) + "\"/>");
//TODO: Also support https ...
sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true, map) + "\" method=\"POST\">");
sb.append("<form>");
sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>");
sb.append("<param description=\"Username\" name=\"username\"/>");
sb.append("<param description=\"Password\" name=\"password\"/>");
sb.append("</form>");
sb.append("</login>");
// NOTE: Needs to be a full URL, because user might switch the server ...
sb.append("<logout url=\"" + getRequestURLQS(request, "yanel.usecase=logout", true, map) + "\" realm=\"" + realm.getName() + "\"/>");
sb.append("</authentication>");
sb.append("</exception>");
log.debug("Neutron-Auth response: " + sb);
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NEUTRON-AUTH");
PrintWriter w = response.getWriter();
w.print(sb);
} else if (request.getRequestURI().endsWith(".ics")) {
log.warn("Somebody seems to ask for a Calendar (ICS) ...");
response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realm.getName() + "\"");
response.sendError(response.SC_UNAUTHORIZED);
} else {
getXHTMLAuthenticationForm(request, response, realm, null, reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
}
return response;
/*
if (log.isDebugEnabled()) log.debug("TODO: Was this authentication request really necessary!");
return null;
*/
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
}
}
/**
* Custom XHTML Form for authentication
*/
public void getXHTMLAuthenticationForm(HttpServletRequest request, HttpServletResponse response, Realm realm, String message, String reservedPrefix, String xsltLoginScreenDefault, String servletContextRealPath, String sslPort, Map map) throws ServletException, IOException {
if(log.isDebugEnabled()) log.debug("Default authentication form implementation!");
String pathRelativeToRealm = request.getServletPath().replaceFirst(realm.getMountPoint(),"/");
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(pathRelativeToRealm);
try {
org.w3c.dom.Document adoc = YanelServlet.getDocument(YanelServlet.NAMESPACE, "yanel-auth-screen");
Element rootElement = adoc.getDocumentElement();
if (message != null) {
Element messageElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "message"));
messageElement.appendChild(adoc.createTextNode(message));
}
Element requestElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "request"));
requestElement.setAttributeNS(YanelServlet.NAMESPACE, "urlqs", getRequestURLQS(request, null, true, map));
if (request.getQueryString() != null) {
requestElement.setAttributeNS(YanelServlet.NAMESPACE, "qs", request.getQueryString().replaceAll("&", "&"));
}
Element realmElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "realm"));
realmElement.setAttributeNS(YanelServlet.NAMESPACE, "name", realm.getName());
realmElement.setAttributeNS(YanelServlet.NAMESPACE, "mount-point", realm.getMountPoint().toString());
Element sslElement = (Element) rootElement.appendChild(adoc.createElementNS(YanelServlet.NAMESPACE, "ssl"));
if(sslPort != null) {
sslElement.setAttributeNS(YanelServlet.NAMESPACE, "status", "ON");
} else {
sslElement.setAttributeNS(YanelServlet.NAMESPACE, "status", "OFF");
}
String yanelFormat = request.getParameter("yanel.format");
if(yanelFormat != null && yanelFormat.equals("xml")) {
response.setContentType("application/xml; charset=" + YanelServlet.DEFAULT_ENCODING);
//OutputStream out = response.getOutputStream();
javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(adoc), new javax.xml.transform.stream.StreamResult(response.getOutputStream()));
//out.close();
} else {
String mimeType = YanelServlet.patchMimeType("application/xhtml+xml", request);
response.setContentType(mimeType + "; charset=" + YanelServlet.DEFAULT_ENCODING);
response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED);
File realmDir = realm.getRootDir();
if (realmDir == null) realmDir = new File(realm.getConfigFile().getParent());
File xsltLoginScreen = org.wyona.commons.io.FileUtil.file(realmDir.getAbsolutePath(), "src" + File.separator + "webapp" + File.separator + xsltLoginScreenDefault);
if (!xsltLoginScreen.isFile()) xsltLoginScreen = org.wyona.commons.io.FileUtil.file(servletContextRealPath, xsltLoginScreenDefault);
Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltLoginScreen));
transformer.setParameter("yanel.back2realm", backToRealm);
transformer.setParameter("yanel.reservedPrefix", reservedPrefix);
transformer.transform(new javax.xml.transform.dom.DOMSource(adoc), new javax.xml.transform.stream.StreamResult(response.getWriter()));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage());
}
}
/**
* Patch request with proxy settings re realm configuration
*/
private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml, Map map) {
try {
Realm realm = map.getRealm(request.getServletPath());
// TODO: Handle this exception more gracefully!
if (realm == null) log.error("No realm found for path " +request.getServletPath());
String proxyHostName = realm.getProxyHostName();
int proxyPort = realm.getProxyPort();
String proxyPrefix = realm.getProxyPrefix();
URL url = null;
url = new URL(request.getRequestURL().toString());
//if(proxyHostName != null || proxyPort >= null || proxyPrefix != null) {
if(realm.isProxySet()) {
if (proxyHostName != null) {
url = new URL(url.getProtocol(), proxyHostName, url.getPort(), url.getFile());
}
if (proxyPort >= 0) {
url = new URL(url.getProtocol(), url.getHost(), proxyPort, url.getFile());
} else {
url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile());
}
if (proxyPrefix != null) {
url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length()));
}
//log.debug("Proxy enabled for this realm resp. request: " + realm + ", " + url);
} else {
//log.debug("No proxy set for this realm resp. request: " + realm + ", " + url);
}
String urlQS = url.toString();
if (request.getQueryString() != null) {
urlQS = urlQS + "?" + request.getQueryString();
if (addQS != null) urlQS = urlQS + "&" + addQS;
} else {
if (addQS != null) urlQS = urlQS + "?" + addQS;
}
if (xml) urlQS = urlQS.replaceAll("&", "&");
if(log.isDebugEnabled()) log.debug("Request: " + urlQS);
return urlQS;
} catch (Exception e) {
log.error(e);
return null;
}
}
// Using openid4java library
/**
* Get OpenID redirect URL (to the OpenID provider). Also see http://code.google.com/p/openid4java/wiki/Documentation and particularly http://code.google.com/p/openid4java/wiki/SampleConsumer
*/
private String getOpenIDRedirectURL(String openID, HttpServletRequest request, Map map) throws Exception {
String returnToUrlString = getRequestURLQS(request, null, false, map);
Identifier identifier = Discovery.parseIdentifier(openID);
java.util.List discoveries = new Discovery().discover(identifier);
DiscoveryInformation discovered = null;
try {
discovered = manager.associate(discoveries);
} catch(Exception e) {
log.warn(e, e);
}
if (discovered == null) {
throw new Exception("OpenID DiscoverInfo is null");
}
request.getSession(true).setAttribute(OPENID_DISCOVERED_KEY, discovered);
AuthRequest authReq = manager.authenticate(discovered, returnToUrlString);
return authReq.getDestinationUrl(true);
}
// Using JOID library
/*
private String getOpenIDRedirectURL(String openID, HttpServletRequest request, Map map) throws Exception {
String returnToUrlString = UrlUtils.getFullUrl(request);
log.debug("After successful authentication return to: " + returnToUrlString);
String redirectUrlString = OpenIdFilter.joid().getAuthUrl(openID, returnToUrlString, returnToUrlString);
log.debug("OpenID Provider URL: " + redirectUrlString);
return redirectUrlString;
}
*/
/**
* Verify OpenID provider response
*/
private boolean verifyOpenIDProviderResponse (HttpServletRequest request) throws Exception {
ParameterList responseParas = new ParameterList(request.getParameterMap());
DiscoveryInformation discovered = (DiscoveryInformation) request.getSession().getAttribute(OPENID_DISCOVERED_KEY);
StringBuffer receivingURL = request.getRequestURL();
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
receivingURL.append("?").append(request.getQueryString());
VerificationResult verification = manager.verify(receivingURL.toString(), responseParas, discovered);
Identifier verified = verification.getVerifiedId();
if (verified != null) {
/*
AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
List emails = fetchResp.getAttributeValues("email");
String email = (String) emails.get(0);
}
*/
return true;
}
}
return false;
}
/*
// TODO: src/org/verisign/joid/consumer/JoidConsumer.java
// see AuthenticationResult result = joid.authenticate(convertToStringValueMap(servletRequest.getParameterMap())); (src/org/verisign/joid/consumer/OpenIdFilter.java)
// https://127.0.0.1:8443/yanel/foaf/login.html?openid.sig=2%2FjpOdpJpEMfibrb9v9OHuzm0kg%3D&openid.mode=id_res&openid.return_to=https%3A%2F%2F127.0.0.1%3A8443%2Fyanel%2Ffoaf%2Flogin.html&openid.identity=http%3A%2F%2Fopenid.claimid.com%2Fmichi&openid.signed=identity%2Creturn_to%2Cmode&openid.assoc_handle=%7BHMAC-SHA1%7D%7B47967654%7D%7BB8gYrw%3D%3D%7D
*/
}
| create user with openid as user id and add to identity map
| src/webapp/src/java/org/wyona/yanel/servlet/security/impl/DefaultWebAuthenticatorImpl.java | create user with openid as user id and add to identity map | <ide><path>rc/webapp/src/java/org/wyona/yanel/servlet/security/impl/DefaultWebAuthenticatorImpl.java
<ide> import org.wyona.security.core.ExpiredIdentityException;
<ide> import org.wyona.security.core.api.Identity;
<ide> import org.wyona.security.core.api.User;
<add>import org.wyona.security.core.api.UserManager;
<ide>
<ide> import javax.servlet.ServletException;
<ide> import javax.servlet.http.HttpServletRequest;
<ide> } else if (openIDSignature != null) {
<ide> log.debug("Verify OpenID provider response ...");
<ide> if (verifyOpenIDProviderResponse(request)) {
<del> getXHTMLAuthenticationForm(request, response, realm, "OpenID verification successful, but OpenID session implementation is not finished yet!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
<del> // TODO: Add verified OpenID user to the session
<del>/*
<del> log.info("Authentication successful: " + username);
<del> IdentityMap identityMap = (IdentityMap)session.getAttribute(YanelServlet.IDENTITY_MAP_KEY);
<add> UserManager uManager = realm.getIdentityManager().getUserManager();
<add> String openIdentity = request.getParameter("openid.identity");
<add> if (openIdentity != null) {
<add> if (!uManager.existsUser(openIdentity)) {
<add> uManager.createUser(openIdentity, null, null, null);
<add> log.warn("An OpenID user has been created: " + openIdentity);
<add> }
<add> User user = uManager.getUser(openIdentity);
<add> IdentityMap identityMap = (IdentityMap)request.getSession(true).getAttribute(YanelServlet.IDENTITY_MAP_KEY);
<ide> if (identityMap == null) {
<ide> identityMap = new IdentityMap();
<del> session.setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
<add> request.getSession().setAttribute(YanelServlet.IDENTITY_MAP_KEY, identityMap);
<ide> }
<ide> identityMap.put(realm.getID(), new Identity(user));
<del>*/
<add> // OpenID authentication successful, hence return null instead an "exceptional" response
<add> return null;
<add> } else {
<add> log.error("No openid.identity!");
<add> getXHTMLAuthenticationForm(request, response, realm, "OpenID verification successful, but no openid.identity!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
<add> }
<ide> } else {
<ide> getXHTMLAuthenticationForm(request, response, realm, "Login failed: OpenID response from provider could not be verified!", reservedPrefix, xsltLoginScreenDefault, servletContextRealPath, sslPort, map);
<ide> } |
|
Java | apache-2.0 | 73a12aa34d4494f87df6a03a6465c020f54a777e | 0 | MagicWiz/log4j2,lburgazzoli/apache-logging-log4j2,apache/logging-log4j2,GFriedrich/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/apache-logging-log4j2,xnslong/logging-log4j2,jinxuan/logging-log4j2,jinxuan/logging-log4j2,neuro-sys/logging-log4j2,ChetnaChaudhari/logging-log4j2,GFriedrich/logging-log4j2,MagicWiz/log4j2,lburgazzoli/logging-log4j2,GFriedrich/logging-log4j2,lqbweb/logging-log4j2,renchunxiao/logging-log4j2,pisfly/logging-log4j2,xnslong/logging-log4j2,lburgazzoli/logging-log4j2,jsnikhil/nj-logging-log4j2,lburgazzoli/apache-logging-log4j2,neuro-sys/logging-log4j2,codescale/logging-log4j2,codescale/logging-log4j2,codescale/logging-log4j2,pisfly/logging-log4j2,renchunxiao/logging-log4j2,xnslong/logging-log4j2,lburgazzoli/logging-log4j2,ChetnaChaudhari/logging-log4j2,apache/logging-log4j2,jsnikhil/nj-logging-log4j2,lqbweb/logging-log4j2,apache/logging-log4j2 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.core.config.plugins.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.PluginAliases;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.config.plugins.visitors.PluginVisitor;
import org.apache.logging.log4j.core.config.plugins.visitors.PluginVisitors;
import org.apache.logging.log4j.core.util.Assert;
import org.apache.logging.log4j.core.util.Builder;
import org.apache.logging.log4j.status.StatusLogger;
/**
* Builder class to instantiate and configure a Plugin object using a PluginFactory method or PluginBuilderFactory
* builder class.
*
* @param <T> type of Plugin class.
*/
public class PluginBuilder<T> implements Builder<T> {
private static final Logger LOGGER = StatusLogger.getLogger();
private final PluginType<T> pluginType;
private final Class<T> clazz;
private Configuration configuration;
private Node node;
private LogEvent event;
/**
* Constructs a PluginBuilder for a given PluginType.
*
* @param pluginType type of plugin to configure
*/
public PluginBuilder(final PluginType<T> pluginType) {
this.pluginType = pluginType;
this.clazz = pluginType.getPluginClass();
}
/**
* Specifies the Configuration to use for constructing the plugin instance.
*
* @param configuration the configuration to use.
* @return {@code this}
*/
public PluginBuilder<T> withConfiguration(final Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Specifies the Node corresponding to the plugin object that will be created.
*
* @param node the plugin configuration node to use.
* @return {@code this}
*/
public PluginBuilder<T> withConfigurationNode(final Node node) {
this.node = node;
return this;
}
/**
* Specifies the LogEvent that may be used to provide extra context for string substitutions.
*
* @param event the event to use for extra information.
* @return {@code this}
*/
public PluginBuilder<T> forLogEvent(final LogEvent event) {
this.event = event;
return this;
}
/**
* Builds the plugin object.
*
* @return the plugin object or {@code null} if there was a problem creating it.
*/
@Override
public T build() {
verify();
// first try to use a builder class if one is available
try {
LOGGER.debug("Building Plugin[name={}, class={}]. Searching for builder factory method...", pluginType.getElementName(),
pluginType.getPluginClass().getName());
final Builder<T> builder = createBuilder(this.clazz);
if (builder != null) {
injectFields(builder);
final T result = builder.build();
LOGGER.debug("Built Plugin[name={}] OK from builder factory method.", pluginType.getElementName());
return result;
}
} catch (final Exception e) {
LOGGER.catching(Level.ERROR, e);
LOGGER.error("Unable to inject fields into builder class for plugin type {}, element {}.", this.clazz,
node.getName());
}
// or fall back to factory method if no builder class is available
try {
LOGGER.debug("Still building Plugin[name={}, class={}]. Searching for factory method...",
pluginType.getElementName(), pluginType.getPluginClass().getName());
final Method factory = findFactoryMethod(this.clazz);
final Object[] params = generateParameters(factory);
@SuppressWarnings("unchecked")
final T plugin = (T) factory.invoke(null, params);
LOGGER.debug("Built Plugin[name={}] OK from factory method.", pluginType.getElementName());
return plugin;
} catch (final Exception e) {
LOGGER.catching(Level.ERROR, e);
LOGGER.error("Unable to invoke factory method in class {} for element {}.", this.clazz, this.node.getName());
return null;
}
}
private void verify() {
Assert.requireNonNull(this.configuration, "No Configuration object was set.");
Assert.requireNonNull(this.node, "No Node object was set.");
}
private static <T> Builder<T> createBuilder(final Class<T> clazz)
throws InvocationTargetException, IllegalAccessException {
for (final Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(PluginBuilderFactory.class) &&
Modifier.isStatic(method.getModifiers())) {
@SuppressWarnings("unchecked")
final Builder<T> builder = (Builder<T>) method.invoke(null);
LOGGER.debug("Found builder factory method [{}]: {}.", method.getName(), method);
return builder;
}
}
LOGGER.debug("No builder factory method found in class {}. Going to try finding a factory method instead.",
clazz.getName());
return null;
}
private void injectFields(final Builder<T> builder) throws IllegalAccessException {
final Field[] fields = builder.getClass().getDeclaredFields();
final StringBuilder log = new StringBuilder();
for (final Field field : fields) {
log.append(log.length() == 0 ? "with params(" : ", ");
field.setAccessible(true);
final Annotation[] annotations = field.getDeclaredAnnotations();
final String[] aliases = extractPluginAliases(annotations);
for (final Annotation a : annotations) {
if (a instanceof PluginAliases) {
continue; // already processed
}
final PluginVisitor<? extends Annotation> visitor =
PluginVisitors.findVisitor(a.annotationType());
if (visitor != null) {
final Object value = visitor.setAliases(aliases)
.setAnnotation(a)
.setConversionType(field.getType())
.setStrSubstitutor(configuration.getStrSubstitutor())
.setMember(field)
.visit(configuration, node, event, log);
// don't overwrite default values if the visitor gives us no value to inject
if (value != null) {
field.set(builder, value);
}
}
}
}
if (log.length() > 0) {
log.append(')');
}
LOGGER.debug("Calling build() on class {} for element {} {}", builder.getClass(), node.getName(),
log.toString());
checkForRemainingAttributes();
verifyNodeChildrenUsed();
}
private static <T> Method findFactoryMethod(final Class<T> clazz) {
for (final Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(PluginFactory.class) &&
Modifier.isStatic(method.getModifiers())) {
LOGGER.debug("Found factory method [{}]: {}.", method.getName(), method);
return method;
}
}
LOGGER.debug("No factory method found in class {}.", clazz.getName());
return null;
}
private Object[] generateParameters(final Method factory) {
final StringBuilder log = new StringBuilder();
final Class<?>[] types = factory.getParameterTypes();
final Annotation[][] annotations = factory.getParameterAnnotations();
final Object[] args = new Object[annotations.length];
for (int i = 0; i < annotations.length; i++) {
log.append(log.length() == 0 ? "with params(" : ", ");
final String[] aliases = extractPluginAliases(annotations[i]);
for (final Annotation a : annotations[i]) {
if (a instanceof PluginAliases) {
continue; // already processed
}
final PluginVisitor<? extends Annotation> visitor = PluginVisitors.findVisitor(
a.annotationType());
if (visitor != null) {
final Object value = visitor.setAliases(aliases)
.setAnnotation(a)
.setConversionType(types[i])
.setStrSubstitutor(configuration.getStrSubstitutor())
.setMember(factory)
.visit(configuration, node, event, log);
// don't overwrite existing values if the visitor gives us no value to inject
if (value != null) {
args[i] = value;
}
}
}
}
if (log.length() > 0) {
log.append(')');
}
checkForRemainingAttributes();
verifyNodeChildrenUsed();
LOGGER.debug("Calling {} on class {} for element {} {}", factory.getName(), clazz.getName(), node.getName(),
log.toString());
return args;
}
private static String[] extractPluginAliases(final Annotation... parmTypes) {
String[] aliases = null;
for (final Annotation a : parmTypes) {
if (a instanceof PluginAliases) {
aliases = ((PluginAliases) a).value();
}
}
return aliases;
}
private void checkForRemainingAttributes() {
final Map<String, String> attrs = node.getAttributes();
if (!attrs.isEmpty()) {
final StringBuilder sb = new StringBuilder();
for (final String key : attrs.keySet()) {
if (sb.length() == 0) {
sb.append(node.getName());
sb.append(" contains ");
if (attrs.size() == 1) {
sb.append("an invalid element or attribute ");
} else {
sb.append("invalid attributes ");
}
} else {
sb.append(", ");
}
sb.append('"');
sb.append(key);
sb.append('"');
}
LOGGER.error(sb.toString());
}
}
private void verifyNodeChildrenUsed() {
final List<Node> children = node.getChildren();
if (!(pluginType.isDeferChildren() || children.isEmpty())) {
for (final Node child : children) {
final String nodeType = node.getType().getElementName();
final String start = nodeType.equals(node.getName()) ? node.getName() : nodeType + ' ' + node.getName();
LOGGER.error("{} has no parameter that matches element {}", start, child.getName());
}
}
}
}
| log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/PluginBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.core.config.plugins.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.Node;
import org.apache.logging.log4j.core.config.plugins.PluginAliases;
import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.apache.logging.log4j.core.config.plugins.visitors.PluginVisitor;
import org.apache.logging.log4j.core.config.plugins.visitors.PluginVisitors;
import org.apache.logging.log4j.core.util.Assert;
import org.apache.logging.log4j.core.util.Builder;
import org.apache.logging.log4j.status.StatusLogger;
/**
* Builder class to instantiate and configure a Plugin object using a PluginFactory method or PluginBuilderFactory
* builder class.
*
* @param <T> type of Plugin class.
*/
public class PluginBuilder<T> implements Builder<T> {
private static final Logger LOGGER = StatusLogger.getLogger();
private final PluginType<T> pluginType;
private final Class<T> clazz;
private Configuration configuration;
private Node node;
private LogEvent event;
/**
* Constructs a PluginBuilder for a given PluginType.
*
* @param pluginType type of plugin to configure
*/
public PluginBuilder(final PluginType<T> pluginType) {
this.pluginType = pluginType;
this.clazz = pluginType.getPluginClass();
}
/**
* Specifies the Configuration to use for constructing the plugin instance.
*
* @param configuration the configuration to use.
* @return {@code this}
*/
public PluginBuilder<T> withConfiguration(final Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Specifies the Node corresponding to the plugin object that will be created.
*
* @param node the plugin configuration node to use.
* @return {@code this}
*/
public PluginBuilder<T> withConfigurationNode(final Node node) {
this.node = node;
return this;
}
/**
* Specifies the LogEvent that may be used to provide extra context for string substitutions.
*
* @param event the event to use for extra information.
* @return {@code this}
*/
public PluginBuilder<T> forLogEvent(final LogEvent event) {
this.event = event;
return this;
}
/**
* Builds the plugin object.
*
* @return the plugin object or {@code null} if there was a problem creating it.
*/
@Override
public T build() {
verify();
// first try to use a builder class if one is available
try {
LOGGER.debug("Building Plugin[name={}, class={}]. Searching for builder factory method...", pluginType.getElementName(),
pluginType.getPluginClass().getName());
final Builder<T> builder = createBuilder(this.clazz);
if (builder != null) {
injectFields(builder);
final T result = builder.build();
LOGGER.debug("Built Plugin[name={}] OK from builder factory method.", pluginType.getElementName());
return result;
}
} catch (final Exception e) {
LOGGER.catching(Level.ERROR, e);
LOGGER.error("Unable to inject fields into builder class for plugin type {}, element {}.", this.clazz,
node.getName());
}
// or fall back to factory method if no builder class is available
try {
LOGGER.debug("Still building Plugin[name={}, class={}]. Searching for factory method...",
pluginType.getElementName(), pluginType.getPluginClass().getName());
final Method factory = findFactoryMethod(this.clazz);
final Object[] params = generateParameters(factory);
@SuppressWarnings("unchecked")
final T plugin = (T) factory.invoke(null, params);
LOGGER.debug("Built Plugin[name={}] OK from factory method.", pluginType.getElementName());
return plugin;
} catch (final Exception e) {
LOGGER.catching(Level.ERROR, e);
LOGGER.error("Unable to invoke factory method in class {} for element {}.", this.clazz, this.node.getName());
return null;
}
}
private void verify() {
Assert.requireNonNull(this.configuration, "No Configuration object was set.");
Assert.requireNonNull(this.node, "No Node object was set.");
}
private static <T> Builder<T> createBuilder(final Class<T> clazz)
throws InvocationTargetException, IllegalAccessException {
for (final Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(PluginBuilderFactory.class) &&
Modifier.isStatic(method.getModifiers())) {
@SuppressWarnings("unchecked")
final Builder<T> builder = (Builder<T>) method.invoke(null);
LOGGER.debug("Found builder factory method [{}]: {}.", method.getName(), method);
return builder;
}
}
LOGGER.debug("No builder factory method found in class {}. Going to try finding a factory method instead.",
clazz.getName());
return null;
}
private void injectFields(final Builder<T> builder) throws IllegalAccessException {
final Field[] fields = builder.getClass().getDeclaredFields();
final StringBuilder log = new StringBuilder();
for (final Field field : fields) {
log.append(log.length() == 0 ? "with params(" : ", ");
field.setAccessible(true);
final Annotation[] annotations = field.getDeclaredAnnotations();
final String[] aliases = extractPluginAliases(annotations);
for (final Annotation a : annotations) {
if (a instanceof PluginAliases) {
continue; // already processed
}
final PluginVisitor<? extends Annotation> visitor =
PluginVisitors.findVisitor(a.annotationType());
if (visitor != null) {
final Object value = visitor.setAliases(aliases)
.setAnnotation(a)
.setConversionType(field.getType())
.setStrSubstitutor(configuration.getStrSubstitutor())
.setMember(field)
.visit(configuration, node, event, log);
// don't overwrite default values if the visitor gives us no value to inject
if (value != null) {
field.set(builder, value);
}
}
}
}
if (log.length() > 0) {
log.append(')');
}
LOGGER.debug("Calling build() on class {} for element {} {}", builder.getClass(), node.getName(),
log.toString());
checkForRemainingAttributes();
verifyNodeChildrenUsed();
}
private static <T> Method findFactoryMethod(final Class<T> clazz) {
for (final Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(PluginFactory.class) &&
Modifier.isStatic(method.getModifiers())) {
LOGGER.debug("Found factory method [{}]: {}.", method.getName(), method);
return method;
}
}
LOGGER.debug("No factory method found in class {}.", clazz.getName());
return null;
}
private Object[] generateParameters(final Method factory) {
final StringBuilder log = new StringBuilder();
final Class<?>[] types = factory.getParameterTypes();
final Annotation[][] annotations = factory.getParameterAnnotations();
final Object[] args = new Object[annotations.length];
for (int i = 0; i < annotations.length; i++) {
log.append(log.length() == 0 ? "with params(" : ", ");
final String[] aliases = extractPluginAliases(annotations[i]);
for (final Annotation a : annotations[i]) {
if (a instanceof PluginAliases) {
continue; // already processed
}
final PluginVisitor<? extends Annotation> visitor = PluginVisitors.findVisitor(
a.annotationType());
if (visitor != null) {
args[i] = visitor.setAliases(aliases)
.setAnnotation(a)
.setConversionType(types[i])
.setStrSubstitutor(configuration.getStrSubstitutor())
.setMember(factory)
.visit(configuration, node, event, log);
}
}
}
if (log.length() > 0) {
log.append(')');
}
checkForRemainingAttributes();
verifyNodeChildrenUsed();
LOGGER.debug("Calling {} on class {} for element {} {}", factory.getName(), clazz.getName(), node.getName(),
log.toString());
return args;
}
private static String[] extractPluginAliases(final Annotation... parmTypes) {
String[] aliases = null;
for (final Annotation a : parmTypes) {
if (a instanceof PluginAliases) {
aliases = ((PluginAliases) a).value();
}
}
return aliases;
}
private void checkForRemainingAttributes() {
final Map<String, String> attrs = node.getAttributes();
if (!attrs.isEmpty()) {
final StringBuilder sb = new StringBuilder();
for (final String key : attrs.keySet()) {
if (sb.length() == 0) {
sb.append(node.getName());
sb.append(" contains ");
if (attrs.size() == 1) {
sb.append("an invalid element or attribute ");
} else {
sb.append("invalid attributes ");
}
} else {
sb.append(", ");
}
sb.append('"');
sb.append(key);
sb.append('"');
}
LOGGER.error(sb.toString());
}
}
private void verifyNodeChildrenUsed() {
final List<Node> children = node.getChildren();
if (!(pluginType.isDeferChildren() || children.isEmpty())) {
for (final Node child : children) {
final String nodeType = node.getType().getElementName();
final String start = nodeType.equals(node.getName()) ? node.getName() : nodeType + ' ' + node.getName();
LOGGER.error("{} has no parameter that matches element {}", start, child.getName());
}
}
}
}
| Only use plugin visitor value if non-null.
- Makes behavior in factory method version match up better with builder class version.
- Allows for multiple annotations on a single item where only one of them may return a value (e.g., for LOG4J2-825).
| log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/PluginBuilder.java | Only use plugin visitor value if non-null. | <ide><path>og4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/util/PluginBuilder.java
<ide> final PluginVisitor<? extends Annotation> visitor = PluginVisitors.findVisitor(
<ide> a.annotationType());
<ide> if (visitor != null) {
<del> args[i] = visitor.setAliases(aliases)
<add> final Object value = visitor.setAliases(aliases)
<ide> .setAnnotation(a)
<ide> .setConversionType(types[i])
<ide> .setStrSubstitutor(configuration.getStrSubstitutor())
<ide> .setMember(factory)
<ide> .visit(configuration, node, event, log);
<add> // don't overwrite existing values if the visitor gives us no value to inject
<add> if (value != null) {
<add> args[i] = value;
<add> }
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 19f587f279a1c7e60ba43f04f956cd333add4251 | 0 | OmarElGabry/miniPHP,OmarElGabry/miniPHP | /*
* Document : main.js
* Author : Omar El Gabry <[email protected]>
* Description: Main Javascript file for the application.
* It handles all Ajax calls, Events, and DOM Manipulations
*
*/
/*
* Configuration Variables
* An Object with key-value paris assigned in footer.php
*
* @see footer.php
* @see core/Controller.php
*/
var config = {};
/*
* Ajax
*/
var ajax = {
/**
* Default ajax function.
*
* @param string url URL to send ajax call
* @param mixed postData data that will be sent to the server(PHP)
* @param function callback Callback Function that will be called upon success or failure
* @param string spinnerBlock An element where the spinner will be next to it
*
*/
send: function(url, postData, callback, spinnerBlock){
var spinnerEle = null;
$.ajax({
url: config.root + url,
type: "POST",
data: helpers.appendCsrfToken(postData),
dataType: "json",
beforeSend: function() {
// create the spinner element, and add it after the spinnerBlock
spinnerEle = $("<i>").addClass("fa fa-spinner fa-3x fa-spin spinner").css("display", "none");
$(spinnerBlock).after(spinnerEle);
// run the spinner
ajax.runSpinner(spinnerBlock, spinnerEle);
}
})
.done(function(data) {
// stopSpinner(spinnerBlock);
callback(data);
})
.fail(function(jqXHR) {
// stopSpinner(spinnerBlock);
switch (jqXHR.status){
case 302:
helpers.redirectTo(config.root);
break;
default:
helpers.displayErrorPage(jqXHR);
}
})
.always(function() {
ajax.stopSpinner(spinnerBlock, spinnerEle);
});
},
/**
* Ajax call - ONLY for files.
*
* @param string url URL to send ajax call
* @param object fileData data(formData) that will be sent to the server(PHP)
* @param function callback Callback Function that will be called upon success or failure
*
*/
upload: function(url, fileData, callback){
$.ajax({
url: config.root + url,
type: "POST",
data: helpers.appendCsrfToken(fileData),
dataType: "json",
beforeSend: function () {
// reset the progress bar
$(".progress .progress-bar").css("width", "0%").html("0%");
},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
// check if upload property exists
if(myXhr.upload){
myXhr.upload.addEventListener('progress', ajax.progressbar, false);
$(".progress").removeClass("display-none");
}
return myXhr;
},
contentType: false,
cache: false,
processData:false
})
.done(function(data) {
callback(data);
})
.fail(function(jqXHR) {
switch (jqXHR.status){
case 302:
helpers.redirectTo(config.root);
break;
default:
helpers.displayErrorPage(jqXHR);
}
})
.always(function() {
$(".progress").addClass("display-none");
});
},
progressbar: function(e){
if(e.lengthComputable){
var meter = parseInt((e.loaded/e.total) * 100);
$(".progress .progress-bar").css("width", meter+"%").html(meter + "%");
}
},
runSpinner: function(spinnerBlock, spinnerEle){
if(!helpers.empty(spinnerBlock)) {
// var spinner = $(spinnerBlock).nextAll(".spinner:eq(0)");
$(spinnerEle).show();
$(spinnerBlock).css("opacity","0.6");
}
},
stopSpinner: function(spinnerBlock, spinnerEle){
if(!helpers.empty(spinnerBlock) ) {
// var spinner = $(spinnerBlock).nextAll(".spinner:eq(0)");
$(spinnerEle).remove();
$(spinnerBlock).css("opacity","1");
}
}
};
/*
* Helpers
*
*/
var helpers = {
/**
* append csrf token to data that will be sent in ajax
*
* @param mixed data
*
*/
appendCsrfToken: function (data){
if(typeof (data) === "string"){
if(data.length > 0){
data = data + "&csrf_token=" + config.csrfToken;
}else{
data = data + "csrf_token=" + config.csrfToken;
}
}
else if(data.constructor.name === "FormData"){
data.append("csrf_token", config.csrfToken);
}
else if(typeof(data) === "object"){
data.csrf_token = config.csrfToken;
}
return data;
},
/**
* replaces the current page with error page returned from ajax
*
* @param XMLHttpRequest jqXHR
* @see http://stackoverflow.com/questions/4387688/replace-current-page-with-ajax-content
*/
displayErrorPage: function (jqXHR) {
document.open();
document.write(jqXHR.responseText);
document.close();
},
/**
* Extract keys from JavaScript object to be used as variables
* @param object data
*/
extract: function (data) {
for (var key in data) {
window[key] = data[key];
}
},
/**
* Checks if an element is empty(set to null or undefined)
*
* @param mixed foo
* @return boolean
*
*/
empty: function (foo){
return (foo === null || typeof(foo) === "undefined")? true: false;
},
/**
* extends $().html() in jQuery
*
* @param string target
* @param string str
*/
html: function (target, str){
$(target).html(str);
},
/**
* extends $().after() in jQuery
*
* @param string target
* @param string str
*/
after: function (target, str){
$(target).after(str);
},
/**
* clears all error and success messages
*
* @param string target
*/
clearMessages: function (target){
if(helpers.empty(target)){
$(".error").remove();
$(".success").remove();
} else{
// $(target).next(".error").remove();
// $(target).next(".success").remove();
$(target).nextAll(".error:eq(0)").remove();
$(target).nextAll(".success:eq(0)").remove();
}
},
/**
* Extend the serialize() function in jQuery.
* This function is designed to add extra data(name => value) to the form.
*
* @param object ele Form element
* @param string str String to be appended to the form data.
* @return string The serialized form data in form of: "name=value&name=value"
*
*/
serialize: function (ele, str){
if(helpers.empty(str)){
return $(ele).serialize();
} else {
return $(ele).serialize() + "&" + str;
}
},
/**
* This function is used to redirect.
*
* @param string location
*/
redirectTo: function (location){
window.location.href = location;
},
/**
* encode potential text
* All encoding are done and must be done on the server side,
* but you can use this function in case it's needed on client.
*
* @param string str
*/
encodeHTML: function (str){
return $('<div />').text(str).html();
},
/**
* validate form file size
* It's important to validate file size on client-side to avoid overflow in $_POST & $_FILES
*
* @param string form form element
* @param string id id of the file input element
* @see app/core/Request/dataSizeOverflow()
*/
validateFileSize: function (fileId){
var size = document.getElementById(fileId).files[0].size;
return size < config.fileSizeOverflow;
},
/**
* display error message
*
* @param string targetBlock The target block where the error or success alerts will be inserted
* @param string message error message
*
*/
displayError: function (targetBlock, message){
// 1. clear
helpers.clearMessages(targetBlock);
// 2. display
var alert = $("<div>").addClass("alert alert-danger");
var notation = $("<i>").addClass("fa fa-exclamation-circle");
alert.append(notation);
message = helpers.empty(message)? "Sorry there was a problem": message;
alert.append(" " + message);
var error = $("<div>").addClass("error").html(alert);
$(targetBlock).after(error);
},
/**
* Validate the data coming from server side(PHP)
*
* The data coming from PHP should be something like this:
* data = [error = "some html code", success = "some html code", data = "some html code", redirect = "link"];
*
* @param object result The Data that was sent from the server(PHP)
* @param string targetBlock The target block where the error or success alerts(if exists) will be inserted inside/after it
* @param string errorFunc The function that will be used to display the error, Ex: html(), after(), ..etc.
* @param string errorType specifies how the error will be displayed, default or as row
* @param string returnVal the expected value returned from the server(regardless of errors and redirections), Ex: success, data, ..etc.
* @return boolean
*/
validateData: function (result, targetBlock, errorFunc, errorType, returnVal){
// 1. clear all existing error or success messages
helpers.clearMessages(targetBlock);
// 2. Define and extend jQuery functions required to display the error.
if(errorFunc === "html") errorFunc = helpers.html;
else if(errorFunc === "after") errorFunc = helpers.after;
else errorFunc = helpers.html;
// 3. check if result is empty
if(helpers.empty(result)){
helpers.displayError(targetBlock);
return false;
}
// If there was a redirection
else if(!helpers.empty(result.redirect)){
helpers.redirectTo(result.redirect);
return false;
}
// If there was errors encountered and sent from the server, then display it
else if(!helpers.empty(result.error)){
if(errorType === "default" || helpers.empty(errorType)){
errorFunc(targetBlock, result.error);
} else if(errorType === "row"){
var td = $("<td>").attr("colspan", "5");
errorFunc(targetBlock, $(td).html(result.error));
}
return false;
}
else{
if(returnVal === "success" && helpers.empty(result.success)){
helpers.displayError(targetBlock);
return false;
} else if(returnVal === "data" && helpers.empty(result.data)){
helpers.displayError(targetBlock);
return false;
} else if(returnVal !== "data" && returnVal !== "success"){
helpers.displayError(targetBlock);
return false;
}
}
return true;
}
};
/*
* App
*
*/
var app = {
init: function (){
// initialize todo application event
events.todo.init();
if(!helpers.empty(config.curPage)){
// pagination
events.pagination.init();
// events of current page
if(config.curPage.constructor === Array){
config.curPage.forEach(function(sub) {
// add 'active' class to current navigation list
$(".sidebar-nav #"+ sub +" a").addClass("active");
events[sub].init();
});
}else{
$(".sidebar-nav #"+ config.curPage +" a").addClass("active");
events[config.curPage].init();
}
}
}
};
/*
* Events
*
*/
var events = {
/*
* Pagination
*/
pagination: {
/**
* @var integer Acts like the page number for comments
*/
viewMoreCounter: 1,
/**
* @var integer Whenever there is a new comment created in-place, this will be incremented.
*/
commentsCreated: 0,
init: function(){
$("ul.pagination a").click(function(e){
var pageNumber;
if(config.curPage === "comments" || config.curPage.indexOf("comments") > -1){
pageNumber = ++events.pagination.viewMoreCounter;
}
else if($(this).hasClass("prev")){
pageNumber = events.pagination.getSelectedPaginationLink() - 1;
}
else if($(this).hasClass("next")){
pageNumber = events.pagination.getSelectedPaginationLink() + 1;
}
else{
// index() returns 0-indexed
pageNumber = $(this).index("ul.pagination a:not(.prev):not(.next)") + 1;
}
if(config.curPage === "comments" || config.curPage.indexOf("comments") != -1) {
e.preventDefault();
events.comments.get(pageNumber, events.pagination.commentsCreated);
}
else if(config.curPage === "users") {
e.preventDefault();
events.users.get(pageNumber);
}
});
},
getSelectedPaginationLink: function(){
var link = 1;
// using index Vs the page number(text) inside the pagination
$("ul.pagination a:not(.prev):not(.next)").each(function(index){
if($(this).parent().hasClass("active")){
link = index + 1;
return false;
}
});
return parseInt(link);
}
},
/*
* LogIn Page
*/
login: {
init: function(){
events.login.tabs();
},
tabs: function(){
$("#form-login #link-forgot-password, #form-forgot-password #link-login").click(function() {
$("#form-login, #form-forgot-password" ).toggleClass("display-none");
$(".error, .success").remove();
});
$("#link-register").click(function() {
$("#form-login, #form-forgot-password").addClass("display-none");
$("#form-register").removeClass("display-none");
$(".panel-title").text("Register");
$(".error, .success").remove();
});
$("#form-register #link-login").click(function() {
$(".panel-title").text("Login");
$("#form-register").addClass("display-none");
$("#form-login").removeClass("display-none");
$(".error, .success").remove();
});
}
},
/*
* Profile
*/
profile: {
init: function(){
}
},
/*
* News Feed
*/
newsfeed:{
init: function(){
events.newsfeed.update();
events.newsfeed.delete();
},
reInit: function(){
// It's important to have the update & delete events encapsulated inside a function,
// so you can call the function after ajax calls to re-initialize them
events.newsfeed.update();
events.newsfeed.delete();
},
update: function(){
$("#list-newsfeed .header .edit").off('click').on('click', function() {
var newsfeedBody = $(this).parent().parent().parent().parent();
var newsfeedId = newsfeedBody.attr("id");
getNewsFeedUpdateForm();
// 1. get the update form merged with the current newsfeed data
function getNewsFeedUpdateForm(){
ajax.send("NewsFeed/getUpdateForm", {newsfeed_id: newsfeedId}, getNewsFeedUpdateFormCallBack);
function getNewsFeedUpdateFormCallBack(result){
if(helpers.validateData(result, newsfeedBody, "html", "default", "data")){
newsfeedBody.html(result.data);
activateCancelNewsFeedEvent();
activateUpdateNewsFeedEvent();
}
}
}
// 2. if cancel, then go and get the current newsfeed(regardless of any changes)
function activateCancelNewsFeedEvent(){
$("#form-update-"+newsfeedId+" button[name='cancel']").click(function(e){
e.preventDefault();
ajax.send("NewsFeed/getById", {newsfeed_id: newsfeedId}, getNewsFeedByIdCallBack);
function getNewsFeedByIdCallBack(result){
if(helpers.validateData(result, newsfeedBody, "html", "default", "data")){
$(newsfeedBody).after(result.data);
$(newsfeedBody).remove();
events.newsfeed.reInit();
}
}
});
}
// 3. if update, then update the current newsfeed and get back the updated one
function activateUpdateNewsFeedEvent(){
$("#form-update-"+newsfeedId).submit(function(e){
e.preventDefault();
ajax.send("NewsFeed/update", helpers.serialize("#form-update-"+newsfeedId, "newsfeed_id="+newsfeedId), updateNewsFeedCallBack);
function updateNewsFeedCallBack(result){
if(helpers.validateData(result, newsfeedBody, "after", "default", "data")){
$(newsfeedBody).after(result.data);
$(newsfeedBody).remove();
events.newsfeed.reInit();
}
}
});
}
});
},
delete: function(){
$("#list-newsfeed .header .delete").off('click').on('click', function(e) {
e.preventDefault();
if (!confirm("Are you sure?")) { return; }
var newsfeedBody = $(this).parent().parent().parent().parent();
var newsfeedId = newsfeedBody.attr("id");
ajax.send("NewsFeed/delete", {newsfeed_id: newsfeedId}, deleteNewsFeedCallBack);
function deleteNewsFeedCallBack(result){
if(helpers.validateData(result, newsfeedBody, "html", "default", "success")){
$(newsfeedBody).remove();
}
}
});
}
},
/*
* Posts
*/
posts: {
init: function(){
}
},
/*
* Comments
*/
comments: {
init: function(){
events.comments.create();
events.comments.update();
events.comments.delete();
},
reInit: function(){
events.comments.update();
events.comments.delete();
},
get: function(pageNumber, commentsCreated){
if(helpers.empty(pageNumber)) pageNumber = 1;
if(helpers.empty(commentsCreated)) commentsCreated = 0;
ajax.send("Comments/getAll", {post_id: config.postId, page: pageNumber,
comments_created: commentsCreated}, getCommentsCallBack, "#list-comments");
function getCommentsCallBack(result){
if(helpers.validateData(result, "#list-comments", "html", "default", "data")){
$("#list-comments").append(result.data.comments);
events.comments.reInit();
$("ul.pagination").html(result.data.pagination);
events.pagination.init();
}else{
$("ul.pagination").html("");
}
}
},
create: function(){
$("#form-create-comment").submit(function(e){
e.preventDefault();
ajax.send("Comments/create", helpers.serialize(this, "post_id="+config.postId), createCommentCallBack, "#form-create-comment");
});
function createCommentCallBack(result){
if(helpers.validateData(result, "#form-create-comment", "after", "default", "data")){
$("#list-comments .no-data").remove();
$("#list-comments").append(result.data);
$("#form-create-comment textarea").val('');
// increment number of comments created in-place
events.pagination.commentsCreated++;
events.comments.reInit();
}
}
},
update: function(){
$("#list-comments .header .edit").off('click').on('click', function() {
var commentBody = $(this).parent().parent().parent().parent();
var commentId = commentBody.attr("id");
getCommentUpdateForm();
// 1. get the update form
function getCommentUpdateForm(){
ajax.send("Comments/getUpdateForm", {comment_id: commentId}, getCommentUpdateFormCallBack);
function getCommentUpdateFormCallBack(result){
if(helpers.validateData(result, commentBody, "html", "default", "data")){
commentBody.html(result.data);
activateCancelCommentEvent();
activateUpdateCommentEvent();
}
}
}
// 2.
function activateCancelCommentEvent(){
$("#form-update-"+commentId+" button[name='cancel']").click(function(e){
e.preventDefault();
ajax.send("Comments/getById", {comment_id: commentId}, getCommentByIdCallBack);
function getCommentByIdCallBack(result){
if(helpers.validateData(result, commentBody, "html", "default", "data")){
$(commentBody).after(result.data);
$(commentBody).remove();
events.comments.reInit();
}
}
});
}
// 3.
function activateUpdateCommentEvent(){
$("#form-update-"+commentId).submit(function(e){
e.preventDefault();
ajax.send("Comments/update", helpers.serialize("#form-update-"+commentId, "comment_id="+commentId), updateCommentCallBack);
function updateCommentCallBack(result){
if(helpers.validateData(result, commentBody, "after", "default", "data")){
$(commentBody).after(result.data);
$(commentBody).remove();
events.comments.reInit();
}
}
});
}
});
},
delete: function(){
$("#list-comments .header .delete").off('click').on('click', function(e) {
e.preventDefault();
if (!confirm("Are you sure?")) { return; }
var commentBody = $(this).parent().parent().parent().parent();
var commentId = commentBody.attr("id");
ajax.send("Comments/delete", {comment_id: commentId}, deleteCommentCallBack);
function deleteCommentCallBack(result){
if(helpers.validateData(result, commentBody, "html", "default", "success")){
$(commentBody).remove();
}
}
});
}
},
/*
* Files
*/
files: {
init: function(){
events.files.create();
events.files.delete();
},
reInit: function(){
events.files.delete();
},
create: function(){
$("#form-upload-file").submit(function(e){
e.preventDefault();
if(helpers.validateFileSize("file")){
ajax.upload("Files/create", new FormData(this), createFileCallBack);
}else{
helpers.displayError("#form-upload-file", "File size can't exceed max limit");
}
});
function createFileCallBack(result){
if(helpers.validateData(result, "#form-upload-file", "after", "default", "data")){
$("#list-files .no-data").remove();
//How to insert/append an element by fadeIn()?
//@see http://stackoverflow.com/questions/4687579/append-an-element-with-fade-in-effect-jquery
$(result.data).hide().prependTo("#list-files tbody").fadeIn();
events.files.reInit();
}
}
},
delete: function(){
$("#list-files tr td .delete").off('click').on('click', function(e) {
e.preventDefault();
if (!confirm("Are you sure?")) { return; }
var row = $(this).parent().parent();
var fileId = row.attr("id");
ajax.send("Files/delete", {file_id: fileId}, deleteFileCallBack);
function deleteFileCallBack(result){
if(helpers.validateData(result, row, "after", "row", "success")){
$(row).remove();
}
}
});
}
},
/*
* Users
*/
users: {
init: function(){
events.users.search();
events.users.update();
events.users.delete();
},
reInit: function(){
events.users.delete();
},
get: function(pageNumber){
if(helpers.empty(pageNumber)) pageNumber = 1;
var name = $("#form-search-users input[name='name']").val();
var email = $("#form-search-users input[name='email']").val();
var role = $("#form-search-users select[name='role']").val();
ajax.send("Admin/getUsers", {name: name, email: email, role: role, page: pageNumber},
events.users.get_search_callback, "#list-users");
},
search: function(){
$("#form-search-users").submit(function(e){
e.preventDefault();
ajax.send("Admin/getUsers", helpers.serialize(this, "page=1"), events.users.get_search_callback, "#list-users");
});
},
get_search_callback: function(result){
if(helpers.validateData(result, "#form-search-users", "after", "default", "data")){
$("#list-users tbody").html(result.data.users);
events.users.reInit();
$("ul.pagination").html(result.data.pagination);
events.pagination.init();
}else{
$("ul.pagination").html("");
}
},
update: function(){
$("#form-update-user-info").submit(function(e){
e.preventDefault();
ajax.send("Admin/updateUserInfo", helpers.serialize(this, "user_id="+config.userId), updateUserInfoCallBack, "#form-update-user-info");
});
function updateUserInfoCallBack(result){
if(helpers.validateData(result, "#form-update-user-info", "after", "default", "success")){
$("#form-update-user-info").after(result.success);
}
}
},
delete: function(){
$("#list-users tr td .delete").click(function(e){
e.preventDefault();
if (!confirm("Are you sure?")) { return; }
var row = $(this).parent().parent().parent();
var userId = row.attr("id");
ajax.send("Admin/deleteUser", {user_id: userId}, deleteUserCallBack);
function deleteUserCallBack(result){
if(helpers.validateData(result, row, "after", "row", "success")){
$(row).remove();
}
}
});
}
},
/*
* Bug, Feature or Enhancement
*/
bugs:{
init: function(){
}
},
/*
* Backups
*/
backups:{
init: function(){
}
},
/*
* Todo application
*/
todo:{
init: function(){
events.todo.create();
events.todo.delete();
},
create: function(){
$("#form-create-todo").submit(function(e){
e.preventDefault();
ajax.send("Todo/create", helpers.serialize(this), createTodoCallBack, "#form-create-todo");
});
function createTodoCallBack(result){
if(helpers.validateData(result, "#form-create-todo", "after", "default", "success")){
alert(result.success + " refresh the page to see the results");
}
}
},
delete: function(){
$("#todo-list form.form-delete-todo").submit(function(e){
e.preventDefault();
if (!confirm("Are you sure?")) { return; }
var cur_todo = $(this).parent();
ajax.send("Todo/delete", helpers.serialize(this), deleteTodoCallBack, cur_todo);
function deleteTodoCallBack(result){
if(helpers.validateData(result, cur_todo, "after", "default", "success")){
$(cur_todo).remove();
alert(result.success);
}
}
});
}
}
};
| public/js/main.js | /*
* Document : main.js
* Author : Omar El Gabry <[email protected]>
* Description: Main Javascript file for the application.
* It handles all Ajax calls, Events, and DOM Manipulations
*
*/
/*
* Configuration Variables
* An Object with key-value paris assigned in footer.php
*
* @see footer.php
* @see core/Controller.php
*/
var config = {};
/*
* Ajax
*/
var ajax = {
/**
* Default ajax function.
*
* @param string url URL to send ajax call
* @param mixed postData data that will be sent to the server(PHP)
* @param function callback Callback Function that will be called upon success or failure
* @param string spinnerBlock An element where the spinner will be next to it
*
*/
send: function(url, postData, callback, spinnerBlock){
var spinnerEle = null;
$.ajax({
url: config.root + url,
type: "POST",
data: helpers.appendCsrfToken(postData),
dataType: "json",
beforeSend: function() {
// create the spinner element, and add it after the spinnerBlock
spinnerEle = $("<i>").addClass("fa fa-spinner fa-3x fa-spin spinner").css("display", "none");
$(spinnerBlock).after(spinnerEle);
// run the spinner
ajax.runSpinner(spinnerBlock, spinnerEle);
}
})
.done(function(data) {
// stopSpinner(spinnerBlock);
callback(data);
})
.fail(function(jqXHR) {
// stopSpinner(spinnerBlock);
switch (jqXHR.status){
case 302:
helpers.redirectTo(config.root);
break;
default:
helpers.displayErrorPage(jqXHR);
}
})
.always(function() {
ajax.stopSpinner(spinnerBlock, spinnerEle);
});
},
/**
* Ajax call - ONLY for files.
*
* @param string url URL to send ajax call
* @param object fileData data(formData) that will be sent to the server(PHP)
* @param function callback Callback Function that will be called upon success or failure
*
*/
upload: function(url, fileData, callback){
$.ajax({
url: config.root + url,
type: "POST",
data: helpers.appendCsrfToken(fileData),
dataType: "json",
beforeSend: function () {
// reset the progress bar
$(".progress .progress-bar").css("width", "0%").html("0%");
},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
// check if upload property exists
if(myXhr.upload){
myXhr.upload.addEventListener('progress', ajax.progressbar, false);
$(".progress").removeClass("display-none");
}
return myXhr;
},
contentType: false,
cache: false,
processData:false
})
.done(function(data) {
callback(data);
})
.fail(function(jqXHR) {
switch (jqXHR.status){
case 302:
helpers.redirectTo(config.root);
break;
default:
helpers.displayErrorPage(jqXHR);
}
})
.always(function() {
$(".progress").addClass("display-none");
});
},
progressbar: function(e){
if(e.lengthComputable){
var meter = parseInt((e.loaded/e.total) * 100);
$(".progress .progress-bar").css("width", meter+"%").html(meter + "%");
}
},
runSpinner: function(spinnerBlock, spinnerEle){
if(!helpers.empty(spinnerBlock)) {
// var spinner = $(spinnerBlock).nextAll(".spinner:eq(0)");
$(spinnerEle).show();
$(spinnerBlock).css("opacity","0.6");
}
},
stopSpinner: function(spinnerBlock, spinnerEle){
if(!helpers.empty(spinnerBlock) ) {
// var spinner = $(spinnerBlock).nextAll(".spinner:eq(0)");
$(spinnerEle).remove();
$(spinnerBlock).css("opacity","1");
}
}
};
/*
* Helpers
*
*/
var helpers = {
/**
* append csrf token to data that will be sent in ajax
*
* @param mixed data
*
*/
appendCsrfToken: function (data){
if(typeof (data) === "string"){
if(data.length > 0){
data = data + "&csrf_token=" + config.csrfToken;
}else{
data = data + "csrf_token=" + config.csrfToken;
}
}
else if(data.constructor.name === "FormData"){
data.append("csrf_token", config.csrfToken);
}
else if(typeof(data) === "object"){
data.csrf_token = config.csrfToken;
}
return data;
},
/**
* replaces the current page with error page returned from ajax
*
* @param XMLHttpRequest jqXHR
* @see http://stackoverflow.com/questions/4387688/replace-current-page-with-ajax-content
*/
displayErrorPage: function (jqXHR) {
document.open();
document.write(jqXHR.responseText);
document.close();
},
/**
* Extract keys from JavaScript object to be used as variables
* @param object data
*/
extract: function (data) {
for (var key in data) {
window[key] = data[key];
}
},
/**
* Checks if an element is empty(set to null or undefined)
*
* @param mixed foo
* @return boolean
*
*/
empty: function (foo){
return (foo === null || typeof(foo) === "undefined")? true: false;
},
/**
* extends $().html() in jQuery
*
* @param string target
* @param string str
*/
html: function (target, str){
$(target).html(str);
},
/**
* extends $().after() in jQuery
*
* @param string target
* @param string str
*/
after: function (target, str){
$(target).after(str);
},
/**
* clears all error and success messages
*
* @param string target
*/
clearMessages: function (target){
if(helpers.empty(target)){
$(".error").remove();
$(".success").remove();
} else{
// $(target).next(".error").remove();
// $(target).next(".success").remove();
$(target).nextAll(".error:eq(0)").remove();
$(target).nextAll(".success:eq(0)").remove();
}
},
/**
* Extend the serialize() function in jQuery.
* This function is designed to add extra data(name => value) to the form.
*
* @param object ele Form element
* @param string str String to be appended to the form data.
* @return string The serialized form data in form of: "name=value&name=value"
*
*/
serialize: function (ele, str){
if(helpers.empty(str)){
return $(ele).serialize();
} else {
return $(ele).serialize() + "&" + str;
}
},
/**
* This function is used to redirect.
*
* @param string location
*/
redirectTo: function (location){
window.location.href = location;
},
/**
* encode potential text
* All encoding are done and must be done on the server side,
* but you can use this function in case it's needed on client.
*
* @param string str
*/
encodeHTML: function (str){
return $('<div />').text(str).html();
},
/**
* validate form file size
* It's important to validate file size on client-side to avoid overflow in $_POST & $_FILES
*
* @param string form form element
* @param string id id of the file input element
* @see app/core/Request/dataSizeOverflow()
*/
validateFileSize: function (fileId){
var size = document.getElementById(fileId).files[0].size;
return size < config.fileSizeOverflow;
},
/**
* display error message
*
* @param string targetBlock The target block where the error or success alerts will be inserted
* @param string message error message
*
*/
displayError: function (targetBlock, message){
// 1. clear
helpers.clearMessages(targetBlock);
// 2. display
var alert = $("<div>").addClass("alert alert-danger");
var notation = $("<i>").addClass("fa fa-exclamation-circle");
alert.append(notation);
message = helpers.empty(message)? "Sorry there was a problem": message;
alert.append(" " + message);
var error = $("<div>").addClass("error").html(alert);
$(targetBlock).after(error);
},
/**
* Validate the data coming from server side(PHP)
*
* The data coming from PHP should be something like this:
* data = [error = "some html code", success = "some html code", data = "some html code", redirect = "link"];
*
* @param object result The Data that was sent from the server(PHP)
* @param string targetBlock The target block where the error or success alerts(if exists) will be inserted inside/after it
* @param string errorFunc The function that will be used to display the error, Ex: html(), after(), ..etc.
* @param string errorType specifies how the error will be displayed, default or as row
* @param string returnVal the expected value returned from the server(regardless of errors and redirections), Ex: success, data, ..etc.
* @return boolean
*/
validateData: function (result, targetBlock, errorFunc, errorType, returnVal){
// 1. clear all existing error or success messages
helpers.clearMessages(targetBlock);
// 2. Define and extend jQuery functions required to display the error.
if(errorFunc === "html") errorFunc = helpers.html;
else if(errorFunc === "after") errorFunc = helpers.after;
else errorFunc = helpers.html;
// 3. check if result is empty
if(helpers.empty(result)){
helpers.displayError(targetBlock);
return false;
}
// If there was a redirection
else if(!helpers.empty(result.redirect)){
helpers.redirectTo(result.redirect);
return false;
}
// If there was errors encountered and sent from the server, then display it
else if(!helpers.empty(result.error)){
if(errorType === "default" || helpers.empty(errorType)){
errorFunc(targetBlock, result.error);
} else if(errorType === "row"){
var td = $("<td>").attr("colspan", "5");
errorFunc(targetBlock, $(td).html(result.error));
}
return false;
}
else{
if(returnVal === "success" && helpers.empty(result.success)){
helpers.displayError(targetBlock);
return false;
} else if(returnVal === "data" && helpers.empty(result.data)){
helpers.displayError(targetBlock);
return false;
} else if(returnVal !== "data" && returnVal !== "success"){
helpers.displayError(targetBlock);
return false;
}
}
return true;
}
};
/*
* App
*
*/
var app = {
init: function (){
// initialize todo application event
events.todo.init();
if(!helpers.empty(config.curPage)){
// pagination
events.pagination.init();
// events of current page
if(config.curPage.constructor === Array){
config.curPage.forEach(function(sub) {
// add 'active' class to current navigation list
$(".sidebar-nav #"+ sub +" a").addClass("active");
events[sub].init();
});
}else{
$(".sidebar-nav #"+ config.curPage +" a").addClass("active");
events[config.curPage].init();
}
}
}
};
/*
* Events
*
*/
var events = {
/*
* Pagination
*/
pagination: {
/**
* @var integer Acts like the page number for comments
*/
viewMoreCounter: 1,
/**
* @var integer Whenever there is a new comment created in-place, this will be incremented.
*/
commentsCreated: 0,
init: function(){
$("ul.pagination a").click(function(e){
var pageNumber;
if(config.curPage === "comments" || config.curPage.indexOf("comments") > -1){
pageNumber = ++events.pagination.viewMoreCounter;
}
else if($(this).hasClass("prev")){
pageNumber = events.pagination.getSelectedPaginationLink() - 1;
}
else if($(this).hasClass("next")){
pageNumber = events.pagination.getSelectedPaginationLink() + 1;
}
else{
// index() returns 0-indexed
pageNumber = $(this).index("ul.pagination a:not(.prev):not(.next)") + 1;
}
if(config.curPage === "comments" || config.curPage.indexOf("comments") != -1) {
e.preventDefault();
events.comments.get(pageNumber, events.pagination.commentsCreated);
}
else if(config.curPage === "users") {
e.preventDefault();
events.users.get(pageNumber);
}
});
},
getSelectedPaginationLink: function(){
var link = 1;
// using index Vs the page number(text) inside the pagination
$("ul.pagination a:not(.prev):not(.next)").each(function(index){
if($(this).parent().hasClass("active")){
link = index + 1;
return false;
}
});
return parseInt(link);
}
},
/*
* LogIn Page
*/
login: {
init: function(){
}
},
/*
* Profile
*/
profile: {
init: function(){
}
},
/*
* News Feed
*/
newsfeed:{
init: function(){
events.newsfeed.update();
events.newsfeed.delete();
},
reInit: function(){
// It's important to have the update & delete events encapsulated inside a function,
// so you can call the function after ajax calls to re-initialize them
events.newsfeed.update();
events.newsfeed.delete();
},
update: function(){
$("#list-newsfeed .header .edit").off('click').on('click', function() {
var newsfeedBody = $(this).parent().parent().parent().parent();
var newsfeedId = newsfeedBody.attr("id");
getNewsFeedUpdateForm();
// 1. get the update form merged with the current newsfeed data
function getNewsFeedUpdateForm(){
ajax.send("NewsFeed/getUpdateForm", {newsfeed_id: newsfeedId}, getNewsFeedUpdateFormCallBack);
function getNewsFeedUpdateFormCallBack(result){
if(helpers.validateData(result, newsfeedBody, "html", "default", "data")){
newsfeedBody.html(result.data);
activateCancelNewsFeedEvent();
activateUpdateNewsFeedEvent();
}
}
}
// 2. if cancel, then go and get the current newsfeed(regardless of any changes)
function activateCancelNewsFeedEvent(){
$("#form-update-"+newsfeedId+" button[name='cancel']").click(function(e){
e.preventDefault();
ajax.send("NewsFeed/getById", {newsfeed_id: newsfeedId}, getNewsFeedByIdCallBack);
function getNewsFeedByIdCallBack(result){
if(helpers.validateData(result, newsfeedBody, "html", "default", "data")){
$(newsfeedBody).after(result.data);
$(newsfeedBody).remove();
events.newsfeed.reInit();
}
}
});
}
// 3. if update, then update the current newsfeed and get back the updated one
function activateUpdateNewsFeedEvent(){
$("#form-update-"+newsfeedId).submit(function(e){
e.preventDefault();
ajax.send("NewsFeed/update", helpers.serialize("#form-update-"+newsfeedId, "newsfeed_id="+newsfeedId), updateNewsFeedCallBack);
function updateNewsFeedCallBack(result){
if(helpers.validateData(result, newsfeedBody, "after", "default", "data")){
$(newsfeedBody).after(result.data);
$(newsfeedBody).remove();
events.newsfeed.reInit();
}
}
});
}
});
},
delete: function(){
$("#list-newsfeed .header .delete").off('click').on('click', function(e) {
e.preventDefault();
if (!confirm("Are you sure?")) { return; }
var newsfeedBody = $(this).parent().parent().parent().parent();
var newsfeedId = newsfeedBody.attr("id");
ajax.send("NewsFeed/delete", {newsfeed_id: newsfeedId}, deleteNewsFeedCallBack);
function deleteNewsFeedCallBack(result){
if(helpers.validateData(result, newsfeedBody, "html", "default", "success")){
$(newsfeedBody).remove();
}
}
});
}
},
/*
* Posts
*/
posts: {
init: function(){
}
},
/*
* Comments
*/
comments: {
init: function(){
events.comments.create();
events.comments.update();
events.comments.delete();
},
reInit: function(){
events.comments.update();
events.comments.delete();
},
get: function(pageNumber, commentsCreated){
if(helpers.empty(pageNumber)) pageNumber = 1;
if(helpers.empty(commentsCreated)) commentsCreated = 0;
ajax.send("Comments/getAll", {post_id: config.postId, page: pageNumber,
comments_created: commentsCreated}, getCommentsCallBack, "#list-comments");
function getCommentsCallBack(result){
if(helpers.validateData(result, "#list-comments", "html", "default", "data")){
$("#list-comments").append(result.data.comments);
events.comments.reInit();
$("ul.pagination").html(result.data.pagination);
events.pagination.init();
}else{
$("ul.pagination").html("");
}
}
},
create: function(){
$("#form-create-comment").submit(function(e){
e.preventDefault();
ajax.send("Comments/create", helpers.serialize(this, "post_id="+config.postId), createCommentCallBack, "#form-create-comment");
});
function createCommentCallBack(result){
if(helpers.validateData(result, "#form-create-comment", "after", "default", "data")){
$("#list-comments .no-data").remove();
$("#list-comments").append(result.data);
$("#form-create-comment textarea").val('');
// increment number of comments created in-place
events.pagination.commentsCreated++;
events.comments.reInit();
}
}
},
update: function(){
$("#list-comments .header .edit").off('click').on('click', function() {
var commentBody = $(this).parent().parent().parent().parent();
var commentId = commentBody.attr("id");
getCommentUpdateForm();
// 1. get the update form
function getCommentUpdateForm(){
ajax.send("Comments/getUpdateForm", {comment_id: commentId}, getCommentUpdateFormCallBack);
function getCommentUpdateFormCallBack(result){
if(helpers.validateData(result, commentBody, "html", "default", "data")){
commentBody.html(result.data);
activateCancelCommentEvent();
activateUpdateCommentEvent();
}
}
}
// 2.
function activateCancelCommentEvent(){
$("#form-update-"+commentId+" button[name='cancel']").click(function(e){
e.preventDefault();
ajax.send("Comments/getById", {comment_id: commentId}, getCommentByIdCallBack);
function getCommentByIdCallBack(result){
if(helpers.validateData(result, commentBody, "html", "default", "data")){
$(commentBody).after(result.data);
$(commentBody).remove();
events.comments.reInit();
}
}
});
}
// 3.
function activateUpdateCommentEvent(){
$("#form-update-"+commentId).submit(function(e){
e.preventDefault();
ajax.send("Comments/update", helpers.serialize("#form-update-"+commentId, "comment_id="+commentId), updateCommentCallBack);
function updateCommentCallBack(result){
if(helpers.validateData(result, commentBody, "after", "default", "data")){
$(commentBody).after(result.data);
$(commentBody).remove();
events.comments.reInit();
}
}
});
}
});
},
delete: function(){
$("#list-comments .header .delete").off('click').on('click', function(e) {
e.preventDefault();
if (!confirm("Are you sure?")) { return; }
var commentBody = $(this).parent().parent().parent().parent();
var commentId = commentBody.attr("id");
ajax.send("Comments/delete", {comment_id: commentId}, deleteCommentCallBack);
function deleteCommentCallBack(result){
if(helpers.validateData(result, commentBody, "html", "default", "success")){
$(commentBody).remove();
}
}
});
}
},
/*
* Files
*/
files: {
init: function(){
events.files.create();
events.files.delete();
},
reInit: function(){
events.files.delete();
},
create: function(){
$("#form-upload-file").submit(function(e){
e.preventDefault();
if(helpers.validateFileSize("file")){
ajax.upload("Files/create", new FormData(this), createFileCallBack);
}else{
helpers.displayError("#form-upload-file", "File size can't exceed max limit");
}
});
function createFileCallBack(result){
if(helpers.validateData(result, "#form-upload-file", "after", "default", "data")){
$("#list-files .no-data").remove();
//How to insert/append an element by fadeIn()?
//@see http://stackoverflow.com/questions/4687579/append-an-element-with-fade-in-effect-jquery
$(result.data).hide().prependTo("#list-files tbody").fadeIn();
events.files.reInit();
}
}
},
delete: function(){
$("#list-files tr td .delete").off('click').on('click', function(e) {
e.preventDefault();
if (!confirm("Are you sure?")) { return; }
var row = $(this).parent().parent();
var fileId = row.attr("id");
ajax.send("Files/delete", {file_id: fileId}, deleteFileCallBack);
function deleteFileCallBack(result){
if(helpers.validateData(result, row, "after", "row", "success")){
$(row).remove();
}
}
});
}
},
/*
* Users
*/
users: {
init: function(){
events.users.search();
events.users.update();
events.users.delete();
},
reInit: function(){
events.users.delete();
},
get: function(pageNumber){
if(helpers.empty(pageNumber)) pageNumber = 1;
var name = $("#form-search-users input[name='name']").val();
var email = $("#form-search-users input[name='email']").val();
var role = $("#form-search-users select[name='role']").val();
ajax.send("Admin/getUsers", {name: name, email: email, role: role, page: pageNumber},
events.users.get_search_callback, "#list-users");
},
search: function(){
$("#form-search-users").submit(function(e){
e.preventDefault();
ajax.send("Admin/getUsers", helpers.serialize(this, "page=1"), events.users.get_search_callback, "#list-users");
});
},
get_search_callback: function(result){
if(helpers.validateData(result, "#form-search-users", "after", "default", "data")){
$("#list-users tbody").html(result.data.users);
events.users.reInit();
$("ul.pagination").html(result.data.pagination);
events.pagination.init();
}else{
$("ul.pagination").html("");
}
},
update: function(){
$("#form-update-user-info").submit(function(e){
e.preventDefault();
ajax.send("Admin/updateUserInfo", helpers.serialize(this, "user_id="+config.userId), updateUserInfoCallBack, "#form-update-user-info");
});
function updateUserInfoCallBack(result){
if(helpers.validateData(result, "#form-update-user-info", "after", "default", "success")){
$("#form-update-user-info").after(result.success);
}
}
},
delete: function(){
$("#list-users tr td .delete").click(function(e){
e.preventDefault();
if (!confirm("Are you sure?")) { return; }
var row = $(this).parent().parent().parent();
var userId = row.attr("id");
ajax.send("Admin/deleteUser", {user_id: userId}, deleteUserCallBack);
function deleteUserCallBack(result){
if(helpers.validateData(result, row, "after", "row", "success")){
$(row).remove();
}
}
});
}
},
/*
* Bug, Feature or Enhancement
*/
bugs:{
init: function(){
}
},
/*
* Backups
*/
backups:{
init: function(){
}
},
/*
* Todo application
*/
todo:{
init: function(){
events.todo.create();
events.todo.delete();
},
create: function(){
$("#form-create-todo").submit(function(e){
e.preventDefault();
ajax.send("Todo/create", helpers.serialize(this), createTodoCallBack, "#form-create-todo");
});
function createTodoCallBack(result){
if(helpers.validateData(result, "#form-create-todo", "after", "default", "success")){
alert(result.success + " refresh the page to see the results");
}
}
},
delete: function(){
$("#todo-list form.form-delete-todo").submit(function(e){
e.preventDefault();
if (!confirm("Are you sure?")) { return; }
var cur_todo = $(this).parent();
ajax.send("Todo/delete", helpers.serialize(this), deleteTodoCallBack, cur_todo);
function deleteTodoCallBack(result){
if(helpers.validateData(result, cur_todo, "after", "default", "success")){
$(cur_todo).remove();
alert(result.success);
}
}
});
}
}
};
| #8 Fix Login tabs events
Tabs at login page were removed by mistake | public/js/main.js | #8 Fix Login tabs events | <ide><path>ublic/js/main.js
<ide> */
<ide> login: {
<ide> init: function(){
<add> events.login.tabs();
<add> },
<add> tabs: function(){
<add> $("#form-login #link-forgot-password, #form-forgot-password #link-login").click(function() {
<add>
<add> $("#form-login, #form-forgot-password" ).toggleClass("display-none");
<add> $(".error, .success").remove();
<add> });
<add>
<add> $("#link-register").click(function() {
<add>
<add> $("#form-login, #form-forgot-password").addClass("display-none");
<add> $("#form-register").removeClass("display-none");
<add> $(".panel-title").text("Register");
<add> $(".error, .success").remove();
<add> });
<add>
<add> $("#form-register #link-login").click(function() {
<add>
<add> $(".panel-title").text("Login");
<add> $("#form-register").addClass("display-none");
<add> $("#form-login").removeClass("display-none");
<add> $(".error, .success").remove();
<add> });
<ide> }
<ide> },
<ide> |
|
JavaScript | agpl-3.0 | 9c6e6a9858f9dcc636a54cb964e5ddb56254aae2 | 0 | atelier-cartographique/waend,atelier-cartographique/waend,atelier-cartographique/waend | /*
* app/lib/commands/widgets/ValueSelect.js
*
*
* Copyright (C) 2015 Pierre Marchand <[email protected]>
*
* License in LICENSE file at the root of the repository.
*
*/
var _ = require('underscore'),
rbush = require('rbush'),
O = require('../../../../lib/object').Object;
function Value (val, size, align) {
this.value = val;
this.size = size;
this.align = align || 'center';
}
Value.prototype.setValue = function (val) {
this.value = val;
this.draw();
}
Value.prototype.draw = function (context, pos) {
var extent;
if (0 === arguments.length){
if(!this.visualState) {
throw (new Error('ValueDrawNoArgsNoState'));
}
pos = this.visualState.pos;
context = this.visualState.context;
extent = this.visualState.extent;
}
if (extent) {
context.clearRect(
extent[0], extent[1],
extent[2] - extent[0], extent[3] - extent[1]
);
}
var str = ' ' + this.value.toString() + ' ',
x = pos[0],
y = pos[1],
align = this.align;
context.save();
context.fillStyle = '#0092FF';
context.font = this.size +'px dauphine_regular';
context.textAlign = align;
context.fillText(str, x, y);
// store text bounding box
var metrics = context.measureText(str),
minY = y - metrics.fontBoundingBoxAscent,
maxY = y + metrics.fontBoundingBoxDescent;
if ('center' === align) {
var hw = metrics.width / 2;
extent = [ x - hw, minY, x + hw, maxY ];
}
else if ('right' === align) {
extent = [ x - metrics.width, minY, x , maxY ];
}
else { // left
extent = [ x, minY, x + metrics.width, maxY ];
}
this.visualState = {
extent: extent,
context: context,
pos: pos
};
//
// context.strokeRect(
// extent[0], extent[1],
// extent[2] - extent[0], extent[3] - extent[1]
// );
context.restore();
};
Value.prototype.getControl = function () {
var extent = this.visualState ? _.clone(this.visualState.extent) : [0,0,0,0];
extent.push(this);
return extent;
};
Value.prototype.callback = function (pos, widget) {
widget.emit('value', this.value);
};
function Range (min, max) {
this.min = min;
this.max = max;
this.value = min + Math.floor((max - min) / 2);
this.thickness = 24;
this.valueMin = new Value(min, this.thickness / 2);
this.valueMax = new Value(max, this.thickness / 2);
this.valueMiddle = new Value(this.value, this.thickness);
}
Range.prototype.getControl = function () {
var extent = this.extent ? _.clone(this.extent) : [0,0,0,0];
extent.push(this);
return extent;
};
Range.prototype.getControls = function () {
var c = this.getControl(),
cmin = this.valueMin.getControl(),
cmid = this.valueMiddle.getControl(),
cmax = this.valueMax.getControl();
return [c, cmin, cmid, cmax];
};
Range.prototype.draw = function (context, startPos, endPos) {
var sp = startPos,
ep = endPos,
mp = [
startPos[0] + ((endPos[0] - startPos[0]) / 2),
startPos[1]
];
var thickness = this.thickness,
ticks = [sp, mp, ep];
context.save();
context.strokeStyle = 'black';
context.beginPath();
_.each(ticks, function(t){
context.moveTo(t[0], t[1]);
context.lineTo(t[0], t[1] - thickness);
});
context.moveTo(sp[0], sp[1] - (thickness / 2));
context.lineTo(ep[0], ep[1] - (thickness / 2));
context.stroke();
context.restore();
this.extent = [sp[0], sp[1] - thickness, ep[0], ep[1]];
this.context = context;
sp[1] = sp[1] - (thickness * 1.3);
ep[1] = ep[1] - (thickness * 1.3);
mp[1] = mp[1] - (thickness * 1.3);
this.valueMin.draw(context, sp);
this.valueMiddle.draw(context, mp);
this.valueMax.draw(context, ep);
};
Range.prototype.transition = function (pos) {
var x = pos[0],
val = this.valueAt(pos),
range = this.makeRange(val),
valMin = this.valueMin,
valCen = this.valueMiddle,
valMax = this.valueMax,
self = this;
// this.min = range[0];
// this.max = range[1];
// this.valueMin.setValue(this.min);
// this.valueMax.setValue(this.max);
// this.valueMiddle.setValue(Math.floor(val));
var context = this.context,
extent = this.extent,
thickness = this.thickness,
sp = [extent[0], extent[1]],
ep = [extent[2], extent[3]],
centerX = extent[0] + ((extent[2] - extent[0]) / 2),
height = extent[3] - extent[1],
centerY = extent[1] + (height / 2),
baseY = extent[3],
mp = pos,
d0 = pos[0] - sp[0],
d1 = centerX - pos[0],
d2 = pos[0] - ep[0],
duration = 450,
start = null;
var step = function (ts) {
if (!start) {
start = ts;
}
var elapsed = ts - start,
remaining = duration - elapsed;
context.clearRect(
extent[0] - 1,
extent[1] - 1,
(extent[2] - extent[0]) + 2,
(extent[3] - extent[1]) + 2
);
if (remaining < 0) {
context.restore();
self.min = range[0];
self.max = range[1];
self.value = Math.floor(val);
valMin.setValue(self.min);
valMax.setValue(self.max);
valCen.setValue(self.value);
self.draw(context, [extent[0], baseY], [extent[2], baseY]);
return;
}
var s = elapsed / duration,
r = remaining / duration,
a = d0 * r,
b = d1 * r,
c = d2 * r;
valMin.setValue(Math.floor(self.min + ((range[0] - self.min) * s)));
valMax.setValue(Math.ceil(self.max - ((self.max - range[1]) * s)));
valCen.setValue(Math.floor(self.value + ((val - self.value) * s)))
var ticks = [
// sp, [centerX, baseY], ep,
[sp[0] + a, baseY],
[centerX - b, baseY],
[ep[0] + c, baseY]
];
context.beginPath();
_.each(ticks, function(t){
context.moveTo(t[0], baseY);
context.lineTo(t[0], baseY - height);
});
context.moveTo(sp[0], centerY);
context.lineTo(ep[0], centerY);
context.stroke();
window.requestAnimationFrame(step);
};
context.save();
context.strokeStyle = 'black';
window.requestAnimationFrame(step);
};
Range.prototype.makeRange = function (val) {
var max = this.max,
min = this.min,
interval = ((max - min) / 10) / 2,
start = val - interval,
end = val + interval,
diff;
if (start < min) {
diff = min - start;
start += diff;
end += diff;
}
else if (end > max) {
diff = end - max;
start -= diff;
end -= diff;
}
return [Math.floor(start), Math.ceil(end)];
};
Range.prototype.valueAt = function (pos) {
var x = pos[0],
start = this.extent[0],
end = this.extent[2],
val;
if (x < start) {
val = this.min;
}
else if (x > end) {
val = this.max;
}
else {
var rg = end - start,
d = x - start;
val = this.min + ((d / rg) * (this.max - this.min));
}
return val;
};
Range.prototype.callback = function (pos, widget) {
// widget.addRange(this.makeRange(this.valueAt(pos)));
this.transition(pos);
};
var ValueSelect = O.extend({
initialize: function (config) {
Object.defineProperty(this, 'config', {'value': config});
Object.defineProperty(this, 'controlSize', {'value': 12});
this.ranges = [];
this.controls = rbush();
},
getControls: function (pos) {
var chs = 0.5;
var rect = [
pos[0] - chs, pos[1] - chs,
pos[0] + chs, pos[1] + chs
];
var controls = this.controls.search(rect),
indices = [];
for (var i = 0, li = controls.length; i < li; i++) {
indices.push(controls[i][4]);
}
return indices;
},
clickHandler: function (event) {
var pos = [event.clientX, event.clientY],
controls = this.getControls(pos);
if (0 === controls.length) {
return;
}
var control = controls[0],
callback = control.callback;
callback.call(control, pos, this);
},
build: function (ender) {
var container = this.config.container,
width = this.config.width,
height = this.config.height,
min = this.config.min,
max = this.config.max;
var canvas = document.createElement('canvas');
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
this.context = canvas.getContext('2d');
this.canvas = canvas;
this.addRange(min, max);
container.appendChild(canvas);
canvas.addEventListener('click',
_.bind(this.clickHandler, this), false);
this.on('value', function(v){
ender(v);
}, this);
},
addRange: function (min, max) {
if (_.isArray(min)) {
this.ranges.push(min);
}
else {
this.ranges.push([min, max]);
}
if(this.ranges.length > 6) {
this.ranges.shift();
}
if (this.existingRanges) {
this.transitionRanges();
}
else {
this.traceRanges();
}
},
transitionRanges: function () {
var self = this,
context = this.context,
canvas = context.canvas,
ranges = self.existingRanges,
width = this.config.width,
height = this.config.height,
startX = width * 0.2,
endX = width * 0.8,
yStep = height / (ranges.length + 1),
nextYStep = height / (ranges.length + 2),
start = null,
animStep = 1;
var step = function (ts) {
if (yStep > nextYStep) {
yStep -= animStep;
context.clearRect(0, 0, width, height);
for (var i = 0; i < ranges.length; i++) {
var y = yStep + (yStep * i),
r = ranges[i];
r.draw(context, [startX, y], [endX, y]);
}
window.requestAnimationFrame(step);
}
else {
self.traceRanges();
}
};
window.requestAnimationFrame(step);
},
traceRanges: function () {
var context = this.context,
canvas = context.canvas,
ranges = this.ranges,
width = this.config.width,
height = this.config.height,
startX = width * 0.2,
endX = width * 0.8,
yStep = height / (ranges.length + 1);
context.clearRect(0, 0, width, height);
this.controls.clear();
this.existingRanges = [];
for (var i = 0; i < ranges.length; i++) {
var y = yStep + (yStep * i),
r = ranges[i];
var rv = new Range(r[0], r[1]);
rv.draw(context, [startX, y], [endX, y]);
_.each(rv.getControls(), function (control) {
this.controls.insert(control);
}, this);
this.existingRanges.push(rv);
}
}
});
module.exports = exports = ValueSelect;
| app/lib/commands/widgets/ValueSelect.js | /*
* app/lib/commands/widgets/ValueSelect.js
*
*
* Copyright (C) 2015 Pierre Marchand <[email protected]>
*
* License in LICENSE file at the root of the repository.
*
*/
var _ = require('underscore'),
rbush = require('rbush'),
O = require('../../../../lib/object').Object;
function Value (val, size) {
this.value = val;
this.size = size;
}
Value.prototype.draw = function (context, pos, align) {
var str = ' ' + this.value.toString() + ' ',
x = pos[0],
y = pos[1];
context.save();
context.fillStyle = 'orange';
context.font = this.size +'px monospace';
context.textAlign = align || 'left';
context.fillText(str, x, y);
// store text bounding box
var metrics = context.measureText(str),
minY = y - metrics.fontBoundingBoxAscent,
maxY = y + metrics.fontBoundingBoxDescent,
extent;
if ('center' === align) {
var hw = metrics.width / 2;
extent = [ x - hw, minY, x + hw, maxY ];
}
else if ('right' === align) {
extent = [ x - metrics.width, minY, x , maxY ];
}
else { // left
extent = [ x, minY, x + metrics.width, maxY ];
}
this.extent = extent;
context.strokeRect(
extent[0], extent[1],
extent[2] - extent[0], extent[3] - extent[1]
);
context.restore();
};
Value.prototype.getControl = function () {
var extent = this.extent ? _.clone(this.extent) : [0,0,0,0];
extent.push(this);
return extent;
};
Value.prototype.callback = function (pos, widget) {
widget.emit('value', this.value);
};
function Range (min, max) {
this.min = min;
this.max = max;
this.thickness = 24;
this.valueMin = new Value(min, this.thickness);
this.valueMax = new Value(max, this.thickness);
var middleValue = min + Math.floor((max - min) / 2);
this.valueMiddle = new Value(middleValue, this.thickness);
}
Range.prototype.getControl = function () {
var extent = this.extent ? _.clone(this.extent) : [0,0,0,0];
extent.push(this);
return extent;
};
Range.prototype.getControls = function () {
var c = this.getControl(),
cmin = this.valueMin.getControl(),
cmid = this.valueMiddle.getControl(),
cmax = this.valueMax.getControl();
return [c, cmin, cmid, cmax];
};
Range.prototype.draw = function (context, startPos, endPos) {
var sp = startPos,
ep = endPos,
mp = [
startPos[0] + ((endPos[0] - startPos[0]) / 2),
startPos[1] - this.thickness
];
var thickness = this.thickness;
context.save();
context.fillStyle = 'blue';
context.beginPath();
context.moveTo(sp[0], sp[1]);
context.lineTo(ep[0], ep[1]);
context.lineTo(ep[0], ep[1] - thickness);
context.lineTo(sp[0], sp[1] - thickness);
context.closePath()
context.fill();
context.restore();
this.extent = [sp[0], sp[1] - thickness, ep[0], ep[1]];
this.valueMin.draw(context, sp, 'right');
this.valueMiddle.draw(context, mp, 'center');
this.valueMax.draw(context, ep, 'left');
};
Range.prototype.makeRange = function (val) {
var max = this.max,
min = this.min,
interval = ((max - min) / 10) / 2,
start = val - interval,
end = val + interval,
diff;
if (start < min) {
diff = min - start;
start += diff;
end += diff;
}
else if (end > max) {
diff = end - max;
start -= diff;
end -= diff;
}
return [Math.floor(start), Math.ceil(end)];
};
Range.prototype.callback = function (pos, widget) {
var x = pos[0],
start = this.extent[0],
end = this.extent[2];
if (x < start) {
widget.addRange(this.makeRange(this.min));
}
else if (x > end) {
widget.addRange(this.makeRange(this.max));
}
else {
var rg = end - start,
d = x - start,
val = (d / rg) * (this.max - this.min);
widget.addRange(this.makeRange(val));
}
};
var ValueSelect = O.extend({
initialize: function (config) {
Object.defineProperty(this, 'config', {'value': config});
Object.defineProperty(this, 'controlSize', {'value': 12});
this.ranges = [];
this.controls = rbush();
},
getControls: function (pos) {
var chs = 0.5;
var rect = [
pos[0] - chs, pos[1] - chs,
pos[0] + chs, pos[1] + chs
];
var controls = this.controls.search(rect),
indices = [];
for (var i = 0, li = controls.length; i < li; i++) {
indices.push(controls[i][4]);
}
return indices;
},
clickHandler: function (event) {
var pos = [event.clientX, event.clientY],
controls = this.getControls(pos);
if (0 === controls.length) {
return;
}
var control = controls[0],
callback = control.callback;
callback.call(control, pos, this);
},
build: function (ender) {
var container = this.config.container,
width = this.config.width,
height = this.config.height,
min = this.config.min,
max = this.config.max;
var canvas = document.createElement('canvas');
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
this.context = canvas.getContext('2d');
this.canvas = canvas;
this.addRange(min, max);
container.appendChild(canvas);
canvas.addEventListener('click',
_.bind(this.clickHandler, this), false);
this.on('value', function(v){
ender(v);
}, this);
},
addRange: function (min, max) {
if (_.isArray(min)) {
this.ranges.push(min);
}
else {
this.ranges.push([min, max]);
}
if(this.ranges.length > 6) {
this.ranges.shift();
}
if (this.existingRanges) {
this.transitionRanges();
}
else {
this.traceRanges();
}
},
transitionRanges: function () {
var self = this,
context = this.context,
canvas = context.canvas,
ranges = self.existingRanges,
width = this.config.width,
height = this.config.height,
startX = width * 0.2,
endX = width * 0.8,
yStep = height / (ranges.length + 1),
nextYStep = height / (ranges.length + 2),
start = null,
animStep = 1;
var step = function (ts) {
if (yStep > nextYStep) {
yStep -= animStep;
context.clearRect(0, 0, width, height);
for (var i = 0; i < ranges.length; i++) {
var y = yStep + (yStep * i),
r = ranges[i];
r.draw(context, [startX, y], [endX, y]);
}
window.requestAnimationFrame(step);
}
else {
self.traceRanges();
}
};
window.requestAnimationFrame(step);
},
traceRanges: function () {
var context = this.context,
canvas = context.canvas,
ranges = this.ranges,
width = this.config.width,
height = this.config.height,
startX = width * 0.2,
endX = width * 0.8,
yStep = height / (ranges.length + 1);
context.clearRect(0, 0, width, height);
this.controls.clear();
this.existingRanges = [];
for (var i = 0; i < ranges.length; i++) {
var y = yStep + (yStep * i),
r = ranges[i];
var rv = new Range(r[0], r[1]);
rv.draw(context, [startX, y], [endX, y]);
_.each(rv.getControls(), function (control) {
this.controls.insert(control);
}, this);
this.existingRanges.push(rv);
}
}
});
module.exports = exports = ValueSelect;
| valueselect new proto
| app/lib/commands/widgets/ValueSelect.js | valueselect new proto | <ide><path>pp/lib/commands/widgets/ValueSelect.js
<ide> O = require('../../../../lib/object').Object;
<ide>
<ide>
<del>function Value (val, size) {
<add>function Value (val, size, align) {
<ide> this.value = val;
<ide> this.size = size;
<add> this.align = align || 'center';
<ide> }
<ide>
<del>Value.prototype.draw = function (context, pos, align) {
<add>Value.prototype.setValue = function (val) {
<add> this.value = val;
<add> this.draw();
<add>}
<add>
<add>Value.prototype.draw = function (context, pos) {
<add> var extent;
<add> if (0 === arguments.length){
<add> if(!this.visualState) {
<add> throw (new Error('ValueDrawNoArgsNoState'));
<add> }
<add> pos = this.visualState.pos;
<add> context = this.visualState.context;
<add> extent = this.visualState.extent;
<add> }
<add> if (extent) {
<add> context.clearRect(
<add> extent[0], extent[1],
<add> extent[2] - extent[0], extent[3] - extent[1]
<add> );
<add> }
<add>
<ide> var str = ' ' + this.value.toString() + ' ',
<ide> x = pos[0],
<del> y = pos[1];
<add> y = pos[1],
<add> align = this.align;
<ide>
<ide> context.save();
<del> context.fillStyle = 'orange';
<del> context.font = this.size +'px monospace';
<del> context.textAlign = align || 'left';
<add> context.fillStyle = '#0092FF';
<add> context.font = this.size +'px dauphine_regular';
<add> context.textAlign = align;
<ide> context.fillText(str, x, y);
<ide>
<ide> // store text bounding box
<ide> var metrics = context.measureText(str),
<ide> minY = y - metrics.fontBoundingBoxAscent,
<del> maxY = y + metrics.fontBoundingBoxDescent,
<del> extent;
<add> maxY = y + metrics.fontBoundingBoxDescent;
<ide>
<ide> if ('center' === align) {
<ide> var hw = metrics.width / 2;
<ide> extent = [ x, minY, x + metrics.width, maxY ];
<ide> }
<ide>
<del> this.extent = extent;
<del>
<del> context.strokeRect(
<del> extent[0], extent[1],
<del> extent[2] - extent[0], extent[3] - extent[1]
<del> );
<add> this.visualState = {
<add> extent: extent,
<add> context: context,
<add> pos: pos
<add> };
<add> //
<add> // context.strokeRect(
<add> // extent[0], extent[1],
<add> // extent[2] - extent[0], extent[3] - extent[1]
<add> // );
<ide>
<ide> context.restore();
<ide> };
<ide>
<ide> Value.prototype.getControl = function () {
<del> var extent = this.extent ? _.clone(this.extent) : [0,0,0,0];
<add> var extent = this.visualState ? _.clone(this.visualState.extent) : [0,0,0,0];
<ide> extent.push(this);
<ide> return extent;
<ide> };
<ide> function Range (min, max) {
<ide> this.min = min;
<ide> this.max = max;
<add> this.value = min + Math.floor((max - min) / 2);
<ide> this.thickness = 24;
<del> this.valueMin = new Value(min, this.thickness);
<del> this.valueMax = new Value(max, this.thickness);
<del> var middleValue = min + Math.floor((max - min) / 2);
<del> this.valueMiddle = new Value(middleValue, this.thickness);
<add> this.valueMin = new Value(min, this.thickness / 2);
<add> this.valueMax = new Value(max, this.thickness / 2);
<add> this.valueMiddle = new Value(this.value, this.thickness);
<ide> }
<ide>
<ide> Range.prototype.getControl = function () {
<ide> ep = endPos,
<ide> mp = [
<ide> startPos[0] + ((endPos[0] - startPos[0]) / 2),
<del> startPos[1] - this.thickness
<add> startPos[1]
<ide> ];
<ide>
<del> var thickness = this.thickness;
<add> var thickness = this.thickness,
<add> ticks = [sp, mp, ep];
<ide> context.save();
<del> context.fillStyle = 'blue';
<add> context.strokeStyle = 'black';
<ide> context.beginPath();
<del> context.moveTo(sp[0], sp[1]);
<del> context.lineTo(ep[0], ep[1]);
<del> context.lineTo(ep[0], ep[1] - thickness);
<del> context.lineTo(sp[0], sp[1] - thickness);
<del> context.closePath()
<del> context.fill();
<add> _.each(ticks, function(t){
<add> context.moveTo(t[0], t[1]);
<add> context.lineTo(t[0], t[1] - thickness);
<add> });
<add>
<add> context.moveTo(sp[0], sp[1] - (thickness / 2));
<add> context.lineTo(ep[0], ep[1] - (thickness / 2));
<add> context.stroke();
<ide> context.restore();
<ide>
<ide> this.extent = [sp[0], sp[1] - thickness, ep[0], ep[1]];
<del>
<del> this.valueMin.draw(context, sp, 'right');
<del> this.valueMiddle.draw(context, mp, 'center');
<del> this.valueMax.draw(context, ep, 'left');
<add> this.context = context;
<add>
<add> sp[1] = sp[1] - (thickness * 1.3);
<add> ep[1] = ep[1] - (thickness * 1.3);
<add> mp[1] = mp[1] - (thickness * 1.3);
<add>
<add> this.valueMin.draw(context, sp);
<add> this.valueMiddle.draw(context, mp);
<add> this.valueMax.draw(context, ep);
<add>};
<add>
<add>
<add>Range.prototype.transition = function (pos) {
<add> var x = pos[0],
<add> val = this.valueAt(pos),
<add> range = this.makeRange(val),
<add> valMin = this.valueMin,
<add> valCen = this.valueMiddle,
<add> valMax = this.valueMax,
<add> self = this;
<add>
<add> // this.min = range[0];
<add> // this.max = range[1];
<add> // this.valueMin.setValue(this.min);
<add> // this.valueMax.setValue(this.max);
<add> // this.valueMiddle.setValue(Math.floor(val));
<add>
<add> var context = this.context,
<add> extent = this.extent,
<add> thickness = this.thickness,
<add> sp = [extent[0], extent[1]],
<add> ep = [extent[2], extent[3]],
<add> centerX = extent[0] + ((extent[2] - extent[0]) / 2),
<add> height = extent[3] - extent[1],
<add> centerY = extent[1] + (height / 2),
<add> baseY = extent[3],
<add> mp = pos,
<add> d0 = pos[0] - sp[0],
<add> d1 = centerX - pos[0],
<add> d2 = pos[0] - ep[0],
<add> duration = 450,
<add> start = null;
<add>
<add> var step = function (ts) {
<add> if (!start) {
<add> start = ts;
<add> }
<add> var elapsed = ts - start,
<add> remaining = duration - elapsed;
<add> context.clearRect(
<add> extent[0] - 1,
<add> extent[1] - 1,
<add> (extent[2] - extent[0]) + 2,
<add> (extent[3] - extent[1]) + 2
<add> );
<add> if (remaining < 0) {
<add> context.restore();
<add> self.min = range[0];
<add> self.max = range[1];
<add> self.value = Math.floor(val);
<add> valMin.setValue(self.min);
<add> valMax.setValue(self.max);
<add> valCen.setValue(self.value);
<add> self.draw(context, [extent[0], baseY], [extent[2], baseY]);
<add> return;
<add> }
<add> var s = elapsed / duration,
<add> r = remaining / duration,
<add> a = d0 * r,
<add> b = d1 * r,
<add> c = d2 * r;
<add>
<add> valMin.setValue(Math.floor(self.min + ((range[0] - self.min) * s)));
<add> valMax.setValue(Math.ceil(self.max - ((self.max - range[1]) * s)));
<add> valCen.setValue(Math.floor(self.value + ((val - self.value) * s)))
<add>
<add> var ticks = [
<add> // sp, [centerX, baseY], ep,
<add> [sp[0] + a, baseY],
<add> [centerX - b, baseY],
<add> [ep[0] + c, baseY]
<add> ];
<add> context.beginPath();
<add> _.each(ticks, function(t){
<add> context.moveTo(t[0], baseY);
<add> context.lineTo(t[0], baseY - height);
<add> });
<add>
<add> context.moveTo(sp[0], centerY);
<add> context.lineTo(ep[0], centerY);
<add> context.stroke();
<add> window.requestAnimationFrame(step);
<add> };
<add> context.save();
<add> context.strokeStyle = 'black';
<add> window.requestAnimationFrame(step);
<ide> };
<ide>
<ide> Range.prototype.makeRange = function (val) {
<ide> return [Math.floor(start), Math.ceil(end)];
<ide> };
<ide>
<del>Range.prototype.callback = function (pos, widget) {
<add>Range.prototype.valueAt = function (pos) {
<ide> var x = pos[0],
<ide> start = this.extent[0],
<del> end = this.extent[2];
<add> end = this.extent[2],
<add> val;
<ide> if (x < start) {
<del> widget.addRange(this.makeRange(this.min));
<add> val = this.min;
<ide> }
<ide> else if (x > end) {
<del> widget.addRange(this.makeRange(this.max));
<add> val = this.max;
<ide> }
<ide> else {
<ide> var rg = end - start,
<del> d = x - start,
<del> val = (d / rg) * (this.max - this.min);
<del> widget.addRange(this.makeRange(val));
<del> }
<add> d = x - start;
<add> val = this.min + ((d / rg) * (this.max - this.min));
<add> }
<add> return val;
<add>};
<add>
<add>Range.prototype.callback = function (pos, widget) {
<add> // widget.addRange(this.makeRange(this.valueAt(pos)));
<add> this.transition(pos);
<ide> };
<ide>
<ide>
<ide> this.on('value', function(v){
<ide> ender(v);
<ide> }, this);
<del>
<del>
<ide> },
<ide>
<ide> addRange: function (min, max) { |
|
Java | apache-2.0 | 2e39ac2cdd4c5442196523cc92d913b0f319d7bb | 0 | learning-layers/LivingDocumentsServer,learning-layers/LivingDocumentsServer,learning-layers/LivingDocumentsServer | /**
* Code contributed to the Learning Layers project
* http://www.learning-layers.eu
* Development is partly funded by the FP7 Programme of the European
* Commission under Grant Agreement FP7-ICT-318209.
* Copyright (c) 2014, Karlsruhe University of Applied Sciences.
* For a list of contributors see the AUTHORS file at the top-level directory
* of this distribution.
*
* 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 de.hska.ld.content.controller;
import de.hska.ld.content.dto.FolderDto;
import de.hska.ld.content.persistence.domain.Document;
import de.hska.ld.content.persistence.domain.Folder;
import de.hska.ld.content.util.Content;
import de.hska.ld.core.AbstractIntegrationTest;
import de.hska.ld.core.UserSession;
import de.hska.ld.core.persistence.domain.User;
import de.hska.ld.core.service.UserService;
import org.apache.http.HttpResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class FolderControllerIntegrationTest extends AbstractIntegrationTest {
private static final String RESOURCE_FOLDER = Content.RESOURCE_FOLDER;
private static final String RESOURCE_DOCUMENT = Content.RESOURCE_DOCUMENT;
private static final String TITLE = "Title";
private static final String DESCRIPTION = "Description";
Document document;
@Autowired
UserService userService;
@Before
public void setUp() throws Exception {
super.setUp();
setAuthentication(testUser);
document = new Document();
document.setTitle(TITLE);
document.setDescription(DESCRIPTION);
}
@Test
public void testCreateFolderUsesHttpCreatedOnPersist() throws Exception {
Folder folder = new Folder("Test");
HttpResponse response = UserSession.user().post(RESOURCE_FOLDER, folder);
Assert.assertEquals(HttpStatus.CREATED, UserSession.getStatusCode(response));
folder = UserSession.getBody(response, Folder.class);
Assert.assertNotNull(folder.getId());
}
@Test
public void testCreateSubFolderUsesHttpCreatedOnPersist() throws Exception {
Folder folder = new Folder("Test");
HttpResponse response = UserSession.user().post(RESOURCE_FOLDER, folder);
Assert.assertEquals(HttpStatus.CREATED, UserSession.getStatusCode(response));
folder = UserSession.getBody(response, Folder.class);
Long folderId = folder.getId();
Assert.assertNotNull(folderId);
Folder subFolder = new Folder("Sub Test");
HttpResponse response2 = UserSession.user().post(RESOURCE_FOLDER + "/" + folderId + "/folders", subFolder);
Assert.assertEquals(HttpStatus.CREATED, UserSession.getStatusCode(response2));
Assert.assertEquals(UserSession.getBody(response2, FolderDto.class).getJsonParentId(), folderId);
}
// TODO johannes
@Test
public void testAddDocumentToFolderUsesHttpOkOnPersist() {
Folder folder = new Folder("Test");
ResponseEntity<Folder> response = post().resource(RESOURCE_FOLDER).asUser().body(folder).exec(Folder.class);
Assert.assertEquals(HttpStatus.CREATED, response.getStatusCode());
Long folderId = response.getBody().getId();
Assert.assertNotNull(folderId);
ResponseEntity<Document> responseDocument = post().resource(RESOURCE_DOCUMENT).asUser().body(document).exec(Document.class);
Assert.assertEquals(HttpStatus.CREATED, responseDocument.getStatusCode());
Long documentId = responseDocument.getBody().getId();
Assert.assertNotNull(documentId);
ResponseEntity<FolderDto> responseAddDocument = post().resource(RESOURCE_FOLDER + "/" + folderId + "/documents/" + documentId + "?old-parent=-1").asUser().exec(FolderDto.class);
Assert.assertEquals(HttpStatus.OK, responseAddDocument.getStatusCode());
// TODO add check if the document is in the parent folder
}
@Test
public void testShareFolderWithOtherUsersUsesHttpOkOnPersist() {
Folder folder = new Folder("Test");
ResponseEntity<Folder> response = post().resource(RESOURCE_FOLDER).asUser().body(folder).exec(Folder.class);
Assert.assertEquals(HttpStatus.CREATED, response.getStatusCode());
Long folderId = response.getBody().getId();
Assert.assertNotNull(folderId);
User adminUser = userService.findByUsername("admin");
ResponseEntity<FolderDto> responseShareFolder = post()
.resource(RESOURCE_FOLDER + "/" + folderId + "/share" + "?users=" + adminUser.getId() + "&permissions=" + "WRITE;READ")
.asUser().exec(FolderDto.class);
Assert.assertEquals(HttpStatus.OK, responseShareFolder.getStatusCode());
}
@Test
public void testRevokeShareFolderHttpOKOnPersist() {
Folder folder = new Folder("Test");
ResponseEntity<Folder> response = post().resource(RESOURCE_FOLDER).asUser().body(folder).exec(Folder.class);
Assert.assertEquals(HttpStatus.CREATED, response.getStatusCode());
Long folderId = response.getBody().getId();
Assert.assertNotNull(folderId);
User adminUser = userService.findByUsername("admin");
ResponseEntity<FolderDto> responseShareFolder = post()
.resource(RESOURCE_FOLDER + "/" + folderId + "/share" + "?users=" + adminUser.getId() + "&permissions=" + "WRITE;READ")
.asUser().exec(FolderDto.class);
Assert.assertEquals(HttpStatus.OK, responseShareFolder.getStatusCode());
ResponseEntity<FolderDto> responseRevokeShareFolder = post()
.resource(RESOURCE_FOLDER + "/" + folderId + "/share/revoke" + "?users=" + adminUser.getId() + "&permissions=" + "WRITE;READ")
.asUser().exec(FolderDto.class);
Assert.assertEquals(HttpStatus.OK, responseRevokeShareFolder.getStatusCode());
}
}
| ld-content/src/test/java/de/hska/ld/content/controller/FolderControllerIntegrationTest.java | /**
* Code contributed to the Learning Layers project
* http://www.learning-layers.eu
* Development is partly funded by the FP7 Programme of the European
* Commission under Grant Agreement FP7-ICT-318209.
* Copyright (c) 2014, Karlsruhe University of Applied Sciences.
* For a list of contributors see the AUTHORS file at the top-level directory
* of this distribution.
*
* 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 de.hska.ld.content.controller;
import de.hska.ld.content.dto.FolderDto;
import de.hska.ld.content.persistence.domain.Document;
import de.hska.ld.content.persistence.domain.Folder;
import de.hska.ld.content.persistence.domain.Tag;
import de.hska.ld.content.util.Content;
import de.hska.ld.core.AbstractIntegrationTest;
import de.hska.ld.core.UserSession;
import de.hska.ld.core.persistence.domain.User;
import de.hska.ld.core.service.UserService;
import org.apache.http.HttpResponse;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.io.IOException;
public class FolderControllerIntegrationTest extends AbstractIntegrationTest {
private static final String RESOURCE_FOLDER = Content.RESOURCE_FOLDER;
private static final String RESOURCE_DOCUMENT = Content.RESOURCE_DOCUMENT;
private static final String TITLE = "Title";
private static final String DESCRIPTION = "Description";
Document document;
@Autowired
UserService userService;
@Before
public void setUp() throws Exception {
super.setUp();
setAuthentication(testUser);
document = new Document();
document.setTitle(TITLE);
document.setDescription(DESCRIPTION);
}
@Test
public void testCreateFolderUsesHttpCreatedOnPersist() throws Exception {
Folder folder = new Folder("Test");
HttpResponse response = UserSession.user().post(RESOURCE_FOLDER, folder);
Assert.assertEquals(HttpStatus.CREATED, UserSession.getStatusCode(response));
folder = UserSession.getBody(response, Folder.class);
Assert.assertNotNull(folder.getId());
}
@Test
public void testCreateSubFolderUsesHttpCreatedOnPersist() throws Exception {
Folder folder = new Folder("Test");
HttpResponse response = UserSession.user().post(RESOURCE_FOLDER, folder);
Assert.assertEquals(HttpStatus.CREATED, UserSession.getStatusCode(response));
folder = UserSession.getBody(response, Folder.class);
Long folderId = folder.getId();
Assert.assertNotNull(folderId);
Folder subFolder = new Folder("Sub Test");
HttpResponse response2 = UserSession.user().post(RESOURCE_FOLDER + "/" + folderId + "/folders", subFolder);
Assert.assertEquals(HttpStatus.CREATED, UserSession.getStatusCode(response2));
Assert.assertEquals(UserSession.getBody(response2, FolderDto.class).getJsonParentId(), folderId);
}
@Test
public void testAddDocumentToFolderUsesHttpOkOnPersist() {
Folder folder = new Folder("Test");
ResponseEntity<Folder> response = post().resource(RESOURCE_FOLDER).asUser().body(folder).exec(Folder.class);
Assert.assertEquals(HttpStatus.CREATED, response.getStatusCode());
Long folderId = response.getBody().getId();
Assert.assertNotNull(folderId);
ResponseEntity<Document> responseDocument = post().resource(RESOURCE_DOCUMENT).asUser().body(document).exec(Document.class);
Assert.assertEquals(HttpStatus.CREATED, responseDocument.getStatusCode());
Long documentId = responseDocument.getBody().getId();
Assert.assertNotNull(documentId);
ResponseEntity<FolderDto> responseAddDocument = post().resource(RESOURCE_FOLDER + "/" + folderId + "/documents/" + documentId + "?old-parent=-1").asUser().exec(FolderDto.class);
Assert.assertEquals(HttpStatus.OK, responseAddDocument.getStatusCode());
// TODO add check if the document is in the parent folder
}
@Test
public void testShareFolderWithOtherUsersUsesHttpOkOnPersist() {
Folder folder = new Folder("Test");
ResponseEntity<Folder> response = post().resource(RESOURCE_FOLDER).asUser().body(folder).exec(Folder.class);
Assert.assertEquals(HttpStatus.CREATED, response.getStatusCode());
Long folderId = response.getBody().getId();
Assert.assertNotNull(folderId);
User adminUser = userService.findByUsername("admin");
ResponseEntity<FolderDto> responseShareFolder = post()
.resource(RESOURCE_FOLDER + "/" + folderId + "/share" + "?users=" + adminUser.getId() + "&permissions=" + "WRITE;READ")
.asUser().exec(FolderDto.class);
Assert.assertEquals(HttpStatus.OK, responseShareFolder.getStatusCode());
}
@Test
public void testRevokeShareFolderHttpOKOnPersist() {
Folder folder = new Folder("Test");
ResponseEntity<Folder> response = post().resource(RESOURCE_FOLDER).asUser().body(folder).exec(Folder.class);
Assert.assertEquals(HttpStatus.CREATED, response.getStatusCode());
Long folderId = response.getBody().getId();
Assert.assertNotNull(folderId);
User adminUser = userService.findByUsername("admin");
ResponseEntity<FolderDto> responseShareFolder = post()
.resource(RESOURCE_FOLDER + "/" + folderId + "/share" + "?users=" + adminUser.getId() + "&permissions=" + "WRITE;READ")
.asUser().exec(FolderDto.class);
Assert.assertEquals(HttpStatus.OK, responseShareFolder.getStatusCode());
ResponseEntity<FolderDto> responseRevokeShareFolder = post()
.resource(RESOURCE_FOLDER + "/" + folderId + "/share/revoke" + "?users=" + adminUser.getId() + "&permissions=" + "WRITE;READ")
.asUser().exec(FolderDto.class);
Assert.assertEquals(HttpStatus.OK, responseRevokeShareFolder.getStatusCode());
}
}
| - added toDo comment for johannes
| ld-content/src/test/java/de/hska/ld/content/controller/FolderControllerIntegrationTest.java | - added toDo comment for johannes | <ide><path>d-content/src/test/java/de/hska/ld/content/controller/FolderControllerIntegrationTest.java
<ide> import de.hska.ld.content.dto.FolderDto;
<ide> import de.hska.ld.content.persistence.domain.Document;
<ide> import de.hska.ld.content.persistence.domain.Folder;
<del>import de.hska.ld.content.persistence.domain.Tag;
<ide> import de.hska.ld.content.util.Content;
<ide> import de.hska.ld.core.AbstractIntegrationTest;
<ide> import de.hska.ld.core.UserSession;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.ResponseEntity;
<del>
<del>import java.io.IOException;
<ide>
<ide> public class FolderControllerIntegrationTest extends AbstractIntegrationTest {
<ide>
<ide> Assert.assertEquals(UserSession.getBody(response2, FolderDto.class).getJsonParentId(), folderId);
<ide> }
<ide>
<add> // TODO johannes
<ide> @Test
<ide> public void testAddDocumentToFolderUsesHttpOkOnPersist() {
<ide> Folder folder = new Folder("Test"); |
|
Java | apache-2.0 | 3f2a9e515e415636ba2b41eae66b95b5a2a60e4b | 0 | coxjc/penn-pong,coxjc/penn-pong | /**
* CIS 120 Game HW
* (c) University of Pennsylvania
* @version 2.0, Mar 2013
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
* GameCourt
*
* This class holds the primary game logic for how different objects interact
* with one another. Take time to understand how the timer interacts with the
* different methods and how it repaints the GUI on every tick().
*
*/
@SuppressWarnings("serial")
public class GameCourt extends JPanel implements MouseMotionListener {
// Game constants
public static final int COURT_WIDTH = 600;
public static final int COURT_HEIGHT = 300;
public static final int SQUARE_VELOCITY = 4;
// Update interval for timer, in milliseconds
public static final int INTERVAL = 35;
public boolean playing = false; // whether the game is running
// the state of the game logic
private Rectangle paddle_left;
private Rectangle paddle_right;
private Circle snitch; // the Golden Snitch, bounces
private JLabel status; // Current status text (i.e. Running...)
public GameCourt(JLabel status) {
// creates border around the court area, JComponent method
setBorder(BorderFactory.createLineBorder(Color.BLACK));
// The timer is an object which triggers an action periodically
// with the given INTERVAL. One registers an ActionListener with
// this timer, whose actionPerformed() method will be called
// each time the timer triggers. We define a helper method
// called tick() that actually does everything that should
// be done in a single timestep.
Timer timer = new Timer(INTERVAL, new ActionListener() {
public void actionPerformed(ActionEvent e) {
tick();
}
});
timer.start(); // MAKE SURE TO START THE TIMER!
// Enable keyboard focus on the court area.
// When this component has the keyboard focus, key
// events will be handled by its key listener.
setFocusable(true);
this.status = status;
this.addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e) {
this.paddle_left.setPos_y(e.getY());
}
public void mouseDragged(MouseEvent e) {
}
/**
* (Re-)set the game to its initial state.
*/
public void reset() {
paddle_left = new Rectangle(0, 0, COURT_WIDTH, COURT_HEIGHT);
paddle_right = new Rectangle(this.getWidth() - Rectangle.SIZE_X
, 0, COURT_WIDTH, COURT_HEIGHT); //Have to remove the width
// of the Rectangle in order to keep it on the board.
snitch = new Circle(COURT_WIDTH, COURT_HEIGHT);
playing = true;
status.setText("Running...");
// Make sure that this component has the keyboard focus
requestFocusInWindow();
}
/**
* This method is called every time the timer defined in the constructor
* triggers.
*/
void tick() {
if (playing) {
// advance the paddle_left and snitch in their
// current direction.
paddle_left.move();
snitch.move();
// make the snitch bounce off walls...
snitch.bounce(snitch.hitWall());
// ...and the mushroom
// check for the game end conditions
// update the display
repaint();
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
paddle_left.draw(g);
paddle_right.draw(g);
snitch.draw(g);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(COURT_WIDTH, COURT_HEIGHT);
}
}
| GameCourt.java | /**
* CIS 120 Game HW
* (c) University of Pennsylvania
* @version 2.0, Mar 2013
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
* GameCourt
*
* This class holds the primary game logic for how different objects interact
* with one another. Take time to understand how the timer interacts with the
* different methods and how it repaints the GUI on every tick().
*
*/
@SuppressWarnings("serial")
public class GameCourt extends JPanel implements MouseMotionListener {
// Game constants
public static final int COURT_WIDTH = 600;
public static final int COURT_HEIGHT = 300;
public static final int SQUARE_VELOCITY = 4;
// Update interval for timer, in milliseconds
public static final int INTERVAL = 35;
public boolean playing = false; // whether the game is running
// the state of the game logic
private Rectangle paddle_left;
private Rectangle paddle_right;
private Circle snitch; // the Golden Snitch, bounces
private Poison poison; // the Poison Mushroom, doesn't move
private JLabel status; // Current status text (i.e. Running...)
public GameCourt(JLabel status) {
// creates border around the court area, JComponent method
setBorder(BorderFactory.createLineBorder(Color.BLACK));
// The timer is an object which triggers an action periodically
// with the given INTERVAL. One registers an ActionListener with
// this timer, whose actionPerformed() method will be called
// each time the timer triggers. We define a helper method
// called tick() that actually does everything that should
// be done in a single timestep.
Timer timer = new Timer(INTERVAL, new ActionListener() {
public void actionPerformed(ActionEvent e) {
tick();
}
});
timer.start(); // MAKE SURE TO START THE TIMER!
// Enable keyboard focus on the court area.
// When this component has the keyboard focus, key
// events will be handled by its key listener.
setFocusable(true);
this.status = status;
this.addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e) {
this.paddle_left.setPos_y(e.getY());
}
public void mouseDragged(MouseEvent e) {
}
/**
* (Re-)set the game to its initial state.
*/
public void reset() {
paddle_left = new Rectangle(0, 0, COURT_WIDTH, COURT_HEIGHT);
paddle_right = new Rectangle(this.getWidth() - Rectangle.SIZE_X
, 0, COURT_WIDTH, COURT_HEIGHT); //Have to remove the width
// of the Rectangle in order to keep it on the board.
poison = new Poison(COURT_WIDTH, COURT_HEIGHT);
snitch = new Circle(COURT_WIDTH, COURT_HEIGHT);
playing = true;
status.setText("Running...");
// Make sure that this component has the keyboard focus
requestFocusInWindow();
}
/**
* This method is called every time the timer defined in the constructor
* triggers.
*/
void tick() {
if (playing) {
// advance the paddle_left and snitch in their
// current direction.
paddle_left.move();
snitch.move();
// make the snitch bounce off walls...
snitch.bounce(snitch.hitWall());
// ...and the mushroom
snitch.bounce(snitch.hitObj(poison));
// check for the game end conditions
if (paddle_left.intersects(poison)) {
playing = false;
status.setText("You lose!");
} else if (paddle_left.intersects(snitch)) {
playing = false;
status.setText("You win!");
}
// update the display
repaint();
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
paddle_left.draw(g);
paddle_right.draw(g);
poison.draw(g);
snitch.draw(g);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(COURT_WIDTH, COURT_HEIGHT);
}
}
| SUBJ: Remove Mushroom
MSG:
1) Remove stupid mushroom from the GameBoard
| GameCourt.java | SUBJ: Remove Mushroom MSG: 1) Remove stupid mushroom from the GameBoard | <ide><path>ameCourt.java
<ide> private Rectangle paddle_left;
<ide> private Rectangle paddle_right;
<ide> private Circle snitch; // the Golden Snitch, bounces
<del> private Poison poison; // the Poison Mushroom, doesn't move
<ide> private JLabel status; // Current status text (i.e. Running...)
<ide>
<ide> public GameCourt(JLabel status) {
<ide> public void reset() {
<ide>
<ide> paddle_left = new Rectangle(0, 0, COURT_WIDTH, COURT_HEIGHT);
<add>
<add>
<ide> paddle_right = new Rectangle(this.getWidth() - Rectangle.SIZE_X
<ide> , 0, COURT_WIDTH, COURT_HEIGHT); //Have to remove the width
<ide> // of the Rectangle in order to keep it on the board.
<del> poison = new Poison(COURT_WIDTH, COURT_HEIGHT);
<ide> snitch = new Circle(COURT_WIDTH, COURT_HEIGHT);
<ide>
<ide> playing = true;
<ide> // make the snitch bounce off walls...
<ide> snitch.bounce(snitch.hitWall());
<ide> // ...and the mushroom
<del> snitch.bounce(snitch.hitObj(poison));
<ide>
<ide> // check for the game end conditions
<del> if (paddle_left.intersects(poison)) {
<del> playing = false;
<del> status.setText("You lose!");
<del>
<del> } else if (paddle_left.intersects(snitch)) {
<del> playing = false;
<del> status.setText("You win!");
<del> }
<ide>
<ide> // update the display
<ide> repaint();
<ide> super.paintComponent(g);
<ide> paddle_left.draw(g);
<ide> paddle_right.draw(g);
<del> poison.draw(g);
<ide> snitch.draw(g);
<ide> }
<ide> |
|
Java | apache-2.0 | b87d3b4891fe098d9a6ed48a2ecbd0f37b6f78c5 | 0 | serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2016-2016 Karl Griesser ([email protected])
* Copyright (C) 2010-2016 Serge Rieder ([email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2)
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jkiss.dbeaver.ext.exasol.model;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.exasol.ExasolConstants;
import org.jkiss.dbeaver.ext.exasol.editors.ExasolSourceObject;
import org.jkiss.dbeaver.ext.exasol.model.dict.ExasolScriptLanguage;
import org.jkiss.dbeaver.ext.exasol.model.dict.ExasolScriptResultType;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.DBPRefreshableObject;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectState;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedure;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureParameter;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureType;
import org.jkiss.utils.CommonUtils;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Collection;
/**
* Exasol Scripts
*
* @author Karl Griesser
*/
public class ExasolScript extends ExasolObject<DBSObject> implements DBSProcedure, DBPRefreshableObject, ExasolSourceObject {
private String remarks;
private Timestamp createTime;
private String owner;
private ExasolScriptLanguage scriptLanguage;
private String scriptSQL;
private ExasolScriptResultType scriptReturnType;
private String script_type;
private ExasolSchema exasolSchema;
public ExasolScript(DBSObject owner, ResultSet dbResult) {
super(owner, JDBCUtils.safeGetString(dbResult, "SCRIPT_NAME"), true);
this.owner = JDBCUtils.safeGetString(dbResult, "SCRIPT_OWNER");
this.createTime = JDBCUtils.safeGetTimestamp(dbResult, "CREATED");
this.remarks = JDBCUtils.safeGetString(dbResult, "SCRIPT_COMMENT");
this.scriptLanguage = CommonUtils.valueOf(ExasolScriptLanguage.class, JDBCUtils.safeGetString(dbResult, "SCRIPT_LANGUAGE"));
this.scriptReturnType = CommonUtils.valueOf(ExasolScriptResultType.class, JDBCUtils.safeGetString(dbResult, "SCRIPT_RESULT_TYPE"));
this.scriptSQL = JDBCUtils.safeGetString(dbResult, "SCRIPT_TEXT");
this.name = JDBCUtils.safeGetString(dbResult, "SCRIPT_NAME");
this.script_type = JDBCUtils.safeGetString(dbResult, "SCRIPT_TYPE");
exasolSchema = (ExasolSchema) owner;
}
// -----------------
// Business Contract
// -----------------
@NotNull
@Override
public DBSObjectState getObjectState() {
return DBSObjectState.UNKNOWN;
}
@Override
public void refreshObjectState(@NotNull DBRProgressMonitor monitor) throws DBCException {
}
@Override
public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException {
return this;
}
// -----------------------
// Properties
// -----------------------
@NotNull
@Override
@Property(viewable = true, order = 1)
public String getName() {
return this.name;
}
@Property(viewable = true, order = 2)
public ExasolSchema getSchema() {
return exasolSchema;
}
@Property(viewable = true, order = 5)
public ExasolScriptLanguage getLanguage() {
return scriptLanguage;
}
@Property(viewable = false, order = 10)
public ExasolScriptResultType getResultType() {
return scriptReturnType;
}
@Nullable
@Override
@Property(viewable = false, order = 11)
public String getDescription() {
return this.remarks;
}
@Nullable
@Property(viewable = false, order = 12)
public String getType() {
return this.script_type;
}
@NotNull
@Property(hidden = true)
public String getSql() {
return this.scriptSQL;
}
@NotNull
@Property(viewable = true, order = 6)
public Timestamp getCreationTime() {
return this.createTime;
}
@Property(viewable = false, category = ExasolConstants.CAT_OWNER)
public String getOwner() {
return owner;
}
@Override
public DBSObject getContainer() {
return exasolSchema;
}
@Override
public DBSProcedureType getProcedureType() {
return null;
}
@Override
public Collection<? extends DBSProcedureParameter> getParameters(DBRProgressMonitor monitor) throws DBException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getFullyQualifiedName(DBPEvaluationContext context) {
return name;
}
@Override
public String getObjectDefinitionText(DBRProgressMonitor monitor) throws DBException {
return this.scriptSQL;
}
}
| plugins/org.jkiss.dbeaver.ext.exasol/src/org/jkiss/dbeaver/ext/exasol/model/ExasolScript.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2016-2016 Karl Griesser ([email protected])
* Copyright (C) 2010-2016 Serge Rieder ([email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2)
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.jkiss.dbeaver.ext.exasol.model;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.exasol.ExasolConstants;
import org.jkiss.dbeaver.ext.exasol.editors.ExasolSourceObject;
import org.jkiss.dbeaver.ext.exasol.model.dict.ExasolScriptLanguage;
import org.jkiss.dbeaver.ext.exasol.model.dict.ExasolScriptResultType;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.DBPRefreshableObject;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectState;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedure;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureParameter;
import org.jkiss.dbeaver.model.struct.rdb.DBSProcedureType;
import org.jkiss.utils.CommonUtils;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Collection;
/**
* Exasol Scripts
*
* @author Karl Griesser
*/
public class ExasolScript extends ExasolObject<DBSObject> implements DBSProcedure, DBPRefreshableObject, ExasolSourceObject {
private String remarks;
private Timestamp createTime;
private String owner;
private ExasolScriptLanguage scriptLanguage;
private String scriptSQL;
private ExasolScriptResultType scriptReturnType;
private String script_type;
private ExasolSchema exasolSchema;
public ExasolScript(DBSObject owner, ResultSet dbResult) {
super(owner, JDBCUtils.safeGetString(dbResult, "SCRIPT_NAME"), true);
this.owner = JDBCUtils.safeGetString(dbResult, "SCRIPT_OWNER");
this.createTime = JDBCUtils.safeGetTimestamp(dbResult, "CREATED");
this.remarks = JDBCUtils.safeGetString(dbResult, "SCRIPT_COMMENT");
this.scriptLanguage = CommonUtils.valueOf(ExasolScriptLanguage.class, JDBCUtils.safeGetString(dbResult, "SCRIPT_LANGUAGE"));
this.scriptReturnType = CommonUtils.valueOf(ExasolScriptResultType.class, JDBCUtils.safeGetString(dbResult, "SCRIPT_RESULT_TYPE"));
this.scriptSQL = JDBCUtils.safeGetString(dbResult, "SCRIPT_TEXT");
this.name = JDBCUtils.safeGetString(dbResult, "SCRIPT_NAME");
this.script_type = JDBCUtils.safeGetString(dbResult, "SCRIPT_TYPE");
exasolSchema = (ExasolSchema) owner;
}
// -----------------
// Business Contract
// -----------------
@NotNull
@Override
public DBSObjectState getObjectState() {
return DBSObjectState.UNKNOWN;
}
@Override
public void refreshObjectState(@NotNull DBRProgressMonitor monitor) throws DBCException {
}
@Override
public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException {
return this;
}
// -----------------------
// Properties
// -----------------------
@NotNull
@Override
@Property(viewable = true, order = 1)
public String getName() {
return this.name;
}
@Property(viewable = true, order = 2)
public ExasolSchema getSchema() {
return exasolSchema;
}
@Property(viewable = true, order = 5)
public ExasolScriptLanguage getLanguage() {
return scriptLanguage;
}
@Property(viewable = false, order = 10)
public ExasolScriptResultType getResultType() {
return scriptReturnType;
}
@Nullable
@Override
@Property(viewable = false, order = 11)
public String getDescription() {
return this.remarks;
}
@Nullable
@Property(viewable = false, order = 12)
public String getType() {
return this.script_type;
}
@NotNull
@Property(viewable = false, order = 15)
public String getSql() {
return this.scriptSQL;
}
@NotNull
@Property(viewable = true, order = 6)
public Timestamp getCreationTime() {
return this.createTime;
}
@Property(viewable = false, category = ExasolConstants.CAT_OWNER)
public String getOwner() {
return owner;
}
@Override
public DBSObject getContainer() {
return exasolSchema;
}
@Override
public DBSProcedureType getProcedureType() {
return null;
}
@Override
public Collection<? extends DBSProcedureParameter> getParameters(DBRProgressMonitor monitor) throws DBException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getFullyQualifiedName(DBPEvaluationContext context) {
return name;
}
@Override
public String getObjectDefinitionText(DBRProgressMonitor monitor) throws DBException {
return this.scriptSQL;
}
}
| Hide SQL Text Field -> is show in DDL
Former-commit-id: 0b8d9c3aad24d1c18b9492c3da3ff98a48849048 | plugins/org.jkiss.dbeaver.ext.exasol/src/org/jkiss/dbeaver/ext/exasol/model/ExasolScript.java | Hide SQL Text Field -> is show in DDL | <ide><path>lugins/org.jkiss.dbeaver.ext.exasol/src/org/jkiss/dbeaver/ext/exasol/model/ExasolScript.java
<ide> }
<ide>
<ide> @NotNull
<del> @Property(viewable = false, order = 15)
<add> @Property(hidden = true)
<ide> public String getSql() {
<ide> return this.scriptSQL;
<ide> } |
|
JavaScript | bsd-3-clause | 2e7d9cab9b876e87015503d8a168444ea437bbb2 | 0 | monarch-initiative/monarch-app,kshefchek/monarch-app,jmcmurry/monarch-app,jmcmurry/monarch-app,monarch-initiative/monarch-app,kshefchek/monarch-app,DoctorBud/monarch-app,kshefchek/monarch-app,jmcmurry/monarch-app,jmcmurry/monarch-app,monarch-initiative/monarch-app,monarch-initiative/monarch-app,DoctorBud/monarch-app,monarch-initiative/monarch-app,kshefchek/monarch-app,jmcmurry/monarch-app,DoctorBud/monarch-app,DoctorBud/monarch-app,kshefchek/monarch-app,DoctorBud/monarch-app | /*
* Package: datagraph.js
*
* Namespace: monarch.bbop.datagraph
*
*/
// Module and namespace checking.
if (typeof bbop == 'undefined') { var bbop = {};}
if (typeof bbop.monarch == 'undefined') { bbop.monarch = {};}
bbop.monarch.datagraph = function(config){
if (config == null || typeof config == 'undefined'){
this.config = this.getDefaultConfig();
} else {
this.config = config;
}
this.setPolygonCoordinates();
this.config.xFirstIndex = this.getXFirstIndex();
//Tooltip offsetting
this.config.arrowOffset = {height: 21, width: -90};
this.config.barOffset = {
grouped:{
height: 95,
width: 10
},
stacked:{
height: 80
}
};
if (this.config.isDynamicallyResized){
this.config.graphSizingRatios = this.setSizingRatios();
}
}
bbop.monarch.datagraph.prototype.run = function(html_div,DATA){
var dataGraph = this;
dataGraph.makeGraphDOM(html_div,DATA);
var d3Config = dataGraph.setD3Config(html_div,DATA);
dataGraph.drawGraph(DATA,d3Config,html_div);
}
bbop.monarch.datagraph.prototype.init = function(html_div,DATA){
var dataGraph = this;
var config = dataGraph.config;
if (config.isDynamicallyResized){
if ($(window).width() < (config.benchmarkWidth-100) || $(window).height() < (config.benchmarkHeight-100)){
dataGraph.setSizeConfiguration(config.graphSizingRatios);
dataGraph.run(html_div,DATA);
} else {
dataGraph.run(html_div,DATA);
}
window.addEventListener('resize', function(event){
if ($(window).width() < (config.benchmarkWidth-100) || $(window).height() < (config.benchmarkHeight-100)){
$(html_div).children().remove();
dataGraph.setSizeConfiguration(config.graphSizingRatios);
dataGraph.run(html_div,DATA);
}
});
} else {
dataGraph.run(html_div,DATA);
}
}
bbop.monarch.datagraph.prototype.setSizeConfiguration = function(graphRatio){
var dataGraph = this;
var w = $(window).width();
var h = $(window).height();
var total = w+h;
dataGraph.setWidth( ((w*graphRatio.width) / getBaseLog(12,w)) * 3);
dataGraph.setHeight( ((h*graphRatio.height) / getBaseLog(12,h)) *3.5);
dataGraph.setYFontSize( ((total*(graphRatio.yFontSize))/ getBaseLog(20,total)) * 3);
}
bbop.monarch.datagraph.prototype.setSizingRatios = function(){
var config = this.config;
var graphRatio = {};
if (!config.benchmarkHeight || !config.benchmarkWidth){
console.log("Dynamic sizing set without "+
"setting benchmarkHeight and/or benchmarkWidth");
}
graphRatio.width = config.width / config.benchmarkWidth;
graphRatio.height = config.height / config.benchmarkHeight;
graphRatio.yFontSize = (config.yFontSize / (config.benchmarkHeight+config.benchmarkWidth));
return graphRatio;
}
//Uses JQuery to create the DOM for the datagraph
bbop.monarch.datagraph.prototype.makeGraphDOM = function(html_div,data){
var config = this.config;
var dataGraph = this;
var groups = dataGraph.getGroups(data);
//Create html structure
//Add graph title
$(html_div).append( "<div class=title"+
" style=text-indent:" + config.title['text-indent'] +
";text-align:" + config.title['text-align'] +
";background-color:" + config.title['background-color'] +
";border-bottom-color:" + config.title['border-bottom-color'] +
";font-size:" + config.title['font-size'] +
";font-weight:" + config.title['font-weight'] +
"; >"+config.chartTitle+"</div>" );
$(html_div).append( "<div class=interaction></div>" );
$(html_div+" .interaction").append( "<li></li>" );
//Override breadcrumb config if subgraphs exist
config.useCrumb = dataGraph.checkForSubGraphs(data);
//remove breadcrumb div
if (config.useCrumb){
$(html_div+" .interaction li").append("<div class=breadcrumbs></div>");
}
//Add stacked/grouped form if more than one group
if (groups.length >1){
$(html_div+" .interaction li").append(" <form class=configure"+
" style=font-size:" + config.settingsFontSize + "; >" +
"<label><input id=\"group\" type=\"radio\" name=\"mode\"" +
" value=\"grouped\" checked> Grouped</label> " +
"<label><input id=\"stack\" type=\"radio\" name=\"mode\"" +
" value=\"stacked\"> Stacked</label>" +
"</form> ");
}
//Update tooltip positioning
if (!config.useCrumb && groups.length>1){
config.arrowOffset.height = 12;
config.barOffset.grouped.height = 102;
config.barOffset.stacked.height = 81;
} else if (!config.useCrumb){
config.arrowOffset.height = -10;
config.barOffset.grouped.height = 71;
config.barOffset.stacked.height = 50;
}
}
bbop.monarch.datagraph.prototype.setD3Config = function (html_div,DATA){
var d3Config = {};
var dataGraph = this;
var conf = dataGraph.config;
//Define scales
d3Config.y0 = d3.scale.ordinal()
.rangeRoundBands([0,conf.height], .1);
d3Config.y1 = d3.scale.ordinal();
d3Config.x = d3.scale.linear()
.range([0, conf.width]);
//Bar colors
d3Config.color = d3.scale.ordinal()
.range([conf.color.first,conf.color.second,conf.color.third,
conf.color.fourth,conf.color.fifth,conf.color.sixth]);
d3Config.xAxis = d3.svg.axis()
.scale(d3Config.x)
.orient("top")
.tickFormat(d3.format(".2s"));
d3Config.yAxis = d3.svg.axis()
.scale(d3Config.y0)
.orient("left");
d3Config.svg = d3.select(html_div).append("svg")
.attr("width", conf.width + conf.margin.left + conf.margin.right)
.attr("height", conf.height + conf.margin.top + conf.margin.bottom)
.append("g")
.attr("transform", "translate(" + conf.margin.left + "," + conf.margin.top + ")");
d3Config.crumbSVG = d3.select(html_div).select(".breadcrumbs")
.append("svg")
.attr("height",(conf.bread.height+2))
.attr("width",conf.bcWidth);
d3Config.tooltip = d3.select(html_div)
.append("div")
.attr("class", "tip");
d3Config.groups = dataGraph.getGroups(DATA);
//Variables to keep track of graph transitions
d3Config.level = 0;
d3Config.parents = [];
d3Config.html_div = html_div;
return d3Config;
}
bbop.monarch.datagraph.prototype.makeLegend = function (graphConfig){
var config = this.config;
var svg = graphConfig.svg;
var groups = graphConfig.groups;
var color = graphConfig.color;
//Set legend
var legend = svg.selectAll(".legend")
.data(groups.slice())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * (config.legend.height+7) + ")"; });
legend.append("rect")
.attr("x", config.width+config.legend.width+37)//HARDCODE
.attr("y", 4)
.attr("width", config.legend.width)
.attr("height", config.legend.height)
.style("fill", color);
legend.append("text")
.attr("x", config.width+config.legend.width+32)
.attr("y", 12)
.attr("dy", config.legendText.height)
.attr("font-size",config.legendFontSize)
.style("text-anchor", "end")
.text(function(d) { return d; });
}
bbop.monarch.datagraph.prototype.makeNavArrow = function(data,navigate,triangleDim,barGroup,rect,graphConfig){
var dataGraph = this;
var config = dataGraph.config;
//boolean variable to check for subclasses that is returned
var isSubClass;
var tooltip = graphConfig.tooltip;
var svg = graphConfig.svg;
var html_div = graphConfig.html_div;
var arrow = navigate.selectAll(".tick.major")
.data(data)
.append("svg:polygon")
.attr("points",triangleDim)
.attr("fill", config.color.arrow.fill)
.attr("display", function(d){
if (d.subGraph && d.subGraph[0]){
isSubClass=1; return "initial";
} else {
return "none";
}
})
.on("mouseover", function(d){
if (d.subGraph && d.subGraph[0]){
dataGraph.displaySubClassTip(tooltip,this)
}
})
.on("mouseout", function(){
d3.select(this)
.style("fill",config.color.arrow.fill);
tooltip.style("display", "none");
})
.on("click", function(d){
if (d.subGraph && d.subGraph[0]){
dataGraph.transitionToNewGraph(tooltip,graphConfig,d,
data,barGroup,rect);
}
});
return isSubClass;
}
bbop.monarch.datagraph.prototype.transitionToNewGraph = function(tooltip,graphConfig,d,data,barGroup,rect){
dataGraph = this;
config = dataGraph.config;
tooltip.style("display", "none");
graphConfig.svg.selectAll(".tick.major").remove();
graphConfig.level++;
dataGraph.transitionSubGraph(graphConfig,d.subGraph,data);
//remove old bars
barGroup.transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
rect.transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
if (config.useCrumb){
dataGraph.makeBreadcrumb(graphConfig,d.label,graphConfig.groups,
rect,barGroup,d.fullLabel);
}
}
bbop.monarch.datagraph.prototype.displaySubClassTip = function(tooltip,d3Selection){
var dataGraph = this;
var config = dataGraph.config;
d3.select(d3Selection)
.style("fill", config.color.arrow.hover);
var coords = d3.transform(d3.select(d3Selection.parentNode)
.attr("transform")).translate;
var h = coords[1];
var w = coords[0];
tooltip.style("display", "block")
.html("Click to see subclasses")
.style("top",h+config.margin.top+config.bread.height+
config.arrowOffset.height+"px")
.style("left",w+config.margin.left+config.arrowOffset.width+"px");
}
bbop.monarch.datagraph.prototype.getCountMessage = function(value,name){
return "Counts: "+"<span style='font-weight:bold'>"+value+"</span>"+"<br/>"
+"Organism: "+ "<span style='font-weight:bold'>"+name;
}
bbop.monarch.datagraph.prototype.displayCountTip = function(tooltip,value,name,d3Selection,barLayout){
var dataGraph = this;
var config = dataGraph.config;
var coords = d3.transform(d3.select(d3Selection.parentNode)
.attr("transform")).translate;
var w = coords[0];
var h = coords[1];
var heightOffset = d3Selection.getBBox().y;
var widthOffset = d3Selection.getBBox().width;
tooltip.style("display", "block")
.html(dataGraph.getCountMessage(value,name));
if (barLayout == 'grouped'){
tooltip.style("top",h+heightOffset+config.barOffset.grouped.height+"px")
.style("left",w+config.barOffset.grouped.width+widthOffset+
config.margin.left+"px");
} else if (barLayout == 'stacked'){
tooltip.style("top",h+heightOffset+config.barOffset.stacked.height+"px")
.style("left",w+config.barOffset.grouped.width+widthOffset+
config.margin.left+"px");
}
}
bbop.monarch.datagraph.prototype.setGroupPositioning = function (graphConfig,graphData) {
var groupPos = graphConfig.svg.selectAll(".barGroup")
.data(graphData)
.enter().append("svg:g")
.attr("class", ("bar"+graphConfig.level))
.attr("transform", function(d) { return "translate(0," + graphConfig.y0(d.label) + ")"; });
return groupPos;
}
bbop.monarch.datagraph.prototype.setXYDomains = function (graphConfig,graphData,groups,barLayout) {
var dataGraph = this;
//Set y0 domain
graphConfig.y0.domain(graphData.map(function(d) { return d.label; }));
if (barLayout == 'grouped'){
var xGroupMax = dataGraph.getGroupMax(graphData);
graphConfig.x.domain([0, xGroupMax]);
graphConfig.y1.domain(groups)
.rangeRoundBands([0, graphConfig.y0.rangeBand()]);
} else if (barLayout == 'stacked'){
var xStackMax = dataGraph.getStackMax(graphData);
graphConfig.x.domain([0, xStackMax]);
graphConfig.y1.domain(groups).rangeRoundBands([0,0]);
} else {
graphConfig.y1.domain(groups)
.rangeRoundBands([0, graphConfig.y0.rangeBand()]);
}
}
bbop.monarch.datagraph.prototype.makeBar = function (barGroup,graphConfig,barLayout) {
var rect;
var dataGraph = this;
var config = dataGraph.config;
//Create bars
if (barLayout == 'grouped'){
rect = barGroup.selectAll("g")
.data(function(d) { return d.counts; })
.enter().append("rect")
.attr("class",("rect"+graphConfig.level))
.attr("height", graphConfig.y1.rangeBand())
.attr("y", function(d) { return graphConfig.y1(d.name); })
.attr("x", function(){return config.xFirstIndex;})
.attr("width", function(d) { return graphConfig.x(d.value); })
.on("mouseover", function(d){
d3.select(this)
.style("fill", config.color.bar.fill);
dataGraph.displayCountTip(graphConfig.tooltip,d.value,d.name,this,'grouped');
})
.on("mouseout", function(){
d3.select(this)
.style("fill", function(d) { return graphConfig.color(d.name); });
graphConfig.tooltip.style("display", "none");
})
.style("fill", function(d) { return graphConfig.color(d.name); });
} else if (barLayout == 'stacked') {
rect = barGroup.selectAll("g")
.data(function(d) { return d.counts; })
.enter().append("rect")
.attr("class",("rect"+graphConfig.level))
.attr("x", function(d){
if (d.x0 == 0){
return config.xFirstIndex;
} else {
return graphConfig.x(d.x0);
}
})
.attr("width", function(d) {
return graphConfig.x(d.x1) - graphConfig.x(d.x0);
})
.attr("height", graphConfig.y0.rangeBand())
.attr("y", function(d) { return graphConfig.y1(d.name); })
.on("mouseover", function(d){
d3.select(this)
.style("fill", config.color.bar.fill);
dataGraph.displayCountTip(graphConfig.tooltip,d.value,d.name,this,'stacked');
})
.on("mouseout", function(){
d3.select(this)
.style("fill", function(d) { return graphConfig.color(d.name); });
graphConfig.tooltip.style("display", "none");
})
.style("fill", function(d) { return graphConfig.color(d.name); });
}
return rect;
}
bbop.monarch.datagraph.prototype.transitionGrouped = function (graphConfig,data,groups,rect) {
var dataGraph = this;
var config = dataGraph.config;
dataGraph.setXYDomains(graphConfig,data,groups,'grouped');
var xTransition = graphConfig.svg.transition().duration(750);
xTransition.select(".x.axis").call(graphConfig.xAxis);
rect.transition()
.duration(500)
.delay(function(d, i) { return i * 10; })
.attr("height", graphConfig.y1.rangeBand())
.attr("y", function(d) { return graphConfig.y1(d.name); })
.transition()
.attr("x", function(){return config.xFirstIndex;})
.attr("width", function(d) { return graphConfig.x(d.value); })
rect.on("mouseover", function(d){
d3.select(this)
.style("fill", config.color.bar.fill);
dataGraph.displayCountTip(graphConfig.tooltip,d.value,d.name,this,'grouped');
})
.on("mouseout", function(){
graphConfig.tooltip.style("display", "none")
d3.select(this)
.style("fill", function(d) { return graphConfig.color(d.name); });
})
}
bbop.monarch.datagraph.prototype.transitionStacked = function (graphConfig,data,groups,rect) {
var dataGraph = this;
var config = dataGraph.config;
dataGraph.setXYDomains(graphConfig,data,groups,'stacked');
var t = graphConfig.svg.transition().duration(750);
t.select(".x.axis").call(graphConfig.xAxis);
rect.transition()
.duration(500)
.delay(function(d, i) { return i * 10; })
.attr("x", function(d){
if (d.x0 == 0){
return config.xFirstIndex;
} else {
return graphConfig.x(d.x0);
}
})
.attr("width", function(d) { return graphConfig.x(d.x1) - graphConfig.x(d.x0); })
.transition()
.attr("height", graphConfig.y0.rangeBand())
.attr("y", function(d) { return graphConfig.y1(d.name); })
rect.on("mouseover", function(d){
d3.select(this)
.style("fill", config.color.bar.fill);
dataGraph.displayCountTip(graphConfig.tooltip,d.value,d.name,this,'stacked');
})
.on("mouseout", function(){
graphConfig.tooltip.style("display", "none");
d3.select(this)
.style("fill", function(d) { return graphConfig.color(d.name); });
})
}
bbop.monarch.datagraph.prototype.drawGraph = function (data,graphConfig) {
var dataGraph = this;
var config = this.config;
var html_div = graphConfig.html_div;
var y0 = graphConfig.y0;
var y1 = graphConfig.y1;
var x = graphConfig.x;
var color = graphConfig.color;
var xAxis = graphConfig.xAxis;
var yAxis = graphConfig.yAxis;
var svg = graphConfig.svg;
var tooltip = graphConfig.tooltip;
var groups = graphConfig.groups;
data = dataGraph.getStackedStats(data,groups);
data = dataGraph.addEllipsisToLabel(data,config.maxLabelSize);
dataGraph.setXYDomains(graphConfig,data,groups,'grouped');
if (groups.length == 1){
config.barOffset.grouped.height = config.barOffset.grouped.height+8;
config.barOffset.stacked.height = config.barOffset.stacked.height+8;
}
//Dynamically decrease font size for large labels
var yFont = dataGraph.adjustYAxisElements(data.length);
//Set x axis ticks
var xTicks = svg.append("g")
.attr("class", "x axis")
.call(xAxis)
.style("font-size",config.xFontSize)
.append("text")
.attr("transform", "rotate(0)")
.attr("y", config.xAxisPos.y)
.attr("dx", config.xAxisPos.dx)
.attr("dy", "0em")
.style("text-anchor", "end")
.style("font-size",config.xLabelFontSize)
.text(config.xAxisLabel);
//Set Y axis ticks and labels
var yTicks = svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.selectAll("text")
.filter(function(d){ return typeof(d) == "string"; })
.attr("font-size", yFont)
.on("mouseover", function(d){
if (config.isYLabelURL){
d3.select(this).style("cursor", "pointer");
d3.select(this).style("fill", config.color.yLabel.hover);
d3.select(this).style("text-decoration", "underline");
}
if (/\.\.\./.test(d)){
var fullLabel = dataGraph.getFullLabel(d,data);
d3.select(this).append("svg:title")
.text(fullLabel);
//Hardcode alert
} else if (yFont < 12) {
d3.select(this).append("svg:title")
.text(d);
}
})
.on("mouseout", function(){
d3.select(this).style("fill", config.color.yLabel.fill );
d3.select(this).style("text-decoration", "none");
})
.on("click", function(d){
if (config.isYLabelURL){
d3.select(this).style("cursor", "pointer");
var monarchID = dataGraph.getGroupID(d,data);
document.location.href = config.yLabelBaseURL + monarchID;
}
})
.style("text-anchor", "end")
.attr("dx", config.yOffset);
//Create SVG:G element that holds groups
var barGroup = dataGraph.setGroupPositioning(graphConfig,data);
//Create bars
var rect = dataGraph.makeBar(barGroup,graphConfig,'grouped');
//Create navigation arrow
var navigate = svg.selectAll(".y.axis");
dataGraph.makeNavArrow(data,navigate,config.arrowDim,
barGroup,rect,graphConfig);
//Create legend
if (config.useLegend){
dataGraph.makeLegend(graphConfig);
}
//Make first breadcrumb
if (config.useCrumb){
dataGraph.makeBreadcrumb(graphConfig,config.firstCrumb,
groups,rect,barGroup);
}
d3.select(html_div).selectAll("input").on("change", change);
function change() {
if (this.value === "grouped"){
dataGraph.transitionGrouped(graphConfig,data,groups,rect);
} else {
dataGraph.transitionStacked(graphConfig,data,groups,rect);
}
}
}
//Resize height of chart after transition
bbop.monarch.datagraph.prototype.resizeChart = function(subGraph){
var config = this.config;
var height = config.height;
if (subGraph.length < 25){
height = subGraph.length*26;
if (height > config.height){
height = config.height;
}
}
return height;
}
bbop.monarch.datagraph.prototype.pickUpBreadcrumb = function(graphConfig,index,groups,rect,barGroup) {
var dataGraph = this;
var config = dataGraph.config;
var lastIndex = graphConfig.level;
var superclass = graphConfig.parents[index];
var isFromCrumb = true;
var parent;
//set global level
graphConfig.level = index;
graphConfig.svg.selectAll(".tick.major").remove();
dataGraph.transitionSubGraph(graphConfig,superclass,graphConfig.parents,isFromCrumb);
for (var i=(index+1); i <= graphConfig.parents.length; i++){
d3.select(graphConfig.html_div).select(".bread"+i).remove();
}
graphConfig.svg.selectAll((".rect"+lastIndex)).transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
graphConfig.svg.selectAll((".bar"+lastIndex)).transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
graphConfig.parents.splice(index,(graphConfig.parents.length));
//Deactivate top level crumb
if (config.useCrumbShape){
d3.select(graphConfig.html_div).select(".poly"+index)
.attr("fill", config.color.crumb.top)
.on("mouseover", function(){})
.on("mouseout", function(){
d3.select(this)
.attr("fill", config.color.crumb.top);
})
.on("click", function(){});
d3.select(graphConfig.html_div).select(".text"+index)
.on("mouseover", function(){})
.on("mouseout", function(){
d3.select(this.parentNode)
.select("polygon")
.attr("fill", config.color.crumb.top);
})
.on("click", function(){});
} else {
d3.select(graphConfig.html_div).select(".text"+index)
.style("fill",config.color.crumbText)
.on("mouseover", function(){})
.on("mouseout", function(){})
.on("click", function(){});
}
}
bbop.monarch.datagraph.prototype.makeBreadcrumb = function(graphConfig,label,groups,rect,phenoDiv,fullLabel) {
var dataGraph = this;
var config = dataGraph.config;
var html_div = graphConfig.html_div;
var index = graphConfig.level;
if (!label){
label = config.firstCrumb;
}
var lastIndex = (index-1);
var phenLen = label.length;
var fontSize = config.crumbFontSize;
//Change color of previous crumb
if (lastIndex > -1){
if (config.useCrumbShape){
d3.select(html_div).select(".poly"+lastIndex)
.attr("fill", config.color.crumb.bottom)
.on("mouseover", function(){
d3.select(this)
.attr("fill", config.color.crumb.hover);
})
.on("mouseout", function(){
d3.select(this)
.attr("fill", config.color.crumb.bottom);
})
.on("click", function(){
dataGraph.pickUpBreadcrumb(graphConfig,lastIndex,groups,rect,phenoDiv);
});
}
d3.select(html_div).select(".text"+lastIndex)
.on("mouseover", function(){
d3.select(this.parentNode)
.select("polygon")
.attr("fill", config.color.crumb.hover);
if (!config.useCrumbShape){
d3.select(this)
.style("fill",config.color.crumb.hover);
}
})
.on("mouseout", function(){
d3.select(this.parentNode)
.select("polygon")
.attr("fill", config.color.crumb.bottom);
if (!config.useCrumbShape){
d3.select(this)
.style("fill",config.color.crumbText);
}
})
.on("click", function(){
dataGraph.pickUpBreadcrumb(graphConfig,lastIndex,groups,rect,phenoDiv);
});
}
d3.select(html_div).select(".breadcrumbs")
.select("svg")
.append("g")
.attr("class",("bread"+index))
.attr("transform", "translate(" + index*(config.bread.offset+config.bread.space) + ", 0)");
if (config.useCrumbShape){
d3.select(html_div).select((".bread"+index))
.append("svg:polygon")
.attr("class",("poly"+index))
.attr("points",index ? config.trailCrumbs : config.firstCr)
.attr("fill", config.color.crumb.top);
}
//This creates the hover tooltip
if (fullLabel){
d3.select(html_div).select((".bread"+index))
.append("svg:title")
.text(fullLabel);
} else {
d3.select(html_div).select((".bread"+index))
.append("svg:title")
.text(label);
}
d3.select(html_div).select((".bread"+index))
.append("text")
.style("fill",config.color.crumbText)
.attr("class",("text"+index))
.attr("font-size", fontSize)
.each(function () {
var words = label.split(/\s|\/|\-/);
var len = words.length;
if (len > 2 && !label.match(/head and neck/i)){
words.splice(2,len);
words[1]=words[1]+"...";
}
len = words.length;
for (i = 0;i < len; i++) {
if (words[i].length > 12){
fontSize = ((1/words[i].length)*150);
var reg = new RegExp("(.{"+8+"})(.+)");
words[i] = words[i].replace(reg,"$1...");
}
}
//Check that we haven't increased over the default
if (fontSize > config.crumbFontSize){
fontSize = config.crumbFontSize;
}
for (i = 0;i < len; i++) {
d3.select(this).append("tspan")
.text(words[i])
.attr("font-size",fontSize)
.attr("x", (config.bread.width)*.45)
.attr("y", (config.bread.height)*.42)
.attr("dy", function(){
if (i == 0 && len == 1){
return ".55em";
} else if (i == 0){
return ".1em";
} else if (i < 2 && len > 2
&& words[i].match(/and/i)){
return ".1em";;
} else {
return "1.2em";
}
})
.attr("dx", function(){
if (index == 0){
return ".1em";
}
if (i == 0 && len == 1){
return ".8em";
} else if (i == 0 && len >2
&& words[1].match(/and/i)){
return "-1.2em";
} else if (i == 0){
return ".3em";
} else if (i == 1 && len > 2
&& words[1].match(/and/i)){
return "1.2em";
} else {
return ".25em";
}
})
.attr("text-anchor", "middle")
.attr("class", "tspan" + i);
}
});
}
//TODO DRY - there is quite a bit of duplicated code
// here from the parent drawGraph() function
// NOTE - this will be refactored as AJAX calls
bbop.monarch.datagraph.prototype.transitionSubGraph = function(graphConfig,subGraph,parent,isFromCrumb) {
var dataGraph = this;
var config = dataGraph.config;
graphConfig.groups = dataGraph.getGroups(subGraph);
var groups = graphConfig.groups;
subGraph = dataGraph.getStackedStats(subGraph,groups);
if (!isFromCrumb){
subGraph = dataGraph.addEllipsisToLabel(subGraph,config.maxLabelSize);
}
var rect;
if (parent){
graphConfig.parents.push(parent);
}
var height = dataGraph.resizeChart(subGraph);
//reset d3 config after changing height
graphConfig.y0 = d3.scale.ordinal()
.rangeRoundBands([0,height], .1);
graphConfig.yAxis = d3.svg.axis()
.scale(graphConfig.y0)
.orient("left");
dataGraph.setXYDomains(graphConfig,subGraph,groups);
var xGroupMax = dataGraph.getGroupMax(subGraph);
var xStackMax = dataGraph.getStackMax(subGraph);
//Dynamically decrease font size for large labels
var yFont = dataGraph.adjustYAxisElements(subGraph.length);
var yTransition = graphConfig.svg.transition().duration(1000);
yTransition.select(".y.axis").call(graphConfig.yAxis);
graphConfig.svg.select(".y.axis")
.selectAll("text")
.filter(function(d){ return typeof(d) == "string"; })
.attr("font-size", yFont)
.on("mouseover", function(d){
if (config.isYLabelURL){
d3.select(this).style("cursor", "pointer");
d3.select(this).style("fill", config.color.yLabel.hover);
d3.select(this).style("text-decoration", "underline");
}
if (/\.\.\./.test(d)){
var fullLabel = dataGraph.getFullLabel(d,subGraph);
d3.select(this).append("svg:title")
.text(fullLabel);
} else if (yFont < 12) {//HARDCODE alert
d3.select(this).append("svg:title")
.text(d);
}
})
.on("mouseout", function(){
d3.select(this).style("fill", config.color.yLabel.fill );
d3.select(this).style("text-decoration", "none");
})
.on("click", function(d){
if (config.isYLabelURL){
d3.select(this).style("cursor", "pointer");
var monarchID = dataGraph.getGroupID(d,subGraph);
document.location.href = config.yLabelBaseURL + monarchID;
}
})
.style("text-anchor", "end")
.attr("dx", config.yOffset);
var barGroup = dataGraph.setGroupPositioning(graphConfig,subGraph);
if ($('input[name=mode]:checked').val()=== 'grouped' || groups.length == 1) {
dataGraph.setXYDomains(graphConfig,subGraph,groups,'grouped');
var xTransition = graphConfig.svg.transition().duration(1000);
xTransition.select(".x.axis")
.call(graphConfig.xAxis);
rect = dataGraph.makeBar(barGroup,graphConfig,'grouped');
} else {
dataGraph.setXYDomains(graphConfig,subGraph,groups,'stacked');
var xTransition = graphConfig.svg.transition().duration(1000);
xTransition.select(".x.axis")
.call(graphConfig.xAxis);
rect = dataGraph.makeBar(barGroup,graphConfig,'stacked');
}
var navigate = graphConfig.svg.selectAll(".y.axis");
var isSubClass = dataGraph.makeNavArrow(subGraph,navigate,
config.arrowDim,barGroup,rect,graphConfig);
if (!isSubClass){
graphConfig.svg.selectAll("polygon.arr").remove();
graphConfig.svg.select(".y.axis")
.selectAll("text")
.attr("dx","0")
.on("mouseover", function(d){
d3.select(this).style("cursor", "pointer");
d3.select(this).style("fill",config.color.yLabel.hover);
d3.select(this).style("text-decoration", "underline");
});
}
d3.select(graphConfig.html_div).selectAll("input").on("change", change);
function change() {
if (this.value === "grouped"){
dataGraph.transitionGrouped(graphConfig,subGraph,groups,rect);
} else {
dataGraph.transitionStacked(graphConfig,subGraph,groups,rect);
}
}
}
////////////////////////////////////////////////////////////////////
//
//Data object manipulation
//
//The functions below manipulate the data object for
//various functionality
//
//get X Axis limit for grouped configuration
bbop.monarch.datagraph.prototype.getGroupMax = function(data){
return d3.max(data, function(d) {
return d3.max(d.counts, function(d) { return d.value; });
});
}
//get X Axis limit for stacked configuration
bbop.monarch.datagraph.prototype.getStackMax = function(data){
return d3.max(data, function(d) {
return d3.max(d.counts, function(d) { return d.x1; });
});
}
//get largest Y axis label for font resizing
bbop.monarch.datagraph.prototype.getYMax = function(data){
return d3.max(data, function(d) {
return d.label.length;
});
}
bbop.monarch.datagraph.prototype.checkForSubGraphs = function(data){
for (i = 0;i < data.length; i++) {
if (Object.keys(data[i]).indexOf('subGraph') >= 0) {
return true;
}
}
return false;
}
bbop.monarch.datagraph.prototype.getStackedStats = function(data,groups){
//Add x0,x1 values for stacked barchart
data.forEach(function (r){
var count = 0;
r.counts.forEach(function (i){
i["x0"] = count;
i["x1"] = i.value+count;
if (i.value > 0){
count = i.value;
}
});
});
var lastElement = groups.length-1;
data.sort(function(obj1, obj2) {
if ((obj2.counts[lastElement])&&(obj1.counts[lastElement])){
return obj2.counts[lastElement].x1 - obj1.counts[lastElement].x1;
} else {
return 0;
}
});
return data;
}
bbop.monarch.datagraph.prototype.getGroups = function(data) {
var groups = [];
var unique = {};
for (var i=0, len=data.length; i<len; i++) {
for (var j=0, cLen=data[i].counts.length; j<cLen; j++) {
unique[ data[i].counts[j].name ] =1;
}
}
groups = Object.keys(unique);
return groups;
},
//remove zero length bars
bbop.monarch.datagraph.prototype.removeZeroCounts = function(data){
trimmedGraph = [];
data.forEach(function (r){
var count = 0;
r.counts.forEach(function (i){
count += i.value;
});
if (count > 0){
trimmedGraph.push(r);
}
});
return trimmedGraph;
}
bbop.monarch.datagraph.prototype.addEllipsisToLabel = function(data,max){
var reg = new RegExp("(.{"+max+"})(.+)");
data.forEach(function (r){
if (r.label.length > max){
r.fullLabel = r.label;
r.label = r.label.replace(reg,"$1...");
}
});
return data;
}
bbop.monarch.datagraph.prototype.getFullLabel = function (d,data){
for (var i=0, len=data.length; i < len; i++){
if (data[i].label === d){
var fullLabel = data[i].fullLabel;
return fullLabel;
break;
}
}
}
bbop.monarch.datagraph.prototype.getGroupID = function (d,data){
for (var i=0, len=data.length; i < len; i++){
if (data[i].label === d){
monarchID = data[i].id;
return monarchID;
break;
}
}
}
////////////////////////////////////////////////////////////////////
//End data object functions
////////////////////////////////////////////////////////////////////
//Log given base x
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
//Adjust Y label font, arrow size, and spacing
//when transitioning
//this is getting funky with graph resizing, maybe should do away
bbop.monarch.datagraph.prototype.adjustYAxisElements = function(len){
var conf = this.config;
var h = conf.height;
var density = h/len;
var isUpdated = false;
yFont = conf.yFontSize;
var yOffset = conf.yOffset;
var arrowDim = conf.arrowDim;
//Check for density BETA
if (density < 15 && density < yFont ){
yFont = density+2;
//yOffset = "-2em";
//arrowDim = "-20,-3, -11,1 -20,5";
isUpdated = true;
}
if (isUpdated && yFont > conf.yFontSize){
yFont = conf.yFontSize;
}
return yFont;
}
///////////////////////////////////
//Setters for sizing configurations
bbop.monarch.datagraph.prototype.setWidth = function(w){
this.config.width = w;
}
bbop.monarch.datagraph.prototype.setHeight = function(h){
this.config.height = h;
}
bbop.monarch.datagraph.prototype.setYFontSize = function(fSize){
this.config.yFontSize = fSize;
}
bbop.monarch.datagraph.prototype.setxFontSize = function(fSize){
this.config.xFontSize = fSize;
}
bbop.monarch.datagraph.prototype.setXLabelFontSize = function(fSize){
this.config.xLabelFontSize = fSize;
}
bbop.monarch.datagraph.prototype.setXAxisPos = function(w,h){
this.config.xAxisPos = {dx:w,y:h};
}
//The starting index (0 or 1) for the x axis seems to be
//dependent on browser version, for now always return 1
//Firefox <33 should be 0
bbop.monarch.datagraph.prototype.getXFirstIndex = function (){
//Check browser
var isOpera = (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0);
var isChrome = (!!window.chrome && !(!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0));
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
if (isChrome || isSafari){
return 1;
} else {
return 1;
}
}
//datagraph default SVG Coordinates
bbop.monarch.datagraph.prototype.setPolygonCoordinates = function(){
//Nav arrow (now triangle)
if (this.config.arrowDim == null || typeof this.config.arrowDim == 'undefined'){
this.config.arrowDim = "-23,-6, -12,0 -23,6";
}
//Breadcrumb dimensions
if (this.config.firstCr == null || typeof this.config.firstCr == 'undefined'){
this.config.firstCr = "0,0 0,30 90,30 105,15 90,0";
}
if (this.config.trailCrumbs == null || typeof this.config.trailCrumbs == 'undefined'){
this.config.trailCrumbs = "0,0 15,15 0,30 90,30 105,15 90,0";
}
//Polygon dimensions
if (this.config.bread == null || typeof this.config.bread == 'undefined'){
this.config.bread = {width:105, height: 30, offset:90, space: 1};
}
//breadcrumb div dimensions
this.config.bcWidth = 560;
//Y axis positioning when arrow present
if (this.config.yOffset == null || typeof this.config.yOffset == 'undefined'){
this.config.yOffset = "-1.48em";
}
//Check that breadcrumb width is valid
if (this.config.bcWidth > this.config.width+this.config.margin.right+this.config.margin.left){
this.config.bcWidth = this.config.bread.width+(this.config.bread.offset*5)+5;
}
}
//datagraph default configurations
bbop.monarch.datagraph.prototype.getDefaultConfig = function(){
var defaultConfiguration = {
//Chart margins
margin : {top: 40, right: 140, bottom: 5, left: 255},
width : 375,
height : 400,
//X Axis Label
xAxisLabel : "Some Metric",
xLabelFontSize : "14px",
xFontSize : "14px",
xAxisPos : {dx:"20em",y:"-29"},
//Chart title and first breadcrumb
chartTitle : "Chart Title",
firstCrumb : "first bread crumb",
//Title size/font settings
title : {
'text-align': 'center',
'text-indent' : '0px',
'font-size' : '20px',
'font-weight': 'bold',
'background-color' : '#E8E8E8',
'border-bottom-color' : '#000000'
},
//Yaxis links
yFontSize : 'default',
isYLabelURL : true,
yLabelBaseURL : "/phenotype/",
//Font sizes
settingsFontSize : '14px',
//Maximum label length before adding an ellipse
maxLabelSize : 31,
//Turn on/off legend
useLegend : true,
//Fontsize
legendFontSize : 14,
//Legend dimensions
legend : {width:18,height:18},
legendText : {height:".35em"},
//Colors set in the order they appear in the JSON object
color : {
first : '#44A293',
second : '#A4D6D4',
third : '#EA763B',
fourth : '#496265',
fifth : '#44A293',
sixth : '#A4D6D4',
yLabel : {
fill : '#000000',
hover : '#EA763B'
},
arrow : {
fill : "#496265",
hover : "#EA763B"
},
bar : {
fill : '#EA763B'
},
crumb : {
top : '#496265',
bottom: '#3D6FB7',
hover : '#EA763B'
},
crumbText : '#FFFFFF'
},
//Turn on/off breadcrumbs
useCrumb : false,
crumbFontSize : 10,
//Turn on/off breadcrumb shapes
useCrumbShape : true
};
return defaultConfiguration;
} | widgets/datagraph/js/datagraph.js | /*
* Package: datagraph.js
*
* Namespace: monarch.bbop.datagraph
*
*/
// Module and namespace checking.
if (typeof bbop == 'undefined') { var bbop = {};}
if (typeof bbop.monarch == 'undefined') { bbop.monarch = {};}
bbop.monarch.datagraph = function(config){
if (config == null || typeof config == 'undefined'){
this.config = this.getDefaultConfig();
} else {
this.config = config;
}
this.setPolygonCoordinates();
this.config.xFirstIndex = this.getXFirstIndex();
//Tooltip offsetting
this.config.arrowOffset = {height: 21, width: -90};
this.config.barOffset = {
grouped:{
height: 95,
width: 10
},
stacked:{
height: 80
}
};
if (this.config.isDynamicallyResized){
this.config.graphSizingRatios = this.setSizingRatios();
}
}
bbop.monarch.datagraph.prototype.run = function(html_div,DATA){
var dataGraph = this;
dataGraph.makeGraphDOM(html_div,DATA);
var d3Config = dataGraph.setD3Config(html_div,DATA);
dataGraph.drawGraph(DATA,d3Config,html_div);
}
bbop.monarch.datagraph.prototype.init = function(html_div,DATA){
var dataGraph = this;
var config = dataGraph.config;
if (config.isDynamicallyResized){
if ($(window).width() < (config.benchmarkWidth-100) || $(window).height() < (config.benchmarkHeight-100)){
dataGraph.setSizeConfiguration(config.graphSizingRatios);
dataGraph.run(html_div,DATA);
} else {
dataGraph.run(html_div,DATA);
}
window.addEventListener('resize', function(event){
if ($(window).width() < (config.benchmarkWidth-100) || $(window).height() < (config.benchmarkHeight-100)){
$(html_div).children().remove();
dataGraph.setSizeConfiguration(config.graphSizingRatios);
dataGraph.run(html_div,DATA);
}
});
} else {
dataGraph.run(html_div,DATA);
}
}
bbop.monarch.datagraph.prototype.setSizeConfiguration = function(graphRatio){
var dataGraph = this;
var w = $(window).width();
var h = $(window).height();
var total = w+h;
dataGraph.setWidth( ((w*graphRatio.width) / getBaseLog(12,w)) * 3);
dataGraph.setHeight( ((h*graphRatio.height) / getBaseLog(12,h)) *3.5);
dataGraph.setYFontSize( ((total*(graphRatio.yFontSize))/ getBaseLog(20,total)) * 3);
}
bbop.monarch.datagraph.prototype.setSizingRatios = function(){
var config = this.config;
var graphRatio = {};
if (!config.benchmarkHeight || !config.benchmarkWidth){
console.log("Dynamic sizing set without "+
"setting benchmarkHeight and/or benchmarkWidth");
}
graphRatio.width = config.width / config.benchmarkWidth;
graphRatio.height = config.height / config.benchmarkHeight;
graphRatio.yFontSize = (config.yFontSize / (config.benchmarkHeight+config.benchmarkWidth));
return graphRatio;
}
//Uses JQuery to create the DOM for the datagraph
bbop.monarch.datagraph.prototype.makeGraphDOM = function(html_div,data){
var config = this.config;
var dataGraph = this;
var groups = dataGraph.getGroups(data);
//Create html structure
//Add graph title
$(html_div).append( "<div class=title"+
" style=text-indent:" + config.title['text-indent'] +
";text-align:" + config.title['text-align'] +
";background-color:" + config.title['background-color'] +
";border-bottom-color:" + config.title['border-bottom-color'] +
";font-size:" + config.title['font-size'] +
";font-weight:" + config.title['font-weight'] +
"; >"+config.chartTitle+"</div>" );
$(html_div).append( "<div class=interaction></div>" );
$(html_div+" .interaction").append( "<li></li>" );
//Override breadcrumb config if subgraphs exist
config.useCrumb = dataGraph.checkForSubGraphs(data);
//remove breadcrumb div
if (config.useCrumb){
$(html_div+" .interaction li").append("<div class=breadcrumbs></div>");
}
//Add stacked/grouped form if more than one group
if (groups.length >1){
$(html_div+" .interaction li").append(" <form class=configure"+
" style=font-size:" + config.settingsFontSize + "; >" +
"<label><input id=\"group\" type=\"radio\" name=\"mode\"" +
" value=\"grouped\" checked> Grouped</label> " +
"<label><input id=\"stack\" type=\"radio\" name=\"mode\"" +
" value=\"stacked\"> Stacked</label>" +
"</form> ");
}
//Update tooltip positioning
if (!config.useCrumb && groups.length>1){
config.arrowOffset.height = 12;
config.barOffset.grouped.height = 102;
config.barOffset.stacked.height = 81;
} else if (!config.useCrumb){
config.arrowOffset.height = -10;
config.barOffset.grouped.height = 71;
config.barOffset.stacked.height = 50;
}
}
bbop.monarch.datagraph.prototype.setD3Config = function (html_div,DATA){
var d3Config = {};
var dataGraph = this;
var conf = dataGraph.config;
//Define scales
d3Config.y0 = d3.scale.ordinal()
.rangeRoundBands([0,conf.height], .1);
d3Config.y1 = d3.scale.ordinal();
d3Config.x = d3.scale.linear()
.range([0, conf.width]);
//Bar colors
d3Config.color = d3.scale.ordinal()
.range([conf.color.first,conf.color.second,conf.color.third,
conf.color.fourth,conf.color.fifth,conf.color.sixth]);
d3Config.xAxis = d3.svg.axis()
.scale(d3Config.x)
.orient("top")
.tickFormat(d3.format(".2s"));
d3Config.yAxis = d3.svg.axis()
.scale(d3Config.y0)
.orient("left");
d3Config.svg = d3.select(html_div).append("svg")
.attr("width", conf.width + conf.margin.left + conf.margin.right)
.attr("height", conf.height + conf.margin.top + conf.margin.bottom)
.append("g")
.attr("transform", "translate(" + conf.margin.left + "," + conf.margin.top + ")");
d3Config.crumbSVG = d3.select(html_div).select(".breadcrumbs")
.append("svg")
.attr("height",(conf.bread.height+2))
.attr("width",conf.bcWidth);
d3Config.tooltip = d3.select(html_div)
.append("div")
.attr("class", "tip");
d3Config.groups = dataGraph.getGroups(DATA);
//Variables to keep track of graph transitions
d3Config.level = 0;
d3Config.parents = [];
d3Config.html_div = html_div;
return d3Config;
}
bbop.monarch.datagraph.prototype.makeLegend = function (graphConfig){
var config = this.config;
var svg = graphConfig.svg;
var groups = graphConfig.groups;
var color = graphConfig.color;
//Set legend
var legend = svg.selectAll(".legend")
.data(groups.slice())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * (config.legend.height+7) + ")"; });
legend.append("rect")
.attr("x", config.width+config.legend.width+37)//HARDCODE
.attr("y", 4)
.attr("width", config.legend.width)
.attr("height", config.legend.height)
.style("fill", color);
legend.append("text")
.attr("x", config.width+config.legend.width+32)
.attr("y", 12)
.attr("dy", config.legendText.height)
.attr("font-size",config.legendFontSize)
.style("text-anchor", "end")
.text(function(d) { return d; });
}
bbop.monarch.datagraph.prototype.makeNavArrow = function(data,navigate,triangleDim,barGroup,rect,graphConfig){
var dataGraph = this;
var config = dataGraph.config;
//boolean variable to check for subclasses that is returned
var isSubClass;
var tooltip = graphConfig.tooltip;
var svg = graphConfig.svg;
var html_div = graphConfig.html_div;
var arrow = navigate.selectAll(".tick.major")
.data(data)
.append("svg:polygon")
.attr("points",triangleDim)
.attr("fill", config.color.arrow.fill)
.attr("display", function(d){
if (d.subGraph && d.subGraph[0]){
isSubClass=1; return "initial";
} else {
return "none";
}
})
.on("mouseover", function(d){
if (d.subGraph && d.subGraph[0]){
dataGraph.displaySubClassTip(tooltip,this)
}
})
.on("mouseout", function(){
d3.select(this)
.style("fill",config.color.arrow.fill);
tooltip.style("display", "none");
})
.on("click", function(d){
if (d.subGraph && d.subGraph[0]){
dataGraph.transitionToNewGraph(tooltip,graphConfig,d,
data,barGroup,rect);
}
});
return isSubClass;
}
bbop.monarch.datagraph.prototype.transitionToNewGraph = function(tooltip,graphConfig,d,data,barGroup,rect){
dataGraph = this;
config = dataGraph.config;
tooltip.style("display", "none");
graphConfig.svg.selectAll(".tick.major").remove();
graphConfig.level++;
dataGraph.transitionSubGraph(graphConfig,d.subGraph,data);
//remove old bars
barGroup.transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
rect.transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
if (config.useCrumb){
dataGraph.makeBreadcrumb(graphConfig,d.label,graphConfig.groups,
rect,barGroup,d.fullLabel);
}
}
bbop.monarch.datagraph.prototype.displaySubClassTip = function(tooltip,d3Selection){
var dataGraph = this;
var config = dataGraph.config;
d3.select(d3Selection)
.style("fill", config.color.arrow.hover);
var coords = d3.transform(d3.select(d3Selection.parentNode)
.attr("transform")).translate;
var h = coords[1];
var w = coords[0];
tooltip.style("display", "block")
.html("Click to see subclasses")
.style("top",h+config.margin.top+config.bread.height+
config.arrowOffset.height+"px")
.style("left",w+config.margin.left+config.arrowOffset.width+"px");
}
bbop.monarch.datagraph.prototype.getCountMessage = function(value,name){
return "Counts: "+"<span style='font-weight:bold'>"+value+"</span>"+"<br/>"
+"Organism: "+ "<span style='font-weight:bold'>"+name;
}
bbop.monarch.datagraph.prototype.displayCountTip = function(tooltip,value,name,d3Selection,barLayout){
var dataGraph = this;
var config = dataGraph.config;
var coords = d3.transform(d3.select(d3Selection.parentNode)
.attr("transform")).translate;
var w = coords[0];
var h = coords[1];
var heightOffset = d3Selection.getBBox().y;
var widthOffset = d3Selection.getBBox().width;
tooltip.style("display", "block")
.html(dataGraph.getCountMessage(value,name));
if (barLayout == 'grouped'){
tooltip.style("top",h+heightOffset+config.barOffset.grouped.height+"px")
.style("left",w+config.barOffset.grouped.width+widthOffset+
config.margin.left+"px");
} else if (barLayout == 'stacked'){
tooltip.style("top",h+heightOffset+config.barOffset.stacked.height+"px")
.style("left",w+config.barOffset.grouped.width+widthOffset+
config.margin.left+"px");
}
}
bbop.monarch.datagraph.prototype.setGroupPositioning = function (graphConfig,graphData) {
var groupPos = graphConfig.svg.selectAll(".barGroup")
.data(graphData)
.enter().append("svg:g")
.attr("class", ("bar"+graphConfig.level))
.attr("transform", function(d) { return "translate(0," + graphConfig.y0(d.label) + ")"; });
return groupPos;
}
bbop.monarch.datagraph.prototype.setXYDomains = function (graphConfig,graphData,groups,barLayout) {
var dataGraph = this;
//Set y0 domain
graphConfig.y0.domain(graphData.map(function(d) { return d.label; }));
if (barLayout == 'grouped'){
var xGroupMax = dataGraph.getGroupMax(graphData);
graphConfig.x.domain([0, xGroupMax]);
graphConfig.y1.domain(groups)
.rangeRoundBands([0, graphConfig.y0.rangeBand()]);
} else if (barLayout == 'stacked'){
var xStackMax = dataGraph.getStackMax(graphData);
graphConfig.x.domain([0, xStackMax]);
graphConfig.y1.domain(groups).rangeRoundBands([0,0]);
} else {
graphConfig.y1.domain(groups)
.rangeRoundBands([0, graphConfig.y0.rangeBand()]);
}
}
bbop.monarch.datagraph.prototype.makeBar = function (barGroup,graphConfig,barLayout) {
var rect;
var dataGraph = this;
var config = dataGraph.config;
//Create bars
if (barLayout == 'grouped'){
rect = barGroup.selectAll("g")
.data(function(d) { return d.counts; })
.enter().append("rect")
.attr("class",("rect"+graphConfig.level))
.attr("height", graphConfig.y1.rangeBand())
.attr("y", function(d) { return graphConfig.y1(d.name); })
.attr("x", function(){return config.xFirstIndex;})
.attr("width", function(d) { return graphConfig.x(d.value); })
.on("mouseover", function(d){
d3.select(this)
.style("fill", config.color.bar.fill);
dataGraph.displayCountTip(graphConfig.tooltip,d.value,d.name,this,'grouped');
})
.on("mouseout", function(){
d3.select(this)
.style("fill", function(d) { return graphConfig.color(d.name); });
graphConfig.tooltip.style("display", "none");
})
.style("fill", function(d) { return graphConfig.color(d.name); });
} else if (barLayout == 'stacked') {
rect = barGroup.selectAll("g")
.data(function(d) { return d.counts; })
.enter().append("rect")
.attr("class",("rect"+graphConfig.level))
.attr("x", function(d){
if (d.x0 == 0){
return config.xFirstIndex;
} else {
return graphConfig.x(d.x0);
}
})
.attr("width", function(d) {
return graphConfig.x(d.x1) - graphConfig.x(d.x0);
})
.attr("height", graphConfig.y0.rangeBand())
.attr("y", function(d) { return graphConfig.y1(d.name); })
.on("mouseover", function(d){
d3.select(this)
.style("fill", config.color.bar.fill);
dataGraph.displayCountTip(graphConfig.tooltip,d.value,d.name,this,'stacked');
})
.on("mouseout", function(){
d3.select(this)
.style("fill", function(d) { return graphConfig.color(d.name); });
graphConfig.tooltip.style("display", "none");
})
.style("fill", function(d) { return graphConfig.color(d.name); });
}
return rect;
}
bbop.monarch.datagraph.prototype.transitionGrouped = function (graphConfig,data,groups,rect) {
var dataGraph = this;
var config = dataGraph.config;
dataGraph.setXYDomains(graphConfig,data,groups,'grouped');
var xTransition = graphConfig.svg.transition().duration(750);
xTransition.select(".x.axis").call(graphConfig.xAxis);
rect.transition()
.duration(500)
.delay(function(d, i) { return i * 10; })
.attr("height", graphConfig.y1.rangeBand())
.attr("y", function(d) { return graphConfig.y1(d.name); })
.transition()
.attr("x", function(){return config.xFirstIndex;})
.attr("width", function(d) { return graphConfig.x(d.value); })
rect.on("mouseover", function(d){
d3.select(this)
.style("fill", config.color.bar.fill);
dataGraph.displayCountTip(graphConfig.tooltip,d.value,d.name,this,'grouped');
})
.on("mouseout", function(){
graphConfig.tooltip.style("display", "none")
d3.select(this)
.style("fill", function(d) { return graphConfig.color(d.name); });
})
}
bbop.monarch.datagraph.prototype.transitionStacked = function (graphConfig,data,groups,rect) {
var dataGraph = this;
var config = dataGraph.config;
dataGraph.setXYDomains(graphConfig,data,groups,'stacked');
var t = graphConfig.svg.transition().duration(750);
t.select(".x.axis").call(graphConfig.xAxis);
rect.transition()
.duration(500)
.delay(function(d, i) { return i * 10; })
.attr("x", function(d){
if (d.x0 == 0){
return config.xFirstIndex;
} else {
return graphConfig.x(d.x0);
}
})
.attr("width", function(d) { return graphConfig.x(d.x1) - graphConfig.x(d.x0); })
.transition()
.attr("height", graphConfig.y0.rangeBand())
.attr("y", function(d) { return graphConfig.y1(d.name); })
rect.on("mouseover", function(d){
d3.select(this)
.style("fill", config.color.bar.fill);
dataGraph.displayCountTip(graphConfig.tooltip,d.value,d.name,this,'stacked');
})
.on("mouseout", function(){
graphConfig.tooltip.style("display", "none");
d3.select(this)
.style("fill", function(d) { return graphConfig.color(d.name); });
})
}
bbop.monarch.datagraph.prototype.drawGraph = function (data,graphConfig) {
var dataGraph = this;
var config = this.config;
var html_div = graphConfig.html_div;
var y0 = graphConfig.y0;
var y1 = graphConfig.y1;
var x = graphConfig.x;
var color = graphConfig.color;
var xAxis = graphConfig.xAxis;
var yAxis = graphConfig.yAxis;
var svg = graphConfig.svg;
var tooltip = graphConfig.tooltip;
var groups = graphConfig.groups;
data = dataGraph.getStackedStats(data,groups);
data = dataGraph.addEllipsisToLabel(data,config.maxLabelSize);
dataGraph.setXYDomains(graphConfig,data,groups,'grouped');
if (groups.length == 1){
config.barOffset.grouped.height = config.barOffset.grouped.height+8;
config.barOffset.stacked.height = config.barOffset.stacked.height+8;
}
//Dynamically decrease font size for large labels
var confList = dataGraph.adjustYAxisElements(data.length);
var yFont = confList[0];
var yLabelPos = confList[1];
var triangleDim = confList[2];
//Set x axis ticks
var xTicks = svg.append("g")
.attr("class", "x axis")
.call(xAxis)
.style("font-size",config.xFontSize)
.append("text")
.attr("transform", "rotate(0)")
.attr("y", config.xAxisPos.y)
.attr("dx", config.xAxisPos.dx)
.attr("dy", "0em")
.style("text-anchor", "end")
.style("font-size",config.xLabelFontSize)
.text(config.xAxisLabel);
//Set Y axis ticks and labels
var yTicks = svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.selectAll("text")
.filter(function(d){ return typeof(d) == "string"; })
.attr("font-size", yFont)
.on("mouseover", function(d){
if (config.isYLabelURL){
d3.select(this).style("cursor", "pointer");
d3.select(this).style("fill", config.color.yLabel.hover);
d3.select(this).style("text-decoration", "underline");
}
if (/\.\.\./.test(d)){
var fullLabel = dataGraph.getFullLabel(d,data);
d3.select(this).append("svg:title")
.text(fullLabel);
//Hardcode alert
} else if (yFont < 12) {
d3.select(this).append("svg:title")
.text(d);
}
})
.on("mouseout", function(){
d3.select(this).style("fill", config.color.yLabel.fill );
d3.select(this).style("text-decoration", "none");
})
.on("click", function(d){
if (config.isYLabelURL){
d3.select(this).style("cursor", "pointer");
var monarchID = dataGraph.getGroupID(d,data);
document.location.href = config.yLabelBaseURL + monarchID;
}
})
.style("text-anchor", "end")
.attr("dx", yLabelPos);
//Create SVG:G element that holds groups
var barGroup = dataGraph.setGroupPositioning(graphConfig,data);
//Create bars
var rect = dataGraph.makeBar(barGroup,graphConfig,'grouped');
//Create navigation arrow
var navigate = svg.selectAll(".y.axis");
dataGraph.makeNavArrow(data,navigate,triangleDim,
barGroup,rect,graphConfig);
//Create legend
if (config.useLegend){
dataGraph.makeLegend(graphConfig);
}
//Make first breadcrumb
if (config.useCrumb){
dataGraph.makeBreadcrumb(graphConfig,config.firstCrumb,
groups,rect,barGroup);
}
d3.select(html_div).selectAll("input").on("change", change);
function change() {
if (this.value === "grouped"){
dataGraph.transitionGrouped(graphConfig,data,groups,rect);
} else {
dataGraph.transitionStacked(graphConfig,data,groups,rect);
}
}
function transitionGrouped() {
dataGraph.setXYDomains(graphConfig,data,groups,'grouped');
var xTransition = svg.transition().duration(750);
xTransition.select(".x.axis").call(xAxis);
rect.transition()
.duration(500)
.delay(function(d, i) { return i * 10; })
.attr("height", y1.rangeBand())
.attr("y", function(d) { return y1(d.name); })
.transition()
.attr("x", function(){if (config.isChrome || config.isSafari) {return 1;}else{ return 0;}})
.attr("width", function(d) { return x(d.value); })
rect.on("mouseover", function(d){
d3.select(this)
.style("fill", config.color.bar.fill);
dataGraph.displayCountTip(tooltip,d.value,d.name,this,'grouped');
})
.on("mouseout", function(){
tooltip.style("display", "none")
d3.select(this)
.style("fill", function(d) { return color(d.name); });
})
}
function transitionStacked() {
dataGraph.setXYDomains(graphConfig,data,groups,'stacked');
var t = svg.transition().duration(750);
t.select(".x.axis").call(xAxis);
rect.transition()
.duration(500)
.delay(function(d, i) { return i * 10; })
.attr("x", function(d){
if (d.x0 == 0){
if (config.isChrome || config.isSafari){return 1;}
else {return d.x0;}
} else {
return x(d.x0);
}
})
.attr("width", function(d) { return x(d.x1) - x(d.x0); })
.transition()
.attr("height", y0.rangeBand())
.attr("y", function(d) { return y1(d.name); })
rect.on("mouseover", function(d){
d3.select(this)
.style("fill", config.color.bar.fill);
dataGraph.displayCountTip(tooltip,d.value,d.name,this,'stacked');
})
.on("mouseout", function(){
tooltip.style("display", "none");
d3.select(this)
.style("fill", function(d) { return color(d.name); });
})
}
}
//Resize height of chart after transition
bbop.monarch.datagraph.prototype.resizeChart = function(subGraph){
var config = this.config;
var height = config.height;
if (subGraph.length < 25){
height = subGraph.length*26;
if (height > config.height){
height = config.height;
}
}
return height;
}
bbop.monarch.datagraph.prototype.pickUpBreadcrumb = function(graphConfig,index,groups,rect,barGroup) {
var dataGraph = this;
var config = dataGraph.config;
var lastIndex = graphConfig.level;
var superclass = graphConfig.parents[index];
var isFromCrumb = true;
var parent;
//set global level
graphConfig.level = index;
graphConfig.svg.selectAll(".tick.major").remove();
dataGraph.transitionSubGraph(graphConfig,superclass,graphConfig.parents,isFromCrumb);
for (var i=(index+1); i <= graphConfig.parents.length; i++){
d3.select(graphConfig.html_div).select(".bread"+i).remove();
}
graphConfig.svg.selectAll((".rect"+lastIndex)).transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
graphConfig.svg.selectAll((".bar"+lastIndex)).transition()
.duration(750)
.attr("y", 60)
.style("fill-opacity", 1e-6)
.remove();
graphConfig.parents.splice(index,(graphConfig.parents.length));
//Deactivate top level crumb
if (config.useCrumbShape){
d3.select(graphConfig.html_div).select(".poly"+index)
.attr("fill", config.color.crumb.top)
.on("mouseover", function(){})
.on("mouseout", function(){
d3.select(this)
.attr("fill", config.color.crumb.top);
})
.on("click", function(){});
d3.select(graphConfig.html_div).select(".text"+index)
.on("mouseover", function(){})
.on("mouseout", function(){
d3.select(this.parentNode)
.select("polygon")
.attr("fill", config.color.crumb.top);
})
.on("click", function(){});
} else {
d3.select(graphConfig.html_div).select(".text"+index)
.style("fill",config.color.crumbText)
.on("mouseover", function(){})
.on("mouseout", function(){})
.on("click", function(){});
}
}
bbop.monarch.datagraph.prototype.makeBreadcrumb = function(graphConfig,label,groups,rect,phenoDiv,fullLabel) {
var dataGraph = this;
var config = dataGraph.config;
var html_div = graphConfig.html_div;
var index = graphConfig.level;
if (!label){
label = config.firstCrumb;
}
var lastIndex = (index-1);
var phenLen = label.length;
var fontSize = config.crumbFontSize;
//Change color of previous crumb
if (lastIndex > -1){
if (config.useCrumbShape){
d3.select(html_div).select(".poly"+lastIndex)
.attr("fill", config.color.crumb.bottom)
.on("mouseover", function(){
d3.select(this)
.attr("fill", config.color.crumb.hover);
})
.on("mouseout", function(){
d3.select(this)
.attr("fill", config.color.crumb.bottom);
})
.on("click", function(){
dataGraph.pickUpBreadcrumb(graphConfig,lastIndex,groups,rect,phenoDiv);
});
}
d3.select(html_div).select(".text"+lastIndex)
.on("mouseover", function(){
d3.select(this.parentNode)
.select("polygon")
.attr("fill", config.color.crumb.hover);
if (!config.useCrumbShape){
d3.select(this)
.style("fill",config.color.crumb.hover);
}
})
.on("mouseout", function(){
d3.select(this.parentNode)
.select("polygon")
.attr("fill", config.color.crumb.bottom);
if (!config.useCrumbShape){
d3.select(this)
.style("fill",config.color.crumbText);
}
})
.on("click", function(){
dataGraph.pickUpBreadcrumb(graphConfig,lastIndex,groups,rect,phenoDiv);
});
}
d3.select(html_div).select(".breadcrumbs")
.select("svg")
.append("g")
.attr("class",("bread"+index))
.attr("transform", "translate(" + index*(config.bread.offset+config.bread.space) + ", 0)");
if (config.useCrumbShape){
d3.select(html_div).select((".bread"+index))
.append("svg:polygon")
.attr("class",("poly"+index))
.attr("points",index ? config.trailCrumbs : config.firstCr)
.attr("fill", config.color.crumb.top);
}
//This creates the hover tooltip
if (fullLabel){
d3.select(html_div).select((".bread"+index))
.append("svg:title")
.text(fullLabel);
} else {
d3.select(html_div).select((".bread"+index))
.append("svg:title")
.text(label);
}
d3.select(html_div).select((".bread"+index))
.append("text")
.style("fill",config.color.crumbText)
.attr("class",("text"+index))
.attr("font-size", fontSize)
.each(function () {
var words = label.split(/\s|\/|\-/);
var len = words.length;
if (len > 2 && !label.match(/head and neck/i)){
words.splice(2,len);
words[1]=words[1]+"...";
}
len = words.length;
for (i = 0;i < len; i++) {
if (words[i].length > 12){
fontSize = ((1/words[i].length)*150);
var reg = new RegExp("(.{"+8+"})(.+)");
words[i] = words[i].replace(reg,"$1...");
}
}
//Check that we haven't increased over the default
if (fontSize > config.crumbFontSize){
fontSize = config.crumbFontSize;
}
for (i = 0;i < len; i++) {
d3.select(this).append("tspan")
.text(words[i])
.attr("font-size",fontSize)
.attr("x", (config.bread.width)*.45)
.attr("y", (config.bread.height)*.42)
.attr("dy", function(){
if (i == 0 && len == 1){
return ".55em";
} else if (i == 0){
return ".1em";
} else if (i < 2 && len > 2
&& words[i].match(/and/i)){
return ".1em";;
} else {
return "1.2em";
}
})
.attr("dx", function(){
if (index == 0){
return ".1em";
}
if (i == 0 && len == 1){
return ".8em";
} else if (i == 0 && len >2
&& words[1].match(/and/i)){
return "-1.2em";
} else if (i == 0){
return ".3em";
} else if (i == 1 && len > 2
&& words[1].match(/and/i)){
return "1.2em";
} else {
return ".25em";
}
})
.attr("text-anchor", "middle")
.attr("class", "tspan" + i);
}
});
}
//TODO DRY - there is quite a bit of duplicated code
// here from the parent drawGraph() function
// NOTE - this will be refactored as AJAX calls
bbop.monarch.datagraph.prototype.transitionSubGraph = function(graphConfig,subGraph,parent,isFromCrumb) {
var dataGraph = this;
var config = dataGraph.config;
graphConfig.groups = dataGraph.getGroups(subGraph);
var groups = graphConfig.groups;
subGraph = dataGraph.getStackedStats(subGraph,groups);
if (!isFromCrumb){
subGraph = dataGraph.addEllipsisToLabel(subGraph,config.maxLabelSize);
}
var rect;
if (parent){
graphConfig.parents.push(parent);
}
var height = dataGraph.resizeChart(subGraph);
//reset d3 config after changing height
graphConfig.y0 = d3.scale.ordinal()
.rangeRoundBands([0,height], .1);
graphConfig.yAxis = d3.svg.axis()
.scale(graphConfig.y0)
.orient("left");
dataGraph.setXYDomains(graphConfig,subGraph,groups);
var xGroupMax = dataGraph.getGroupMax(subGraph);
var xStackMax = dataGraph.getStackMax(subGraph);
//Dynamically decrease font size for large labels
var confList = dataGraph.adjustYAxisElements(subGraph.length);
var yFont = confList[0];
var yLabelPos = confList[1];
var triangleDim = confList[2];
var yTransition = graphConfig.svg.transition().duration(1000);
yTransition.select(".y.axis").call(graphConfig.yAxis);
graphConfig.svg.select(".y.axis")
.selectAll("text")
.filter(function(d){ return typeof(d) == "string"; })
.attr("font-size", yFont)
.on("mouseover", function(d){
if (config.isYLabelURL){
d3.select(this).style("cursor", "pointer");
d3.select(this).style("fill", config.color.yLabel.hover);
d3.select(this).style("text-decoration", "underline");
}
if (/\.\.\./.test(d)){
var fullLabel = dataGraph.getFullLabel(d,subGraph);
d3.select(this).append("svg:title")
.text(fullLabel);
} else if (yFont < 12) {//HARDCODE alert
d3.select(this).append("svg:title")
.text(d);
}
})
.on("mouseout", function(){
d3.select(this).style("fill", config.color.yLabel.fill );
d3.select(this).style("text-decoration", "none");
})
.on("click", function(d){
if (config.isYLabelURL){
d3.select(this).style("cursor", "pointer");
var monarchID = dataGraph.getGroupID(d,subGraph);
document.location.href = config.yLabelBaseURL + monarchID;
}
})
.style("text-anchor", "end")
.attr("dx", yLabelPos);
var barGroup = dataGraph.setGroupPositioning(graphConfig,subGraph);
if ($('input[name=mode]:checked').val()=== 'grouped' || groups.length == 1) {
dataGraph.setXYDomains(graphConfig,subGraph,groups,'grouped');
var xTransition = graphConfig.svg.transition().duration(1000);
xTransition.select(".x.axis")
.call(graphConfig.xAxis);
rect = dataGraph.makeBar(barGroup,graphConfig,'grouped');
} else {
dataGraph.setXYDomains(graphConfig,subGraph,groups,'stacked');
var xTransition = graphConfig.svg.transition().duration(1000);
xTransition.select(".x.axis")
.call(graphConfig.xAxis);
rect = dataGraph.makeBar(barGroup,graphConfig,'stacked');
}
var navigate = graphConfig.svg.selectAll(".y.axis");
var isSubClass = dataGraph.makeNavArrow(subGraph,navigate,
triangleDim,barGroup,rect,graphConfig);
if (!isSubClass){
graphConfig.svg.selectAll("polygon.arr").remove();
graphConfig.svg.select(".y.axis")
.selectAll("text")
.attr("dx","0")
.on("mouseover", function(d){
d3.select(this).style("cursor", "pointer");
d3.select(this).style("fill",config.color.yLabel.hover);
d3.select(this).style("text-decoration", "underline");
});
}
d3.select(graphConfig.html_div).selectAll("input").on("change", change);
function change() {
if (this.value === "grouped"){
dataGraph.transitionGrouped(graphConfig,subGraph,groups,rect);
} else {
dataGraph.transitionStacked(graphConfig,subGraph,groups,rect);
}
}
}
////////////////////////////////////////////////////////////////////
//
//Data object manipulation
//
//The functions below manipulate the data object for
//various functionality
//
//get X Axis limit for grouped configuration
bbop.monarch.datagraph.prototype.getGroupMax = function(data){
return d3.max(data, function(d) {
return d3.max(d.counts, function(d) { return d.value; });
});
}
//get X Axis limit for stacked configuration
bbop.monarch.datagraph.prototype.getStackMax = function(data){
return d3.max(data, function(d) {
return d3.max(d.counts, function(d) { return d.x1; });
});
}
//get largest Y axis label for font resizing
bbop.monarch.datagraph.prototype.getYMax = function(data){
return d3.max(data, function(d) {
return d.label.length;
});
}
bbop.monarch.datagraph.prototype.checkForSubGraphs = function(data){
for (i = 0;i < data.length; i++) {
if (Object.keys(data[i]).indexOf('subGraph') >= 0) {
return true;
}
}
return false;
}
bbop.monarch.datagraph.prototype.getStackedStats = function(data,groups){
//Add x0,x1 values for stacked barchart
data.forEach(function (r){
var count = 0;
r.counts.forEach(function (i){
i["x0"] = count;
i["x1"] = i.value+count;
if (i.value > 0){
count = i.value;
}
});
});
var lastElement = groups.length-1;
data.sort(function(obj1, obj2) {
if ((obj2.counts[lastElement])&&(obj1.counts[lastElement])){
return obj2.counts[lastElement].x1 - obj1.counts[lastElement].x1;
} else {
return 0;
}
});
return data;
}
bbop.monarch.datagraph.prototype.getGroups = function(data) {
var groups = [];
var unique = {};
for (var i=0, len=data.length; i<len; i++) {
for (var j=0, cLen=data[i].counts.length; j<cLen; j++) {
unique[ data[i].counts[j].name ] =1;
}
}
groups = Object.keys(unique);
return groups;
},
//remove zero length bars
bbop.monarch.datagraph.prototype.removeZeroCounts = function(data){
trimmedGraph = [];
data.forEach(function (r){
var count = 0;
r.counts.forEach(function (i){
count += i.value;
});
if (count > 0){
trimmedGraph.push(r);
}
});
return trimmedGraph;
}
bbop.monarch.datagraph.prototype.addEllipsisToLabel = function(data,max){
var reg = new RegExp("(.{"+max+"})(.+)");
data.forEach(function (r){
if (r.label.length > max){
r.fullLabel = r.label;
r.label = r.label.replace(reg,"$1...");
}
});
return data;
}
bbop.monarch.datagraph.prototype.getFullLabel = function (d,data){
for (var i=0, len=data.length; i < len; i++){
if (data[i].label === d){
var fullLabel = data[i].fullLabel;
return fullLabel;
break;
}
}
}
bbop.monarch.datagraph.prototype.getGroupID = function (d,data){
for (var i=0, len=data.length; i < len; i++){
if (data[i].label === d){
monarchID = data[i].id;
return monarchID;
break;
}
}
}
////////////////////////////////////////////////////////////////////
//End data object functions
////////////////////////////////////////////////////////////////////
//Log given base x
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
//Adjust Y label font, arrow size, and spacing
//when transitioning
//this is getting funky with graph resizing, maybe should do away
bbop.monarch.datagraph.prototype.adjustYAxisElements = function(len){
var conf = this.config;
var h = conf.height;
var density = h/len;
var isUpdated = false;
yFont = conf.yFontSize;
var yOffset = conf.yOffset;
var arrowDim = conf.arrowDim;
//Check for density BETA
if (density < 15 && density < yFont ){
yFont = density+2;
//yOffset = "-2em";
//arrowDim = "-20,-3, -11,1 -20,5";
isUpdated = true;
}
if (isUpdated && yFont > conf.yFontSize){
yFont = conf.yFontSize;
}
var retList = [yFont,yOffset,arrowDim];
return retList;
}
///////////////////////////////////
//Setters for sizing configurations
bbop.monarch.datagraph.prototype.setWidth = function(w){
this.config.width = w;
}
bbop.monarch.datagraph.prototype.setHeight = function(h){
this.config.height = h;
}
bbop.monarch.datagraph.prototype.setYFontSize = function(fSize){
this.config.yFontSize = fSize;
}
bbop.monarch.datagraph.prototype.setxFontSize = function(fSize){
this.config.xFontSize = fSize;
}
bbop.monarch.datagraph.prototype.setXLabelFontSize = function(fSize){
this.config.xLabelFontSize = fSize;
}
bbop.monarch.datagraph.prototype.setXAxisPos = function(w,h){
this.config.xAxisPos = {dx:w,y:h};
}
//The starting index (0 or 1) for the x axis seems to be
//dependent on browser version, for now always return 1
//Firefox <33 should be 0
bbop.monarch.datagraph.prototype.getXFirstIndex = function (){
//Check browser
var isOpera = (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0);
var isChrome = (!!window.chrome && !(!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0));
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
if (isChrome || isSafari){
return 1;
} else {
return 1;
}
}
//datagraph default SVG Coordinates
bbop.monarch.datagraph.prototype.setPolygonCoordinates = function(){
//Nav arrow (now triangle)
if (this.config.arrowDim == null || typeof this.config.arrowDim == 'undefined'){
this.config.arrowDim = "-23,-6, -12,0 -23,6";
}
//Breadcrumb dimensions
if (this.config.firstCr == null || typeof this.config.firstCr == 'undefined'){
this.config.firstCr = "0,0 0,30 90,30 105,15 90,0";
}
if (this.config.trailCrumbs == null || typeof this.config.trailCrumbs == 'undefined'){
this.config.trailCrumbs = "0,0 15,15 0,30 90,30 105,15 90,0";
}
//Polygon dimensions
if (this.config.bread == null || typeof this.config.bread == 'undefined'){
this.config.bread = {width:105, height: 30, offset:90, space: 1};
}
//breadcrumb div dimensions
this.config.bcWidth = 560;
//Y axis positioning when arrow present
if (this.config.yOffset == null || typeof this.config.yOffset == 'undefined'){
this.config.yOffset = "-1.48em";
}
//Check that breadcrumb width is valid
if (this.config.bcWidth > this.config.width+this.config.margin.right+this.config.margin.left){
this.config.bcWidth = this.config.bread.width+(this.config.bread.offset*5)+5;
}
}
//datagraph default configurations
bbop.monarch.datagraph.prototype.getDefaultConfig = function(){
var defaultConfiguration = {
//Chart margins
margin : {top: 40, right: 140, bottom: 5, left: 255},
width : 375,
height : 400,
//X Axis Label
xAxisLabel : "Some Metric",
xLabelFontSize : "14px",
xFontSize : "14px",
xAxisPos : {dx:"20em",y:"-29"},
//Chart title and first breadcrumb
chartTitle : "Chart Title",
firstCrumb : "first bread crumb",
//Title size/font settings
title : {
'text-align': 'center',
'text-indent' : '0px',
'font-size' : '20px',
'font-weight': 'bold',
'background-color' : '#E8E8E8',
'border-bottom-color' : '#000000'
},
//Yaxis links
yFontSize : 'default',
isYLabelURL : true,
yLabelBaseURL : "/phenotype/",
//Font sizes
settingsFontSize : '14px',
//Maximum label length before adding an ellipse
maxLabelSize : 31,
//Turn on/off legend
useLegend : true,
//Fontsize
legendFontSize : 14,
//Legend dimensions
legend : {width:18,height:18},
legendText : {height:".35em"},
//Colors set in the order they appear in the JSON object
color : {
first : '#44A293',
second : '#A4D6D4',
third : '#EA763B',
fourth : '#496265',
fifth : '#44A293',
sixth : '#A4D6D4',
yLabel : {
fill : '#000000',
hover : '#EA763B'
},
arrow : {
fill : "#496265",
hover : "#EA763B"
},
bar : {
fill : '#EA763B'
},
crumb : {
top : '#496265',
bottom: '#3D6FB7',
hover : '#EA763B'
},
crumbText : '#FFFFFF'
},
//Turn on/off breadcrumbs
useCrumb : false,
crumbFontSize : 10,
//Turn on/off breadcrumb shapes
useCrumbShape : true
};
return defaultConfiguration;
} | datagraph refactor transition/grouped transitions | widgets/datagraph/js/datagraph.js | datagraph refactor transition/grouped transitions | <ide><path>idgets/datagraph/js/datagraph.js
<ide> .attr("height", graphConfig.y0.rangeBand())
<ide> .attr("y", function(d) { return graphConfig.y1(d.name); })
<ide>
<del> rect.on("mouseover", function(d){
<del>
<del> d3.select(this)
<add> rect.on("mouseover", function(d){
<add>
<add> d3.select(this)
<ide> .style("fill", config.color.bar.fill);
<ide> dataGraph.displayCountTip(graphConfig.tooltip,d.value,d.name,this,'stacked');
<del> })
<del> .on("mouseout", function(){
<del> graphConfig.tooltip.style("display", "none");
<del> d3.select(this)
<del> .style("fill", function(d) { return graphConfig.color(d.name); });
<del> })
<add> })
<add> .on("mouseout", function(){
<add> graphConfig.tooltip.style("display", "none");
<add> d3.select(this)
<add> .style("fill", function(d) { return graphConfig.color(d.name); });
<add> })
<ide> }
<ide>
<ide> bbop.monarch.datagraph.prototype.drawGraph = function (data,graphConfig) {
<ide> }
<ide>
<ide> //Dynamically decrease font size for large labels
<del> var confList = dataGraph.adjustYAxisElements(data.length);
<del> var yFont = confList[0];
<del> var yLabelPos = confList[1];
<del> var triangleDim = confList[2];
<add> var yFont = dataGraph.adjustYAxisElements(data.length);
<ide>
<ide> //Set x axis ticks
<ide> var xTicks = svg.append("g")
<ide> }
<ide> })
<ide> .style("text-anchor", "end")
<del> .attr("dx", yLabelPos);
<add> .attr("dx", config.yOffset);
<ide>
<ide> //Create SVG:G element that holds groups
<ide> var barGroup = dataGraph.setGroupPositioning(graphConfig,data);
<ide>
<ide> //Create navigation arrow
<ide> var navigate = svg.selectAll(".y.axis");
<del> dataGraph.makeNavArrow(data,navigate,triangleDim,
<add> dataGraph.makeNavArrow(data,navigate,config.arrowDim,
<ide> barGroup,rect,graphConfig);
<ide> //Create legend
<ide> if (config.useLegend){
<ide> } else {
<ide> dataGraph.transitionStacked(graphConfig,data,groups,rect);
<ide> }
<del> }
<del>
<del> function transitionGrouped() {
<del>
<del> dataGraph.setXYDomains(graphConfig,data,groups,'grouped');
<del>
<del> var xTransition = svg.transition().duration(750);
<del> xTransition.select(".x.axis").call(xAxis);
<del>
<del> rect.transition()
<del> .duration(500)
<del> .delay(function(d, i) { return i * 10; })
<del> .attr("height", y1.rangeBand())
<del> .attr("y", function(d) { return y1(d.name); })
<del> .transition()
<del> .attr("x", function(){if (config.isChrome || config.isSafari) {return 1;}else{ return 0;}})
<del> .attr("width", function(d) { return x(d.value); })
<del>
<del> rect.on("mouseover", function(d){
<del>
<del> d3.select(this)
<del> .style("fill", config.color.bar.fill);
<del> dataGraph.displayCountTip(tooltip,d.value,d.name,this,'grouped');
<del> })
<del> .on("mouseout", function(){
<del> tooltip.style("display", "none")
<del> d3.select(this)
<del> .style("fill", function(d) { return color(d.name); });
<del> })
<del> }
<del>
<del> function transitionStacked() {
<del>
<del> dataGraph.setXYDomains(graphConfig,data,groups,'stacked');
<del>
<del> var t = svg.transition().duration(750);
<del> t.select(".x.axis").call(xAxis);
<del>
<del> rect.transition()
<del> .duration(500)
<del> .delay(function(d, i) { return i * 10; })
<del> .attr("x", function(d){
<del> if (d.x0 == 0){
<del> if (config.isChrome || config.isSafari){return 1;}
<del> else {return d.x0;}
<del> } else {
<del> return x(d.x0);
<del> }
<del> })
<del> .attr("width", function(d) { return x(d.x1) - x(d.x0); })
<del> .transition()
<del> .attr("height", y0.rangeBand())
<del> .attr("y", function(d) { return y1(d.name); })
<del>
<del> rect.on("mouseover", function(d){
<del>
<del> d3.select(this)
<del> .style("fill", config.color.bar.fill);
<del> dataGraph.displayCountTip(tooltip,d.value,d.name,this,'stacked');
<del> })
<del> .on("mouseout", function(){
<del> tooltip.style("display", "none");
<del> d3.select(this)
<del> .style("fill", function(d) { return color(d.name); });
<del> })
<ide> }
<ide> }
<ide>
<ide> var xStackMax = dataGraph.getStackMax(subGraph);
<ide>
<ide> //Dynamically decrease font size for large labels
<del> var confList = dataGraph.adjustYAxisElements(subGraph.length);
<del> var yFont = confList[0];
<del> var yLabelPos = confList[1];
<del> var triangleDim = confList[2];
<del>
<add> var yFont = dataGraph.adjustYAxisElements(subGraph.length);
<ide>
<ide> var yTransition = graphConfig.svg.transition().duration(1000);
<ide> yTransition.select(".y.axis").call(graphConfig.yAxis);
<ide> }
<ide> })
<ide> .style("text-anchor", "end")
<del> .attr("dx", yLabelPos);
<add> .attr("dx", config.yOffset);
<ide>
<ide> var barGroup = dataGraph.setGroupPositioning(graphConfig,subGraph);
<ide>
<ide>
<ide> var navigate = graphConfig.svg.selectAll(".y.axis");
<ide> var isSubClass = dataGraph.makeNavArrow(subGraph,navigate,
<del> triangleDim,barGroup,rect,graphConfig);
<add> config.arrowDim,barGroup,rect,graphConfig);
<ide>
<ide> if (!isSubClass){
<ide> graphConfig.svg.selectAll("polygon.arr").remove();
<ide> if (isUpdated && yFont > conf.yFontSize){
<ide> yFont = conf.yFontSize;
<ide> }
<del>
<del> var retList = [yFont,yOffset,arrowDim];
<del> return retList;
<add> return yFont;
<ide> }
<ide> ///////////////////////////////////
<ide> //Setters for sizing configurations |
|
JavaScript | apache-2.0 | e95f331c95326e79b59affcd2157eba011614862 | 0 | Kegsay/github-pull-review,Kegsay/github-pull-review,Kegsay/github-pull-review | "use strict";
var Comment = require("./models/comment");
var User = require("./models/user");
var Commit = require("./models/commit");
var FileDiff = require("./models/file-diff");
var Patch = require("./models/patch");
var Ref = require("./models/ref");
var Repo = require("./models/repo");
var LineComment = require("./models/line-comment");
function toComment(obj) {
var usr = getUserFromGithubApi(obj.user);
return new Comment(
obj.id, usr, obj.body, new Date(obj.created_at), obj.html_url
);
}
function toCommit(obj) {
var author = obj.author;
if (!obj.author) {
author = {
login: `${obj.commit.author.name} <${obj.commit.author.email}>`,
avatar_url: "https://assets-cdn.github.com/images/gravatars/gravatar-user-420.png?ssl=1",
html_url: null
};
}
return new Commit(
obj.sha,
obj.commit.message,
new Date(obj.commit.author.date),
obj.html_url,
getUserFromGithubApi(author)
);
}
function getUserFromGithubApi(obj) {
return new User(
obj.login, obj.avatar_url, obj.html_url
);
}
module.exports.getCommentsFromGithubApi = function(apiComments, apiData) {
var comments = apiComments.map(function(apiComment) {
return toComment(apiComment);
});
if (apiData) {
// PR has a starting comment; wodge with the rest
comments.unshift(toComment(apiData));
}
return comments;
};
module.exports.getCommitsFromGithubApi = function(apiCommits, apiData) {
// apiCommits is an array of objects (age order, last = newest) with keys like:
// .sha => commit hash
// .html_url => HTML url for this commit
// .commit.message => commit message
// .commit.author.[name/email/date] => stuff from git config
// .author.[login/avatar_url] => the github user
// .committer.[login/avatar_url] => the github user
// latest commit is apiData.head.sha
// base commit (when branched) is apiData.base.sha
return {
head: apiData.head.sha,
base: apiData.base.sha,
commits: apiCommits.map(function(c) {
return toCommit(c);
})
};
};
module.exports.getCommitDiffsFromGithubApi = function(apiCommitDiffs) {
// the /compare endpoint also has other guff like the commits made but for
// diffing purposes we don't give a damn.
return module.exports.getDiffsFromGithubApi(apiCommitDiffs.files);
};
module.exports.getDiffsFromGithubApi = function(apiDiffs) {
// apiDiffs is an array of objects (files, no real order) with keys like:
// .filename => Path to the file from root
// .status => enum[renamed|modified|added] (deleted too?)
// .additions => Number of lines added
// .deletions => Number of lines removed
// .changes => Number of lines changed (== additions for new files)
// .patch => patch string to apply to the file
// .previous_filename => Previous file name if any.
// .blob_url => link to the file at this commit
// .sha => SHA for...?
return apiDiffs.map(function(diff) {
return new FileDiff(
diff.filename,
diff.status,
diff.patch,
{
additions: diff.additions,
deletions: diff.deletions,
changes: diff.changes
},
diff.previous_filename,
diff.blob_url
);
});
};
module.exports.getLineCommentsFromGithubApi = function(apiLineComments) {
// apiLineComments is an array of objects (age order, last = newest) with
// keys like:
// .id => Line comment ID
// .html_url => HTML url for this comment
// .diff_hunk => multi-line string with the diff (last line being the comment line)
// .path => Path from root to the file being commented on
// .user.[login/avatar_url] => the github user making the comment
// .body => Comment body
// .original_commit_id => The commit sha when this comment was made.
// .commit_id => The HEAD commit for this PR (same for all comments)
// .original_position => The line index in the diff where the comment was made. (0 indexed)
return apiLineComments.map(function(lineComment) {
return new LineComment(
lineComment.path,
toComment(lineComment),
lineComment.original_position,
lineComment.original_commit_id,
new Patch(lineComment.diff_hunk)
);
});
}
module.exports.getUserFromGithubApi = getUserFromGithubApi;
function getRepoFromGithubApi(apiRepo) {
return new Repo(apiRepo.clone_url);
}
module.exports.getRepoFromGithubApi = getRepoFromGithubApi;
module.exports.getRefFromGithubApi = function(apiRef) {
return new Ref(
getRepoFromGithubApi(apiRef.repo),
getUserFromGithubApi(apiRef.user),
apiRef.label,
apiRef.sha,
apiRef.ref
);
};
| lib/logic/api-mapper.js | "use strict";
var Comment = require("./models/comment");
var User = require("./models/user");
var Commit = require("./models/commit");
var FileDiff = require("./models/file-diff");
var Patch = require("./models/patch");
var Ref = require("./models/ref");
var Repo = require("./models/repo");
var LineComment = require("./models/line-comment");
function toComment(obj) {
var usr = getUserFromGithubApi(obj.user);
return new Comment(
obj.id, usr, obj.body, new Date(obj.created_at), obj.html_url
);
}
function toCommit(obj) {
var author = obj.author;
if (!obj.author) {
author = {
login: `${obj.commit.author.name} <${obj.commit.author.email}>`,
avatar_url: "https://i2.wp.com/assets-cdn.github.com/images/gravatars/gravatar-user-420.png?ssl=1",
html_url: null
};
}
return new Commit(
obj.sha,
obj.commit.message,
new Date(obj.commit.author.date),
obj.html_url,
getUserFromGithubApi(author)
);
}
function getUserFromGithubApi(obj) {
return new User(
obj.login, obj.avatar_url, obj.html_url
);
}
module.exports.getCommentsFromGithubApi = function(apiComments, apiData) {
var comments = apiComments.map(function(apiComment) {
return toComment(apiComment);
});
if (apiData) {
// PR has a starting comment; wodge with the rest
comments.unshift(toComment(apiData));
}
return comments;
};
module.exports.getCommitsFromGithubApi = function(apiCommits, apiData) {
// apiCommits is an array of objects (age order, last = newest) with keys like:
// .sha => commit hash
// .html_url => HTML url for this commit
// .commit.message => commit message
// .commit.author.[name/email/date] => stuff from git config
// .author.[login/avatar_url] => the github user
// .committer.[login/avatar_url] => the github user
// latest commit is apiData.head.sha
// base commit (when branched) is apiData.base.sha
return {
head: apiData.head.sha,
base: apiData.base.sha,
commits: apiCommits.map(function(c) {
return toCommit(c);
})
};
};
module.exports.getCommitDiffsFromGithubApi = function(apiCommitDiffs) {
// the /compare endpoint also has other guff like the commits made but for
// diffing purposes we don't give a damn.
return module.exports.getDiffsFromGithubApi(apiCommitDiffs.files);
};
module.exports.getDiffsFromGithubApi = function(apiDiffs) {
// apiDiffs is an array of objects (files, no real order) with keys like:
// .filename => Path to the file from root
// .status => enum[renamed|modified|added] (deleted too?)
// .additions => Number of lines added
// .deletions => Number of lines removed
// .changes => Number of lines changed (== additions for new files)
// .patch => patch string to apply to the file
// .previous_filename => Previous file name if any.
// .blob_url => link to the file at this commit
// .sha => SHA for...?
return apiDiffs.map(function(diff) {
return new FileDiff(
diff.filename,
diff.status,
diff.patch,
{
additions: diff.additions,
deletions: diff.deletions,
changes: diff.changes
},
diff.previous_filename,
diff.blob_url
);
});
};
module.exports.getLineCommentsFromGithubApi = function(apiLineComments) {
// apiLineComments is an array of objects (age order, last = newest) with
// keys like:
// .id => Line comment ID
// .html_url => HTML url for this comment
// .diff_hunk => multi-line string with the diff (last line being the comment line)
// .path => Path from root to the file being commented on
// .user.[login/avatar_url] => the github user making the comment
// .body => Comment body
// .original_commit_id => The commit sha when this comment was made.
// .commit_id => The HEAD commit for this PR (same for all comments)
// .original_position => The line index in the diff where the comment was made. (0 indexed)
return apiLineComments.map(function(lineComment) {
return new LineComment(
lineComment.path,
toComment(lineComment),
lineComment.original_position,
lineComment.original_commit_id,
new Patch(lineComment.diff_hunk)
);
});
}
module.exports.getUserFromGithubApi = getUserFromGithubApi;
function getRepoFromGithubApi(apiRepo) {
return new Repo(apiRepo.clone_url);
}
module.exports.getRepoFromGithubApi = getRepoFromGithubApi;
module.exports.getRefFromGithubApi = function(apiRef) {
return new Ref(
getRepoFromGithubApi(apiRef.repo),
getUserFromGithubApi(apiRef.user),
apiRef.label,
apiRef.sha,
apiRef.ref
);
};
| Use a slightly more sane URL
| lib/logic/api-mapper.js | Use a slightly more sane URL | <ide><path>ib/logic/api-mapper.js
<ide> if (!obj.author) {
<ide> author = {
<ide> login: `${obj.commit.author.name} <${obj.commit.author.email}>`,
<del> avatar_url: "https://i2.wp.com/assets-cdn.github.com/images/gravatars/gravatar-user-420.png?ssl=1",
<add> avatar_url: "https://assets-cdn.github.com/images/gravatars/gravatar-user-420.png?ssl=1",
<ide> html_url: null
<ide> };
<ide> } |
|
Java | lgpl-2.1 | 06eeb75ded9096b14f73c5a8c046b760276b0a92 | 0 | RemiKoutcherawy/exist,opax/exist,patczar/exist,zwobit/exist,joewiz/exist,ambs/exist,dizzzz/exist,hungerburg/exist,zwobit/exist,windauer/exist,zwobit/exist,zwobit/exist,kohsah/exist,wshager/exist,adamretter/exist,wshager/exist,windauer/exist,jensopetersen/exist,wshager/exist,jessealama/exist,eXist-db/exist,olvidalo/exist,dizzzz/exist,jessealama/exist,ambs/exist,dizzzz/exist,adamretter/exist,lcahlander/exist,patczar/exist,kohsah/exist,hungerburg/exist,joewiz/exist,shabanovd/exist,olvidalo/exist,joewiz/exist,opax/exist,RemiKoutcherawy/exist,joewiz/exist,eXist-db/exist,hungerburg/exist,lcahlander/exist,jensopetersen/exist,MjAbuz/exist,kohsah/exist,eXist-db/exist,jessealama/exist,opax/exist,ambs/exist,kohsah/exist,MjAbuz/exist,kohsah/exist,lcahlander/exist,wshager/exist,patczar/exist,eXist-db/exist,hungerburg/exist,wolfgangmm/exist,shabanovd/exist,ljo/exist,opax/exist,dizzzz/exist,jessealama/exist,RemiKoutcherawy/exist,ambs/exist,adamretter/exist,wolfgangmm/exist,eXist-db/exist,olvidalo/exist,ljo/exist,windauer/exist,patczar/exist,jessealama/exist,RemiKoutcherawy/exist,wolfgangmm/exist,ambs/exist,wolfgangmm/exist,kohsah/exist,adamretter/exist,lcahlander/exist,ambs/exist,adamretter/exist,jensopetersen/exist,olvidalo/exist,dizzzz/exist,wolfgangmm/exist,RemiKoutcherawy/exist,wolfgangmm/exist,MjAbuz/exist,RemiKoutcherawy/exist,patczar/exist,jessealama/exist,adamretter/exist,joewiz/exist,jensopetersen/exist,jensopetersen/exist,wshager/exist,olvidalo/exist,jensopetersen/exist,opax/exist,zwobit/exist,MjAbuz/exist,ljo/exist,shabanovd/exist,windauer/exist,wshager/exist,windauer/exist,shabanovd/exist,joewiz/exist,patczar/exist,ljo/exist,dizzzz/exist,hungerburg/exist,windauer/exist,zwobit/exist,lcahlander/exist,ljo/exist,ljo/exist,shabanovd/exist,MjAbuz/exist,MjAbuz/exist,shabanovd/exist,lcahlander/exist,eXist-db/exist | /*
* eXist Open Source Native XML Database
* Copyright (C) 2000-04, Wolfgang M. Meier ([email protected])
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id$
*/
package org.exist.xquery;
import java.util.Iterator;
import org.exist.dom.DocumentImpl;
import org.exist.dom.DocumentSet;
import org.exist.dom.ExtArrayNodeSet;
import org.exist.dom.NodeImpl;
import org.exist.dom.NodeProxy;
import org.exist.dom.NodeSet;
import org.exist.dom.NodeSetHelper;
import org.exist.dom.NodeVisitor;
import org.exist.dom.StoredNode;
import org.exist.dom.VirtualNodeSet;
import org.exist.numbering.NodeId;
import org.exist.storage.ElementIndex;
import org.exist.storage.ElementValue;
import org.exist.storage.NotificationService;
import org.exist.storage.UpdateListener;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
import org.w3c.dom.Node;
/**
* Processes all location path steps (like descendant::*, ancestor::XXX).
*
* The results of the first evaluation of the expression are cached for the
* lifetime of the object and only reloaded if the context sequence (as passed
* to the {@link #eval(Sequence, Item)} method) has changed.
*
* @author wolf
*/
public class LocationStep extends Step {
private final int ATTR_DIRECT_SELECT_THRESHOLD = 3;
protected NodeSet currentSet = null;
protected DocumentSet currentDocs = null;
protected UpdateListener listener = null;
protected Expression parent = null;
// Fields for caching the last result
protected CachedResult cached = null;
protected int parentDeps = Dependency.UNKNOWN_DEPENDENCY;
protected boolean preload = false;
protected boolean inUpdate = false;
// Cache for the current NodeTest type
private Integer nodeTestType = null;
public LocationStep(XQueryContext context, int axis) {
super(context, axis);
}
public LocationStep(XQueryContext context, int axis, NodeTest test) {
super(context, axis, test);
}
/*
* (non-Javadoc)
*
* @see org.exist.xquery.AbstractExpression#getDependencies()
*/
public int getDependencies() {
int deps = Dependency.CONTEXT_SET;
for (Iterator i = predicates.iterator(); i.hasNext();) {
deps |= ((Predicate) i.next()).getDependencies();
}
return deps;
}
/**
* If the current path expression depends on local variables from a for
* expression, we can optimize by preloading entire element or attribute
* sets.
*
* @return
*/
protected boolean preloadNodeSets() {
// TODO : log elsewhere ?
if (preload) {
context.getProfiler().message(this, Profiler.OPTIMIZATIONS, null,
"Preloaded NodeSets");
return true;
}
if (inUpdate)
return false;
if ((parentDeps & Dependency.LOCAL_VARS) == Dependency.LOCAL_VARS) {
context.getProfiler().message(this, Profiler.OPTIMIZATIONS, null,
"Preloaded NodeSets");
return true;
}
return false;
}
protected Sequence applyPredicate(Sequence outerSequence,
Sequence contextSequence) throws XPathException {
if (contextSequence == null)
return Sequence.EMPTY_SEQUENCE;
if (predicates.size() == 0)
// Nothing to apply
return contextSequence;
Predicate pred;
Sequence result = contextSequence;
for (Iterator i = predicates.iterator(); i.hasNext();) {
// TODO : log and/or profile ?
pred = (Predicate) i.next();
pred.setContextDocSet(getContextDocSet());
result = pred.evalPredicate(outerSequence, result, axis);
}
return result;
}
/*
* (non-Javadoc)
*
* @see org.exist.xquery.Step#analyze(org.exist.xquery.Expression)
*/
public void analyze(AnalyzeContextInfo contextInfo) throws XPathException {
this.parent = contextInfo.getParent();
parentDeps = parent.getDependencies();
if ((contextInfo.getFlags() & IN_UPDATE) > 0)
inUpdate = true;
if ((contextInfo.getFlags() & SINGLE_STEP_EXECUTION) > 0) {
preload = true;
}
// TODO : log somewhere ?
super.analyze(contextInfo);
}
public Sequence eval(Sequence contextSequence, Item contextItem)
throws XPathException {
if (context.getProfiler().isEnabled()) {
context.getProfiler().start(this);
context.getProfiler().message(this, Profiler.DEPENDENCIES,
"DEPENDENCIES",
Dependency.getDependenciesName(this.getDependencies()));
if (contextSequence != null)
context.getProfiler().message(this, Profiler.START_SEQUENCES,
"CONTEXT SEQUENCE", contextSequence);
if (contextItem != null)
context.getProfiler().message(this, Profiler.START_SEQUENCES,
"CONTEXT ITEM", contextItem.toSequence());
}
Sequence result;
if (contextItem != null)
contextSequence = contextItem.toSequence();
/*
* if(contextSequence == null) //Commented because this the high level
* result nodeset is *really* null result = NodeSet.EMPTY_SET; //Try to
* return cached results else
*/if (cached != null && cached.isValid(contextSequence)) {
// WARNING : commented since predicates are *also* applied below !
// -pb
/*
* if (predicates.size() > 0) { applyPredicate(contextSequence,
* cached.getResult()); } else {
*/
result = cached.getResult();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"Using cached results", result);
// }
} else if (needsComputation()) {
if (contextSequence == null)
throw new XPathException(getASTNode(), "XPDY0002 : undefined context sequence for '" + this.toString() + "'");
switch (axis) {
case Constants.DESCENDANT_AXIS:
case Constants.DESCENDANT_SELF_AXIS:
result = getDescendants(context, contextSequence
.toNodeSet());
break;
case Constants.CHILD_AXIS:
result = getChildren(context, contextSequence.toNodeSet());
break;
case Constants.ANCESTOR_SELF_AXIS:
case Constants.ANCESTOR_AXIS:
result = getAncestors(context, contextSequence.toNodeSet());
break;
case Constants.PARENT_AXIS:
result = getParents(context, contextSequence.toNodeSet());
break;
case Constants.SELF_AXIS:
if (!(contextSequence instanceof VirtualNodeSet)
&& Type.subTypeOf(contextSequence.getItemType(),
Type.ATOMIC))
result = getSelfAtomic(contextSequence);
else
result = getSelf(context, contextSequence.toNodeSet());
break;
case Constants.ATTRIBUTE_AXIS:
case Constants.DESCENDANT_ATTRIBUTE_AXIS:
result = getAttributes(context, contextSequence.toNodeSet());
break;
case Constants.PRECEDING_AXIS:
result = getPreceding(context, contextSequence.toNodeSet());
break;
case Constants.FOLLOWING_AXIS:
result = getFollowing(context, contextSequence.toNodeSet());
break;
case Constants.PRECEDING_SIBLING_AXIS:
case Constants.FOLLOWING_SIBLING_AXIS:
result = getSiblings(context, contextSequence.toNodeSet());
break;
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
} else
result = NodeSet.EMPTY_SET;
// Caches the result
if (contextSequence instanceof NodeSet) {
// TODO : cache *after* removing duplicates ? -pb
cached = new CachedResult((NodeSet) contextSequence, result);
registerUpdateListener();
}
// Remove duplicate nodes
result.removeDuplicates();
// Apply the predicate
result = applyPredicate(contextSequence, result);
if (context.getProfiler().isEnabled())
context.getProfiler().end(this, "", result);
return result;
}
// Avoid unnecessary tests (these should be detected by the parser)
private boolean needsComputation() {
// TODO : log this ?
switch (axis) {
// Certainly not exhaustive
case Constants.ANCESTOR_SELF_AXIS:
case Constants.PARENT_AXIS:
case Constants.SELF_AXIS:
if (nodeTestType == null)
nodeTestType = new Integer(test.getType());
if (nodeTestType.intValue() != Type.NODE
&& nodeTestType.intValue() != Type.ELEMENT) {
if (context.getProfiler().isEnabled())
context.getProfiler().message(this,
Profiler.OPTIMIZATIONS, "OPTIMIZATION",
"avoid useless computations");
return false;
}
}
return true;
}
/**
* @param context
* @param contextSet
* @return
*/
protected Sequence getSelf(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
if (nodeTestType == null)
nodeTestType = new Integer(test.getType());
if (Type.subTypeOf(nodeTestType.intValue(), Type.NODE)) {
if (Expression.NO_CONTEXT_ID != contextId) {
if (contextSet instanceof VirtualNodeSet) {
((VirtualNodeSet) contextSet).setInPredicate(true);
((VirtualNodeSet) contextSet).setSelfIsContext();
((VirtualNodeSet) contextSet).setContextId(contextId);
} else if (Type.subTypeOf(contextSet.getItemType(),
Type.NODE)) {
NodeProxy p;
for (Iterator i = contextSet.iterator(); i.hasNext();) {
p = (NodeProxy) i.next();
if (test.matches(p))
p.addContextNode(contextId, p);
}
}
}
return contextSet;
} else {
VirtualNodeSet vset = new VirtualNodeSet(axis, test, contextId,
contextSet);
vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId);
return vset;
}
} else {
DocumentSet docs = getDocumentSet(contextSet);
NodeSelector selector = new SelfSelector(contextSet, contextId);
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
return index.findElementsByTagName(ElementValue.ELEMENT, docs, test
.getName(), selector);
}
}
protected Sequence getSelfAtomic(Sequence contextSequence)
throws XPathException {
if (!test.isWildcardTest())
throw new XPathException(getASTNode(), test.toString()
+ " cannot be applied to an atomic value.");
return contextSequence;
}
protected NodeSet getAttributes(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
NodeSet result = new VirtualNodeSet(axis, test, contextId,
contextSet);
((VirtualNodeSet) result)
.setInPredicate(Expression.NO_CONTEXT_ID != contextId);
return result;
// if there's just a single known node in the context, it is faster
// do directly search for the attribute in the parent node.
} else if (!(contextSet instanceof VirtualNodeSet)
&& axis == Constants.ATTRIBUTE_AXIS
&& contextSet.getLength() < ATTR_DIRECT_SELECT_THRESHOLD) {
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION", "direct attribute selection");
NodeProxy proxy = contextSet.get(0);
if (proxy != null
&& proxy.getInternalAddress() != NodeProxy.UNKNOWN_NODE_ADDRESS)
return contextSet.directSelectAttribute(test.getName(),
contextId);
}
if (contextSet instanceof VirtualNodeSet)
((VirtualNodeSet)contextSet).setNodeTest(test);
if (preloadNodeSets()) {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
// TODO : why a null selector here ? We have one below !
currentSet = index.findElementsByTagName(
ElementValue.ATTRIBUTE, docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
switch (axis) {
case Constants.ATTRIBUTE_AXIS:
return currentSet.selectParentChild(contextSet,
NodeSet.DESCENDANT, contextId);
case Constants.DESCENDANT_ATTRIBUTE_AXIS:
return currentSet.selectAncestorDescendant(contextSet,
NodeSet.DESCENDANT, false, contextId);
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
} else {
NodeSelector selector;
DocumentSet docs = getDocumentSet(contextSet);
// TODO : why a selector here ? We havn't one above !
switch (axis) {
case Constants.ATTRIBUTE_AXIS:
selector = new ChildSelector(contextSet, contextId);
break;
case Constants.DESCENDANT_ATTRIBUTE_AXIS:
selector = new DescendantSelector(contextSet, contextId);
break;
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
return index.getAttributesByName(docs, test.getName(), selector);
}
}
protected NodeSet getChildren(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
// test is one out of *, text(), node()
VirtualNodeSet vset = new VirtualNodeSet(axis, test, contextId,
contextSet);
vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId);
return vset;
} else if (preloadNodeSets()) {
DocumentSet docs = getDocumentSet(contextSet);
// TODO : understand why this one is different from the other ones
if (currentSet == null || currentDocs == null
|| !(docs == currentDocs || docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
return currentSet.selectParentChild(contextSet, NodeSet.DESCENDANT,
contextId);
} else {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
DocumentSet docs = getDocumentSet(contextSet);
NodeSelector selector = new ChildSelector(contextSet, contextId);
return index.findElementsByTagName(ElementValue.ELEMENT, docs, test
.getName(), selector);
}
}
protected NodeSet getDescendants(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
// test is one out of *, text(), node()
VirtualNodeSet vset = new VirtualNodeSet(axis, test, contextId,
contextSet);
vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId);
return vset;
} else if (preloadNodeSets()) {
DocumentSet docs = getDocumentSet(contextSet);
// TODO : understand why this one is different from the other ones
if (currentSet == null || currentDocs == null
|| !(docs == currentDocs || docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
switch (axis) {
case Constants.DESCENDANT_SELF_AXIS:
return currentSet.selectAncestorDescendant(contextSet,
NodeSet.DESCENDANT, true, contextId);
case Constants.DESCENDANT_AXIS:
return currentSet.selectAncestorDescendant(contextSet,
NodeSet.DESCENDANT, false, contextId);
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
} else {
NodeSelector selector;
DocumentSet docs = contextSet.getDocumentSet();
switch (axis) {
case Constants.DESCENDANT_SELF_AXIS:
selector = new DescendantOrSelfSelector(contextSet,
contextId);
break;
case Constants.DESCENDANT_AXIS:
selector = new DescendantSelector(contextSet, contextId);
break;
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
return index.findElementsByTagName(ElementValue.ELEMENT, docs, test
.getName(), selector);
}
}
protected NodeSet getSiblings(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
NodeSet result = new ExtArrayNodeSet(contextSet.getLength());
SiblingVisitor visitor = new SiblingVisitor(result);
for (Iterator i = contextSet.iterator(); i.hasNext();) {
NodeProxy current = (NodeProxy) i.next();
NodeId parentId = current.getNodeId().getParentId();
StoredNode parentNode = (StoredNode) context.getBroker().objectWith(current.getOwnerDocument(), parentId);
visitor.setContext(current);
parentNode.accept(visitor);
}
return result;
} else {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
switch (axis) {
case Constants.PRECEDING_SIBLING_AXIS:
return currentSet.selectPrecedingSiblings(contextSet, contextId);
case Constants.FOLLOWING_SIBLING_AXIS:
return currentSet.selectFollowingSiblings(contextSet, contextId);
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
}
}
private class SiblingVisitor implements NodeVisitor {
private NodeSet resultSet;
private NodeProxy contextNode;
public SiblingVisitor(NodeSet resultSet) {
this.resultSet = resultSet;
}
public void setContext(NodeProxy contextNode) {
this.contextNode = contextNode;
}
public boolean visit(StoredNode current) {
if (contextNode.getNodeId().getTreeLevel() == current.getNodeId().getTreeLevel()) {
int cmp = current.getNodeId().compareTo(contextNode.getNodeId());
if (((axis == Constants.FOLLOWING_SIBLING_AXIS && cmp > 0) ||
(axis == Constants.PRECEDING_SIBLING_AXIS && cmp < 0)) &&
test.matches(current)) {
NodeProxy sibling = resultSet.get((DocumentImpl) current.getOwnerDocument(), current.getNodeId());
if (sibling == null) {
sibling = new NodeProxy((DocumentImpl) current.getOwnerDocument(), current.getNodeId(),
current.getInternalAddress());
if (Expression.NO_CONTEXT_ID != contextId) {
sibling.addContextNode(contextId, contextNode);
} else
sibling.copyContext(contextNode);
resultSet.add(sibling);
} else if (Expression.NO_CONTEXT_ID != contextId)
sibling.addContextNode(contextId, contextNode);
}
}
return true;
}
}
protected NodeSet getPreceding(XQueryContext context, NodeSet contextSet)
throws XPathException {
if (test.isWildcardTest()) {
// TODO : throw an exception here ! Don't let this pass through
return NodeSet.EMPTY_SET;
} else {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
return currentSet.selectPreceding(contextSet);
}
}
protected NodeSet getFollowing(XQueryContext context, NodeSet contextSet)
throws XPathException {
if (test.isWildcardTest()) {
// TODO : throw an exception here ! Don't let this pass through
return NodeSet.EMPTY_SET;
} else {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
return currentSet.selectFollowing(contextSet);
}
}
protected NodeSet getAncestors(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
NodeSet result = new ExtArrayNodeSet();
for (Iterator i = contextSet.iterator(); i.hasNext();) {
NodeProxy current = (NodeProxy) i.next();
NodeProxy ancestor;
if (axis == Constants.ANCESTOR_SELF_AXIS
&& test.matches(current)) {
ancestor = new NodeProxy(current.getDocument(), current.getNodeId(),
Node.ELEMENT_NODE, current.getInternalAddress());
NodeProxy t = result.get(ancestor);
if (t == null) {
if (Expression.NO_CONTEXT_ID != contextId)
ancestor.addContextNode(contextId, current);
else
ancestor.copyContext(current);
result.add(ancestor);
} else
t.addContextNode(contextId, current);
}
NodeId parentID = current.getNodeId().getParentId();
while (parentID != null) {
ancestor = new NodeProxy(current.getDocument(), parentID, Node.ELEMENT_NODE);
// Filter out the temporary nodes wrapper element
if (parentID != NodeId.DOCUMENT_NODE &&
!(parentID.getTreeLevel() == 1 && current.getDocument().getCollection().isTempCollection())) {
if (test.matches(ancestor)) {
NodeProxy t = result.get(ancestor);
if (t == null) {
if (Expression.NO_CONTEXT_ID != contextId)
ancestor.addContextNode(contextId, current);
else
ancestor.copyContext(current);
result.add(ancestor);
} else
t.addContextNode(contextId, current);
}
}
parentID = parentID.getParentId();
}
}
return result;
} else if (preloadNodeSets()) {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
switch (axis) {
case Constants.ANCESTOR_SELF_AXIS:
return currentSet.selectAncestors(contextSet, true,
contextId);
case Constants.ANCESTOR_AXIS:
return currentSet.selectAncestors(contextSet, false,
contextId);
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
} else {
NodeSelector selector;
DocumentSet docs = getDocumentSet(contextSet);
switch (axis) {
case Constants.ANCESTOR_SELF_AXIS:
selector = new AncestorSelector(contextSet, contextId, true);
break;
case Constants.ANCESTOR_AXIS:
selector = new AncestorSelector(contextSet, contextId,
false);
break;
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
return index.findElementsByTagName(ElementValue.ELEMENT, docs, test
.getName(), selector);
}
}
protected NodeSet getParents(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
NodeSet temp = contextSet.getParents(contextId);
NodeSet result = new ExtArrayNodeSet();
NodeProxy p;
for (Iterator i = temp.iterator(); i.hasNext(); ) {
p = (NodeProxy) i.next();
if (test.matches(p))
result.add(p);
}
return result;
} else if (preloadNodeSets()) {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
return contextSet.selectParentChild(currentSet, NodeSet.ANCESTOR);
} else {
DocumentSet docs = getDocumentSet(contextSet);
NodeSelector selector = new ParentSelector(contextSet, contextId);
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
return index.findElementsByTagName(ElementValue.ELEMENT, docs, test
.getName(), selector);
}
}
protected DocumentSet getDocumentSet(NodeSet contextSet) {
DocumentSet ds = getContextDocSet();
if (ds == null)
ds = contextSet.getDocumentSet();
return ds;
}
protected void registerUpdateListener() {
if (listener == null) {
listener = new UpdateListener() {
public void documentUpdated(DocumentImpl document, int event) {
if (event == UpdateListener.ADD) {
// clear all
currentDocs = null;
currentSet = null;
cached = null;
} else {
if (currentDocs != null
&& currentDocs.contains(document.getDocId())) {
currentDocs = null;
currentSet = null;
}
if (cached != null
&& cached.getResult().getDocumentSet()
.contains(document.getDocId()))
cached = null;
}
};
};
NotificationService service = context.getBroker().getBrokerPool()
.getNotificationService();
service.subscribe(listener);
}
}
protected void deregisterUpdateListener() {
if (listener != null) {
NotificationService service = context.getBroker().getBrokerPool()
.getNotificationService();
service.unsubscribe(listener);
}
}
/*
* (non-Javadoc)
*
* @see org.exist.xquery.Step#resetState()
*/
public void resetState() {
super.resetState();
currentSet = null;
currentDocs = null;
cached = null;
deregisterUpdateListener();
listener = null;
}
}
| src/org/exist/xquery/LocationStep.java | /*
* eXist Open Source Native XML Database
* Copyright (C) 2000-04, Wolfgang M. Meier ([email protected])
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id$
*/
package org.exist.xquery;
import java.util.Iterator;
import org.exist.dom.DocumentImpl;
import org.exist.dom.DocumentSet;
import org.exist.dom.ExtArrayNodeSet;
import org.exist.dom.NodeImpl;
import org.exist.dom.NodeProxy;
import org.exist.dom.NodeSet;
import org.exist.dom.NodeSetHelper;
import org.exist.dom.StoredNode;
import org.exist.dom.VirtualNodeSet;
import org.exist.numbering.NodeId;
import org.exist.storage.ElementIndex;
import org.exist.storage.ElementValue;
import org.exist.storage.NotificationService;
import org.exist.storage.UpdateListener;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.Type;
import org.w3c.dom.Node;
/**
* Processes all location path steps (like descendant::*, ancestor::XXX).
*
* The results of the first evaluation of the expression are cached for the
* lifetime of the object and only reloaded if the context sequence (as passed
* to the {@link #eval(Sequence, Item)} method) has changed.
*
* @author wolf
*/
public class LocationStep extends Step {
private final int ATTR_DIRECT_SELECT_THRESHOLD = 3;
protected NodeSet currentSet = null;
protected DocumentSet currentDocs = null;
protected UpdateListener listener = null;
protected Expression parent = null;
// Fields for caching the last result
protected CachedResult cached = null;
protected int parentDeps = Dependency.UNKNOWN_DEPENDENCY;
protected boolean preload = false;
protected boolean inUpdate = false;
// Cache for the current NodeTest type
private Integer nodeTestType = null;
public LocationStep(XQueryContext context, int axis) {
super(context, axis);
}
public LocationStep(XQueryContext context, int axis, NodeTest test) {
super(context, axis, test);
}
/*
* (non-Javadoc)
*
* @see org.exist.xquery.AbstractExpression#getDependencies()
*/
public int getDependencies() {
int deps = Dependency.CONTEXT_SET;
for (Iterator i = predicates.iterator(); i.hasNext();) {
deps |= ((Predicate) i.next()).getDependencies();
}
return deps;
}
/**
* If the current path expression depends on local variables from a for
* expression, we can optimize by preloading entire element or attribute
* sets.
*
* @return
*/
protected boolean preloadNodeSets() {
// TODO : log elsewhere ?
if (preload) {
context.getProfiler().message(this, Profiler.OPTIMIZATIONS, null,
"Preloaded NodeSets");
return true;
}
if (inUpdate)
return false;
if ((parentDeps & Dependency.LOCAL_VARS) == Dependency.LOCAL_VARS) {
context.getProfiler().message(this, Profiler.OPTIMIZATIONS, null,
"Preloaded NodeSets");
return true;
}
return false;
}
protected Sequence applyPredicate(Sequence outerSequence,
Sequence contextSequence) throws XPathException {
if (contextSequence == null)
return Sequence.EMPTY_SEQUENCE;
if (predicates.size() == 0)
// Nothing to apply
return contextSequence;
Predicate pred;
Sequence result = contextSequence;
for (Iterator i = predicates.iterator(); i.hasNext();) {
// TODO : log and/or profile ?
pred = (Predicate) i.next();
pred.setContextDocSet(getContextDocSet());
result = pred.evalPredicate(outerSequence, result, axis);
}
return result;
}
/*
* (non-Javadoc)
*
* @see org.exist.xquery.Step#analyze(org.exist.xquery.Expression)
*/
public void analyze(AnalyzeContextInfo contextInfo) throws XPathException {
this.parent = contextInfo.getParent();
parentDeps = parent.getDependencies();
if ((contextInfo.getFlags() & IN_UPDATE) > 0)
inUpdate = true;
if ((contextInfo.getFlags() & SINGLE_STEP_EXECUTION) > 0) {
preload = true;
}
// TODO : log somewhere ?
super.analyze(contextInfo);
}
public Sequence eval(Sequence contextSequence, Item contextItem)
throws XPathException {
if (context.getProfiler().isEnabled()) {
context.getProfiler().start(this);
context.getProfiler().message(this, Profiler.DEPENDENCIES,
"DEPENDENCIES",
Dependency.getDependenciesName(this.getDependencies()));
if (contextSequence != null)
context.getProfiler().message(this, Profiler.START_SEQUENCES,
"CONTEXT SEQUENCE", contextSequence);
if (contextItem != null)
context.getProfiler().message(this, Profiler.START_SEQUENCES,
"CONTEXT ITEM", contextItem.toSequence());
}
Sequence result;
if (contextItem != null)
contextSequence = contextItem.toSequence();
/*
* if(contextSequence == null) //Commented because this the high level
* result nodeset is *really* null result = NodeSet.EMPTY_SET; //Try to
* return cached results else
*/if (cached != null && cached.isValid(contextSequence)) {
// WARNING : commented since predicates are *also* applied below !
// -pb
/*
* if (predicates.size() > 0) { applyPredicate(contextSequence,
* cached.getResult()); } else {
*/
result = cached.getResult();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"Using cached results", result);
// }
} else if (needsComputation()) {
if (contextSequence == null)
throw new XPathException(getASTNode(), "XPDY0002 : undefined context sequence for '" + this.toString() + "'");
switch (axis) {
case Constants.DESCENDANT_AXIS:
case Constants.DESCENDANT_SELF_AXIS:
result = getDescendants(context, contextSequence
.toNodeSet());
break;
case Constants.CHILD_AXIS:
result = getChildren(context, contextSequence.toNodeSet());
break;
case Constants.ANCESTOR_SELF_AXIS:
case Constants.ANCESTOR_AXIS:
result = getAncestors(context, contextSequence.toNodeSet());
break;
case Constants.PARENT_AXIS:
result = getParents(context, contextSequence.toNodeSet());
break;
case Constants.SELF_AXIS:
if (!(contextSequence instanceof VirtualNodeSet)
&& Type.subTypeOf(contextSequence.getItemType(),
Type.ATOMIC))
result = getSelfAtomic(contextSequence);
else
result = getSelf(context, contextSequence.toNodeSet());
break;
case Constants.ATTRIBUTE_AXIS:
case Constants.DESCENDANT_ATTRIBUTE_AXIS:
result = getAttributes(context, contextSequence.toNodeSet());
break;
case Constants.PRECEDING_AXIS:
result = getPreceding(context, contextSequence.toNodeSet());
break;
case Constants.FOLLOWING_AXIS:
result = getFollowing(context, contextSequence.toNodeSet());
break;
case Constants.PRECEDING_SIBLING_AXIS:
case Constants.FOLLOWING_SIBLING_AXIS:
result = getSiblings(context, contextSequence.toNodeSet());
break;
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
} else
result = NodeSet.EMPTY_SET;
// Caches the result
if (contextSequence instanceof NodeSet) {
// TODO : cache *after* removing duplicates ? -pb
cached = new CachedResult((NodeSet) contextSequence, result);
registerUpdateListener();
}
// Remove duplicate nodes
result.removeDuplicates();
// Apply the predicate
result = applyPredicate(contextSequence, result);
if (context.getProfiler().isEnabled())
context.getProfiler().end(this, "", result);
return result;
}
// Avoid unnecessary tests (these should be detected by the parser)
private boolean needsComputation() {
// TODO : log this ?
switch (axis) {
// Certainly not exhaustive
case Constants.ANCESTOR_SELF_AXIS:
case Constants.PARENT_AXIS:
case Constants.SELF_AXIS:
if (nodeTestType == null)
nodeTestType = new Integer(test.getType());
if (nodeTestType.intValue() != Type.NODE
&& nodeTestType.intValue() != Type.ELEMENT) {
if (context.getProfiler().isEnabled())
context.getProfiler().message(this,
Profiler.OPTIMIZATIONS, "OPTIMIZATION",
"avoid useless computations");
return false;
}
}
return true;
}
/**
* @param context
* @param contextSet
* @return
*/
protected Sequence getSelf(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
if (nodeTestType == null)
nodeTestType = new Integer(test.getType());
if (Type.subTypeOf(nodeTestType.intValue(), Type.NODE)) {
if (Expression.NO_CONTEXT_ID != contextId) {
if (contextSet instanceof VirtualNodeSet) {
((VirtualNodeSet) contextSet).setInPredicate(true);
((VirtualNodeSet) contextSet).setSelfIsContext();
((VirtualNodeSet) contextSet).setContextId(contextId);
} else if (Type.subTypeOf(contextSet.getItemType(),
Type.NODE)) {
NodeProxy p;
for (Iterator i = contextSet.iterator(); i.hasNext();) {
p = (NodeProxy) i.next();
if (test.matches(p))
p.addContextNode(contextId, p);
}
}
}
return contextSet;
} else {
VirtualNodeSet vset = new VirtualNodeSet(axis, test, contextId,
contextSet);
vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId);
return vset;
}
} else {
DocumentSet docs = getDocumentSet(contextSet);
NodeSelector selector = new SelfSelector(contextSet, contextId);
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
return index.findElementsByTagName(ElementValue.ELEMENT, docs, test
.getName(), selector);
}
}
protected Sequence getSelfAtomic(Sequence contextSequence)
throws XPathException {
if (!test.isWildcardTest())
throw new XPathException(getASTNode(), test.toString()
+ " cannot be applied to an atomic value.");
return contextSequence;
}
protected NodeSet getAttributes(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
NodeSet result = new VirtualNodeSet(axis, test, contextId,
contextSet);
((VirtualNodeSet) result)
.setInPredicate(Expression.NO_CONTEXT_ID != contextId);
return result;
// if there's just a single known node in the context, it is faster
// do directly search for the attribute in the parent node.
} else if (!(contextSet instanceof VirtualNodeSet)
&& axis == Constants.ATTRIBUTE_AXIS
&& contextSet.getLength() < ATTR_DIRECT_SELECT_THRESHOLD) {
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION", "direct attribute selection");
NodeProxy proxy = contextSet.get(0);
if (proxy != null
&& proxy.getInternalAddress() != NodeProxy.UNKNOWN_NODE_ADDRESS)
return contextSet.directSelectAttribute(test.getName(),
contextId);
}
if (contextSet instanceof VirtualNodeSet)
((VirtualNodeSet)contextSet).setNodeTest(test);
if (preloadNodeSets()) {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
// TODO : why a null selector here ? We have one below !
currentSet = index.findElementsByTagName(
ElementValue.ATTRIBUTE, docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
switch (axis) {
case Constants.ATTRIBUTE_AXIS:
return currentSet.selectParentChild(contextSet,
NodeSet.DESCENDANT, contextId);
case Constants.DESCENDANT_ATTRIBUTE_AXIS:
return currentSet.selectAncestorDescendant(contextSet,
NodeSet.DESCENDANT, false, contextId);
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
} else {
NodeSelector selector;
DocumentSet docs = getDocumentSet(contextSet);
// TODO : why a selector here ? We havn't one above !
switch (axis) {
case Constants.ATTRIBUTE_AXIS:
selector = new ChildSelector(contextSet, contextId);
break;
case Constants.DESCENDANT_ATTRIBUTE_AXIS:
selector = new DescendantSelector(contextSet, contextId);
break;
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
return index.getAttributesByName(docs, test.getName(), selector);
}
}
protected NodeSet getChildren(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
// test is one out of *, text(), node()
VirtualNodeSet vset = new VirtualNodeSet(axis, test, contextId,
contextSet);
vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId);
return vset;
} else if (preloadNodeSets()) {
DocumentSet docs = getDocumentSet(contextSet);
// TODO : understand why this one is different from the other ones
if (currentSet == null || currentDocs == null
|| !(docs == currentDocs || docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
return currentSet.selectParentChild(contextSet, NodeSet.DESCENDANT,
contextId);
} else {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
DocumentSet docs = getDocumentSet(contextSet);
NodeSelector selector = new ChildSelector(contextSet, contextId);
return index.findElementsByTagName(ElementValue.ELEMENT, docs, test
.getName(), selector);
}
}
protected NodeSet getDescendants(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
// test is one out of *, text(), node()
VirtualNodeSet vset = new VirtualNodeSet(axis, test, contextId,
contextSet);
vset.setInPredicate(Expression.NO_CONTEXT_ID != contextId);
return vset;
} else if (preloadNodeSets()) {
DocumentSet docs = getDocumentSet(contextSet);
// TODO : understand why this one is different from the other ones
if (currentSet == null || currentDocs == null
|| !(docs == currentDocs || docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
switch (axis) {
case Constants.DESCENDANT_SELF_AXIS:
return currentSet.selectAncestorDescendant(contextSet,
NodeSet.DESCENDANT, true, contextId);
case Constants.DESCENDANT_AXIS:
return currentSet.selectAncestorDescendant(contextSet,
NodeSet.DESCENDANT, false, contextId);
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
} else {
NodeSelector selector;
DocumentSet docs = contextSet.getDocumentSet();
switch (axis) {
case Constants.DESCENDANT_SELF_AXIS:
selector = new DescendantOrSelfSelector(contextSet,
contextId);
break;
case Constants.DESCENDANT_AXIS:
selector = new DescendantSelector(contextSet, contextId);
break;
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
return index.findElementsByTagName(ElementValue.ELEMENT, docs, test
.getName(), selector);
}
}
protected NodeSet getSiblings(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
NodeSet result = new ExtArrayNodeSet(contextSet.getLength());
for (Iterator i = contextSet.iterator(); i.hasNext();) {
NodeProxy current = (NodeProxy) i.next();
StoredNode currentNode = (StoredNode) current.getNode();
while ((currentNode = getNextSibling(currentNode)) != null) {
if (test.matches(currentNode)) {
NodeProxy sibling = result.get((DocumentImpl) currentNode.getOwnerDocument(), currentNode.getNodeId());
if (sibling == null) {
sibling = new NodeProxy((DocumentImpl) currentNode.getOwnerDocument(), currentNode.getNodeId(),
currentNode.getInternalAddress());
if (Expression.NO_CONTEXT_ID != contextId) {
sibling.addContextNode(contextId, current);
} else
sibling.copyContext(current);
} else if (Expression.NO_CONTEXT_ID != contextId)
sibling.addContextNode(contextId, current);
result.add(sibling);
}
}
}
return result;
} else {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
switch (axis) {
case Constants.PRECEDING_SIBLING_AXIS:
return currentSet.selectPrecedingSiblings(contextSet, contextId);
case Constants.FOLLOWING_SIBLING_AXIS:
return currentSet.selectFollowingSiblings(contextSet, contextId);
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
}
}
protected StoredNode getNextSibling(NodeImpl node) {
switch (axis) {
case Constants.FOLLOWING_SIBLING_AXIS:
return (StoredNode) node.getNextSibling();
case Constants.PRECEDING_SIBLING_AXIS:
return (StoredNode) node.getPreviousSibling();
default:
throw new IllegalArgumentException("Unsupported axis specified");
}
}
protected NodeSet getPreceding(XQueryContext context, NodeSet contextSet)
throws XPathException {
if (test.isWildcardTest()) {
// TODO : throw an exception here ! Don't let this pass through
return NodeSet.EMPTY_SET;
} else {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
return currentSet.selectPreceding(contextSet);
}
}
protected NodeSet getFollowing(XQueryContext context, NodeSet contextSet)
throws XPathException {
if (test.isWildcardTest()) {
// TODO : throw an exception here ! Don't let this pass through
return NodeSet.EMPTY_SET;
} else {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
return currentSet.selectFollowing(contextSet);
}
}
protected NodeSet getAncestors(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
NodeSet result = new ExtArrayNodeSet();
for (Iterator i = contextSet.iterator(); i.hasNext();) {
NodeProxy current = (NodeProxy) i.next();
NodeProxy ancestor;
if (axis == Constants.ANCESTOR_SELF_AXIS
&& test.matches(current)) {
ancestor = new NodeProxy(current.getDocument(), current.getNodeId(),
Node.ELEMENT_NODE, current.getInternalAddress());
NodeProxy t = result.get(ancestor);
if (t == null) {
if (Expression.NO_CONTEXT_ID != contextId)
ancestor.addContextNode(contextId, current);
else
ancestor.copyContext(current);
result.add(ancestor);
} else
t.addContextNode(contextId, current);
}
NodeId parentID = current.getNodeId().getParentId();
while (parentID != null) {
ancestor = new NodeProxy(current.getDocument(), parentID, Node.ELEMENT_NODE);
// Filter out the temporary nodes wrapper element
if (parentID != NodeId.DOCUMENT_NODE &&
!(parentID.getTreeLevel() == 1 && current.getDocument().getCollection().isTempCollection())) {
if (test.matches(ancestor)) {
NodeProxy t = result.get(ancestor);
if (t == null) {
if (Expression.NO_CONTEXT_ID != contextId)
ancestor.addContextNode(contextId, current);
else
ancestor.copyContext(current);
result.add(ancestor);
} else
t.addContextNode(contextId, current);
}
}
parentID = parentID.getParentId();
}
}
return result;
} else if (preloadNodeSets()) {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
switch (axis) {
case Constants.ANCESTOR_SELF_AXIS:
return currentSet.selectAncestors(contextSet, true,
contextId);
case Constants.ANCESTOR_AXIS:
return currentSet.selectAncestors(contextSet, false,
contextId);
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
} else {
NodeSelector selector;
DocumentSet docs = getDocumentSet(contextSet);
switch (axis) {
case Constants.ANCESTOR_SELF_AXIS:
selector = new AncestorSelector(contextSet, contextId, true);
break;
case Constants.ANCESTOR_AXIS:
selector = new AncestorSelector(contextSet, contextId,
false);
break;
default:
throw new IllegalArgumentException(
"Unsupported axis specified");
}
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
return index.findElementsByTagName(ElementValue.ELEMENT, docs, test
.getName(), selector);
}
}
protected NodeSet getParents(XQueryContext context, NodeSet contextSet) {
if (test.isWildcardTest()) {
NodeSet temp = contextSet.getParents(contextId);
NodeSet result = new ExtArrayNodeSet();
NodeProxy p;
for (Iterator i = temp.iterator(); i.hasNext(); ) {
p = (NodeProxy) i.next();
if (test.matches(p))
result.add(p);
}
return result;
} else if (preloadNodeSets()) {
DocumentSet docs = getDocumentSet(contextSet);
if (currentSet == null || currentDocs == null
|| !(docs.equals(currentDocs))) {
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
currentSet = index.findElementsByTagName(ElementValue.ELEMENT,
docs, test.getName(), null);
currentDocs = docs;
registerUpdateListener();
}
return contextSet.selectParentChild(currentSet, NodeSet.ANCESTOR);
} else {
DocumentSet docs = getDocumentSet(contextSet);
NodeSelector selector = new ParentSelector(contextSet, contextId);
ElementIndex index = context.getBroker().getElementIndex();
if (context.getProfiler().isEnabled())
context.getProfiler().message(this, Profiler.OPTIMIZATIONS,
"OPTIMIZATION",
"using index '" + index.toString() + "'");
return index.findElementsByTagName(ElementValue.ELEMENT, docs, test
.getName(), selector);
}
}
protected DocumentSet getDocumentSet(NodeSet contextSet) {
DocumentSet ds = getContextDocSet();
if (ds == null)
ds = contextSet.getDocumentSet();
return ds;
}
protected void registerUpdateListener() {
if (listener == null) {
listener = new UpdateListener() {
public void documentUpdated(DocumentImpl document, int event) {
if (event == UpdateListener.ADD) {
// clear all
currentDocs = null;
currentSet = null;
cached = null;
} else {
if (currentDocs != null
&& currentDocs.contains(document.getDocId())) {
currentDocs = null;
currentSet = null;
}
if (cached != null
&& cached.getResult().getDocumentSet()
.contains(document.getDocId()))
cached = null;
}
};
};
NotificationService service = context.getBroker().getBrokerPool()
.getNotificationService();
service.subscribe(listener);
}
}
protected void deregisterUpdateListener() {
if (listener != null) {
NotificationService service = context.getBroker().getBrokerPool()
.getNotificationService();
service.unsubscribe(listener);
}
}
/*
* (non-Javadoc)
*
* @see org.exist.xquery.Step#resetState()
*/
public void resetState() {
super.resetState();
currentSet = null;
currentDocs = null;
cached = null;
deregisterUpdateListener();
listener = null;
}
}
| Improved following/preceding sibling axis selection.
svn path=/branches/DLN/eXist-1.0/; revision=3186
| src/org/exist/xquery/LocationStep.java | Improved following/preceding sibling axis selection. | <ide><path>rc/org/exist/xquery/LocationStep.java
<ide> import org.exist.dom.NodeProxy;
<ide> import org.exist.dom.NodeSet;
<ide> import org.exist.dom.NodeSetHelper;
<add>import org.exist.dom.NodeVisitor;
<ide> import org.exist.dom.StoredNode;
<ide> import org.exist.dom.VirtualNodeSet;
<ide> import org.exist.numbering.NodeId;
<ide> protected NodeSet getSiblings(XQueryContext context, NodeSet contextSet) {
<ide> if (test.isWildcardTest()) {
<ide> NodeSet result = new ExtArrayNodeSet(contextSet.getLength());
<add> SiblingVisitor visitor = new SiblingVisitor(result);
<ide> for (Iterator i = contextSet.iterator(); i.hasNext();) {
<ide> NodeProxy current = (NodeProxy) i.next();
<del> StoredNode currentNode = (StoredNode) current.getNode();
<del> while ((currentNode = getNextSibling(currentNode)) != null) {
<del> if (test.matches(currentNode)) {
<del> NodeProxy sibling = result.get((DocumentImpl) currentNode.getOwnerDocument(), currentNode.getNodeId());
<del> if (sibling == null) {
<del> sibling = new NodeProxy((DocumentImpl) currentNode.getOwnerDocument(), currentNode.getNodeId(),
<del> currentNode.getInternalAddress());
<del> if (Expression.NO_CONTEXT_ID != contextId) {
<del> sibling.addContextNode(contextId, current);
<del> } else
<del> sibling.copyContext(current);
<del> } else if (Expression.NO_CONTEXT_ID != contextId)
<del> sibling.addContextNode(contextId, current);
<del> result.add(sibling);
<del> }
<del> }
<add> NodeId parentId = current.getNodeId().getParentId();
<add> StoredNode parentNode = (StoredNode) context.getBroker().objectWith(current.getOwnerDocument(), parentId);
<add> visitor.setContext(current);
<add> parentNode.accept(visitor);
<ide> }
<ide> return result;
<ide> } else {
<ide> }
<ide> }
<ide> }
<del>
<del> protected StoredNode getNextSibling(NodeImpl node) {
<del> switch (axis) {
<del> case Constants.FOLLOWING_SIBLING_AXIS:
<del> return (StoredNode) node.getNextSibling();
<del> case Constants.PRECEDING_SIBLING_AXIS:
<del> return (StoredNode) node.getPreviousSibling();
<del> default:
<del> throw new IllegalArgumentException("Unsupported axis specified");
<del> }
<add>
<add> private class SiblingVisitor implements NodeVisitor {
<add>
<add> private NodeSet resultSet;
<add> private NodeProxy contextNode;
<add>
<add> public SiblingVisitor(NodeSet resultSet) {
<add> this.resultSet = resultSet;
<add> }
<add>
<add> public void setContext(NodeProxy contextNode) {
<add> this.contextNode = contextNode;
<add> }
<add>
<add> public boolean visit(StoredNode current) {
<add> if (contextNode.getNodeId().getTreeLevel() == current.getNodeId().getTreeLevel()) {
<add> int cmp = current.getNodeId().compareTo(contextNode.getNodeId());
<add> if (((axis == Constants.FOLLOWING_SIBLING_AXIS && cmp > 0) ||
<add> (axis == Constants.PRECEDING_SIBLING_AXIS && cmp < 0)) &&
<add> test.matches(current)) {
<add> NodeProxy sibling = resultSet.get((DocumentImpl) current.getOwnerDocument(), current.getNodeId());
<add> if (sibling == null) {
<add> sibling = new NodeProxy((DocumentImpl) current.getOwnerDocument(), current.getNodeId(),
<add> current.getInternalAddress());
<add> if (Expression.NO_CONTEXT_ID != contextId) {
<add> sibling.addContextNode(contextId, contextNode);
<add> } else
<add> sibling.copyContext(contextNode);
<add> resultSet.add(sibling);
<add> } else if (Expression.NO_CONTEXT_ID != contextId)
<add> sibling.addContextNode(contextId, contextNode);
<add> }
<add> }
<add> return true;
<add> }
<ide> }
<ide>
<ide> protected NodeSet getPreceding(XQueryContext context, NodeSet contextSet) |
|
Java | lgpl-2.1 | 085991f604bd07bafaa1b47d6137483d4b0f868d | 0 | OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs | /////////////////////////////////////////////////////////////////////////////
// This file is part of the "OPeNDAP Web Coverage Service Project."
//
// Copyright (c) 2010 OPeNDAP, Inc.
//
// Authors:
// Haibo Liu <[email protected]>
// Nathan David Potter <[email protected]>
// Benno Blumenthal <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
/////////////////////////////////////////////////////////////////////////////
package opendap.semantics.IRISail;
import opendap.xml.Transformer;
import org.jdom.output.XMLOutputter;
import org.openrdf.model.*;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.query.*;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFParseException;
import org.slf4j.Logger;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
/**
* This class is used to populate the repository. A particular URL is only imported once. Bad URLs
* are skipped. The string vector <code>imports</code> tracks all documents that are imported
* into the repository. The string hashset <code> urlsToBeIgnored</code> is used to track bad urls
* that are skipped. The method <code>importReferencedRdfDocs</code> repeatedly calls method
* <code>findNeededRDFDocuments</code> and <code>addNeededDocuments</code> until no new needed
* RDF documents are found.
* The method <code>findNeededRDFDocuments</code> queries the repository and passes those RDF
* docuemts to <code>addNeededDocuments</code> which in turn adds them into the repository.
*
*
*
*/
public class RdfImporter {
private Logger log;
private HashSet<String> urlsToBeIgnored;
private Vector<String> imports;
private String localResourceDir;
public RdfImporter(String resourceDir) {
log = org.slf4j.LoggerFactory.getLogger(this.getClass());
urlsToBeIgnored = new HashSet<String>();
imports = new Vector<String>();
this.localResourceDir = resourceDir;
}
public void reset() {
urlsToBeIgnored.clear();
imports.clear();
}
public String getLocalResourceDirUrl(){
if(localResourceDir.startsWith("file:"))
return localResourceDir;
return "file:"+ localResourceDir;
}
/**
* Find and import all needed RDF documents into the repository.
*
* @param repository - the RDF store.
* @param doNotImportUrls - a Vector of String holds bad URLs.
* @return true if added new RDF document, otherwise false.
*/
public boolean importReferencedRdfDocs(Repository repository, Vector<String> doNotImportUrls) {
boolean repositoryChanged = false;
Vector<String> rdfDocList = new Vector<String>();
if (doNotImportUrls != null)
urlsToBeIgnored.addAll(doNotImportUrls);
findNeededRDFDocuments(repository, rdfDocList);
while (!rdfDocList.isEmpty()) {
if(addNeededRDFDocuments(repository, rdfDocList)){
repositoryChanged = true;
}
rdfDocList.clear();
findNeededRDFDocuments(repository, rdfDocList);
}
return repositoryChanged;
}
/**
* Find all RDF documents that are referenced by existing documents in the repository.
*
* @param repository - the RDF store.
* @param rdfDocs - URLs of new needed RDF documents.
*/
private void findNeededRDFDocuments(Repository repository, Vector<String> rdfDocs) {
TupleQueryResult result = null;
RepositoryConnection con = null;
try {
con = repository.getConnection();
String queryString = "(SELECT doc "
+ "FROM {doc} rdf:type {rdfcache:"+Terms.StartingPoint.getLocalId() +"} "
+ "union "
+ "SELECT doc "
+ "FROM {tp} rdf:type {rdfcache:"+Terms.StartingPoint.getLocalId() +"}; rdfcache:"+Terms.dependsOn.getLocalId() +" {doc}) "
+ "MINUS "
+ "SELECT doc "
+ "FROM CONTEXT "+"rdfcache:"+Terms.cacheContext.getLocalId()+" {doc} rdfcache:"+Terms.lastModified.getLocalId() +" {lastmod} "
+ "USING NAMESPACE "
+ "rdfcache = <" + Terms.rdfCacheNamespace + ">";
log.debug("Query for NeededRDFDocuments: " + queryString);
TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL,
queryString);
result = tupleQuery.evaluate();
while (result.hasNext()) {
BindingSet bindingSet = result.next();
Value firstValue = bindingSet.getValue("doc");
String doc = firstValue.stringValue();
if (!rdfDocs.contains(doc) && !imports.contains(doc)
&& !urlsToBeIgnored.contains(doc)
&& doc.startsWith("http://")) {
rdfDocs.add(doc);
log.debug("Adding to rdfDocs: " + doc);
}
}
} catch (QueryEvaluationException e) {
log.error("Caught an QueryEvaluationException! Msg: "
+ e.getMessage());
} catch (RepositoryException e) {
log.error("Caught RepositoryException! Msg: " + e.getMessage());
} catch (MalformedQueryException e) {
log.error("Caught MalformedQueryException! Msg: " + e.getMessage());
}
finally {
if (result != null) {
try {
result.close();
} catch (QueryEvaluationException e) {
log.error("Caught a QueryEvaluationException! Msg: "
+ e.getMessage());
}
}
try {
con.close();
} catch (RepositoryException e) {
log.error("Caught a RepositoryException! in findNeededRDFDocuments() Msg: "
+ e.getMessage());
}
}
log.info("Number of needed files identified: "
+ rdfDocs.size());
}
/**
* Add each of the RDF documents whose URL's are in the passed Vector to the Repository.
*
* @param repository - RDF store.
* @param rdfDocs - holds RDF documents to import.
* @return true if one or more RDF document is added into the repository.
*
*/
private boolean addNeededRDFDocuments(Repository repository, Vector<String> rdfDocs) {
long inferStartTime, inferEndTime;
inferStartTime = new Date().getTime();
String documentURL;
RepositoryConnection con = null;
int skipCount;
String contentType;
HttpURLConnection httpConnection = null;
InputStream importIS = null;
boolean addedDocument = false;
try {
con = repository.getConnection();
log.debug("addNeededRDFDocuments(): rdfDocs.size=" + rdfDocs.size());
skipCount = 0;
while (!rdfDocs.isEmpty()) {
documentURL = rdfDocs.remove(0);
try {
log.debug("addNeededRDFDocuments(): Checking import URL: " + documentURL);
if (urlsToBeIgnored.contains(documentURL)) {
log.error("addNeededRDFDocuments(): Previous server error, Skipping " + documentURL);
} else {
URL myurl = new URL(documentURL);
int rsCode;
httpConnection = (HttpURLConnection) myurl.openConnection();
log.debug("addNeededRDFDocuments(): Connected to import URL: " + documentURL);
rsCode = httpConnection.getResponseCode();
contentType = httpConnection.getContentType();
log.debug("addNeededRDFDocuments(): Got HTTP status code: " + rsCode);
log.debug("addNeededRDFDocuments(): Got Content Type: " + contentType);
if (rsCode == -1) {
log.error("addNeededRDFDocuments(): Unable to get an HTTP status code for resource "
+ documentURL + " WILL NOT IMPORT!");
urlsToBeIgnored.add(documentURL);
} else if (rsCode != 200) {
log.error("addNeededRDFDocuments(): Error! HTTP status code " + rsCode + " Skipping documentURL " + documentURL);
urlsToBeIgnored.add(documentURL);
} else {
log.debug("addNeededRDFDocuments(): Import URL appears valid ( " + documentURL + " )");
String transformToRdfUrl = RepositoryOps.getUrlForTransformToRdf(repository, documentURL);
if (transformToRdfUrl != null){
log.info("addNeededRDFDocuments(): Transforming " + documentURL +" with "+ transformToRdfUrl);
if(Terms.localResources.containsKey(transformToRdfUrl)){
transformToRdfUrl = getLocalResourceDirUrl() + Terms.localResources.get(transformToRdfUrl);
log.debug("addNeededRDFDocuments(): Transform URL has local copy: "+transformToRdfUrl);
}
Transformer t = new Transformer(transformToRdfUrl);
InputStream inStream = t.transform(documentURL);
log.info("addNeededRDFDocuments(): Finished transforming RDFa " + documentURL);
importUrl(con, documentURL, contentType, inStream);
addedDocument = true;
} else if (documentURL.endsWith(".xsd")) {
// XML Schema Document has known transform.
transformToRdfUrl = getLocalResourceDirUrl() + "xsl/xsd2owl.xsl";
log.info("addNeededRDFDocuments(): Transforming Schema Document'" + documentURL +"' with '"+ transformToRdfUrl);
Transformer t = new Transformer(transformToRdfUrl);
InputStream inStream = t.transform(documentURL);
log.info("addNeededRDFDocuments(): Finished transforming Xml Schema Document: '" + documentURL+"'");
importUrl(con, documentURL, contentType, inStream);
addedDocument = true;
} else if(documentURL.endsWith(".owl") || documentURL.endsWith(".rdf")) {
// OWL is RDF and so is the repository - no transform needed.
importUrl(con, documentURL, contentType);
addedDocument = true;
} else if ((contentType != null) &&
(contentType.equalsIgnoreCase("text/plain") ||
contentType.equalsIgnoreCase("text/xml") ||
contentType.equalsIgnoreCase("application/xml") ||
contentType.equalsIgnoreCase("application/rdf+xml"))
) {
importUrl(con, documentURL, contentType);
log.info("addNeededRDFDocuments(): Imported non owl/xsd from " + documentURL);
addedDocument = true;
} else {
log.warn("addNeededRDFDocuments(): SKIPPING Import URL '" + documentURL + "' It does not appear to reference a " +
"document that I know how to process.");
urlsToBeIgnored.add(documentURL); //skip this file
skipCount++;
}
log.info("addNeededRDFDocuments(): Total non owl/xsd files skipped: " + skipCount);
}
} // while (!rdfDocs.isEmpty()
} catch (Exception e) {
log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage());
if (documentURL != null){
log.warn("addNeededRDFDocuments(): SKIPPING Import URL '"+ documentURL +"' Because bad things happened when we tried to get it.");
urlsToBeIgnored.add(documentURL); //skip this file
}
} finally {
if (importIS != null)
try {
importIS.close();
} catch (IOException e) {
log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage());
}
if (httpConnection != null)
httpConnection.disconnect();
}
}
}
catch (RepositoryException e) {
log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage());
}
finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
log.error("addNeededRDFDocuments(): Caught an RepositoryException! in addNeededRDFDocuments() Msg: "
+ e.getMessage());
}
}
inferEndTime = new Date().getTime();
double inferTime = (inferEndTime - inferStartTime) / 1000.0;
log.debug("addNeededRDFDocuments(): Import takes " + inferTime + " seconds");
}
return addedDocument;
}
/**
* Add individual RDF document into the repository.
* @param con - connection to the repository.
* @param importURL - URL of RDF document to import.
* @param contentType - content type of the RDF document.
* @param importIS - input stream from of the RDF document.
* @throws IOException - if read importIS error.
* @throws RDFParseException - if parse importIS error.
* @throws RepositoryException - if repository error.
*/
private void importUrl(RepositoryConnection con, String importURL, String contentType, InputStream importIS) throws IOException, RDFParseException, RepositoryException {
if (!this.imports.contains(importURL)) { // not in the repository yet
log.info("Importing URL " + importURL);
ValueFactory valueFactory = con.getValueFactory();
URI importUri = new URIImpl(importURL);
con.add(importIS, importURL, RDFFormat.RDFXML, (Resource) importUri);
RepositoryOps.setLTMODContext(importURL, con, valueFactory); // set last modified time of the context
RepositoryOps.setContentTypeContext(importURL, contentType, con, valueFactory); //
log.info("Finished importing URL " + importURL);
imports.add(importURL);
}
else {
log.error("Import URL '"+importURL+"' already has been imported! SKIPPING!");
}
}
/**
* Add individual RDF document into the repository.
* @param con - connection to the repository
* @param importURL - URL of RDF document to import
* @param contentType - Content type of the RDF document
* @throws IOException - if read url error.
* @throws RDFParseException - if parse url content error.
* @throws RepositoryException - if repository error.
*/
private void importUrl(RepositoryConnection con, String importURL, String contentType) throws IOException, RDFParseException, RepositoryException {
if (!this.imports.contains(importURL)) { // not in the repository yet
log.info("Importing URL " + importURL);
ValueFactory valueFactory = con.getValueFactory();
URI importUri = new URIImpl(importURL);
URL url = new URL(importURL);
con.add(url, importURL, RDFFormat.RDFXML, (Resource) importUri);
RepositoryOps.setLTMODContext(importURL, con, valueFactory); // set last modified time of the context
RepositoryOps.setContentTypeContext(importURL, contentType, con, valueFactory); //
log.info("Finished importing URL " + importURL);
imports.add(importURL);
}
else {
log.error("Import URL '"+importURL+"' already has been imported! SKIPPING!");
}
}
public static void main(String[] args) throws Exception {
StreamSource httpSource = new StreamSource("http://schemas.opengis.net/wcs/1.1/wcsAll.xsd");
StreamSource fileSource = new StreamSource("file:/Users/ndp/OPeNDAP/Projects/Hyrax/swdev/trunk/olfs/resources/WCS/xsl/xsd2owl.xsl");
StreamSource transform = fileSource;
StreamSource document = httpSource;
XMLOutputter xmlo = new XMLOutputter();
xmlo.output(Transformer.getTransformedDocument(document,transform),System.out);
}
}
| src/opendap/semantics/IRISail/RdfImporter.java | /////////////////////////////////////////////////////////////////////////////
// This file is part of the "OPeNDAP Web Coverage Service Project."
//
// Copyright (c) 2010 OPeNDAP, Inc.
//
// Authors:
// Haibo Liu <[email protected]>
// Nathan David Potter <[email protected]>
// Benno Blumenthal <[email protected]>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
/////////////////////////////////////////////////////////////////////////////
package opendap.semantics.IRISail;
import opendap.xml.Transformer;
import org.jdom.output.XMLOutputter;
import org.openrdf.model.*;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.query.*;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFParseException;
import org.slf4j.Logger;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
/**
* This class is used to populate the repository. A particular URL is only imported once. Bad URLs
* are skipped. The string vector <code>imports</code> tracks all documents that are imported
* into the repository. The string hashset <code> urlsToBeIgnored</code> is used to track bad urls
* that are skipped. The method <code>importReferencedRdfDocs</code> repeatedly calls method
* <code>findNeededRDFDocuments</code> and <code>addNeededDocuments</code> until no new needed
* RDF documents are found.
* The method <code>findNeededRDFDocuments</code> queries the repository and passes those RDF
* docuemts to <code>addNeededDocuments</code> which in turn adds them into the repository.
*
*
*
*/
public class RdfImporter {
private Logger log;
private HashSet<String> urlsToBeIgnored;
private Vector<String> imports;
private String localResourceDir;
public RdfImporter(String resourceDir) {
log = org.slf4j.LoggerFactory.getLogger(this.getClass());
urlsToBeIgnored = new HashSet<String>();
imports = new Vector<String>();
this.localResourceDir = resourceDir;
}
public void reset() {
urlsToBeIgnored.clear();
imports.clear();
}
public String getLocalResourceDirUrl(){
if(localResourceDir.startsWith("file:"))
return localResourceDir;
return "file:"+ localResourceDir;
}
/**
* Find and import all needed RDF documents into the repository.
*
* @param repository
* @param doNotImportUrls
* @return
*/
public boolean importReferencedRdfDocs(Repository repository, Vector<String> doNotImportUrls) {
boolean repositoryChanged = false;
Vector<String> rdfDocList = new Vector<String>();
if (doNotImportUrls != null)
urlsToBeIgnored.addAll(doNotImportUrls);
findNeededRDFDocuments(repository, rdfDocList);
while (!rdfDocList.isEmpty()) {
if(addNeededRDFDocuments(repository, rdfDocList)){
repositoryChanged = true;
}
rdfDocList.clear();
findNeededRDFDocuments(repository, rdfDocList);
}
return repositoryChanged;
}
/**
* Find all RDF documents that are referenced by existing documents in the repository.
*
* @param repository
* @param rdfDocs
*/
private void findNeededRDFDocuments(Repository repository, Vector<String> rdfDocs) {
TupleQueryResult result = null;
List<String> bindingNames;
RepositoryConnection con = null;
try {
con = repository.getConnection();
String queryString = "(SELECT doc "
+ "FROM {doc} rdf:type {rdfcache:"+Terms.StartingPoint.getLocalId() +"} "
+ "union "
+ "SELECT doc "
+ "FROM {tp} rdf:type {rdfcache:"+Terms.StartingPoint.getLocalId() +"}; rdfcache:"+Terms.dependsOn.getLocalId() +" {doc}) "
+ "MINUS "
+ "SELECT doc "
+ "FROM CONTEXT "+"rdfcache:"+Terms.cacheContext.getLocalId()+" {doc} rdfcache:"+Terms.lastModified.getLocalId() +" {lastmod} "
+ "USING NAMESPACE "
+ "rdfcache = <" + Terms.rdfCacheNamespace + ">";
log.debug("Query for NeededRDFDocuments: " + queryString);
TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL,
queryString);
result = tupleQuery.evaluate();
while (result.hasNext()) {
BindingSet bindingSet = result.next();
Value firstValue = bindingSet.getValue("doc");
String doc = firstValue.stringValue();
if (!rdfDocs.contains(doc) && !imports.contains(doc)
&& !urlsToBeIgnored.contains(doc)
&& doc.startsWith("http://")) {
rdfDocs.add(doc);
log.debug("Adding to rdfDocs: " + doc);
}
}
} catch (QueryEvaluationException e) {
log.error("Caught an QueryEvaluationException! Msg: "
+ e.getMessage());
} catch (RepositoryException e) {
log.error("Caught RepositoryException! Msg: " + e.getMessage());
} catch (MalformedQueryException e) {
log.error("Caught MalformedQueryException! Msg: " + e.getMessage());
}
finally {
if (result != null) {
try {
result.close();
} catch (QueryEvaluationException e) {
log.error("Caught a QueryEvaluationException! Msg: "
+ e.getMessage());
}
}
try {
con.close();
} catch (RepositoryException e) {
log.error("Caught a RepositoryException! in findNeededRDFDocuments() Msg: "
+ e.getMessage());
}
}
log.info("Number of needed files identified: "
+ rdfDocs.size());
}
/**
* Add each of the RDF documents whose URL's are in the passed Vector to the Repository.
*
* @param repository
* @param rdfDocs-holds RDF documents to import
* @return true if one or more RDF document is added into the repository
*
*/
private boolean addNeededRDFDocuments(Repository repository, Vector<String> rdfDocs) {
long inferStartTime, inferEndTime;
inferStartTime = new Date().getTime();
String documentURL;
RepositoryConnection con = null;
int skipCount;
String contentType;
HttpURLConnection httpConnection = null;
InputStream importIS = null;
boolean addedDocument = false;
try {
con = repository.getConnection();
log.debug("addNeededRDFDocuments(): rdfDocs.size=" + rdfDocs.size());
skipCount = 0;
while (!rdfDocs.isEmpty()) {
documentURL = rdfDocs.remove(0);
try {
log.debug("addNeededRDFDocuments(): Checking import URL: " + documentURL);
if (urlsToBeIgnored.contains(documentURL)) {
log.error("addNeededRDFDocuments(): Previous server error, Skipping " + documentURL);
} else {
URL myurl = new URL(documentURL);
int rsCode;
httpConnection = (HttpURLConnection) myurl.openConnection();
log.debug("addNeededRDFDocuments(): Connected to import URL: " + documentURL);
rsCode = httpConnection.getResponseCode();
contentType = httpConnection.getContentType();
log.debug("addNeededRDFDocuments(): Got HTTP status code: " + rsCode);
log.debug("addNeededRDFDocuments(): Got Content Type: " + contentType);
if (rsCode == -1) {
log.error("addNeededRDFDocuments(): Unable to get an HTTP status code for resource "
+ documentURL + " WILL NOT IMPORT!");
urlsToBeIgnored.add(documentURL);
} else if (rsCode != 200) {
log.error("addNeededRDFDocuments(): Error! HTTP status code " + rsCode + " Skipping documentURL " + documentURL);
urlsToBeIgnored.add(documentURL);
} else {
log.debug("addNeededRDFDocuments(): Import URL appears valid ( " + documentURL + " )");
String transformToRdfUrl = RepositoryOps.getUrlForTransformToRdf(repository, documentURL);
if (transformToRdfUrl != null){
log.info("addNeededRDFDocuments(): Transforming " + documentURL +" with "+ transformToRdfUrl);
if(Terms.localResources.containsKey(transformToRdfUrl)){
transformToRdfUrl = getLocalResourceDirUrl() + Terms.localResources.get(transformToRdfUrl);
log.debug("addNeededRDFDocuments(): Transform URL has local copy: "+transformToRdfUrl);
}
Transformer t = new Transformer(transformToRdfUrl);
InputStream inStream = t.transform(documentURL);
log.info("addNeededRDFDocuments(): Finished transforming RDFa " + documentURL);
importUrl(con, documentURL, contentType, inStream);
addedDocument = true;
} else if (documentURL.endsWith(".xsd")) {
// XML Schema Document has known transform.
transformToRdfUrl = getLocalResourceDirUrl() + "xsl/xsd2owl.xsl";
log.info("addNeededRDFDocuments(): Transforming Schema Document'" + documentURL +"' with '"+ transformToRdfUrl);
Transformer t = new Transformer(transformToRdfUrl);
InputStream inStream = t.transform(documentURL);
log.info("addNeededRDFDocuments(): Finished transforming Xml Schema Document: '" + documentURL+"'");
importUrl(con, documentURL, contentType, inStream);
addedDocument = true;
} else if(documentURL.endsWith(".owl") || documentURL.endsWith(".rdf")) {
// OWL is RDF and so is the repository - no transform needed.
importUrl(con, documentURL, contentType);
addedDocument = true;
} else if ((contentType != null) &&
(contentType.equalsIgnoreCase("text/plain") ||
contentType.equalsIgnoreCase("text/xml") ||
contentType.equalsIgnoreCase("application/xml") ||
contentType.equalsIgnoreCase("application/rdf+xml"))
) {
importUrl(con, documentURL, contentType);
log.info("addNeededRDFDocuments(): Imported non owl/xsd from " + documentURL);
addedDocument = true;
} else {
log.warn("addNeededRDFDocuments(): SKIPPING Import URL '" + documentURL + "' It does not appear to reference a " +
"document that I know how to process.");
urlsToBeIgnored.add(documentURL); //skip this file
skipCount++;
}
log.info("addNeededRDFDocuments(): Total non owl/xsd files skipped: " + skipCount);
}
} // while (!rdfDocs.isEmpty()
} catch (Exception e) {
log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage());
if (documentURL != null){
log.warn("addNeededRDFDocuments(): SKIPPING Import URL '"+ documentURL +"' Because bad things happened when we tried to get it.");
urlsToBeIgnored.add(documentURL); //skip this file
}
} finally {
if (importIS != null)
try {
importIS.close();
} catch (IOException e) {
log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage());
}
if (httpConnection != null)
httpConnection.disconnect();
}
}
}
catch (RepositoryException e) {
log.error("addNeededRDFDocuments(): Caught " + e.getClass().getName() + " Message: " + e.getMessage());
}
finally {
if (con != null) {
try {
con.close();
} catch (RepositoryException e) {
log.error("addNeededRDFDocuments(): Caught an RepositoryException! in addNeededRDFDocuments() Msg: "
+ e.getMessage());
}
}
inferEndTime = new Date().getTime();
double inferTime = (inferEndTime - inferStartTime) / 1000.0;
log.debug("addNeededRDFDocuments(): Import takes " + inferTime + " seconds");
}
return addedDocument;
}
/**
* Add individual RDF document into the repository.
* @param con-connection to the repository
* @param importURL-URL of RDF document to import
* @param contentType-Content type of the RDF document
* @param importIS-Input stream from of the RDF document
* @throws IOException
* @throws RDFParseException
* @throws RepositoryException
*/
private void importUrl(RepositoryConnection con, String importURL, String contentType, InputStream importIS) throws IOException, RDFParseException, RepositoryException {
if (!this.imports.contains(importURL)) { // not in the repository yet
log.info("Importing URL " + importURL);
ValueFactory valueFactory = con.getValueFactory();
URI importUri = new URIImpl(importURL);
con.add(importIS, importURL, RDFFormat.RDFXML, (Resource) importUri);
RepositoryOps.setLTMODContext(importURL, con, valueFactory); // set last modified time of the context
RepositoryOps.setContentTypeContext(importURL, contentType, con, valueFactory); //
log.info("Finished importing URL " + importURL);
imports.add(importURL);
}
else {
log.error("Import URL '"+importURL+"' already has been imported! SKIPPING!");
}
}
/**
* Add individual RDF document into the repository.
* @param con-connection to the repository
* @param importURL-URL of RDF document to import
* @param contentType-Content type of the RDF document
* @throws IOException
* @throws RDFParseException
* @throws RepositoryException
*/
private void importUrl(RepositoryConnection con, String importURL, String contentType) throws IOException, RDFParseException, RepositoryException {
if (!this.imports.contains(importURL)) { // not in the repository yet
log.info("Importing URL " + importURL);
ValueFactory valueFactory = con.getValueFactory();
URI importUri = new URIImpl(importURL);
URL url = new URL(importURL);
con.add(url, importURL, RDFFormat.RDFXML, (Resource) importUri);
RepositoryOps.setLTMODContext(importURL, con, valueFactory); // set last modified time of the context
RepositoryOps.setContentTypeContext(importURL, contentType, con, valueFactory); //
log.info("Finished importing URL " + importURL);
imports.add(importURL);
}
else {
log.error("Import URL '"+importURL+"' already has been imported! SKIPPING!");
}
}
public static void main(String[] args) throws Exception {
StreamSource httpSource = new StreamSource("http://schemas.opengis.net/wcs/1.1/wcsAll.xsd");
StreamSource fileSource = new StreamSource("file:/Users/ndp/OPeNDAP/Projects/Hyrax/swdev/trunk/olfs/resources/WCS/xsl/xsd2owl.xsl");
StreamSource transform = fileSource;
StreamSource document = httpSource;
XMLOutputter xmlo = new XMLOutputter();
xmlo.output(Transformer.getTransformedDocument(document,transform),System.out);
}
}
| document
| src/opendap/semantics/IRISail/RdfImporter.java | document | <ide><path>rc/opendap/semantics/IRISail/RdfImporter.java
<ide> /**
<ide> * Find and import all needed RDF documents into the repository.
<ide> *
<del> * @param repository
<del> * @param doNotImportUrls
<del> * @return
<add> * @param repository - the RDF store.
<add> * @param doNotImportUrls - a Vector of String holds bad URLs.
<add> * @return true if added new RDF document, otherwise false.
<ide> */
<ide> public boolean importReferencedRdfDocs(Repository repository, Vector<String> doNotImportUrls) {
<ide>
<ide> /**
<ide> * Find all RDF documents that are referenced by existing documents in the repository.
<ide> *
<del> * @param repository
<del> * @param rdfDocs
<add> * @param repository - the RDF store.
<add> * @param rdfDocs - URLs of new needed RDF documents.
<ide> */
<ide> private void findNeededRDFDocuments(Repository repository, Vector<String> rdfDocs) {
<ide> TupleQueryResult result = null;
<del> List<String> bindingNames;
<add>
<ide> RepositoryConnection con = null;
<ide>
<ide> try {
<ide> /**
<ide> * Add each of the RDF documents whose URL's are in the passed Vector to the Repository.
<ide> *
<del> * @param repository
<del> * @param rdfDocs-holds RDF documents to import
<del> * @return true if one or more RDF document is added into the repository
<add> * @param repository - RDF store.
<add> * @param rdfDocs - holds RDF documents to import.
<add> * @return true if one or more RDF document is added into the repository.
<ide> *
<ide> */
<ide> private boolean addNeededRDFDocuments(Repository repository, Vector<String> rdfDocs) {
<ide>
<ide> /**
<ide> * Add individual RDF document into the repository.
<del> * @param con-connection to the repository
<del> * @param importURL-URL of RDF document to import
<del> * @param contentType-Content type of the RDF document
<del> * @param importIS-Input stream from of the RDF document
<del> * @throws IOException
<del> * @throws RDFParseException
<del> * @throws RepositoryException
<add> * @param con - connection to the repository.
<add> * @param importURL - URL of RDF document to import.
<add> * @param contentType - content type of the RDF document.
<add> * @param importIS - input stream from of the RDF document.
<add> * @throws IOException - if read importIS error.
<add> * @throws RDFParseException - if parse importIS error.
<add> * @throws RepositoryException - if repository error.
<ide> */
<ide> private void importUrl(RepositoryConnection con, String importURL, String contentType, InputStream importIS) throws IOException, RDFParseException, RepositoryException {
<ide>
<ide> }
<ide> /**
<ide> * Add individual RDF document into the repository.
<del> * @param con-connection to the repository
<del> * @param importURL-URL of RDF document to import
<del> * @param contentType-Content type of the RDF document
<del> * @throws IOException
<del> * @throws RDFParseException
<del> * @throws RepositoryException
<add> * @param con - connection to the repository
<add> * @param importURL - URL of RDF document to import
<add> * @param contentType - Content type of the RDF document
<add> * @throws IOException - if read url error.
<add> * @throws RDFParseException - if parse url content error.
<add> * @throws RepositoryException - if repository error.
<ide> */
<ide> private void importUrl(RepositoryConnection con, String importURL, String contentType) throws IOException, RDFParseException, RepositoryException {
<ide> |
|
Java | apache-2.0 | 715c34cd73cf695b7958f6aeeb219dd609f88c5c | 0 | davidwatkins73/waltz-dev,davidwatkins73/waltz-dev,davidwatkins73/waltz-dev,davidwatkins73/waltz-dev | package org.finos.waltz.model.bulk_upload;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.finos.waltz.model.EntityKind;
import org.finos.waltz.model.EntityReference;
import org.finos.waltz.model.command.Command;
import org.immutables.value.Value;
import java.util.List;
import java.util.Optional;
@Value.Immutable
@JsonSerialize(as = ImmutableBulkUploadCommand.class)
@JsonDeserialize(as = ImmutableBulkUploadCommand.class)
public abstract class BulkUploadCommand implements Command {
public abstract BulkUploadMode uploadMode();
public abstract String inputString();
public abstract EntityReference targetDomain();
public abstract EntityKind rowSubjectKind();
public abstract Optional<EntityReference> rowSubjectQualifier();
}
| waltz-model/src/main/java/org/finos/waltz/model/bulk_upload/BulkUploadCommand.java | package org.finos.waltz.model.bulk_upload;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.finos.waltz.model.EntityKind;
import org.finos.waltz.model.EntityReference;
import org.immutables.value.Value;
import java.util.List;
import java.util.Optional;
@Value.Immutable
@JsonSerialize(as = ImmutableBulkUploadCommand.class)
@JsonDeserialize(as = ImmutableBulkUploadCommand.class)
public abstract class BulkUploadCommand {
public abstract BulkUploadMode uploadMode();
public abstract String inputString();
public abstract EntityReference targetDomain();
public abstract EntityKind rowSubjectKind();
public abstract Optional<EntityReference> rowSubjectQualifier();
}
| Fixing build | waltz-model/src/main/java/org/finos/waltz/model/bulk_upload/BulkUploadCommand.java | Fixing build | <ide><path>altz-model/src/main/java/org/finos/waltz/model/bulk_upload/BulkUploadCommand.java
<ide> import com.fasterxml.jackson.databind.annotation.JsonSerialize;
<ide> import org.finos.waltz.model.EntityKind;
<ide> import org.finos.waltz.model.EntityReference;
<add>import org.finos.waltz.model.command.Command;
<add>
<ide> import org.immutables.value.Value;
<ide>
<ide> import java.util.List;
<ide> @Value.Immutable
<ide> @JsonSerialize(as = ImmutableBulkUploadCommand.class)
<ide> @JsonDeserialize(as = ImmutableBulkUploadCommand.class)
<del>public abstract class BulkUploadCommand {
<add>public abstract class BulkUploadCommand implements Command {
<ide>
<ide> public abstract BulkUploadMode uploadMode();
<ide> |
|
Java | apache-2.0 | 573be48ce0fbb7f11f0d26462289b50f6fca1f34 | 0 | vsilaev/tascalate-concurrent | /**
* Copyright 2015-2020 Valery Silaev (http://vsilaev.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 net.tascalate.concurrent.var;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;
import net.tascalate.concurrent.DependentPromise;
import net.tascalate.concurrent.Promise;
import net.tascalate.concurrent.TaskExecutorService;
import net.tascalate.concurrent.decorators.CustomizableDependentPromiseDecorator;
import net.tascalate.concurrent.decorators.CustomizablePromiseDecorator;
import net.tascalate.concurrent.decorators.PromiseCustomizer;
public class ContextTrampoline {
/**
* Defines a strategy how context variables are propagated to the execution thread
* @author vsilaev
*
*/
public static enum Propagation {
/**
* Default propagation option that is optimized for performance
* <p>The logic is the following:</p>
* <ol>
* <li>Apply context variables from the snapshot</li>
* <li>Execute code</li>
* <li>Reset context variables</li>
* </ol>
*/
OPTIMIZED,
/**
* Pessimistic propagation option for rare cases when thread might have
* its own default values of the context variables and they must be restored.
* <p>The logic is the following:</p>
* <ol>
* <li>Save context variables from the current thread</li>
* <li>Apply context variables from the snapshot</li>
* <li>Execute code</li>
* <li>Restore context variables saved in the step [1]</li>
* </ol>
*/
STRICT;
}
private final List<ContextVar<?>> contextVars;
private ContextTrampoline(List<? extends ContextVar<?>> contextVars) {
this.contextVars = contextVars == null ? Collections.emptyList() :
Collections.unmodifiableList(contextVars);
}
public <T> Function<Promise<T>, Promise<T>> boundPromises() {
return boundPromises(Propagation.OPTIMIZED);
}
public <T> Function<Promise<T>, Promise<T>> boundPromises(Propagation propagation) {
PromiseCustomizer customizer = new ContextualPromiseCustomizer(
contextVars, propagation, captureContext(contextVars)
);
return p -> p instanceof DependentPromise ?
new CustomizableDependentPromiseDecorator<>((DependentPromise<T>)p, customizer)
:
new CustomizablePromiseDecorator<>(p, customizer);
}
public Executor bind(Executor executor) {
return bind(executor, Propagation.OPTIMIZED);
}
public Executor bind(Executor executor, Propagation propagation) {
return bindExecutor(executor, propagation, ContextualExecutor::new);
}
public ExecutorService bind(ExecutorService executorService) {
return bind(executorService, Propagation.OPTIMIZED);
}
public ExecutorService bind(ExecutorService executorService, Propagation propagation) {
return bindExecutor(executorService, propagation, ContextualExecutorService::new);
}
public TaskExecutorService bind(TaskExecutorService executorService) {
return bind(executorService, Propagation.OPTIMIZED);
}
public TaskExecutorService bind(TaskExecutorService executorService, Propagation propagation) {
return bindExecutor(executorService, propagation, ContextualTaskExecutorService::new);
}
public ScheduledExecutorService bind(ScheduledExecutorService executorService) {
return bind(executorService, Propagation.OPTIMIZED);
}
public ScheduledExecutorService bind(ScheduledExecutorService executorService, Propagation propagation) {
return bindExecutor(executorService, propagation, ContextualScheduledExecutorService::new);
}
public static ContextTrampoline relay(ContextVar<?> contextVar) {
return new ContextTrampoline(Collections.singletonList(contextVar));
}
public static ContextTrampoline relay(ThreadLocal<?> threadLocal) {
return relay(ContextVar.from(threadLocal));
}
public static ContextTrampoline relay(ContextVar<?>... contextVars) {
return new ContextTrampoline(Arrays.asList(contextVars));
}
public static ContextTrampoline relay(ThreadLocal<?>... threadLocals) {
return new ContextTrampoline(Arrays.stream(threadLocals).map(ContextVar::from).collect(Collectors.toList()));
}
public static ContextTrampoline relay(List<? extends ContextVar<?>> contextVars) {
if (null == contextVars || contextVars.isEmpty()) {
return NOP;
} else {
return new ContextTrampoline(new ArrayList<>(contextVars));
}
}
public static ContextTrampoline relayThreadLocals(List<? extends ThreadLocal<?>> threadLocals) {
if (null == threadLocals || threadLocals.isEmpty()) {
return NOP;
} else {
return relay(
threadLocals.stream()
.map(tl -> ContextVar.from((ThreadLocal<?>)tl))
.collect(Collectors.toList())
);
}
}
static List<Object> captureContext(List<? extends ContextVar<?>> contextVars) {
return contextVars.stream().map(v -> v.get()).collect(Collectors.toList());
}
private <D extends Executor> D bindExecutor(D delegate,
Propagation propagation,
ContextualExecutorConstructor<D> ctr) {
return ctr.apply(delegate, contextVars, propagation, captureContext(contextVars));
}
private static interface ContextualExecutorConstructor<D extends Executor> {
D apply(D delegate, List<ContextVar<?>> contextVars, Propagation propagation, List<Object> capturedContext);
}
static String generateVarName() {
return "<anonymous" + COUNTER.getAndIncrement() + ">";
}
private static final AtomicLong COUNTER = new AtomicLong();
private static final ContextTrampoline NOP = new ContextTrampoline(null) {
@Override
public <T> Function<Promise<T>, Promise<T>> boundPromises() {
return Function.identity();
}
@Override
public <T> Function<Promise<T>, Promise<T>> boundPromises(Propagation propagation) {
return Function.identity();
}
@Override
public Executor bind(Executor executor) {
return executor;
}
@Override
public Executor bind(Executor executor, Propagation propagation) {
return executor;
}
@Override
public ExecutorService bind(ExecutorService executorService) {
return executorService;
}
@Override
public ExecutorService bind(ExecutorService executorService, Propagation propagation) {
return executorService;
}
@Override
public TaskExecutorService bind(TaskExecutorService executorService) {
return executorService;
}
@Override
public TaskExecutorService bind(TaskExecutorService executorService, Propagation propagation) {
return executorService;
}
@Override
public ScheduledExecutorService bind(ScheduledExecutorService executorService) {
return executorService;
}
@Override
public ScheduledExecutorService bind(ScheduledExecutorService executorService, Propagation propagation) {
return executorService;
}
};
}
| src/main/java/net/tascalate/concurrent/var/ContextTrampoline.java | /**
* Copyright 2015-2020 Valery Silaev (http://vsilaev.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 net.tascalate.concurrent.var;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.stream.Collectors;
import net.tascalate.concurrent.DependentPromise;
import net.tascalate.concurrent.Promise;
import net.tascalate.concurrent.TaskExecutorService;
import net.tascalate.concurrent.decorators.CustomizableDependentPromiseDecorator;
import net.tascalate.concurrent.decorators.CustomizablePromiseDecorator;
import net.tascalate.concurrent.decorators.PromiseCustomizer;
public class ContextTrampoline {
/**
* Defines a strategy how context variables are propagated to the execution thread
* @author vsilaev
*
*/
public static enum Propagation {
/**
* Default propagation option that is optimized for performance
* <p>The logic is the following:</p>
* <ol>
* <li>Apply context variables from the snapshot</li>
* <li>Execute code</li>
* <li>Reset context variables</li>
* </ol>
*/
OPTIMIZED,
/**
* Pessimistic propagation option for rare cases when thread might have
* its own default values of the context variables and they must be restored.
* <p>The logic is the following:</p>
* <ol>
* <li>Save context variables from the current thread</li>
* <li>Apply context variables from the snapshot</li>
* <li>Execute code</li>
* <li>Restore context variables saved in the step [1]</li>
* </ol>
*/
STRICT;
}
private final List<ContextVar<?>> contextVars;
private ContextTrampoline(List<? extends ContextVar<?>> contextVars) {
this.contextVars = contextVars == null ? Collections.emptyList() :
Collections.unmodifiableList(contextVars);
}
public <T> Function<Promise<T>, Promise<T>> boundPromises() {
return boundPromises(Propagation.OPTIMIZED);
}
public <T> Function<Promise<T>, Promise<T>> boundPromises(Propagation propagation) {
PromiseCustomizer customizer = new ContextualPromiseCustomizer(
contextVars, propagation, captureContext(contextVars)
);
return p -> p instanceof DependentPromise ?
new CustomizableDependentPromiseDecorator<>((DependentPromise<T>)p, customizer)
:
new CustomizablePromiseDecorator<>(p, customizer);
}
public Executor bind(Executor executor) {
return bind(executor, Propagation.OPTIMIZED);
}
public Executor bind(Executor executor, Propagation propagation) {
return bindExecutor(executor, propagation, ContextualExecutor::new);
}
public ExecutorService bind(ExecutorService executorService) {
return bind(executorService, Propagation.OPTIMIZED);
}
public ExecutorService bind(ExecutorService executorService, Propagation propagation) {
return bindExecutor(executorService, propagation, ContextualExecutorService::new);
}
public TaskExecutorService bind(TaskExecutorService executorService) {
return bind(executorService, Propagation.OPTIMIZED);
}
public TaskExecutorService bind(TaskExecutorService executorService, Propagation propagation) {
return bindExecutor(executorService, propagation, ContextualTaskExecutorService::new);
}
public ScheduledExecutorService bind(ScheduledExecutorService executorService) {
return bind(executorService, Propagation.OPTIMIZED);
}
public ScheduledExecutorService bind(ScheduledExecutorService executorService, Propagation propagation) {
return bindExecutor(executorService, propagation, ContextualScheduledExecutorService::new);
}
public static ContextTrampoline relay(ContextVar<?> contextVar) {
return new ContextTrampoline(Collections.singletonList(contextVar));
}
public static ContextTrampoline relay(ThreadLocal<?> threadLocal) {
return relay(ContextVar.from(threadLocal));
}
public static ContextTrampoline relay(ContextVar<?>... contextVars) {
return new ContextTrampoline(Arrays.asList(contextVars));
}
public static ContextTrampoline relay(ThreadLocal<?>... threadLocals) {
return new ContextTrampoline(Arrays.stream(threadLocals).map(ContextVar::from).collect(Collectors.toList()));
}
public static ContextTrampoline relay(List<? extends ContextVar<?>> contextVars) {
if (null == contextVars || contextVars.isEmpty()) {
return NOP;
} else {
return new ContextTrampoline(new ArrayList<>(contextVars));
}
}
public static ContextTrampoline relayThreadLocals(List<? extends ThreadLocal<?>> threadLocals) {
if (null == threadLocals || threadLocals.isEmpty()) {
return NOP;
} else {
return relay(
threadLocals.stream()
.map(tl -> ContextVar.from((ThreadLocal<?>)tl))
.collect(Collectors.toList())
);
}
}
static List<Object> captureContext(List<? extends ContextVar<?>> contextVars) {
return contextVars.stream().map(v -> v.get()).collect(Collectors.toList());
}
private <D extends Executor> D bindExecutor(D delegate,
Propagation propagation,
ContextualExecutorConstructor<D> ctr) {
return ctr.apply(delegate, contextVars, propagation, captureContext(contextVars));
}
private static interface ContextualExecutorConstructor<D extends Executor> {
D apply(D delegate, List<ContextVar<?>> contextVars, Propagation propagation, List<Object> capturedContext);
}
static String generateVarName() {
return "<anonymous" + COUNTER.getAndIncrement() + ">";
}
private static final AtomicLong COUNTER = new AtomicLong();
private static final ContextTrampoline NOP = new ContextTrampoline(null) {
@Override
public <T> Function<Promise<T>, Promise<T>> boundPromises() {
return Function.identity();
}
@Override
public <T> Function<Promise<T>, Promise<T>> boundPromises(Propagation propagation) {
return Function.identity();
}
@Override
public Executor bind(Executor executor) {
return executor;
}
@Override
public Executor bind(Executor executor, Propagation propagation) {
return executor;
}
@Override
public ExecutorService bind(ExecutorService executorService) {
return executorService;
}
@Override
public ExecutorService bind(ExecutorService executorService, Propagation propagation) {
return executorService;
}
@Override
public TaskExecutorService bind(TaskExecutorService executorService) {
return executorService;
}
@Override
public TaskExecutorService bind(TaskExecutorService executorService, Propagation propagation) {
return super.bind(executorService, propagation);
}
@Override
public ScheduledExecutorService bind(ScheduledExecutorService executorService) {
return executorService;
}
@Override
public ScheduledExecutorService bind(ScheduledExecutorService executorService, Propagation propagation) {
return executorService;
}
};
}
| minor fix in ContextTrampoline
| src/main/java/net/tascalate/concurrent/var/ContextTrampoline.java | minor fix in ContextTrampoline | <ide><path>rc/main/java/net/tascalate/concurrent/var/ContextTrampoline.java
<ide>
<ide> @Override
<ide> public TaskExecutorService bind(TaskExecutorService executorService, Propagation propagation) {
<del> return super.bind(executorService, propagation);
<add> return executorService;
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | c2759937e3304c1b4f32a239d90e6a0da3ef1a22 | 0 | jujaga/ice-lotto-meteor,jujaga/ice-lotto-meteor,charlieman/ice-lotto-meteor,charlieman/ice-lotto-meteor | isAdmin = function (user) {
user = (typeof user === 'undefined') ? Meteor.user() : user;
return !!user && !!user.profile && user.profile.admin === true;
};
isAdminById = function (userId) {
var user = Meteor.users.findOne(userId);
return isAdmin(user);
};
isVerified = function(user) {
return !!user && !!user.profile && user.profile.verified === true;
};
isSuperAdmin = function(user) {
user = (typeof user === 'undefined') ? Meteor.user() : user;
return !!user && !!user.profile && user.profile.superadmin === true;
}; | lib/permissions.js | isAdmin = function (user) {
user = (typeof user === 'undefined') ? Meteor.user() : user;
return !!user && !!user.profile && user.profile.admin === true;
};
isAdminById = function (userId) {
var user = Meteor.users.findOne(userId);
return isAdmin(user);
};
isVerified = function(user) {
return !!user && !!user.profile && user.profile.verified === true;
};
isSuperAdmin = function(user) {
return !!user && !!user.profile && user.profile.superadmin === true;
}; | Check for the current user if none is passed to the function
| lib/permissions.js | Check for the current user if none is passed to the function | <ide><path>ib/permissions.js
<ide> };
<ide>
<ide> isSuperAdmin = function(user) {
<add> user = (typeof user === 'undefined') ? Meteor.user() : user;
<ide> return !!user && !!user.profile && user.profile.superadmin === true;
<ide> }; |
|
Java | apache-2.0 | c271dfbae5d12cecca07f05463fedd4ae22de115 | 0 | javamelody/javamelody,javamelody/javamelody,javamelody/javamelody | /*
* Copyright 2008-2012 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody 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.
*
* Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
/**
* Énumération des actions possibles dans l'IHM.
* @author Emeric Vernat
* @author <a href="mailto:[email protected]">David J. M. Karlsen (IBM heapdump support)<a>
*/
enum Action { // NOPMD
/**
* Test d'envoi du rapport pdf par mail.
*/
MAIL_TEST(""),
/**
* Réinitialisation d'un compteur non périodique.
*/
CLEAR_COUNTER("http"),
/**
* Garbage Collect.
*/
GC("systeminfo"),
/**
* Invalidations des sessions http.
*/
INVALIDATE_SESSIONS("systeminfo"),
/**
* Invalidation d'une session http.
*/
INVALIDATE_SESSION(""),
/**
* Heap dump.
*/
HEAP_DUMP("systeminfo"),
/**
* Purge le contenu de tous les caches (ie, for ALL_CACHE_MANAGERS {cacheManager.clearAll()})
*/
CLEAR_CACHES("caches"),
/**
* Purge le contenu d'un cache
*/
CLEAR_CACHE("caches"),
/**
* Tue un thread java.
*/
KILL_THREAD("threads"),
/**
* Met un job quartz en pause.
*/
PAUSE_JOB("jobs"),
/**
* Enlève la pause d'un job quartz.
*/
RESUME_JOB("jobs"),
/**
* Réinitialisation des hotspots.
*/
CLEAR_HOTSPOTS(""),
/**
* Purge les fichiers .rrd et .ser.gz obsolètes.
*/
PURGE_OBSOLETE_FILES("bottom");
static final String JAVA_VENDOR = System.getProperty("java.vendor");
/**
* Booléen selon que l'action 'Garbage collector' est possible.
*/
static final boolean GC_ENABLED = !ManagementFactory.getRuntimeMXBean().getInputArguments()
.contains("-XX:+DisableExplicitGC");
/**
* Booléen selon que l'action 'Heap dump' est possible.
*/
static final boolean HEAP_DUMP_ENABLED = "1.6".compareTo(System.getProperty("java.version")) < 0
&& (JAVA_VENDOR.contains("Sun") || JAVA_VENDOR.contains("Oracle") || JAVA_VENDOR
.contains("IBM"));
private static final String ALL = "all";
/**
* Nom du contexte dans lequel est exécutée l'action
* (servira dans l'url pour replacer la page html sur l'anchor de même nom)
*/
private final String contextName;
private Action(String contextName) {
this.contextName = contextName;
}
String getContextName(String counterName) {
if (this == CLEAR_COUNTER && !ALL.equalsIgnoreCase(counterName)) {
return counterName;
}
return contextName;
}
/**
* Convertit le code d'une action en énumération de l'action.
* @param action String
* @return Action
*/
static Action valueOfIgnoreCase(String action) {
return valueOf(action.toUpperCase(Locale.getDefault()).trim());
}
/**
* Vérifie que le paramètre pour activer les actions systèmes est positionné.
*/
static void checkSystemActionsEnabled() {
if (!Parameters.isSystemActionsEnabled()) {
throw new IllegalStateException(I18N.getString("Actions_non_activees"));
}
}
/**
* Exécute l'action.
* @param collector Collector pour une réinitialisation et test de mail
* @param collectorServer Serveur de collecte pour test de mail (null s'il n'y en a pas)
* @param counterName Nom du compteur pour une réinitialisation
* @param sessionId Identifiant de session pour invalidation (null sinon)
* @param threadId Identifiant du thread sous la forme pid_ip_id
* @param jobId Identifiant du job sous la forme pid_ip_id
* @param cacheId Identifiant du cache à vider
* @return Message de résultat
* @throws IOException e
*/
// CHECKSTYLE:OFF
String execute(Collector collector, CollectorServer collectorServer, String counterName, // NOPMD
String sessionId, String threadId, String jobId, String cacheId) throws IOException {
// CHECKSTYLE:ON
String messageForReport;
switch (this) {
case CLEAR_COUNTER:
assert collector != null;
assert counterName != null;
messageForReport = clearCounter(collector, counterName);
break;
case MAIL_TEST:
assert collector != null;
messageForReport = mailTest(collector, collectorServer);
break;
case GC:
if (GC_ENABLED) {
// garbage collector
final long before = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
gc();
final long after = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
messageForReport = I18N.getFormattedString("ramasse_miette_execute",
(before - after) / 1024);
} else {
messageForReport = I18N.getString("ramasse_miette_desactive");
}
break;
case HEAP_DUMP:
if (HEAP_DUMP_ENABLED) {
if (JAVA_VENDOR.contains("IBM")) {
ibmHeapDump();
messageForReport = I18N.getString("heap_dump_genere_ibm");
} else {
// heap dump à générer dans le répertoire temporaire sur le serveur
// avec un suffixe contenant le host, la date et l'heure et avec une extension hprof
// (utiliser jvisualvm du jdk ou MAT d'eclipse en standalone ou en plugin)
final String heapDumpPath = heapDump().getPath();
messageForReport = I18N.getFormattedString("heap_dump_genere",
heapDumpPath.replace('\\', '/'));
}
} else {
messageForReport = I18N.getString("heap_dump_not_good");
}
break;
case INVALIDATE_SESSIONS:
// invalidation des sessions http
SessionListener.invalidateAllSessions();
messageForReport = I18N.getString("sessions_http_invalidees");
break;
case INVALIDATE_SESSION:
// invalidation d'une session http
assert sessionId != null;
SessionListener.invalidateSession(sessionId);
messageForReport = I18N.getString("session_http_invalidee");
break;
case CLEAR_CACHES:
clearCaches();
messageForReport = I18N.getString("caches_purges");
break;
case CLEAR_CACHE:
clearCache(cacheId);
messageForReport = I18N.getFormattedString("cache_purge", cacheId);
break;
case KILL_THREAD:
assert threadId != null;
messageForReport = killThread(threadId);
break;
case PAUSE_JOB:
assert jobId != null;
messageForReport = pauseJob(jobId);
break;
case RESUME_JOB:
assert jobId != null;
messageForReport = resumeJob(jobId);
break;
case CLEAR_HOTSPOTS:
assert collector.getSamplingProfiler() != null;
collector.getSamplingProfiler().clear();
messageForReport = I18N.getString("hotspots_cleared");
break;
case PURGE_OBSOLETE_FILES:
assert collector != null;
collector.deleteObsoleteFiles();
messageForReport = I18N.getString("fichiers_obsoletes_purges") + '\n'
+ I18N.getString("Usage_disque") + ": "
+ (collector.getDiskUsage() / 1024 / 1024 + 1) + ' ' + I18N.getString("Mo");
break;
default:
throw new IllegalStateException(toString());
}
if (messageForReport != null) {
// log pour information en debug
LOG.debug("Action '" + this + "' executed. Result: "
+ messageForReport.replace('\n', ' '));
}
return messageForReport;
}
private String clearCounter(Collector collector, String counterName) {
String messageForReport;
if (ALL.equalsIgnoreCase(counterName)) {
for (final Counter counter : collector.getCounters()) {
collector.clearCounter(counter.getName());
}
messageForReport = I18N.getFormattedString("Toutes_statistiques_reinitialisees",
counterName);
} else {
// l'action Réinitialiser a été appelée pour un compteur
collector.clearCounter(counterName);
messageForReport = I18N.getFormattedString("Statistiques_reinitialisees", counterName);
}
return messageForReport;
}
private String mailTest(Collector collector, CollectorServer collectorServer) {
// note: a priori, inutile de traduire cela
if (!HtmlAbstractReport.isPdfEnabled()) {
throw new IllegalStateException("itext classes not found: add the itext dependency");
}
if (Parameters.getParameter(Parameter.MAIL_SESSION) == null) {
throw new IllegalStateException(
"mail-session has no value: add the mail-session parameter");
}
if (Parameters.getParameter(Parameter.ADMIN_EMAILS) == null) {
throw new IllegalStateException(
"admin-emails has no value: add the admin-emails parameter");
}
try {
if (collectorServer == null) {
// serveur local
new MailReport().sendReportMailForLocalServer(collector, Period.JOUR);
} else {
// serveur de collecte
new MailReport().sendReportMail(collector, true, collectorServer
.getJavaInformationsByApplication(collector.getApplication()), Period.JOUR);
}
} catch (final Exception e) {
throw new RuntimeException(e); // NOPMD
}
return "Mail sent with pdf report for the day to admins";
}
private File heapDump() throws IOException {
final boolean gcBeforeHeapDump = true;
try {
final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
final ObjectInstance instance = platformMBeanServer.getObjectInstance(new ObjectName(
"com.sun.management:type=HotSpotDiagnostic"));
final Object mxBean = platformMBeanServer.instantiate(instance.getClassName());
final Object vmOption = ((com.sun.management.HotSpotDiagnosticMXBean) mxBean)
.getVMOption("HeapDumpPath");
final String heapDumpPath;
if (vmOption == null) {
heapDumpPath = null;
} else {
heapDumpPath = ((com.sun.management.VMOption) vmOption).getValue();
}
final String path;
if (heapDumpPath == null || heapDumpPath.length() == 0) {
path = Parameters.TEMPORARY_DIRECTORY.getPath();
} else {
// -XX:HeapDumpPath=/tmp par exemple a été spécifié comme paramètre de VM.
// Dans ce cas, on prend en compte ce paramètre "standard" de la JVM Hotspot
final File file = new File(heapDumpPath);
if (file.exists()) {
if (file.isDirectory()) {
path = heapDumpPath;
} else {
path = file.getParent();
}
} else {
if (!file.mkdirs()) {
throw new IllegalStateException("Can't create directory " + file.getPath());
}
path = heapDumpPath;
}
}
final DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault());
final File heapDumpFile = new File(path, "heapdump-" + Parameters.getHostName() + '-'
+ dateFormat.format(new Date()) + ".hprof");
if (heapDumpFile.exists()) {
try {
// si le fichier existe déjà, un heap dump a déjà été généré dans la même seconde
// donc on attends 1 seconde pour créer le fichier avec un nom différent
Thread.sleep(1000);
} catch (final InterruptedException e) {
throw new IllegalStateException(e);
}
return heapDump();
}
((com.sun.management.HotSpotDiagnosticMXBean) mxBean).dumpHeap(heapDumpFile.getPath(),
gcBeforeHeapDump);
return heapDumpFile;
} catch (final JMException e) {
throw new IllegalStateException(e);
}
}
private void ibmHeapDump() {
try {
final Class<?> dumpClass = getClass().getClassLoader().loadClass("com.ibm.jvm.Dump"); // NOPMD
final Class<?>[] argTypes = null;
final Method dump = dumpClass.getMethod("HeapDump", argTypes);
final Object[] args = null;
dump.invoke(null, args);
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
// cette méthode doit s'appeler "gc" pour que findbugs ne fasse pas de warning
@SuppressWarnings("all")
private void gc() {
Runtime.getRuntime().gc();
}
@SuppressWarnings("unchecked")
private void clearCaches() {
final List<CacheManager> allCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
for (final CacheManager cacheManager : allCacheManagers) {
cacheManager.clearAll();
}
}
@SuppressWarnings("unchecked")
private void clearCache(String cacheId) {
final List<CacheManager> allCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
for (final CacheManager cacheManager : allCacheManagers) {
final Cache cache = cacheManager.getCache(cacheId);
if (cache != null) {
cache.removeAll();
}
}
}
private String killThread(String threadId) {
final String[] values = threadId.split("_");
if (values.length != 3) {
throw new IllegalArgumentException(threadId);
}
// rq : la syntaxe vérifiée ici doit être conforme à ThreadInformations.buildGlobalThreadId
if (values[0].equals(PID.getPID()) && values[1].equals(Parameters.getHostAddress())) {
final long myThreadId = Long.parseLong(values[2]);
final List<Thread> threads = JavaInformations.getThreadsFromThreadGroups();
for (final Thread thread : threads) {
if (thread.getId() == myThreadId) {
stopThread(thread);
return I18N.getFormattedString("Thread_tue", thread.getName());
}
}
return I18N.getString("Thread_non_trouve");
}
// cette action ne concernait pas cette JVM, donc on ne fait rien
return null;
}
@SuppressWarnings("deprecation")
private void stopThread(Thread thread) {
// I know that it is unsafe and the user has been warned
thread.stop();
}
private String pauseJob(String jobId) {
if (ALL.equalsIgnoreCase(jobId)) {
pauseAllJobs();
return I18N.getString("all_jobs_paused");
}
final String[] values = jobId.split("_");
if (values.length != 3) {
throw new IllegalArgumentException(jobId);
}
// rq : la syntaxe vérifiée ici doit être conforme à JobInformations.buildGlobalJobId
if (values[0].equals(PID.getPID()) && values[1].equals(Parameters.getHostAddress())) {
if (pauseJobById(Integer.parseInt(values[2]))) {
return I18N.getString("job_paused");
}
return I18N.getString("job_notfound");
}
// cette action ne concernait pas cette JVM, donc on ne fait rien
return null;
}
private boolean pauseJobById(int myJobId) {
try {
for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
for (final JobDetail jobDetail : JobInformations.getAllJobsOfScheduler(scheduler)) {
if (QuartzAdapter.getSingleton().getJobFullName(jobDetail).hashCode() == myJobId) {
QuartzAdapter.getSingleton().pauseJob(jobDetail, scheduler);
return true;
}
}
}
return false;
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
private void pauseAllJobs() {
try {
for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
scheduler.pauseAll();
}
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
private String resumeJob(String jobId) {
if (ALL.equalsIgnoreCase(jobId)) {
resumeAllJobs();
return I18N.getString("all_jobs_resumed");
}
final String[] values = jobId.split("_");
if (values.length != 3) {
throw new IllegalArgumentException(jobId);
}
// rq : la syntaxe vérifiée ici doit être conforme à JobInformations.buildGlobalJobId
if (values[0].equals(PID.getPID()) && values[1].equals(Parameters.getHostAddress())) {
if (resumeJobById(Integer.parseInt(values[2]))) {
return I18N.getString("job_resumed");
}
return I18N.getString("job_notfound");
}
// cette action ne concernait pas cette JVM, donc on ne fait rien
return null;
}
private boolean resumeJobById(int myJobId) {
try {
for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
for (final JobDetail jobDetail : JobInformations.getAllJobsOfScheduler(scheduler)) {
if (QuartzAdapter.getSingleton().getJobFullName(jobDetail).hashCode() == myJobId) {
QuartzAdapter.getSingleton().resumeJob(jobDetail, scheduler);
return true;
}
}
}
return false;
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
private void resumeAllJobs() {
try {
for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
scheduler.resumeAll();
}
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
}
| javamelody-core/src/main/java/net/bull/javamelody/Action.java | /*
* Copyright 2008-2012 by Emeric Vernat
*
* This file is part of Java Melody.
*
* Java Melody 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.
*
* Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>.
*/
package net.bull.javamelody;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
/**
* Énumération des actions possibles dans l'IHM.
* @author Emeric Vernat
* @author <a href="mailto:[email protected]">David J. M. Karlsen (IBM heapdump support)<a>
*/
enum Action { // NOPMD
/**
* Test d'envoi du rapport pdf par mail.
*/
MAIL_TEST(""),
/**
* Réinitialisation d'un compteur non périodique.
*/
CLEAR_COUNTER("http"),
/**
* Garbage Collect.
*/
GC("systeminfo"),
/**
* Invalidations des sessions http.
*/
INVALIDATE_SESSIONS("systeminfo"),
/**
* Invalidation d'une session http.
*/
INVALIDATE_SESSION(""),
/**
* Heap dump.
*/
HEAP_DUMP("systeminfo"),
/**
* Purge le contenu de tous les caches (ie, for ALL_CACHE_MANAGERS {cacheManager.clearAll()})
*/
CLEAR_CACHES("caches"),
/**
* Purge le contenu d'un cache
*/
CLEAR_CACHE("caches"),
/**
* Tue un thread java.
*/
KILL_THREAD("threads"),
/**
* Met un job quartz en pause.
*/
PAUSE_JOB("jobs"),
/**
* Enlève la pause d'un job quartz.
*/
RESUME_JOB("jobs"),
/**
* Réinitialisation des hotspots.
*/
CLEAR_HOTSPOTS(""),
/**
* Purge les fichiers .rrd et .ser.gz obsolètes.
*/
PURGE_OBSOLETE_FILES("bottom");
static final String JAVA_VENDOR = System.getProperty("java.vendor");
/**
* Booléen selon que l'action 'Garbage collector' est possible.
*/
static final boolean GC_ENABLED = !ManagementFactory.getRuntimeMXBean().getInputArguments()
.contains("-XX:+DisableExplicitGC");
/**
* Booléen selon que l'action 'Heap dump' est possible.
*/
static final boolean HEAP_DUMP_ENABLED = "1.6".compareTo(System.getProperty("java.version")) < 0
&& (JAVA_VENDOR.contains("Sun") || JAVA_VENDOR.contains("Oracle") || JAVA_VENDOR
.contains("IBM"));
private static final String ALL = "all";
/**
* Nom du contexte dans lequel est exécutée l'action
* (servira dans l'url pour replacer la page html sur l'anchor de même nom)
*/
private final String contextName;
private Action(String contextName) {
this.contextName = contextName;
}
String getContextName(String counterName) {
if (this == CLEAR_COUNTER && !ALL.equalsIgnoreCase(counterName)) {
return counterName;
}
return contextName;
}
/**
* Convertit le code d'une action en énumération de l'action.
* @param action String
* @return Action
*/
static Action valueOfIgnoreCase(String action) {
return valueOf(action.toUpperCase(Locale.getDefault()).trim());
}
/**
* Vérifie que le paramètre pour activer les actions systèmes est positionné.
*/
static void checkSystemActionsEnabled() {
if (!Parameters.isSystemActionsEnabled()) {
throw new IllegalStateException(I18N.getString("Actions_non_activees"));
}
}
/**
* Exécute l'action.
* @param collector Collector pour une réinitialisation et test de mail
* @param collectorServer Serveur de collecte pour test de mail (null s'il n'y en a pas)
* @param counterName Nom du compteur pour une réinitialisation
* @param sessionId Identifiant de session pour invalidation (null sinon)
* @param threadId Identifiant du thread sous la forme pid_ip_id
* @param jobId Identifiant du job sous la forme pid_ip_id
* @param cacheId Identifiant du cache à vider
* @return Message de résultat
* @throws IOException e
*/
// CHECKSTYLE:OFF
String execute(Collector collector, CollectorServer collectorServer, String counterName, // NOPMD
String sessionId, String threadId, String jobId, String cacheId) throws IOException {
// CHECKSTYLE:ON
String messageForReport;
switch (this) {
case CLEAR_COUNTER:
assert collector != null;
assert counterName != null;
messageForReport = clearCounter(collector, counterName);
break;
case MAIL_TEST:
assert collector != null;
messageForReport = mailTest(collector, collectorServer);
break;
case GC:
if (GC_ENABLED) {
// garbage collector
final long before = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
gc();
final long after = Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory();
messageForReport = I18N.getFormattedString("ramasse_miette_execute",
(before - after) / 1024);
} else {
messageForReport = I18N.getString("ramasse_miette_desactive");
}
break;
case HEAP_DUMP:
if (HEAP_DUMP_ENABLED) {
if (JAVA_VENDOR.contains("IBM")) {
ibmHeapDump();
messageForReport = I18N.getString("heap_dump_genere_ibm");
} else {
// heap dump à générer dans le répertoire temporaire sur le serveur
// avec un suffixe contenant le host, la date et l'heure et avec une extension hprof
// (utiliser jvisualvm du jdk ou MAT d'eclipse en standalone ou en plugin)
final String heapDumpPath = heapDump().getPath();
messageForReport = I18N.getFormattedString("heap_dump_genere",
heapDumpPath.replace('\\', '/'));
}
} else {
messageForReport = I18N.getString("heap_dump_not_good");
}
break;
case INVALIDATE_SESSIONS:
// invalidation des sessions http
SessionListener.invalidateAllSessions();
messageForReport = I18N.getString("sessions_http_invalidees");
break;
case INVALIDATE_SESSION:
// invalidation d'une session http
assert sessionId != null;
SessionListener.invalidateSession(sessionId);
messageForReport = I18N.getString("session_http_invalidee");
break;
case CLEAR_CACHES:
clearCaches();
messageForReport = I18N.getString("caches_purges");
break;
case CLEAR_CACHE:
clearCache(cacheId);
messageForReport = I18N.getFormattedString("cache_purge", cacheId);
break;
case KILL_THREAD:
assert threadId != null;
messageForReport = killThread(threadId);
break;
case PAUSE_JOB:
assert jobId != null;
messageForReport = pauseJob(jobId);
break;
case RESUME_JOB:
assert jobId != null;
messageForReport = resumeJob(jobId);
break;
case CLEAR_HOTSPOTS:
assert collector.getSamplingProfiler() != null;
collector.getSamplingProfiler().clear();
messageForReport = I18N.getString("hotspots_cleared");
break;
case PURGE_OBSOLETE_FILES:
assert collector != null;
collector.deleteObsoleteFiles();
messageForReport = I18N.getString("fichiers_obsoletes_purges") + '\n'
+ I18N.getString("Usage_disque") + ": "
+ (collector.getDiskUsage() / 1024 / 1024 + 1) + ' ' + I18N.getString("Mo");
break;
default:
throw new IllegalStateException(toString());
}
if (messageForReport != null) {
// log pour information en debug
LOG.debug("Action '" + this + "' executed. Result: "
+ messageForReport.replace('\n', ' '));
}
return messageForReport;
}
private String clearCounter(Collector collector, String counterName) {
String messageForReport;
if (ALL.equalsIgnoreCase(counterName)) {
for (final Counter counter : collector.getCounters()) {
collector.clearCounter(counter.getName());
}
messageForReport = I18N.getFormattedString("Toutes_statistiques_reinitialisees",
counterName);
} else {
// l'action Réinitialiser a été appelée pour un compteur
collector.clearCounter(counterName);
messageForReport = I18N.getFormattedString("Statistiques_reinitialisees", counterName);
}
return messageForReport;
}
private String mailTest(Collector collector, CollectorServer collectorServer) {
// note: a priori, inutile de traduire cela
if (!HtmlAbstractReport.isPdfEnabled()) {
throw new IllegalStateException("itext classes not found: add the itext dependency");
}
if (Parameters.getParameter(Parameter.MAIL_SESSION) == null) {
throw new IllegalStateException(
"mail-session has no value: add the mail-session parameter");
}
if (Parameters.getParameter(Parameter.ADMIN_EMAILS) == null) {
throw new IllegalStateException(
"admin-emails has no value: add the admin-emails parameter");
}
try {
if (collectorServer == null) {
// serveur local
new MailReport().sendReportMailForLocalServer(collector, Period.JOUR);
} else {
// serveur de collecte
new MailReport().sendReportMail(collector, true, collectorServer
.getJavaInformationsByApplication(collector.getApplication()), Period.JOUR);
}
} catch (final Exception e) {
throw new RuntimeException(e); // NOPMD
}
return "Mail sent with pdf report for the day to admins";
}
private File heapDump() throws IOException {
final boolean gcBeforeHeapDump = true;
try {
final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
final ObjectInstance instance = platformMBeanServer.getObjectInstance(new ObjectName(
"com.sun.management:type=HotSpotDiagnostic"));
final Object mxBean = platformMBeanServer.instantiate(instance.getClassName());
final Object vmOption = ((com.sun.management.HotSpotDiagnosticMXBean) mxBean)
.getVMOption("HeapDumpPath");
final String heapDumpPath;
if (vmOption == null) {
heapDumpPath = null;
} else {
heapDumpPath = ((com.sun.management.VMOption) vmOption).getValue();
}
final String path;
if (heapDumpPath == null || heapDumpPath.length() == 0) {
path = Parameters.TEMPORARY_DIRECTORY.getPath();
} else {
// -XX:HeapDumpPath=/tmp par exemple a été spécifié comme paramètre de VM.
// Dans ce cas, on prend en compte ce paramètre "standard" de la JVM Hotspot
final File file = new File(heapDumpPath);
if (file.exists()) {
if (file.isDirectory()) {
path = heapDumpPath;
} else {
path = file.getParent();
}
} else {
file.mkdirs();
path = heapDumpPath;
}
}
final DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault());
final File heapDumpFile = new File(path, "heapdump-" + Parameters.getHostName() + '-'
+ dateFormat.format(new Date()) + ".hprof");
if (heapDumpFile.exists()) {
try {
// si le fichier existe déjà, un heap dump a déjà été généré dans la même seconde
// donc on attends 1 seconde pour créer le fichier avec un nom différent
Thread.sleep(1000);
} catch (final InterruptedException e) {
throw new IllegalStateException(e);
}
return heapDump();
}
((com.sun.management.HotSpotDiagnosticMXBean) mxBean).dumpHeap(heapDumpFile.getPath(),
gcBeforeHeapDump);
return heapDumpFile;
} catch (final JMException e) {
throw new IllegalStateException(e);
}
}
private void ibmHeapDump() {
try {
final Class<?> dumpClass = getClass().getClassLoader().loadClass("com.ibm.jvm.Dump"); // NOPMD
final Class<?>[] argTypes = null;
final Method dump = dumpClass.getMethod("HeapDump", argTypes);
final Object[] args = null;
dump.invoke(null, args);
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
// cette méthode doit s'appeler "gc" pour que findbugs ne fasse pas de warning
@SuppressWarnings("all")
private void gc() {
Runtime.getRuntime().gc();
}
@SuppressWarnings("unchecked")
private void clearCaches() {
final List<CacheManager> allCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
for (final CacheManager cacheManager : allCacheManagers) {
cacheManager.clearAll();
}
}
@SuppressWarnings("unchecked")
private void clearCache(String cacheId) {
final List<CacheManager> allCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
for (final CacheManager cacheManager : allCacheManagers) {
final Cache cache = cacheManager.getCache(cacheId);
if (cache != null) {
cache.removeAll();
}
}
}
private String killThread(String threadId) {
final String[] values = threadId.split("_");
if (values.length != 3) {
throw new IllegalArgumentException(threadId);
}
// rq : la syntaxe vérifiée ici doit être conforme à ThreadInformations.buildGlobalThreadId
if (values[0].equals(PID.getPID()) && values[1].equals(Parameters.getHostAddress())) {
final long myThreadId = Long.parseLong(values[2]);
final List<Thread> threads = JavaInformations.getThreadsFromThreadGroups();
for (final Thread thread : threads) {
if (thread.getId() == myThreadId) {
stopThread(thread);
return I18N.getFormattedString("Thread_tue", thread.getName());
}
}
return I18N.getString("Thread_non_trouve");
}
// cette action ne concernait pas cette JVM, donc on ne fait rien
return null;
}
@SuppressWarnings("deprecation")
private void stopThread(Thread thread) {
// I know that it is unsafe and the user has been warned
thread.stop();
}
private String pauseJob(String jobId) {
if (ALL.equalsIgnoreCase(jobId)) {
pauseAllJobs();
return I18N.getString("all_jobs_paused");
}
final String[] values = jobId.split("_");
if (values.length != 3) {
throw new IllegalArgumentException(jobId);
}
// rq : la syntaxe vérifiée ici doit être conforme à JobInformations.buildGlobalJobId
if (values[0].equals(PID.getPID()) && values[1].equals(Parameters.getHostAddress())) {
if (pauseJobById(Integer.parseInt(values[2]))) {
return I18N.getString("job_paused");
}
return I18N.getString("job_notfound");
}
// cette action ne concernait pas cette JVM, donc on ne fait rien
return null;
}
private boolean pauseJobById(int myJobId) {
try {
for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
for (final JobDetail jobDetail : JobInformations.getAllJobsOfScheduler(scheduler)) {
if (QuartzAdapter.getSingleton().getJobFullName(jobDetail).hashCode() == myJobId) {
QuartzAdapter.getSingleton().pauseJob(jobDetail, scheduler);
return true;
}
}
}
return false;
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
private void pauseAllJobs() {
try {
for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
scheduler.pauseAll();
}
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
private String resumeJob(String jobId) {
if (ALL.equalsIgnoreCase(jobId)) {
resumeAllJobs();
return I18N.getString("all_jobs_resumed");
}
final String[] values = jobId.split("_");
if (values.length != 3) {
throw new IllegalArgumentException(jobId);
}
// rq : la syntaxe vérifiée ici doit être conforme à JobInformations.buildGlobalJobId
if (values[0].equals(PID.getPID()) && values[1].equals(Parameters.getHostAddress())) {
if (resumeJobById(Integer.parseInt(values[2]))) {
return I18N.getString("job_resumed");
}
return I18N.getString("job_notfound");
}
// cette action ne concernait pas cette JVM, donc on ne fait rien
return null;
}
private boolean resumeJobById(int myJobId) {
try {
for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
for (final JobDetail jobDetail : JobInformations.getAllJobsOfScheduler(scheduler)) {
if (QuartzAdapter.getSingleton().getJobFullName(jobDetail).hashCode() == myJobId) {
QuartzAdapter.getSingleton().resumeJob(jobDetail, scheduler);
return true;
}
}
}
return false;
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
private void resumeAllJobs() {
try {
for (final Scheduler scheduler : JobInformations.getAllSchedulers()) {
scheduler.resumeAll();
}
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
}
| correction warning findbugs | javamelody-core/src/main/java/net/bull/javamelody/Action.java | correction warning findbugs | <ide><path>avamelody-core/src/main/java/net/bull/javamelody/Action.java
<ide> path = file.getParent();
<ide> }
<ide> } else {
<del> file.mkdirs();
<add> if (!file.mkdirs()) {
<add> throw new IllegalStateException("Can't create directory " + file.getPath());
<add> }
<ide> path = heapDumpPath;
<ide> }
<ide> } |
|
Java | apache-2.0 | c64a748243632802520af8efcc25cc99b646b6e4 | 0 | xquery/marklogic-sesame,supriyantomaftuh/marklogic-sesame,marklogic/marklogic-sesame,xquery/marklogic-sesame,supriyantomaftuh/marklogic-sesame,supriyantomaftuh/marklogic-sesame,marklogic/marklogic-sesame,marklogic/marklogic-sesame,xquery/marklogic-sesame | package com.marklogic.semantics.sesame;
import com.marklogic.client.document.XMLDocumentManager;
import com.marklogic.client.io.StringHandle;
import com.marklogic.client.query.QueryManager;
import com.marklogic.client.semantics.Capability;
import com.marklogic.client.semantics.GraphManager;
import com.marklogic.semantics.sesame.query.MarkLogicUpdateQuery;
import org.junit.*;
import org.openrdf.model.Resource;
import org.openrdf.model.ValueFactory;
import org.openrdf.query.BooleanQuery;
import org.openrdf.query.QueryLanguage;
import org.openrdf.repository.RepositoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MarkLogicGraphPermsTest extends SesameTestBase {
private QueryManager qmgr;
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected MarkLogicRepositoryConnection conn;
protected ValueFactory f;
@Before
public void setUp() throws RepositoryException {
logger.debug("setting up test");
rep.initialize();
f = rep.getValueFactory();
conn = rep.getConnection();
logger.info("test setup complete.");
String tripleDocOne =
"<semantic-document>\n" +
"<title>First Title</title>\n" +
"<size>100</size>\n" +
"<sem:triples xmlns:sem=\"http://marklogic.com/semantics\">" +
"<sem:triple><sem:subject>http://example.org/r9928</sem:subject>" +
"<sem:predicate>http://example.org/p3</sem:predicate>" +
"<sem:object datatype=\"http://www.w3.org/2001/XMLSchema#int\">1</sem:object></sem:triple>" +
"</sem:triples>\n" +
"</semantic-document>";
String tripleDocTwo =
"<semantic-document>\n" +
"<title>Second Title</title>\n" +
"<size>500</size>\n" +
"<sem:triples xmlns:sem=\"http://marklogic.com/semantics\">" +
"<sem:triple><sem:subject>http://example.org/r9929</sem:subject>" +
"<sem:predicate>http://example.org/p3</sem:predicate>" +
"<sem:object datatype=\"http://www.w3.org/2001/XMLSchema#int\">2</sem:object></sem:triple>" +
"</sem:triples>\n" +
"</semantic-document>";
XMLDocumentManager docMgr = writerClient.newXMLDocumentManager();
docMgr.write("/directory1/doc1.xml", new StringHandle().with(tripleDocOne));
docMgr.write("/directory2/doc2.xml", new StringHandle().with(tripleDocTwo));
qmgr = writerClient.newQueryManager();
}
@After
public void tearDown()
throws Exception {
logger.debug("tearing down...");
conn.close();
conn = null;
rep.shutDown();
rep = null;
logger.info("tearDown complete.");
XMLDocumentManager docMgr = writerClient.newXMLDocumentManager();
docMgr.delete("/directory1/doc1.xml");
docMgr.delete("/directory2/doc2.xml");
}
@Test
public void testUpdateQueryWithPerms()
throws Exception {
GraphManager gmgr = adminClient.newGraphManager();
Resource context = conn.getValueFactory().createURI("http://marklogic.com/test/graph/permstest");
String defGraphQuery = "INSERT DATA { GRAPH <http://marklogic.com/test/graph/permstest> { <http://marklogic.com/test> <pp1> <oo1> } }";
String checkQuery = "ASK WHERE { GRAPH <http://marklogic.com/test/graph/permstest> {<http://marklogic.com/test> <pp1> <oo1> }}";
MarkLogicUpdateQuery updateQuery = conn.prepareUpdate(QueryLanguage.SPARQL, defGraphQuery);
updateQuery.setGraphPerms(gmgr.permission("read-privileged", Capability.READ));
updateQuery.execute();
BooleanQuery booleanQuery = conn.prepareBooleanQuery(QueryLanguage.SPARQL, checkQuery);
boolean results = booleanQuery.evaluate();
Assert.assertEquals(true, results);
conn.clear(context);
}
@Ignore
public void testGetGraphPermsofResult(){
}
@Ignore
public void testGetGraphPermsofStatement(){
}
} | marklogic-sesame/src/test/java/com/marklogic/semantics/sesame/MarkLogicGraphPermsTest.java | package com.marklogic.semantics.sesame;
import com.marklogic.client.document.XMLDocumentManager;
import com.marklogic.client.io.StringHandle;
import com.marklogic.client.query.QueryManager;
import com.marklogic.client.semantics.Capability;
import com.marklogic.client.semantics.GraphManager;
import com.marklogic.semantics.sesame.query.MarkLogicUpdateQuery;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openrdf.model.Resource;
import org.openrdf.model.ValueFactory;
import org.openrdf.query.BooleanQuery;
import org.openrdf.query.QueryLanguage;
import org.openrdf.repository.RepositoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MarkLogicGraphPermsTest extends SesameTestBase {
private QueryManager qmgr;
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected MarkLogicRepositoryConnection conn;
protected ValueFactory f;
@Before
public void setUp() throws RepositoryException {
logger.debug("setting up test");
rep.initialize();
f = rep.getValueFactory();
conn = rep.getConnection();
logger.info("test setup complete.");
String tripleDocOne =
"<semantic-document>\n" +
"<title>First Title</title>\n" +
"<size>100</size>\n" +
"<sem:triples xmlns:sem=\"http://marklogic.com/semantics\">" +
"<sem:triple><sem:subject>http://example.org/r9928</sem:subject>" +
"<sem:predicate>http://example.org/p3</sem:predicate>" +
"<sem:object datatype=\"http://www.w3.org/2001/XMLSchema#int\">1</sem:object></sem:triple>" +
"</sem:triples>\n" +
"</semantic-document>";
String tripleDocTwo =
"<semantic-document>\n" +
"<title>Second Title</title>\n" +
"<size>500</size>\n" +
"<sem:triples xmlns:sem=\"http://marklogic.com/semantics\">" +
"<sem:triple><sem:subject>http://example.org/r9929</sem:subject>" +
"<sem:predicate>http://example.org/p3</sem:predicate>" +
"<sem:object datatype=\"http://www.w3.org/2001/XMLSchema#int\">2</sem:object></sem:triple>" +
"</sem:triples>\n" +
"</semantic-document>";
XMLDocumentManager docMgr = writerClient.newXMLDocumentManager();
docMgr.write("/directory1/doc1.xml", new StringHandle().with(tripleDocOne));
docMgr.write("/directory2/doc2.xml", new StringHandle().with(tripleDocTwo));
qmgr = writerClient.newQueryManager();
}
@After
public void tearDown()
throws Exception {
logger.debug("tearing down...");
conn.close();
conn = null;
rep.shutDown();
rep = null;
logger.info("tearDown complete.");
XMLDocumentManager docMgr = writerClient.newXMLDocumentManager();
docMgr.delete("/directory1/doc1.xml");
docMgr.delete("/directory2/doc2.xml");
}
@Test
public void testUpdateQueryWithPerms()
throws Exception {
GraphManager gmgr = adminClient.newGraphManager();
Resource context = conn.getValueFactory().createURI("http://marklogic.com/test/graph/permstest");
String defGraphQuery = "INSERT DATA { GRAPH <http://marklogic.com/test/graph/permstest> { <http://marklogic.com/test> <pp1> <oo1> } }";
String checkQuery = "ASK WHERE { GRAPH <http://marklogic.com/test/graph/permstest> {<http://marklogic.com/test> <pp1> <oo1> }}";
MarkLogicUpdateQuery updateQuery = conn.prepareUpdate(QueryLanguage.SPARQL, defGraphQuery);
updateQuery.setGraphPerms(gmgr.permission("read-privileged", Capability.READ));
updateQuery.execute();
BooleanQuery booleanQuery = conn.prepareBooleanQuery(QueryLanguage.SPARQL, checkQuery);
boolean results = booleanQuery.evaluate();
Assert.assertEquals(true, results);
conn.clear(context);
}
} | Tests for graph perms
| marklogic-sesame/src/test/java/com/marklogic/semantics/sesame/MarkLogicGraphPermsTest.java | Tests for graph perms | <ide><path>arklogic-sesame/src/test/java/com/marklogic/semantics/sesame/MarkLogicGraphPermsTest.java
<ide> import com.marklogic.client.semantics.Capability;
<ide> import com.marklogic.client.semantics.GraphManager;
<ide> import com.marklogic.semantics.sesame.query.MarkLogicUpdateQuery;
<del>import org.junit.After;
<del>import org.junit.Assert;
<del>import org.junit.Before;
<del>import org.junit.Test;
<add>import org.junit.*;
<ide> import org.openrdf.model.Resource;
<ide> import org.openrdf.model.ValueFactory;
<ide> import org.openrdf.query.BooleanQuery;
<ide> conn.clear(context);
<ide> }
<ide>
<add> @Ignore
<add> public void testGetGraphPermsofResult(){
<add>
<add> }
<add>
<add> @Ignore
<add> public void testGetGraphPermsofStatement(){
<add>
<add> }
<add>
<ide> } |
|
Java | lgpl-2.1 | 281b2e2cf1bc8e2dddd53029a0b26a7010749a9c | 0 | wildfly/wildfly,wildfly/wildfly,pferraro/wildfly,golovnin/wildfly,tadamski/wildfly,xasx/wildfly,wildfly/wildfly,jstourac/wildfly,pferraro/wildfly,rhusar/wildfly,tomazzupan/wildfly,tadamski/wildfly,tadamski/wildfly,xasx/wildfly,pferraro/wildfly,pferraro/wildfly,tomazzupan/wildfly,rhusar/wildfly,xasx/wildfly,iweiss/wildfly,jstourac/wildfly,golovnin/wildfly,jstourac/wildfly,rhusar/wildfly,iweiss/wildfly,rhusar/wildfly,iweiss/wildfly,wildfly/wildfly,tomazzupan/wildfly,jstourac/wildfly,99sono/wildfly,golovnin/wildfly,iweiss/wildfly,99sono/wildfly,99sono/wildfly | /*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.wildfly.extension.undertow;
import io.undertow.attribute.ExchangeAttribute;
import io.undertow.predicate.Predicate;
import io.undertow.predicate.Predicates;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.accesslog.AccessLogHandler;
import io.undertow.server.handlers.accesslog.AccessLogReceiver;
import io.undertow.server.handlers.accesslog.DefaultAccessLogReceiver;
import io.undertow.server.handlers.accesslog.ExtendedAccessLogParser;
import io.undertow.server.handlers.accesslog.JBossLoggingAccessLogReceiver;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.extension.undertow.logging.UndertowLogger;
import org.xnio.IoUtils;
import org.xnio.XnioWorker;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author Tomaz Cerar (c) 2013 Red Hat Inc.
*/
class AccessLogService implements Service<AccessLogService> {
private final InjectedValue<Host> host = new InjectedValue<>();
protected final InjectedValue<XnioWorker> worker = new InjectedValue<>();
private final String pattern;
private final String path;
private final String pathRelativeTo;
private final String filePrefix;
private final String fileSuffix;
private final boolean rotate;
private final boolean useServerLog;
private final boolean extended;
private final Predicate predicate;
private volatile AccessLogReceiver logReceiver;
private PathManager.Callback.Handle callbackHandle;
private Path directory;
private ExchangeAttribute extendedPattern;
private final InjectedValue<PathManager> pathManager = new InjectedValue<PathManager>();
AccessLogService(String pattern, boolean extended, Predicate predicate) {
this.pattern = pattern;
this.extended = extended;
this.path = null;
this.pathRelativeTo = null;
this.filePrefix = null;
this.fileSuffix = null;
this.useServerLog = true;
this.rotate = false; //doesn't really matter
this.predicate = predicate == null ? Predicates.truePredicate() : predicate;
}
AccessLogService(String pattern, String path, String pathRelativeTo, String filePrefix, String fileSuffix, boolean rotate, boolean extended, Predicate predicate) {
this.pattern = pattern;
this.path = path;
this.pathRelativeTo = pathRelativeTo;
this.filePrefix = filePrefix;
this.fileSuffix = fileSuffix;
this.rotate = rotate;
this.extended = extended;
this.useServerLog = false;
this.predicate = predicate == null ? Predicates.truePredicate() : predicate;
}
@Override
public void start(StartContext context) throws StartException {
if (useServerLog) {
logReceiver = new JBossLoggingAccessLogReceiver();
} else {
if (pathRelativeTo != null) {
callbackHandle = pathManager.getValue().registerCallback(pathRelativeTo, PathManager.ReloadServerCallback.create(), PathManager.Event.UPDATED, PathManager.Event.REMOVED);
}
directory = Paths.get(pathManager.getValue().resolveRelativePathEntry(path, pathRelativeTo));
if (!Files.exists(directory)) {
try {
Files.createDirectories(directory);
} catch (IOException e) {
throw UndertowLogger.ROOT_LOGGER.couldNotCreateLogDirectory(directory, e);
}
}
try {
DefaultAccessLogReceiver.Builder builder = DefaultAccessLogReceiver.builder().setLogWriteExecutor(worker.getValue())
.setOutputDirectory(directory)
.setLogBaseName(filePrefix)
.setLogNameSuffix(fileSuffix)
.setRotate(rotate);
if(extended) {
builder.setLogFileHeaderGenerator(new ExtendedAccessLogParser.ExtendedAccessLogHeaderGenerator(pattern));
extendedPattern = new ExtendedAccessLogParser(getClass().getClassLoader()).parse(pattern);
} else {
extendedPattern = null;
}
logReceiver = builder.build();
} catch (IllegalStateException e) {
throw new StartException(e);
}
}
host.getValue().setAccessLogService(this);
}
@Override
public void stop(StopContext context) {
host.getValue().setAccessLogService(null);
if (callbackHandle != null) {
callbackHandle.remove();
callbackHandle = null;
}
if( logReceiver instanceof DefaultAccessLogReceiver ) {
IoUtils.safeClose((DefaultAccessLogReceiver) logReceiver);
}
logReceiver = null;
}
@Override
public AccessLogService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
InjectedValue<XnioWorker> getWorker() {
return worker;
}
InjectedValue<PathManager> getPathManager() {
return pathManager;
}
protected AccessLogHandler configureAccessLogHandler(HttpHandler handler) {
if(extendedPattern != null) {
return new AccessLogHandler(handler, logReceiver, pattern, extendedPattern, predicate);
} else {
return new AccessLogHandler(handler, logReceiver, pattern, getClass().getClassLoader(), predicate);
}
}
public InjectedValue<Host> getHost() {
return host;
}
boolean isRotate() {
return rotate;
}
String getPath() {
return path;
}
}
| undertow/src/main/java/org/wildfly/extension/undertow/AccessLogService.java | /*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
* /
*/
package org.wildfly.extension.undertow;
import io.undertow.attribute.ExchangeAttribute;
import io.undertow.predicate.Predicate;
import io.undertow.predicate.Predicates;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.accesslog.AccessLogHandler;
import io.undertow.server.handlers.accesslog.AccessLogReceiver;
import io.undertow.server.handlers.accesslog.DefaultAccessLogReceiver;
import io.undertow.server.handlers.accesslog.ExtendedAccessLogParser;
import io.undertow.server.handlers.accesslog.JBossLoggingAccessLogReceiver;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.extension.undertow.logging.UndertowLogger;
import org.xnio.XnioWorker;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author Tomaz Cerar (c) 2013 Red Hat Inc.
*/
class AccessLogService implements Service<AccessLogService> {
private final InjectedValue<Host> host = new InjectedValue<>();
protected final InjectedValue<XnioWorker> worker = new InjectedValue<>();
private final String pattern;
private final String path;
private final String pathRelativeTo;
private final String filePrefix;
private final String fileSuffix;
private final boolean rotate;
private final boolean useServerLog;
private final boolean extended;
private final Predicate predicate;
private volatile AccessLogReceiver logReceiver;
private PathManager.Callback.Handle callbackHandle;
private Path directory;
private ExchangeAttribute extendedPattern;
private final InjectedValue<PathManager> pathManager = new InjectedValue<PathManager>();
AccessLogService(String pattern, boolean extended, Predicate predicate) {
this.pattern = pattern;
this.extended = extended;
this.path = null;
this.pathRelativeTo = null;
this.filePrefix = null;
this.fileSuffix = null;
this.useServerLog = true;
this.rotate = false; //doesn't really matter
this.predicate = predicate == null ? Predicates.truePredicate() : predicate;
}
AccessLogService(String pattern, String path, String pathRelativeTo, String filePrefix, String fileSuffix, boolean rotate, boolean extended, Predicate predicate) {
this.pattern = pattern;
this.path = path;
this.pathRelativeTo = pathRelativeTo;
this.filePrefix = filePrefix;
this.fileSuffix = fileSuffix;
this.rotate = rotate;
this.extended = extended;
this.useServerLog = false;
this.predicate = predicate == null ? Predicates.truePredicate() : predicate;
}
@Override
public void start(StartContext context) throws StartException {
if (useServerLog) {
logReceiver = new JBossLoggingAccessLogReceiver();
} else {
if (pathRelativeTo != null) {
callbackHandle = pathManager.getValue().registerCallback(pathRelativeTo, PathManager.ReloadServerCallback.create(), PathManager.Event.UPDATED, PathManager.Event.REMOVED);
}
directory = Paths.get(pathManager.getValue().resolveRelativePathEntry(path, pathRelativeTo));
if (!Files.exists(directory)) {
try {
Files.createDirectories(directory);
} catch (IOException e) {
throw UndertowLogger.ROOT_LOGGER.couldNotCreateLogDirectory(directory, e);
}
}
try {
DefaultAccessLogReceiver.Builder builder = DefaultAccessLogReceiver.builder().setLogWriteExecutor(worker.getValue())
.setOutputDirectory(directory)
.setLogBaseName(filePrefix)
.setLogNameSuffix(fileSuffix)
.setRotate(rotate);
if(extended) {
builder.setLogFileHeaderGenerator(new ExtendedAccessLogParser.ExtendedAccessLogHeaderGenerator(pattern));
extendedPattern = new ExtendedAccessLogParser(getClass().getClassLoader()).parse(pattern);
} else {
extendedPattern = null;
}
logReceiver = builder.build();
} catch (IllegalStateException e) {
throw new StartException(e);
}
}
host.getValue().setAccessLogService(this);
}
@Override
public void stop(StopContext context) {
host.getValue().setAccessLogService(null);
if (callbackHandle != null) {
callbackHandle.remove();
callbackHandle = null;
}
}
@Override
public AccessLogService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
InjectedValue<XnioWorker> getWorker() {
return worker;
}
InjectedValue<PathManager> getPathManager() {
return pathManager;
}
protected AccessLogHandler configureAccessLogHandler(HttpHandler handler) {
if(extendedPattern != null) {
return new AccessLogHandler(handler, logReceiver, pattern, extendedPattern, predicate);
} else {
return new AccessLogHandler(handler, logReceiver, pattern, getClass().getClassLoader(), predicate);
}
}
public InjectedValue<Host> getHost() {
return host;
}
boolean isRotate() {
return rotate;
}
String getPath() {
return path;
}
}
| WFLY-5648 Access log message fails to be written to recreated access log on Windows
| undertow/src/main/java/org/wildfly/extension/undertow/AccessLogService.java | WFLY-5648 Access log message fails to be written to recreated access log on Windows | <ide><path>ndertow/src/main/java/org/wildfly/extension/undertow/AccessLogService.java
<ide> import org.jboss.msc.service.StopContext;
<ide> import org.jboss.msc.value.InjectedValue;
<ide> import org.wildfly.extension.undertow.logging.UndertowLogger;
<add>import org.xnio.IoUtils;
<ide> import org.xnio.XnioWorker;
<ide>
<ide> import java.io.IOException;
<ide> callbackHandle.remove();
<ide> callbackHandle = null;
<ide> }
<add> if( logReceiver instanceof DefaultAccessLogReceiver ) {
<add> IoUtils.safeClose((DefaultAccessLogReceiver) logReceiver);
<add> }
<add> logReceiver = null;
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | 7b50508d12b842dee98450c09722dd4342ed9f4a | 0 | MayukhKundu/Pokemon-Domain,yashagl/yash-showdown,Tesarand/Pokemon-Showdown,LightningStormServer/Lightning-Storm,SilverTactic/Showdown-Boilerplate,jd4564/Pokemon-Showdown,hayleysworld/harmonia,MayukhKundu/Mudkip-Server,KaitoV4X/Showdown,JennyPRO/Jenny,Breakfastqueen/advanced,Irraquated/Pokemon-Showdown,JellalTheMage/Jellals-Server,Firestatics/Firestatics46,superman8900/Pokemon-Showdown,NoahVSGamingYT/Pokemon-Showdown,ZeroParadox/BlastBurners,zek7rom/SpacialGaze,hayleysworld/harmonia,ScottehMax/Pokemon-Showdown,ZestOfLife/PSserver,xCrystal/Pokemon-Showdown,xCrystal/Pokemon-Showdown,abrulochp/Lumen-Pokemon-Showdown,johtooo/PS,Hidden-Mia/Roleplay-PS,Volcos/SpacialGaze,hayleysworld/serenity,svivian/Pokemon-Showdown,lFernanl/Mudkip-Server,anubhabsen/Pokemon-Showdown,SerperiorBae/Bae-Showdown-2,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,Lord-Haji/SpacialGaze,Mystifi/Exiled,comedianchameleon/test,svivian/Pokemon-Showdown,Pokemon-Devs/Pokemon-Showdown,xfix/Pokemon-Showdown,Ecuacion/Lumen-Pokemon-Showdown,Wando94/Spite,Sora-League/Sora,sama2/Dropp-Pokemon-Showdown,ehk12/bigbangtempclone,yashagl/pokemon-showdown,Irraquated/Pokemon-Showdown,Lauc1an/Perulink-Showdown,aakashrajput/Pokemon-Showdown,Guernouille/Pokemon-Showdown,LegendBorned/PS-Boilerplate,AnaRitaTorres/Pokemon-Showdown,LightningStormServer/Lightning-Storm,xfix/Pokemon-Showdown,SubZeroo99/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,MayukhKundu/Technogear,aakashrajput/Pokemon-Showdown,PrimalGallade45/Dropp-Pokemon-Showdown,Atwar/ServerClassroom,Parukia/Pokemon-Showdown,danpantry/Pokemon-Showdown,Darkshadow6/PokeMoon-Creation,MasterFloat/Pokemon-Showdown,SerperiorBae/BaeShowdown,lFernanl/Lumen-Pokemon-Showdown,Kill-The-Noise/BlakJack-Boilerplate,KewlStatics/Pokeindia-Codes,TheManwithskills/Creature-phil-boiler,kubetz/Pokemon-Showdown,arkanox/MistShowdown,CreaturePhil/Showdown-Boilerplate,BuzzyOG/Pokemon-Showdown,ehk12/coregit,KewlStatics/Pokeindia-Codes,Syurra/Pokemon-Showdown,Alpha-Devs/OmegaRuby-Server,PS-Spectral/Spectral,InvalidDN/Pokemon-Showdown,kuroscafe/Paradox,JellalTheMage/Jellals-Server,xCrystal/Pokemon-Showdown,DesoGit/Tsunami_PS,KewlStatics/Alliance,Firestatics/Firestatics46,theodelhay/test,Alpha-Devs/Alpha-Server,QuiteQuiet/Pokemon-Showdown,JellalTheMage/PS-,Syurra/Pokemon-Showdown,MayukhKundu/Flame-Savior,LegendBorned/PS-Boilerplate,Ecuacion/Lumen-Pokemon-Showdown,Ransei1/Alt,urkerab/Pokemon-Showdown,Irraquated/Pokemon-Showdown,Elveman/RPCShowdownServer,comedianchameleon/test,Yggdrasil-League/Yggdrasil,Irraquated/EOS-Master,abrulochp/Dropp-Pokemon-Showdown,sama2/Universe-Pokemon-Showdown,KewlStatics/Alliance,Vacate/Pokemon-Showdown,ankailou/Pokemon-Showdown,yashagl/pokecommunity,Atwar/ServerClassroom,abulechu/Dropp-Pokemon-Showdown,zek7rom/SpacialGaze,scotchkorean27/Pokemon-Showdown,AnaRitaTorres/Pokemon-Showdown,Zarel/Pokemon-Showdown,Flareninja/Lumen-Pokemon-Showdown,LustyAsh/EOS-Master,AWailOfATail/Pokemon-Showdown,Mystifi/Exiled,TheManwithskills/serenity,ehk12/clone,RustServer/Pokemon-Showdown,miahjennatills/Pokemon-Showdown,DesoGit/TsunamiPS,Bryan-0/Pokemon-Showdown,bai2/Dropp,Celecitia/Plux-Pokemon-Showdown,ShowdownHelper/Saffron,AWailOfATail/Pokemon-Showdown,Flareninja/Lumen-Pokemon-Showdown,Irraquated/Showdown-Boilerplate,kuroscafe/Showdown-Boilerplate,abrulochp/Dropp-Pokemon-Showdown,bai2/Dropp,ShowdownHelper/Saffron,kuroscafe/Showdown-Boilerplate,Ridukuo/Test,hayleysworld/asdfasdf,svivian/Pokemon-Showdown,Alpha-Devs/OmegaRuby-Server,SkyeTheFemaleSylveon/Pokemon-Showdown,Enigami/Pokemon-Showdown,hayleysworld/Pokemon-Showdown,Enigami/Pokemon-Showdown,DesoGit/Tsunami_PS,FakeSloth/Infinite,Sora-League/Sora,Pablo000/aaa,hayleysworld/serenityc9,Pikachuun/Pokemon-Showdown,Parukia/Pokemon-Showdown,Enigami/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,CreaturePhil/Pokemon-Showdown,theodelhay/test,TheManwithskills/DS,forbiddennightmare/Pokemon-Showdown-1,PrimalGallade45/Dropp-Pokemon-Showdown,DalleTest/Pokemon-Showdown,Irraquated/EOS-Master,AWailOfATail/Pokemon-Showdown,zczd/enculer,Extradeath/psserver,psnsVGC/Wish-Server,jd4564/Pokemon-Showdown,SerperiorBae/Pokemon-Showdown-1,JennyPRO/Jenny,Wando94/Pokemon-Showdown,LustyAsh/EOS-Master,SkyeTheFemaleSylveon/Mudkip-Server,SSJGVegito007/Vegito-s-Server,DarkSuicune/Pokemon-Showdown,EienSeiryuu/Pokemon-Showdown,SolarisFox/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,Extradeath/advanced,gustavo515/test,forbiddennightmare/Pokemon-Showdown-1,yashagl/pokemon,Guernouille/Pokemon-Showdown,k3naan/Pokemon-Showdown,hayleysworld/serenityc9,azum4roll/Pokemon-Showdown,hayleysworld/Pokemon-Showdown,DarkSuicune/Kakuja-2.0,Nineage/Origin,BlazingAura/Showdown-Boilerplate,FakeSloth/wulu,hayleysworld/asdfasdf,Kokonoe-san/Glacia-PS,piiiikachuuu/Pokemon-Showdown,Firestatics/omega,brettjbush/Pokemon-Showdown,PrimalGallade45/Lumen-Pokemon-Showdown,lAlejandro22/lolipoop,hayleysworld/serenityserver,yashagl/pokemon,PauLucario/LQP-Server-Showdown,SkyeTheFemaleSylveon/Pokemon-Showdown,Neosweiss/Pokemon-Showdown,ehk12/bigbangtempclone,sama2/Lumen-Pokemon-Showdown,Ransei1/Alt,sirDonovan/Pokemon-Showdown,TheManwithskills/serenity,TogeSR/Lumen-Pokemon-Showdown,Breakfastqueen/advanced,asdfghjklohhnhn/Pokemon-Showdown,Kevinxzllz/PS-Openshift-Server,ZeroParadox/ugh,AbsolitoSweep/Absol-server,TheManwithskills/Creature-phil-boiler,Extradeath/psserver,scotchkorean27/Pokemon-Showdown,MeliodasBH/boarhat,xfix/Pokemon-Showdown,AbsolitoSweep/Absol-server,gustavo515/batata,Irraquated/Showdown-Boilerplate,CharizardtheFireMage/Showdown-Boilerplate,Ridukuo/Test,Kevinxzllz/PS-Openshift-Server,TheManwithskills/COC,DesoGit/Tsunami_PS,Wando94/Pokemon-Showdown,Legit99/Lightning-Storm-Server,Yggdrasil-League/Yggdrasil,Firestatics/Omega-Alpha,Kokonoe-san/Glacia-PS,Atwar/server-epilogueleague.rhcloud.com,ZestOfLife/FestiveLife,TheManwithskills/New-boiler-test,cadaeic/Pokemon-Showdown,johtooo/PS,gustavo515/final,Flareninja/Showdown-Boilerplate,DesoGit/TsunamiPS,Darkshadow6/PokeMoon-Creation,danpantry/Pokemon-Showdown,PS-Spectral/Spectral,ZeroParadox/ugh,BuzzyOG/Pokemon-Showdown,Alpha-Devs/Alpha-Server,Flareninja/Pokemon-Showdown,Articuno-I/Pokemon-Showdown,KewlStatics/Shit,MayukhKundu/Mudkip-Server,TheFenderStory/Pokemon-Showdown,MasterFloat/LQP-Server-Showdown,ZestOfLife/PSserver,yashagl/pokemon-showdown,piiiikachuuu/Pokemon-Showdown,HoeenCoder/SpacialGaze,svivian/Pokemon-Showdown,megaslowbro1/Pokemon-Showdown,azum4roll/Pokemon-Showdown,Git-Worm/City-PS,TheDiabolicGift/Showdown-Boilerplate,TheManwithskills/Dusk--Showdown,superman8900/Pokemon-Showdown,lFernanl/Mudkip-Server,Wando94/Spite,AustinXII/Pokemon-Showdown,MeliodasBH/boarhat,Kill-The-Noise/BlakJack-Boilerplate,Zipzapadam/Server,SerperiorBae/Bae-Showdown,miahjennatills/Pokemon-Showdown,TheManwithskills/Server---Thermal,TbirdClanWish/Pokemon-Showdown,Sora-Server/Sora,javi501/Lumen-Pokemon-Showdown,MayukhKundu/Technogear-Final,lFernanl/Lumen-Pokemon-Showdown,HoeenCoder/SpacialGaze,AustinXII/Pokemon-Showdown,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,xfix/Pokemon-Showdown,lFernanl/Zero-Pokemon-Showdown,kotarou3/Krister-Pokemon-Showdown,MeliodasBH/Articuno-Land,CreaturePhil/Showdown-Boilerplate,Lord-Haji/SpacialGaze,Darkshadow6/git-remote-add-scalingo-git-scalingo.com-pokemoonforums,ehk12/clone,lAlejandro22/lolipoop,TheDiabolicGift/Lumen-Pokemon-Showdown,Zipzapadam/Server,MayukhKundu/Technogear-Final,Flareninja/Pokemon-Showdown,cadaeic/Pokemon-Showdown,TogeSR/Lumen-Pokemon-Showdown,AWailOfATail/awoat,Flareninja/Showdown-Boilerplate,DB898/theregalias,SerperiorBae/BaeShowdown,MayukhKundu/Technogear,Lauc1an/Perulink-Showdown,HoeenCoder/SpacialGaze,Mystifi/Exiled,yashagl/pokecommunity,Pokemon-Devs/Pokemon-Showdown,AWailOfATail/awoat,abulechu/Lumen-Pokemon-Showdown,NoahVSGamingYT/Pokemon-Showdown,SerperiorBae/Bae-Showdown,MayukhKundu/Flame-Savior,SilverTactic/Showdown-Boilerplate,megaslowbro1/Pokemon-Showdown-Server-for-megaslowbro1,comedianchameleon/test,lFernanl/Pokemon-Showdown,SerperiorBae/Pokemon-Showdown,svivian/Pokemon-Showdown,BlazingAura/Showdown-Boilerplate,LightningStormServer/Lightning-Storm,UniversalMan12/Universe-Server,CreaturePhil/Showdown-Boilerplate,SkyeTheFemaleSylveon/Mudkip-Server,SilverTactic/Dragotica-Pokemon-Showdown,SSJGVegito007/Vegito-s-Server,EienSeiryuu/Pokemon-Showdown,CreaturePhil/Pokemon-Showdown,TbirdClanWish/Pokemon-Showdown,SubZeroo99/Pokemon-Showdown,aakashrajput/Pokemon-Showdown,PrimalGallade45/Lumen-Pokemon-Showdown,Atwar/server-epilogueleague.rhcloud.com,kupochu/Pokemon-Showdown,lFernanl/Pokemon-Showdown,Articuno-I/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,Elveman/RPCShowdownServer,brettjbush/Pokemon-Showdown,RustServer/Pokemon-Showdown,MasterFloat/Pokemon-Showdown,UniversalMan12/Universe-Server,SerperiorBae/BaeShowdown,anubhabsen/Pokemon-Showdown,sama2/Dropp-Pokemon-Showdown,Breakfastqueen/advanced,hayleysworld/serenityserver,Ecuacion/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,SilverTactic/Dragotica-Pokemon-Showdown,Darkshadow6/PokeMoon-Creation,panpawn/Pokemon-Showdown,TheDiabolicGift/Showdown-Boilerplate,SerperiorBae/Bae-Showdown-2,kuroscafe/Paradox,kupochu/Pokemon-Showdown,ehk12/coregit,Neosweiss/Pokemon-Showdown,Celecitia/Plux-Pokemon-Showdown,Parukia/Pokemon-Showdown,SerperiorBae/Bae-Showdown,Nineage/Origin,asdfghjklohhnhn/Pokemon-Showdown,Enigami/Pokemon-Showdown,Sora-Server/Sora,KewlStatics/Showdown-Template,xfix/Pokemon-Showdown,InvalidDN/Pokemon-Showdown,sama2/Lumen-Pokemon-Showdown,Sora-League/Sora,Zarel/Pokemon-Showdown,KaitoV4X/Showdown,ankailou/Pokemon-Showdown,Zarel/Pokemon-Showdown,Extradeath/advanced,DalleTest/Pokemon-Showdown,k3naan/Pokemon-Showdown,SolarisFox/Pokemon-Showdown,TheFenderStory/Showdown-Boilerplate,HoeenCoder/SpacialGaze,yashagl/yash-showdown,arkanox/MistShowdown,hayleysworld/serenity,gustavo515/gashoro,EmmaKitty/Pokemon-Showdown,gustavo515/batata,SerperiorBae/Pokemon-Showdown-1,sama2/Universe-Pokemon-Showdown,Legit99/Lightning-Storm-Server,Git-Worm/City-PS,hayleysworld/Showdown-Boilerplate,PauLucario/LQP-Server-Showdown,SerperiorBae/Pokemon-Showdown-1,TheFenderStory/Showdown-Boilerplate,DB898/theregalias,psnsVGC/Wish-Server,MayukhKundu/Pokemon-Domain,Lord-Haji/SpacialGaze,TheManwithskills/Server---Thermal,panpawn/Gold-Server,panpawn/Gold-Server,megaslowbro1/Showdown-Server-again,JellalTheMage/PS-,ScottehMax/Pokemon-Showdown,Tesarand/Pokemon-Showdown,TheManwithskills/Dusk--Showdown,TheManwithskills/Server,urkerab/Pokemon-Showdown,BuzzyOG/Pokemon-Showdown,Sora-Server/Sora,zczd/enculer,KewlStatics/Shit,sirDonovan/Pokemon-Showdown,Pikachuun/Pokemon-Showdown,panpawn/Gold-Server,UniversalMan12/Universe-Server,lFernanl/Zero-Pokemon-Showdown,ZeroParadox/BlastBurners,TheFenderStory/Pokemon-Showdown,FakeSloth/Infinite,KewlStatics/Showdown-Template,kubetz/Pokemon-Showdown,urkerab/Pokemon-Showdown,Firestatics/omega,gustavo515/final,abulechu/Dropp-Pokemon-Showdown,ShowdownHelper/Saffron,ZestOfLife/FestiveLife,Pikachuun/Pokemon-Showdown-SMCMDM,abrulochp/Lumen-Pokemon-Showdown,PS-Spectral/Spectral,TheManwithskills/New-boiler-test,abulechu/Lumen-Pokemon-Showdown,SerperiorBae/Pokemon-Showdown,SerperiorBae/Pokemon-Showdown,TheManwithskills/Server,Pablo000/aaa,kotarou3/Krister-Pokemon-Showdown,jumbowhales/Pokemon-Showdown,panpawn/Pokemon-Showdown,megaslowbro1/Showdown-Server-again,megaslowbro1/Pokemon-Showdown,Vacate/Pokemon-Showdown,Pikachuun/Pokemon-Showdown-SMCMDM,Tesarand/Pokemon-Showdown,Volcos/SpacialGaze,Hidden-Mia/Roleplay-PS,Bryan-0/Pokemon-Showdown,AustinXII/Pokemon-Showdown,megaslowbro1/Pokemon-Showdown-Server-for-megaslowbro1,TheManwithskills/COC,Ecuacion/Pokemon-Showdown,javi501/Lumen-Pokemon-Showdown,TheDiabolicGift/Lumen-Pokemon-Showdown,SerperiorBae/Bae-Showdown-2,TheManwithskills/DS,DarkSuicune/Pokemon-Showdown,gustavo515/test,Firestatics/Omega-Alpha,MasterFloat/LQP-Server-Showdown,MeliodasBH/Articuno-Land,Kill-The-Noise/BlakJack-Boilerplate,DarkSuicune/Kakuja-2.0,gustavo515/gashoro,CharizardtheFireMage/Showdown-Boilerplate,hayleysworld/Showdown-Boilerplate,EmmaKitty/Pokemon-Showdown | exports.BattleFormatsData = {
bulbasaur: {
randomBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","leechseed","synthesis"],
randomDoubleBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["sweetscent","growth","solarbeam","synthesis"]},
{"generation":3,"level":10,"gender":"M","moves":["tackle","growl","leechseed","vinewhip"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tackle","growl","leechseed","vinewhip"]},
{"generation":5,"level":1,"isHidden":false,"moves":["falseswipe","block","frenzyplant","weatherball"]}
],
tier: "LC"
},
ivysaur: {
randomBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","leechseed","synthesis"],
randomDoubleBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","protect"],
tier: "NFE"
},
venusaur: {
randomBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","knockoff","leechseed","synthesis","earthquake"],
randomDoubleBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","protect"],
tier: "OU"
},
venusaurmega: {
randomBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","swordsdance","powerwhip","leechseed","synthesis","earthquake"],
randomDoubleBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","protect"],
requiredItem: "Venusaurite"
},
charmander: {
randomBattleMoves: ["flamethrower","overheat","dragonpulse","hiddenpowergrass","fireblast"],
randomDoubleBattleMoves: ["heatwave","dragonpulse","hiddenpowergrass","fireblast","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["scratch","growl","ember"]},
{"generation":4,"level":40,"gender":"M","nature":"Mild","moves":["return","hiddenpower","quickattack","howl"]},
{"generation":4,"level":40,"gender":"M","nature":"Naive","moves":["return","hiddenpower","quickattack","howl"]},
{"generation":4,"level":40,"gender":"M","nature":"Naughty","moves":["return","hiddenpower","quickattack","howl"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["scratch","growl","ember","smokescreen"]},
{"generation":4,"level":40,"gender":"M","nature":"Hardy","moves":["return","hiddenpower","quickattack","howl"],"pokeball":"cherishball"},
{"generation":5,"level":1,"isHidden":false,"moves":["falseswipe","block","blastburn","acrobatics"]}
],
tier: "LC"
},
charmeleon: {
randomBattleMoves: ["flamethrower","overheat","dragonpulse","hiddenpowergrass","fireblast","dragondance","flareblitz","shadowclaw","dragonclaw"],
randomDoubleBattleMoves: ["heatwave","dragonpulse","hiddenpowergrass","fireblast","protect"],
tier: "NFE"
},
charizard: {
randomBattleMoves: ["fireblast","focusblast","airslash","roost","dragondance","flareblitz","dragonclaw","earthquake"],
randomDoubleBattleMoves: ["heatwave","fireblast","airslash","dragondance","flareblitz","dragonclaw","earthquake","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["wingattack","slash","dragonrage","firespin"]},
{"generation":6,"level":36,"gender":"M","isHidden":false,"moves":["firefang","flameburst","airslash","inferno"],"pokeball":"cherishball"},
{"generation":6,"level":36,"gender":"M","isHidden":false,"moves":["firefang","airslash","dragonclaw","dragonrage"],"pokeball":"cherishball"},
{"generation":6,"level":36,"shiny":true,"gender":"M","isHidden":false,"moves":["overheat","solarbeam","focusblast","holdhands"],"pokeball":"cherishball"}
],
tier: "OU"
},
charizardmegax: {
randomBattleMoves: ["dragondance","flareblitz","dragonclaw","earthquake","roost","substitute"],
randomDoubleBattleMoves: ["dragondance","flareblitz","dragonclaw","earthquake","rockslide","roost","substitute"],
requiredItem: "Charizardite X"
},
charizardmegay: {
randomBattleMoves: ["flamethrower","fireblast","airslash","roost","solarbeam","focusblast"],
randomDoubleBattleMoves: ["heatwave","fireblast","airslash","roost","solarbeam","focusblast","protect"],
requiredItem: "Charizardite Y"
},
squirtle: {
randomBattleMoves: ["icebeam","hydropump","rapidspin","scald","aquajet","toxic"],
randomDoubleBattleMoves: ["muddywater","icebeam","hydropump","fakeout","scald","followme","icywind","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","tailwhip","bubble","withdraw"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tackle","tailwhip","bubble","withdraw"]},
{"generation":5,"level":1,"isHidden":false,"moves":["falseswipe","block","hydrocannon","followme"]}
],
tier: "LC"
},
wartortle: {
randomBattleMoves: ["icebeam","hydropump","rapidspin","scald","aquajet","toxic"],
randomDoubleBattleMoves: ["muddywater","icebeam","hydropump","fakeout","scald","followme","icywind","protect"],
tier: "NFE"
},
blastoise: {
randomBattleMoves: ["icebeam","hydropump","rapidspin","scald","toxic","darkpulse","aurasphere"],
randomDoubleBattleMoves: ["muddywater","icebeam","hydropump","fakeout","scald","darkpulse","aurasphere","followme","icywind","protect","waterspout"],
eventPokemon: [
{"generation":3,"level":70,"moves":["protect","raindance","skullbash","hydropump"]}
],
tier: "UU"
},
blastoisemega: {
randomBattleMoves: ["icebeam","hydropump","rapidspin","scald","aquajet","toxic","dragontail","darkpulse","aurasphere"],
randomDoubleBattleMoves: ["muddywater","icebeam","hydropump","fakeout","scald","darkpulse","aurasphere","followme","icywind","protect"],
requiredItem: "Blastoisinite"
},
caterpie: {
randomBattleMoves: ["bugbite","snore","tackle","electroweb"],
tier: "LC"
},
metapod: {
randomBattleMoves: ["snore","bugbite","tackle","electroweb"],
tier: "NFE"
},
butterfree: {
randomBattleMoves: ["quiverdance","roost","bugbuzz","substitute","sleeppowder","gigadrain","psychic","shadowball"],
randomDoubleBattleMoves: ["quiverdance","bugbuzz","substitute","sleeppowder","gigadrain","psychic","shadowball","protect"],
eventPokemon: [
{"generation":3,"level":30,"moves":["morningsun","psychic","sleeppowder","aerialace"]}
],
tier: "PU"
},
weedle: {
randomBattleMoves: ["bugbite","stringshot","poisonsting","electroweb"],
tier: "LC"
},
kakuna: {
randomBattleMoves: ["electroweb","bugbite","irondefense","poisonsting"],
tier: "NFE"
},
beedrill: {
randomBattleMoves: ["toxicspikes","xscissor","swordsdance","uturn","endeavor","poisonjab","drillrun","knockoff"],
randomDoubleBattleMoves: ["xscissor","uturn","poisonjab","drillrun","brickbreak","knockoff","protect","stringshot"],
eventPokemon: [
{"generation":3,"level":30,"moves":["batonpass","sludgebomb","twineedle","swordsdance"]}
],
tier: "UU"
},
beedrillmega: {
randomBattleMoves: ["toxicspikes","xscissor","swordsdance","uturn","endeavor","poisonjab","drillrun","knockoff"],
randomDoubleBattleMoves: ["xscissor","uturn","substitute","poisonjab","drillrun","knockoff","protect"],
requiredItem: "Beedrillite"
},
pidgey: {
randomBattleMoves: ["roost","bravebird","heatwave","return","workup","uturn","thief"],
randomDoubleBattleMoves: ["bravebird","heatwave","return","uturn","tailwind","protect"],
tier: "LC"
},
pidgeotto: {
randomBattleMoves: ["roost","bravebird","heatwave","return","workup","uturn","thief"],
randomDoubleBattleMoves: ["bravebird","heatwave","return","uturn","tailwind","protect"],
eventPokemon: [
{"generation":3,"level":30,"abilities":["keeneye"],"moves":["refresh","wingattack","steelwing","featherdance"]}
],
tier: "NFE"
},
pidgeot: {
randomBattleMoves: ["roost","bravebird","pursuit","heatwave","return","uturn","hurricane"],
randomDoubleBattleMoves: ["bravebird","heatwave","return","uturn","tailwind","protect"],
eventPokemon: [
{"generation":5,"level":61,"gender":"M","nature":"Naughty","isHidden":false,"abilities":["keeneye"],"moves":["whirlwind","wingattack","skyattack","mirrormove"],"pokeball":"cherishball"}
],
tier: "UU"
},
pidgeotmega: {
randomBattleMoves: ["roost","heatwave","uturn","hurricane","defog"],
randomDoubleBattleMoves: ["tailwind","heatwave","uturn","hurricane","protect"],
requiredItem: "Pidgeotite"
},
rattata: {
randomBattleMoves: ["facade","flamewheel","suckerpunch","uturn","wildcharge","thunderwave","crunch","revenge"],
randomDoubleBattleMoves: ["facade","flamewheel","suckerpunch","uturn","wildcharge","superfang","crunch","protect"],
tier: "LC"
},
raticate: {
randomBattleMoves: ["facade","flamewheel","suckerpunch","uturn","wildcharge","crunch"],
randomDoubleBattleMoves: ["facade","flamewheel","suckerpunch","uturn","wildcharge","superfang","crunch","protect"],
eventPokemon: [
{"generation":3,"level":34,"moves":["refresh","superfang","scaryface","hyperfang"]}
],
tier: "PU"
},
spearow: {
randomBattleMoves: ["return","drillpeck","doubleedge","uturn","quickattack","pursuit","drillrun","featherdance"],
randomDoubleBattleMoves: ["return","drillpeck","doubleedge","uturn","quickattack","drillrun","protect"],
eventPokemon: [
{"generation":3,"level":22,"moves":["batonpass","falseswipe","leer","aerialace"]}
],
tier: "LC"
},
fearow: {
randomBattleMoves: ["return","drillpeck","doubleedge","uturn","quickattack","pursuit","drillrun","roost"],
randomDoubleBattleMoves: ["return","drillpeck","doubleedge","uturn","quickattack","drillrun","protect"],
tier: "PU"
},
ekans: {
randomBattleMoves: ["coil","gunkshot","seedbomb","glare","suckerpunch","aquatail","earthquake","rest","rockslide"],
randomDoubleBattleMoves: ["gunkshot","seedbomb","suckerpunch","aquatail","earthquake","rest","rockslide","protect"],
eventPokemon: [
{"generation":3,"level":14,"abilities":["shedskin"],"moves":["leer","wrap","poisonsting","bite"]},
{"generation":3,"level":10,"gender":"M","moves":["wrap","leer","poisonsting"]}
],
tier: "LC"
},
arbok: {
randomBattleMoves: ["coil","gunkshot","suckerpunch","aquatail","earthquake","rest"],
randomDoubleBattleMoves: ["gunkshot","seedbomb","suckerpunch","aquatail","crunch","earthquake","rest","rockslide","protect"],
eventPokemon: [
{"generation":3,"level":33,"moves":["refresh","sludgebomb","glare","bite"]}
],
tier: "PU"
},
pichu: {
randomBattleMoves: ["fakeout","volttackle","encore","irontail","toxic","thunderbolt"],
randomDoubleBattleMoves: ["fakeout","volttackle","encore","irontail","protect","thunderbolt","discharge"],
eventPokemon: [
{"generation":3,"level":5,"moves":["thundershock","charm","surf"]},
{"generation":3,"level":5,"moves":["thundershock","charm","wish"]},
{"generation":3,"level":5,"moves":["thundershock","charm","teeterdance"]},
{"generation":3,"level":5,"moves":["thundershock","charm","followme"]},
{"generation":4,"level":1,"moves":["volttackle","thunderbolt","grassknot","return"]},
{"generation":4,"level":30,"shiny":true,"gender":"M","nature":"Jolly","moves":["charge","volttackle","endeavor","endure"],"pokeball":"cherishball"},
{"generation":4,"level":30,"shiny":true,"gender":"M","nature":"Jolly","moves":["volttackle","charge","endeavor","endure"],"pokeball":"cherishball"}
],
tier: "LC"
},
pichuspikyeared: {
eventPokemon: [
{"generation":4,"level":30,"gender":"F","nature":"Naughty","moves":["helpinghand","volttackle","swagger","painsplit"]}
],
tier: ""
},
pikachu: {
randomBattleMoves: ["thunderbolt","volttackle","voltswitch","grassknot","hiddenpowerice","brickbreak","extremespeed","encore","substitute","knockoff"],
randomDoubleBattleMoves: ["fakeout","thunderbolt","volttackle","voltswitch","feint","grassknot","hiddenpowerice","brickbreak","extremespeed","encore","substitute","knockoff","protect","discharge"],
eventPokemon: [
{"generation":3,"level":50,"moves":["thunderbolt","agility","thunder","lightscreen"]},
{"generation":3,"level":10,"moves":["thundershock","growl","tailwhip","thunderwave"]},
{"generation":3,"level":10,"moves":["fly","tailwhip","growl","thunderwave"]},
{"generation":3,"level":5,"moves":["surf","growl","tailwhip","thunderwave"]},
{"generation":3,"level":10,"moves":["fly","growl","tailwhip","thunderwave"]},
{"generation":3,"level":10,"moves":["thundershock","growl","thunderwave","surf"]},
{"generation":3,"level":70,"moves":["thunderbolt","thunder","lightscreen","fly"]},
{"generation":3,"level":70,"moves":["thunderbolt","thunder","lightscreen","surf"]},
{"generation":3,"level":70,"moves":["thunderbolt","thunder","lightscreen","agility"]},
{"generation":4,"level":10,"gender":"F","nature":"Hardy","moves":["surf","volttackle","tailwhip","thunderwave"]},
{"generation":3,"level":10,"gender":"M","moves":["thundershock","growl","tailwhip","thunderwave"]},
{"generation":4,"level":50,"gender":"M","nature":"Hardy","moves":["surf","thunderbolt","lightscreen","quickattack"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"F","nature":"Bashful","moves":["present","quickattack","thundershock","tailwhip"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"M","nature":"Jolly","moves":["grassknot","thunderbolt","flash","doubleteam"],"pokeball":"cherishball"},
{"generation":4,"level":40,"gender":"M","nature":"Modest","moves":["surf","thunder","protect"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"F","nature":"Bashful","moves":["quickattack","thundershock","tailwhip","present"],"pokeball":"cherishball"},
{"generation":4,"level":40,"gender":"M","nature":"Mild","moves":["surf","thunder","protect"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"F","nature":"Bashful","moves":["present","quickattack","thunderwave","tailwhip"],"pokeball":"cherishball"},
{"generation":4,"level":30,"gender":"M","moves":["lastresort","present","thunderbolt","quickattack"],"pokeball":"cherishball"},
{"generation":4,"level":50,"gender":"M","nature":"Relaxed","moves":["rest","sleeptalk","yawn","snore"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"M","nature":"Docile","moves":["present","quickattack","thundershock","tailwhip"],"pokeball":"cherishball"},
{"generation":4,"level":50,"gender":"M","nature":"Naughty","moves":["volttackle","irontail","quickattack","thunderbolt"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"M","nature":"Bashful","moves":["present","quickattack","thundershock","tailwhip"],"pokeball":"cherishball"},
{"generation":5,"level":30,"gender":"F","isHidden":true,"moves":["sing","teeterdance","encore","electroball"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["fly","irontail","electroball","quickattack"],"pokeball":"cherishball"},
{"generation":5,"level":100,"gender":"F","isHidden":false,"moves":["thunder","volttackle","grassknot","quickattack"],"pokeball":"cherishball"},
{"generation":5,"level":50,"gender":"F","isHidden":false,"moves":["extremespeed","thunderbolt","grassknot","brickbreak"],"pokeball":"cherishball"},
{"generation":5,"level":50,"gender":"F","isHidden":true,"moves":["fly","thunderbolt","grassknot","protect"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["thundershock","tailwhip","thunderwave","headbutt"]},
{"generation":5,"level":100,"gender":"M","isHidden":true,"moves":["volttackle","quickattack","feint","voltswitch"],"pokeball":"cherishball"},
{"generation":5,"level":50,"gender":"M","nature":"Brave","isHidden":false,"moves":["thunderbolt","quickattack","irontail","electroball"],"pokeball":"cherishball"},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","growl","playnice","quickattack"],"pokeball":"cherishball"},
{"generation":6,"level":22,"isHidden":false,"moves":["quickattack","electroball","doubleteam","megakick"],"pokeball":"cherishball"},
{"generation":6,"level":10,"gender":"M","isHidden":false,"moves":["thunderbolt","quickattack","surf","holdhands"],"pokeball":"cherishball"},
{"generation":6,"level":10,"gender":"F","isHidden":false,"moves":["thunderbolt","quickattack","heartstamp","holdhands"],"pokeball":"healball"},
{"generation":6,"level":36,"shiny":true,"isHidden":true,"moves":["thunder","substitute","playnice","holdhands"],"pokeball":"cherishball"},
{"generation":6,"level":10,"gender":"F","isHidden":false,"moves":["playnice","charm","nuzzle","sweetkiss"],"pokeball":"cherishball"}
],
tier: "NFE"
},
pikachucosplay: {
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
pikachurockstar: {
randomBattleMoves: ["meteormash","wildcharge","knockoff","brickbreak"],
randomDoubleBattleMoves: ["meteormash","discharge","hiddenpowerice","protect"],
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
pikachubelle: {
randomBattleMoves: ["iciclecrash","thunderbolt","knockoff","brickbreak"],
randomDoubleBattleMoves: ["iciclecrash","discharge","protect","brickbreak"],
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
pikachupopstar: {
randomBattleMoves: ["drainingkiss","thunderbolt","hiddenpowerice","knockoff"],
randomDoubleBattleMoves: ["drainingkiss","discharge","hiddenpowerice","protect"],
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
pikachuphd: {
randomBattleMoves: ["electricterrain","thunderbolt","hiddenpowerice","knockoff"],
randomDoubleBattleMoves: ["electricterrain","discharge","hiddenpowerice","protect"],
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
pikachulibre: {
randomBattleMoves: ["flyingpress","thunderbolt","knockoff","grassknot"],
randomDoubleBattleMoves: ["flyingpress","discharge","knockoff","protect"],
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
raichu: {
randomBattleMoves: ["nastyplot","encore","thunderbolt","grassknot","hiddenpowerice","focusblast","substitute"],
randomDoubleBattleMoves: ["fakeout","encore","thunderbolt","grassknot","hiddenpowerice","focusblast","substitute","extremespeed","knockoff","feint","protect"],
tier: "PU"
},
sandshrew: {
randomBattleMoves: ["earthquake","rockslide","swordsdance","rapidspin","xscissor","stealthrock","toxic","knockoff"],
randomDoubleBattleMoves: ["earthquake","rockslide","swordsdance","xscissor","knockoff","protect"],
eventPokemon: [
{"generation":3,"level":12,"moves":["scratch","defensecurl","sandattack","poisonsting"]}
],
tier: "LC"
},
sandslash: {
randomBattleMoves: ["earthquake","stoneedge","swordsdance","rapidspin","xscissor","stealthrock","knockoff"],
randomDoubleBattleMoves: ["earthquake","rockslide","stoneedge","swordsdance","xscissor","knockoff","protect"],
tier: "NU"
},
nidoranf: {
randomBattleMoves: ["toxicspikes","crunch","poisonjab","honeclaws"],
randomDoubleBattleMoves: ["helpinghand","crunch","poisonjab","protect"],
tier: "LC"
},
nidorina: {
randomBattleMoves: ["toxicspikes","crunch","poisonjab","honeclaws","icebeam","thunderbolt","shadowclaw"],
randomDoubleBattleMoves: ["helpinghand","crunch","poisonjab","protect","icebeam","thunderbolt","shadowclaw"],
tier: "NFE"
},
nidoqueen: {
randomBattleMoves: ["toxicspikes","stealthrock","fireblast","thunderbolt","icebeam","earthpower","sludgewave","focusblast"],
randomDoubleBattleMoves: ["helpinghand","protect","fireblast","thunderbolt","icebeam","earthpower","sludgebomb","focusblast"],
tier: "UU"
},
nidoranm: {
randomBattleMoves: ["suckerpunch","poisonjab","headsmash","honeclaws","shadowclaw"],
randomDoubleBattleMoves: ["suckerpunch","poisonjab","shadowclaw","helpinghand","protect"],
tier: "LC"
},
nidorino: {
randomBattleMoves: ["suckerpunch","poisonjab","headsmash","honeclaws","shadowclaw"],
randomDoubleBattleMoves: ["suckerpunch","poisonjab","shadowclaw","helpinghand","protect"],
tier: "NFE"
},
nidoking: {
randomBattleMoves: ["substitute","fireblast","thunderbolt","icebeam","earthpower","sludgewave","focusblast"],
randomDoubleBattleMoves: ["helpinghand","protect","fireblast","thunderbolt","icebeam","earthpower","sludgebomb","focusblast"],
tier: "UU"
},
cleffa: {
randomBattleMoves: ["reflect","thunderwave","lightscreen","toxic","fireblast","encore","wish","protect","aromatherapy","moonblast"],
randomDoubleBattleMoves: ["reflect","thunderwave","lightscreen","safeguard","fireblast","protect","moonblast"],
tier: "LC"
},
clefairy: {
randomBattleMoves: ["healingwish","reflect","thunderwave","lightscreen","toxic","fireblast","encore","wish","protect","aromatherapy","stealthrock","moonblast","knockoff","moonlight"],
randomDoubleBattleMoves: ["reflect","thunderwave","lightscreen","safeguard","fireblast","followme","protect","moonblast"],
tier: "NFE"
},
clefable: {
randomBattleMoves: ["calmmind","softboiled","fireblast","thunderbolt","icebeam","moonblast"],
randomDoubleBattleMoves: ["reflect","thunderwave","lightscreen","safeguard","fireblast","followme","protect","moonblast","softboiled"],
tier: "OU"
},
vulpix: {
randomBattleMoves: ["flamethrower","fireblast","willowisp","energyball","substitute","toxic","hypnosis","painsplit"],
randomDoubleBattleMoves: ["heatwave","fireblast","willowisp","energyball","substitute","protect"],
eventPokemon: [
{"generation":3,"level":18,"moves":["tailwhip","roar","quickattack","willowisp"]},
{"generation":3,"level":18,"moves":["charm","heatwave","ember","dig"]}
],
tier: "LC"
},
ninetales: {
randomBattleMoves: ["flamethrower","fireblast","willowisp","solarbeam","nastyplot","substitute","toxic","painsplit"],
randomDoubleBattleMoves: ["heatwave","fireblast","willowisp","solarbeam","substitute","protect"],
eventPokemon: [
{"generation":5,"level":50,"gender":"M","nature":"Bold","isHidden":true,"moves":["heatwave","solarbeam","psyshock","willowisp"],"pokeball":"cherishball"}
],
tier: "PU"
},
igglybuff: {
randomBattleMoves: ["wish","thunderwave","reflect","lightscreen","healbell","seismictoss","counter","protect","knockoff","dazzlinggleam"],
randomDoubleBattleMoves: ["wish","thunderwave","reflect","lightscreen","seismictoss","protect","knockoff","dazzlinggleam"],
eventPokemon: [
{"generation":3,"level":5,"abilities":["cutecharm"],"moves":["sing","charm","defensecurl","tickle"]}
],
tier: "LC"
},
jigglypuff: {
randomBattleMoves: ["wish","thunderwave","reflect","lightscreen","healbell","seismictoss","counter","stealthrock","protect","knockoff","dazzlinggleam"],
randomDoubleBattleMoves: ["wish","thunderwave","reflect","lightscreen","seismictoss","protect","knockoff","dazzlinggleam"],
tier: "NFE"
},
wigglytuff: {
randomBattleMoves: ["wish","thunderwave","healbell","fireblast","stealthrock","dazzlinggleam","hypervoice"],
randomDoubleBattleMoves: ["thunderwave","reflect","lightscreen","seismictoss","protect","knockoff","dazzlinggleam","fireblast","icebeam","hypervoice"],
tier: "PU"
},
zubat: {
randomBattleMoves: ["bravebird","roost","toxic","taunt","nastyplot","gigadrain","sludgebomb","airslash","uturn","whirlwind","heatwave","superfang"],
randomDoubleBattleMoves: ["bravebird","taunt","nastyplot","gigadrain","sludgebomb","airslash","uturn","protect","heatwave","superfang"],
tier: "LC"
},
golbat: {
randomBattleMoves: ["bravebird","roost","toxic","taunt","defog","superfang","uturn"],
randomDoubleBattleMoves: ["bravebird","taunt","nastyplot","gigadrain","sludgebomb","airslash","uturn","protect","heatwave","superfang"],
tier: "RU"
},
crobat: {
randomBattleMoves: ["bravebird","roost","toxic","taunt","defog","uturn","superfang"],
randomDoubleBattleMoves: ["bravebird","taunt","tailwind","gigadrain","sludgebomb","airslash","uturn","protect","heatwave","superfang"],
eventPokemon: [
{"generation":4,"level":30,"gender":"M","nature":"Timid","moves":["heatwave","airslash","sludgebomb","superfang"],"pokeball":"cherishball"}
],
tier: "UU"
},
oddish: {
randomBattleMoves: ["gigadrain","sludgebomb","synthesis","sleeppowder","stunspore","toxic","hiddenpowerfire","leechseed","dazzlinggleam","sunnyday"],
randomDoubleBattleMoves: ["gigadrain","sludgebomb","sleeppowder","stunspore","protect","hiddenpowerfire","leechseed","dazzlinggleam","sunnyday"],
eventPokemon: [
{"generation":3,"level":26,"moves":["poisonpowder","stunspore","sleeppowder","acid"]},
{"generation":3,"level":5,"moves":["absorb","leechseed"]}
],
tier: "LC"
},
gloom: {
randomBattleMoves: ["gigadrain","sludgebomb","synthesis","sleeppowder","stunspore","toxic","hiddenpowerfire","leechseed","dazzlinggleam","sunnyday"],
randomDoubleBattleMoves: ["gigadrain","sludgebomb","sleeppowder","stunspore","protect","hiddenpowerfire","leechseed","dazzlinggleam","sunnyday"],
eventPokemon: [
{"generation":3,"level":50,"moves":["sleeppowder","acid","moonlight","petaldance"]}
],
tier: "NFE"
},
vileplume: {
randomBattleMoves: ["gigadrain","sludgebomb","synthesis","sleeppowder","stunspore","toxic","hiddenpowerfire","leechseed","aromatherapy"],
randomDoubleBattleMoves: ["gigadrain","sludgebomb","sleeppowder","stunspore","protect","hiddenpowerfire","leechseed","dazzlinggleam","aromatherapy"],
tier: "NU"
},
bellossom: {
randomBattleMoves: ["gigadrain","sludgebomb","synthesis","sleeppowder","hiddenpowerfire","leafstorm","sunnyday"],
randomDoubleBattleMoves: ["gigadrain","sludgebomb","sleeppowder","stunspore","protect","hiddenpowerfire","leechseed","dazzlinggleam","sunnyday","leafstorm"],
tier: "PU"
},
paras: {
randomBattleMoves: ["spore","stunspore","xscissor","seedbomb","synthesis","leechseed","aromatherapy","knockoff"],
randomDoubleBattleMoves: ["spore","stunspore","xscissor","seedbomb","ragepowder","leechseed","protect","knockoff","wideguard"],
eventPokemon: [
{"generation":3,"level":28,"abilities":["effectspore"],"moves":["refresh","spore","slash","falseswipe"]}
],
tier: "LC"
},
parasect: {
randomBattleMoves: ["spore","stunspore","xscissor","seedbomb","synthesis","leechseed","aromatherapy","knockoff"],
randomDoubleBattleMoves: ["spore","stunspore","xscissor","seedbomb","ragepowder","leechseed","protect","knockoff","wideguard"],
tier: "PU"
},
venonat: {
randomBattleMoves: ["sleeppowder","morningsun","toxicspikes","sludgebomb","signalbeam","stunspore","psychic"],
randomDoubleBattleMoves: ["sleeppowder","morningsun","ragepowder","sludgebomb","signalbeam","stunspore","psychic","protect"],
tier: "LC"
},
venomoth: {
randomBattleMoves: ["sleeppowder","roost","quiverdance","batonpass","bugbuzz","sludgebomb","substitute"],
randomDoubleBattleMoves: ["sleeppowder","roost","ragepowder","quiverdance","protect","bugbuzz","sludgebomb","gigadrain","substitute","psychic"],
eventPokemon: [
{"generation":3,"level":32,"abilities":["shielddust"],"moves":["refresh","silverwind","substitute","psychic"]}
],
tier: "BL"
},
diglett: {
randomBattleMoves: ["earthquake","rockslide","stealthrock","suckerpunch","reversal","substitute","shadowclaw"],
randomDoubleBattleMoves: ["earthquake","rockslide","protect","suckerpunch","shadowclaw"],
tier: "LC"
},
dugtrio: {
randomBattleMoves: ["earthquake","stoneedge","stealthrock","suckerpunch","reversal","substitute"],
randomDoubleBattleMoves: ["earthquake","rockslide","protect","suckerpunch","shadowclaw","stoneedge"],
eventPokemon: [
{"generation":3,"level":40,"moves":["charm","earthquake","sandstorm","triattack"]}
],
tier: "RU"
},
meowth: {
randomBattleMoves: ["fakeout","uturn","thief","taunt","return","hypnosis"],
randomDoubleBattleMoves: ["fakeout","uturn","nightslash","taunt","return","hypnosis","feint","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["scratch","growl","petaldance"]},
{"generation":3,"level":5,"moves":["scratch","growl"]},
{"generation":3,"level":10,"gender":"M","moves":["scratch","growl","bite"]},
{"generation":3,"level":22,"moves":["sing","slash","payday","bite"]},
{"generation":4,"level":21,"gender":"F","nature":"Jolly","abilities":["pickup"],"moves":["bite","fakeout","furyswipes","screech"],"pokeball":"cherishball"},
{"generation":4,"level":10,"gender":"M","nature":"Jolly","abilities":["pickup"],"moves":["fakeout","payday","assist","scratch"],"pokeball":"cherishball"},
{"generation":5,"level":15,"gender":"M","isHidden":false,"abilities":["pickup"],"moves":["furyswipes","sing","nastyplot","snatch"],"pokeball":"cherishball"}
],
tier: "LC"
},
persian: {
randomBattleMoves: ["fakeout","uturn","taunt","return","knockoff"],
randomDoubleBattleMoves: ["fakeout","uturn","nightslash","taunt","return","hypnosis","feint","protect"],
tier: "PU"
},
psyduck: {
randomBattleMoves: ["hydropump","scald","icebeam","hiddenpowergrass","crosschop","encore","psychic","signalbeam"],
randomDoubleBattleMoves: ["hydropump","scald","icebeam","hiddenpowergrass","crosschop","encore","psychic","signalbeam","surf","icywind","protect"],
eventPokemon: [
{"generation":3,"level":27,"abilities":["damp"],"moves":["tailwhip","confusion","disable"]},
{"generation":3,"level":5,"moves":["watersport","scratch","tailwhip","mudsport"]}
],
tier: "LC"
},
golduck: {
randomBattleMoves: ["hydropump","scald","icebeam","hiddenpowergrass","encore","focusblast","calmmind"],
randomDoubleBattleMoves: ["hydropump","scald","icebeam","hiddenpowergrass","focusblast","encore","psychic","signalbeam","surf","icywind","protect"],
eventPokemon: [
{"generation":3,"level":33,"moves":["charm","waterfall","psychup","brickbreak"]}
],
tier: "PU"
},
mankey: {
randomBattleMoves: ["closecombat","uturn","icepunch","rockslide","punishment","earthquake","poisonjab"],
randomDoubleBattleMoves: ["closecombat","uturn","icepunch","rockslide","punishment","earthquake","poisonjab","protect"],
tier: "LC"
},
primeape: {
randomBattleMoves: ["closecombat","uturn","icepunch","stoneedge","encore","earthquake","gunkshot"],
randomDoubleBattleMoves: ["closecombat","uturn","icepunch","rockslide","punishment","earthquake","poisonjab","protect","taunt","stoneedge"],
eventPokemon: [
{"generation":3,"level":34,"abilities":["vitalspirit"],"moves":["helpinghand","crosschop","focusenergy","reversal"]}
],
tier: "NU"
},
growlithe: {
randomBattleMoves: ["flareblitz","wildcharge","hiddenpowergrass","closecombat","morningsun","willowisp","toxic","flamethrower"],
randomDoubleBattleMoves: ["flareblitz","wildcharge","hiddenpowergrass","closecombat","willowisp","snarl","heatwave","helpinghand","protect"],
eventPokemon: [
{"generation":3,"level":32,"abilities":["intimidate"],"moves":["leer","odorsleuth","takedown","flamewheel"]},
{"generation":3,"level":10,"gender":"M","moves":["bite","roar","ember"]},
{"generation":3,"level":28,"moves":["charm","flamethrower","bite","takedown"]}
],
tier: "LC"
},
arcanine: {
randomBattleMoves: ["flareblitz","wildcharge","extremespeed","closecombat","morningsun","willowisp","toxic"],
randomDoubleBattleMoves: ["flareblitz","wildcharge","hiddenpowergrass","closecombat","willowisp","snarl","heatwave","helpinghand","protect","extremespeed"],
tier: "UU"
},
poliwag: {
randomBattleMoves: ["hydropump","icebeam","encore","bellydrum","hypnosis","waterfall","return"],
randomDoubleBattleMoves: ["hydropump","icebeam","encore","icywind","hypnosis","waterfall","return","protect","helpinghand"],
eventPokemon: [
{"generation":3,"level":5,"moves":["bubble","sweetkiss"]}
],
tier: "LC"
},
poliwhirl: {
randomBattleMoves: ["hydropump","icebeam","encore","bellydrum","hypnosis","waterfall","return","earthquake"],
randomDoubleBattleMoves: ["hydropump","icebeam","encore","icywind","hypnosis","waterfall","return","protect","helpinghand","earthquake"],
tier: "NFE"
},
poliwrath: {
randomBattleMoves: ["substitute","focuspunch","bulkup","encore","waterfall","toxic","rest","sleeptalk","protect","scald","earthquake","circlethrow"],
randomDoubleBattleMoves: ["substitute","helpinghand","icywind","encore","waterfall","protect","icepunch","poisonjab","earthquake","brickbreak"],
eventPokemon: [
{"generation":3,"level":42,"moves":["helpinghand","hydropump","raindance","brickbreak"]}
],
tier: "PU"
},
politoed: {
randomBattleMoves: ["scald","toxic","encore","perishsong","protect","icebeam","focusblast","hydropump","hiddenpowergrass"],
randomDoubleBattleMoves: ["scald","hypnosis","icywind","encore","helpinghand","protect","icebeam","focusblast","hydropump","hiddenpowergrass"],
eventPokemon: [
{"generation":5,"level":50,"gender":"M","nature":"Calm","isHidden":true,"moves":["scald","icebeam","perishsong","protect"],"pokeball":"cherishball"}
],
tier: "PU"
},
abra: {
randomBattleMoves: ["calmmind","psychic","psyshock","hiddenpowerfighting","shadowball","encore","substitute"],
randomDoubleBattleMoves: ["protect","psychic","psyshock","hiddenpowerfighting","shadowball","encore","substitute"],
tier: "LC"
},
kadabra: {
randomBattleMoves: ["calmmind","psychic","psyshock","hiddenpowerfighting","shadowball","encore","substitute"],
randomDoubleBattleMoves: ["protect","psychic","psyshock","hiddenpowerfighting","shadowball","encore","substitute"],
tier: "PU"
},
alakazam: {
randomBattleMoves: ["psyshock","psychic","focusblast","shadowball","hiddenpowerice","hiddenpowerfire"],
randomDoubleBattleMoves: ["protect","psychic","psyshock","focusblast","shadowball","encore","substitute","energyball"],
eventPokemon: [
{"generation":3,"level":70,"moves":["futuresight","calmmind","psychic","trick"]}
],
tier: "UU"
},
alakazammega: {
randomBattleMoves: ["calmmind","psyshock","focusblast","shadowball","encore","substitute"],
randomDoubleBattleMoves: ["protect","psychic","psyshock","focusblast","shadowball","encore","substitute","energyball"],
requiredItem: "Alakazite",
tier: "BL"
},
machop: {
randomBattleMoves: ["dynamicpunch","bulkup","icepunch","rockslide","bulletpunch","knockoff"],
randomDoubleBattleMoves: ["dynamicpunch","protect","icepunch","rockslide","bulletpunch","knockoff"],
tier: "LC"
},
machoke: {
randomBattleMoves: ["dynamicpunch","bulkup","icepunch","rockslide","bulletpunch","poweruppunch","knockoff"],
randomDoubleBattleMoves: ["dynamicpunch","protect","icepunch","rockslide","bulletpunch","knockoff"],
eventPokemon: [
{"generation":3,"level":38,"abilities":["guts"],"moves":["seismictoss","foresight","revenge","vitalthrow"]},
{"generation":5,"level":30,"isHidden":false,"moves":["lowsweep","foresight","seismictoss","revenge"],"pokeball":"cherishball"}
],
tier: "NFE"
},
machamp: {
randomBattleMoves: ["dynamicpunch","bulkup","icepunch","stoneedge","bulletpunch","earthquake","knockoff"],
randomDoubleBattleMoves: ["dynamicpunch","helpinghand","protect","icepunch","rockslide","bulletpunch","knockoff","wideguard"],
tier: "UU"
},
bellsprout: {
randomBattleMoves: ["swordsdance","sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","seedbomb"],
randomDoubleBattleMoves: ["swordsdance","sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","seedbomb","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["vinewhip","teeterdance"]},
{"generation":3,"level":10,"gender":"M","moves":["vinewhip","growth"]}
],
tier: "LC"
},
weepinbell: {
randomBattleMoves: ["swordsdance","sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","seedbomb","knockoff"],
randomDoubleBattleMoves: ["swordsdance","sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","seedbomb","protect","knockoff"],
eventPokemon: [
{"generation":3,"level":32,"moves":["morningsun","magicalleaf","sludgebomb","sweetscent"]}
],
tier: "NFE"
},
victreebel: {
randomBattleMoves: ["sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","powerwhip","knockoff"],
randomDoubleBattleMoves: ["swordsdance","sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","powerwhip","protect","knockoff"],
tier: "PU"
},
tentacool: {
randomBattleMoves: ["toxicspikes","rapidspin","scald","sludgebomb","icebeam","knockoff","gigadrain","toxic","dazzlinggleam"],
randomDoubleBattleMoves: ["muddywater","scald","sludgebomb","icebeam","knockoff","gigadrain","protect","dazzlinggleam"],
tier: "LC"
},
tentacruel: {
randomBattleMoves: ["toxicspikes","rapidspin","scald","sludgebomb","icebeam","toxic","substitute"],
randomDoubleBattleMoves: ["muddywater","scald","sludgebomb","icebeam","knockoff","gigadrain","protect","dazzlinggleam"],
tier: "UU"
},
geodude: {
randomBattleMoves: ["stealthrock","earthquake","stoneedge","suckerpunch","hammerarm","firepunch","rockblast"],
randomDoubleBattleMoves: ["rockslide","earthquake","stoneedge","suckerpunch","hammerarm","firepunch","rockblast","protect"],
tier: "LC"
},
graveler: {
randomBattleMoves: ["stealthrock","earthquake","stoneedge","suckerpunch","hammerarm","firepunch","rockblast"],
randomDoubleBattleMoves: ["rockslide","earthquake","stoneedge","suckerpunch","hammerarm","firepunch","rockblast","protect"],
tier: "NFE"
},
golem: {
randomBattleMoves: ["stealthrock","earthquake","stoneedge","suckerpunch","toxic","rockblast"],
randomDoubleBattleMoves: ["rockslide","earthquake","stoneedge","suckerpunch","hammerarm","firepunch","rockblast","protect"],
tier: "PU"
},
ponyta: {
randomBattleMoves: ["flareblitz","wildcharge","morningsun","hypnosis","flamecharge"],
randomDoubleBattleMoves: ["flareblitz","wildcharge","protect","hypnosis","flamecharge"],
tier: "LC"
},
rapidash: {
randomBattleMoves: ["flareblitz","wildcharge","morningsun","megahorn","drillrun","willowisp","sunnyday","solarbeam"],
randomDoubleBattleMoves: ["flareblitz","wildcharge","protect","hypnosis","flamecharge","megahorn","drillrun","willowisp","sunnyday","solarbeam"],
eventPokemon: [
{"generation":3,"level":40,"moves":["batonpass","solarbeam","sunnyday","flamethrower"]}
],
tier: "PU"
},
slowpoke: {
randomBattleMoves: ["scald","aquatail","zenheadbutt","thunderwave","toxic","slackoff","trickroom"],
randomDoubleBattleMoves: ["scald","aquatail","zenheadbutt","thunderwave","slackoff","trickroom","protect"],
eventPokemon: [
{"generation":3,"level":31,"abilities":["oblivious"],"moves":["watergun","confusion","disable","headbutt"]},
{"generation":3,"level":10,"gender":"M","moves":["curse","yawn","tackle","growl"]},
{"generation":5,"level":30,"isHidden":false,"moves":["confusion","disable","headbutt","waterpulse"],"pokeball":"cherishball"}
],
tier: "LC"
},
slowbro: {
randomBattleMoves: ["scald","fireblast","icebeam","psychic","grassknot","calmmind","thunderwave","toxic","slackoff","trickroom","psyshock"],
randomDoubleBattleMoves: ["scald","fireblast","icebeam","psychic","grassknot","thunderwave","slackoff","trickroom","protect","psyshock"],
tier: "OU"
},
slowbromega: {
randomBattleMoves: ["scald","fireblast","icebeam","calmmind","psyshock","rest","sleeptalk"],
randomDoubleBattleMoves: ["scald","fireblast","icebeam","psychic","grassknot","thunderwave","slackoff","trickroom","protect","psyshock"],
requiredItem: "Slowbronite"
},
slowking: {
randomBattleMoves: ["scald","fireblast","icebeam","psychic","grassknot","calmmind","thunderwave","toxic","slackoff","trickroom","nastyplot","dragontail","psyshock"],
randomDoubleBattleMoves: ["scald","fireblast","icebeam","psychic","grassknot","thunderwave","slackoff","trickroom","protect","psyshock"],
tier: "RU"
},
magnemite: {
randomBattleMoves: ["thunderbolt","thunderwave","magnetrise","substitute","flashcannon","hiddenpowerice","voltswitch"],
randomDoubleBattleMoves: ["thunderbolt","thunderwave","magnetrise","substitute","flashcannon","hiddenpowerice","voltswitch","protect","electroweb","discharge"],
tier: "LC"
},
magneton: {
randomBattleMoves: ["thunderbolt","substitute","flashcannon","hiddenpowerice","voltswitch","chargebeam","hiddenpowerfire"],
randomDoubleBattleMoves: ["thunderbolt","thunderwave","magnetrise","substitute","flashcannon","hiddenpowerice","voltswitch","protect","electroweb","discharge","hiddenpowerfire"],
eventPokemon: [
{"generation":3,"level":30,"moves":["refresh","doubleedge","raindance","thunder"]}
],
tier: "RU"
},
magnezone: {
randomBattleMoves: ["thunderbolt","substitute","flashcannon","hiddenpowerice","voltswitch","chargebeam","hiddenpowerfire"],
randomDoubleBattleMoves: ["thunderbolt","thunderwave","magnetrise","substitute","flashcannon","hiddenpowerice","voltswitch","protect","electroweb","discharge","hiddenpowerfire"],
tier: "OU"
},
farfetchd: {
randomBattleMoves: ["bravebird","swordsdance","return","leafblade","roost","nightslash"],
randomDoubleBattleMoves: ["bravebird","swordsdance","return","leafblade","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["yawn","wish"]},
{"generation":3,"level":36,"moves":["batonpass","slash","swordsdance","aerialace"]}
],
tier: "PU"
},
doduo: {
randomBattleMoves: ["bravebird","return","doubleedge","roost","quickattack","pursuit"],
randomDoubleBattleMoves: ["bravebird","return","doubleedge","quickattack","protect"],
tier: "LC"
},
dodrio: {
randomBattleMoves: ["bravebird","return","doubleedge","roost","quickattack","knockoff"],
randomDoubleBattleMoves: ["bravebird","return","doubleedge","quickattack","protect"],
eventPokemon: [
{"generation":3,"level":34,"moves":["batonpass","drillpeck","agility","triattack"]}
],
tier: "PU"
},
seel: {
randomBattleMoves: ["surf","icebeam","aquajet","protect","rest","toxic","drillrun"],
randomDoubleBattleMoves: ["surf","icebeam","aquajet","protect","rest","fakeout","drillrun","icywind"],
eventPokemon: [
{"generation":3,"level":23,"abilities":["thickfat"],"moves":["helpinghand","surf","safeguard","icebeam"]}
],
tier: "LC"
},
dewgong: {
randomBattleMoves: ["surf","icebeam","aquajet","iceshard","toxic","drillrun","encore"],
randomDoubleBattleMoves: ["surf","icebeam","aquajet","protect","rest","fakeout","drillrun","icywind"],
tier: "PU"
},
grimer: {
randomBattleMoves: ["curse","gunkshot","poisonjab","shadowsneak","painsplit","icepunch","firepunch","memento"],
randomDoubleBattleMoves: ["gunkshot","poisonjab","shadowsneak","protect","icepunch","firepunch"],
eventPokemon: [
{"generation":3,"level":23,"moves":["helpinghand","sludgebomb","shadowpunch","minimize"]}
],
tier: "LC"
},
muk: {
randomBattleMoves: ["curse","gunkshot","poisonjab","shadowsneak","icepunch","firepunch","memento"],
randomDoubleBattleMoves: ["gunkshot","poisonjab","shadowsneak","protect","icepunch","firepunch","brickbreak"],
tier: "NU"
},
shellder: {
randomBattleMoves: ["shellsmash","hydropump","razorshell","rockblast","iciclespear","rapidspin"],
randomDoubleBattleMoves: ["shellsmash","hydropump","razorshell","rockblast","iciclespear","protect"],
eventPokemon: [
{"generation":3,"level":24,"abilities":["shellarmor"],"moves":["withdraw","iciclespear","supersonic","aurorabeam"]},
{"generation":3,"level":10,"gender":"M","abilities":["shellarmor"],"moves":["tackle","withdraw","iciclespear"]},
{"generation":3,"level":29,"abilities":["shellarmor"],"moves":["refresh","takedown","surf","aurorabeam"]}
],
tier: "LC"
},
cloyster: {
randomBattleMoves: ["shellsmash","hydropump","razorshell","rockblast","iciclespear","iceshard","rapidspin","spikes","toxicspikes"],
randomDoubleBattleMoves: ["shellsmash","hydropump","razorshell","rockblast","iciclespear","protect"],
eventPokemon: [
{"generation":5,"level":30,"gender":"M","nature":"Naughty","isHidden":false,"abilities":["skilllink"],"moves":["iciclespear","rockblast","hiddenpower","razorshell"]}
],
tier: "UU"
},
gastly: {
randomBattleMoves: ["shadowball","sludgebomb","hiddenpowerfighting","thunderbolt","substitute","disable","painsplit","hypnosis","gigadrain","trick","dazzlinggleam"],
randomDoubleBattleMoves: ["shadowball","sludgebomb","hiddenpowerfighting","thunderbolt","substitute","disable","taunt","hypnosis","gigadrain","trick","dazzlinggleam","protect"],
tier: "LC"
},
haunter: {
randomBattleMoves: ["shadowball","sludgebomb","hiddenpowerfighting","thunderbolt","substitute","disable","painsplit","hypnosis","gigadrain","trick"],
randomDoubleBattleMoves: ["shadowball","sludgebomb","hiddenpowerfighting","thunderbolt","substitute","disable","taunt","hypnosis","gigadrain","trick","dazzlinggleam","protect"],
eventPokemon: [
{"generation":3,"level":23,"moves":["spite","curse","nightshade","confuseray"]},
{"generation":5,"level":30,"moves":["confuseray","suckerpunch","shadowpunch","payback"],"pokeball":"cherishball"}
],
tier: "PU"
},
gengar: {
randomBattleMoves: ["shadowball","sludgebomb","focusblast","thunderbolt","substitute","disable","painsplit"],
randomDoubleBattleMoves: ["shadowball","sludgebomb","focusblast","thunderbolt","substitute","disable","taunt","hypnosis","gigadrain","trick","dazzlinggleam","protect"],
eventPokemon: [
{"generation":6,"level":25,"nature":"Timid","moves":["psychic","confuseray","suckerpunch","shadowpunch"],"pokeball":"cherishball"},
{"generation":6,"level":25,"moves":["nightshade","confuseray","suckerpunch","shadowpunch"],"pokeball":"cherishball"},
{"generation":6,"level":50,"moves":["shadowball","sludgebomb","willowisp","destinybond"],"pokeball":"cherishball"},
{"generation":6,"level":25,"shiny":true,"moves":["shadowball","sludgewave","confuseray","astonish"],"pokeball":"duskball"}
],
tier: "OU"
},
gengarmega: {
randomBattleMoves: ["shadowball","sludgebomb","focusblast","thunderbolt","substitute","disable","painsplit","hypnosis","gigadrain"],
randomDoubleBattleMoves: ["shadowball","sludgebomb","focusblast","thunderbolt","substitute","disable","taunt","hypnosis","gigadrain","trick","dazzlinggleam","protect"],
requiredItem: "Gengarite",
tier: "Uber"
},
onix: {
randomBattleMoves: ["stealthrock","earthquake","stoneedge","dragontail","curse"],
randomDoubleBattleMoves: ["stealthrock","earthquake","stoneedge","rockslide","protect","explosion"],
tier: "LC"
},
steelix: {
randomBattleMoves: ["stealthrock","earthquake","ironhead","roar","toxic","rockslide"],
randomDoubleBattleMoves: ["stealthrock","earthquake","ironhead","rockslide","protect","explosion","icefang","firefang"],
tier: "NU"
},
steelixmega: {
randomBattleMoves: ["stealthrock","earthquake","heavyslam","roar","toxic"],
randomDoubleBattleMoves: ["stealthrock","earthquake","heavyslam","rockslide","protect","explosion"],
requiredItem: "Steelixite"
},
drowzee: {
randomBattleMoves: ["psychic","seismictoss","thunderwave","wish","protect","toxic","shadowball","trickroom","calmmind","dazzlinggleam"],
randomDoubleBattleMoves: ["psychic","seismictoss","thunderwave","wish","protect","hypnosis","shadowball","trickroom","calmmind","dazzlinggleam","toxic"],
eventPokemon: [
{"generation":3,"level":5,"abilities":["insomnia"],"moves":["bellydrum","wish"]}
],
tier: "LC"
},
hypno: {
randomBattleMoves: ["psychic","seismictoss","thunderwave","wish","protect","batonpass","toxic"],
randomDoubleBattleMoves: ["psychic","seismictoss","thunderwave","wish","protect","hypnosis","shadowball","trickroom","calmmind","dazzlinggleam","firepunch"],
eventPokemon: [
{"generation":3,"level":34,"abilities":["insomnia"],"moves":["batonpass","psychic","meditate","shadowball"]}
],
tier: "PU"
},
krabby: {
randomBattleMoves: ["crabhammer","swordsdance","agility","rockslide","substitute","xscissor","superpower","knockoff"],
randomDoubleBattleMoves: ["crabhammer","swordsdance","rockslide","substitute","xscissor","superpower","knockoff","protect"],
tier: "LC"
},
kingler: {
randomBattleMoves: ["crabhammer","xscissor","rockslide","swordsdance","agility","superpower","knockoff"],
randomDoubleBattleMoves: ["crabhammer","xscissor","rockslide","substitute","xscissor","superpower","knockoff","protect","wideguard"],
tier: "PU"
},
voltorb: {
randomBattleMoves: ["voltswitch","thunderbolt","taunt","foulplay","hiddenpowerice"],
randomDoubleBattleMoves: ["voltswitch","thunderbolt","taunt","foulplay","hiddenpowerice","protect","thunderwave"],
eventPokemon: [
{"generation":3,"level":19,"moves":["refresh","mirrorcoat","spark","swift"]}
],
tier: "LC"
},
electrode: {
randomBattleMoves: ["voltswitch","thunderbolt","taunt","foulplay","hiddenpowerice"],
randomDoubleBattleMoves: ["voltswitch","discharge","taunt","foulplay","hiddenpowerice","protect","thunderwave"],
tier: "PU"
},
exeggcute: {
randomBattleMoves: ["substitute","leechseed","gigadrain","psychic","sleeppowder","stunspore","hiddenpowerfire","synthesis"],
randomDoubleBattleMoves: ["substitute","leechseed","gigadrain","psychic","sleeppowder","stunspore","hiddenpowerfire","protect","trickroom"],
eventPokemon: [
{"generation":3,"level":5,"moves":["sweetscent","wish"]}
],
tier: "LC"
},
exeggutor: {
randomBattleMoves: ["substitute","leechseed","gigadrain","leafstorm","psychic","sleeppowder","hiddenpowerfire","trickroom","psyshock"],
randomDoubleBattleMoves: ["substitute","leechseed","gigadrain","leafstorm","psychic","sleeppowder","stunspore","hiddenpowerfire","protect","sludgebomb","trickroom","psyshock"],
eventPokemon: [
{"generation":3,"level":46,"moves":["refresh","psychic","hypnosis","ancientpower"]}
],
tier: "NU"
},
cubone: {
randomBattleMoves: ["substitute","bonemerang","doubleedge","rockslide","firepunch","earthquake"],
randomDoubleBattleMoves: ["substitute","bonemerang","doubleedge","rockslide","firepunch","earthquake","protect"],
tier: "LC"
},
marowak: {
randomBattleMoves: ["stealthrock","doubleedge","stoneedge","swordsdance","bonemerang","earthquake","knockoff","substitute"],
randomDoubleBattleMoves: ["substitute","bonemerang","doubleedge","rockslide","firepunch","earthquake","protect","swordsdance"],
eventPokemon: [
{"generation":3,"level":44,"moves":["sing","earthquake","swordsdance","rockslide"]}
],
tier: "PU"
},
tyrogue: {
randomBattleMoves: ["highjumpkick","rapidspin","fakeout","bulletpunch","machpunch","toxic","counter"],
randomDoubleBattleMoves: ["highjumpkick","fakeout","bulletpunch","machpunch","helpinghand","protect"],
tier: "LC"
},
hitmonlee: {
randomBattleMoves: ["highjumpkick","suckerpunch","stoneedge","machpunch","rapidspin","knockoff","poisonjab","fakeout"],
randomDoubleBattleMoves: ["helpinghand","suckerpunch","rockslide","machpunch","substitute","fakeout","closecombat","earthquake","blazekick","wideguard","protect"],
eventPokemon: [
{"generation":3,"level":38,"abilities":["limber"],"moves":["refresh","highjumpkick","mindreader","megakick"]}
],
tier: "RU"
},
hitmonchan: {
randomBattleMoves: ["bulkup","drainpunch","icepunch","firepunch","machpunch","substitute","rapidspin"],
randomDoubleBattleMoves: ["fakeout","drainpunch","icepunch","firepunch","machpunch","substitute","earthquake","rockslide","protect","helpinghand"],
eventPokemon: [
{"generation":3,"level":38,"abilities":["keeneye"],"moves":["helpinghand","skyuppercut","mindreader","megapunch"]}
],
tier: "RU"
},
hitmontop: {
randomBattleMoves: ["suckerpunch","machpunch","rapidspin","closecombat","toxic"],
randomDoubleBattleMoves: ["fakeout","feint","suckerpunch","closecombat","helpinghand","machpunch","wideguard"],
eventPokemon: [
{"generation":5,"level":55,"gender":"M","nature":"Adamant","isHidden":false,"abilities":["intimidate"],"moves":["fakeout","closecombat","suckerpunch","helpinghand"]}
],
tier: "RU"
},
lickitung: {
randomBattleMoves: ["wish","protect","dragontail","curse","bodyslam","return","powerwhip","swordsdance","earthquake","toxic","healbell"],
randomDoubleBattleMoves: ["wish","protect","dragontail","knockoff","bodyslam","return","powerwhip","swordsdance","earthquake","toxic","healbell"],
eventPokemon: [
{"generation":3,"level":5,"moves":["healbell","wish"]},
{"generation":3,"level":38,"moves":["helpinghand","doubleedge","defensecurl","rollout"]}
],
tier: "LC"
},
lickilicky: {
randomBattleMoves: ["wish","protect","dragontail","bodyslam","return","powerwhip","swordsdance","earthquake","toxic","healbell","explosion","knockoff"],
randomDoubleBattleMoves: ["wish","protect","dragontail","knockoff","bodyslam","return","powerwhip","swordsdance","earthquake","toxic","healbell","explosion"],
tier: "PU"
},
koffing: {
randomBattleMoves: ["painsplit","sludgebomb","willowisp","fireblast","toxic","clearsmog","rest","sleeptalk","thunderbolt"],
randomDoubleBattleMoves: ["protect","sludgebomb","willowisp","fireblast","toxic","rest","sleeptalk","thunderbolt"],
tier: "LC"
},
weezing: {
randomBattleMoves: ["painsplit","sludgebomb","willowisp","fireblast","toxic","clearsmog","toxicspikes"],
randomDoubleBattleMoves: ["protect","sludgebomb","willowisp","fireblast","toxic","rest","sleeptalk","thunderbolt","explosion"],
tier: "NU"
},
rhyhorn: {
randomBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockblast","rockpolish"],
randomDoubleBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockslide","protect"],
tier: "LC"
},
rhydon: {
randomBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockblast","rockpolish"],
randomDoubleBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockslide","protect"],
eventPokemon: [
{"generation":3,"level":46,"moves":["helpinghand","megahorn","scaryface","earthquake"]}
],
tier: "NU"
},
rhyperior: {
randomBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockblast","rockpolish","dragontail"],
randomDoubleBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockslide","protect"],
tier: "RU"
},
happiny: {
randomBattleMoves: ["aromatherapy","toxic","thunderwave","counter","endeavor","lightscreen","fireblast"],
randomDoubleBattleMoves: ["aromatherapy","toxic","thunderwave","helpinghand","swagger","lightscreen","fireblast","protect"],
tier: "LC"
},
chansey: {
randomBattleMoves: ["wish","softboiled","protect","toxic","aromatherapy","seismictoss","counter","thunderwave","stealthrock","fireblast","icebeam"],
randomDoubleBattleMoves: ["aromatherapy","toxic","thunderwave","helpinghand","softboiled","lightscreen","seismictoss","protect","wish"],
eventPokemon: [
{"generation":3,"level":5,"gender":"F","moves":["sweetscent","wish"]},
{"generation":3,"level":10,"gender":"F","moves":["pound","growl","tailwhip","refresh"]},
{"generation":3,"level":39,"gender":"F","moves":["sweetkiss","thunderbolt","softboiled","skillswap"]}
],
tier: "OU"
},
blissey: {
randomBattleMoves: ["wish","softboiled","protect","toxic","healbell","seismictoss","counter","thunderwave","stealthrock","flamethrower","icebeam"],
randomDoubleBattleMoves: ["wish","softboiled","protect","toxic","aromatherapy","seismictoss","helpinghand","thunderwave","flamethrower","icebeam"],
eventPokemon: [
{"generation":5,"level":10,"gender":"F","isHidden":true,"moves":["pound","growl","tailwhip","refresh"]}
],
tier: "UU"
},
tangela: {
randomBattleMoves: ["gigadrain","sleeppowder","hiddenpowerfire","hiddenpowerice","leechseed","knockoff","leafstorm","sludgebomb","synthesis"],
randomDoubleBattleMoves: ["gigadrain","sleeppowder","hiddenpowerrock","hiddenpowerice","leechseed","knockoff","leafstorm","stunspore","protect","hiddenpowerfire"],
eventPokemon: [
{"generation":3,"level":30,"abilities":["chlorophyll"],"moves":["morningsun","solarbeam","sunnyday","ingrain"]}
],
tier: "PU"
},
tangrowth: {
randomBattleMoves: ["gigadrain","sleeppowder","hiddenpowerice","leechseed","knockoff","leafstorm","focusblast","synthesis","powerwhip","earthquake"],
randomDoubleBattleMoves: ["gigadrain","sleeppowder","hiddenpowerice","leechseed","knockoff","leafstorm","stunspore","focusblast","protect","powerwhip","earthquake"],
tier: "RU"
},
kangaskhan: {
randomBattleMoves: ["return","suckerpunch","earthquake","drainpunch","crunch","fakeout"],
randomDoubleBattleMoves: ["fakeout","return","suckerpunch","earthquake","doubleedge","poweruppunch","drainpunch","crunch","protect"],
eventPokemon: [
{"generation":3,"level":5,"gender":"F","abilities":["earlybird"],"moves":["yawn","wish"]},
{"generation":3,"level":10,"gender":"F","abilities":["earlybird"],"moves":["cometpunch","leer","bite"]},
{"generation":3,"level":36,"gender":"F","abilities":["earlybird"],"moves":["sing","earthquake","tailwhip","dizzypunch"]},
{"generation":6,"level":50,"gender":"F","isHidden":false,"abilities":["scrappy"],"moves":["fakeout","return","earthquake","suckerpunch"],"pokeball":"cherishball"}
],
tier: "NU"
},
kangaskhanmega: {
randomBattleMoves: ["fakeout","return","suckerpunch","earthquake","poweruppunch","crunch"],
randomDoubleBattleMoves: ["fakeout","return","suckerpunch","earthquake","doubleedge","poweruppunch","drainpunch","crunch","protect"],
requiredItem: "Kangaskhanite",
tier: "Uber"
},
horsea: {
randomBattleMoves: ["hydropump","icebeam","substitute","hiddenpowergrass","raindance"],
randomDoubleBattleMoves: ["hydropump","icebeam","substitute","hiddenpowergrass","raindance","muddywater","protect"],
eventPokemon: [
{"generation":5,"level":1,"shiny":true,"isHidden":false,"moves":["bubble"]}
],
tier: "LC"
},
seadra: {
randomBattleMoves: ["hydropump","icebeam","agility","substitute","hiddenpowergrass"],
randomDoubleBattleMoves: ["hydropump","icebeam","substitute","hiddenpowergrass","agility","muddywater","protect"],
eventPokemon: [
{"generation":3,"level":45,"abilities":["poisonpoint"],"moves":["leer","watergun","twister","agility"]}
],
tier: "NFE"
},
kingdra: {
randomBattleMoves: ["hydropump","dragondance","substitute","outrage","dracometeor","waterfall","dragonpulse","scald"],
randomDoubleBattleMoves: ["hydropump","icebeam","dragondance","substitute","outrage","dracometeor","waterfall","dragonpulse","muddywater","protect"],
eventPokemon: [
{"generation":3,"level":50,"abilities":["swiftswim"],"moves":["leer","watergun","twister","agility"]},
{"generation":5,"level":50,"gender":"M","nature":"Timid","isHidden":false,"abilities":["swiftswim"],"moves":["dracometeor","muddywater","dragonpulse","protect"],"pokeball":"cherishball"}
],
tier: "UU"
},
goldeen: {
randomBattleMoves: ["waterfall","megahorn","knockoff","drillrun","icebeam"],
randomDoubleBattleMoves: ["waterfall","megahorn","knockoff","drillrun","icebeam","protect"],
tier: "LC"
},
seaking: {
randomBattleMoves: ["waterfall","scald","megahorn","knockoff","drillrun","icebeam"],
randomDoubleBattleMoves: ["waterfall","surf","megahorn","knockoff","drillrun","icebeam","icywind","protect"],
tier: "PU"
},
staryu: {
randomBattleMoves: ["scald","thunderbolt","icebeam","rapidspin","recover","dazzlinggleam","hydropump"],
randomDoubleBattleMoves: ["scald","thunderbolt","icebeam","protect","recover","dazzlinggleam","hydropump"],
eventPokemon: [
{"generation":3,"level":50,"moves":["minimize","lightscreen","cosmicpower","hydropump"]},
{"generation":3,"level":18,"abilities":["illuminate"],"moves":["tackle","watergun","rapidspin","recover"]}
],
tier: "LC"
},
starmie: {
randomBattleMoves: ["thunderbolt","icebeam","rapidspin","recover","psyshock","scald","hydropump"],
randomDoubleBattleMoves: ["surf","thunderbolt","icebeam","protect","recover","psychic","psyshock","scald","hydropump"],
eventPokemon: [
{"generation":3,"level":41,"moves":["refresh","waterfall","icebeam","recover"]}
],
tier: "OU"
},
mimejr: {
randomBattleMoves: ["batonpass","psychic","thunderwave","hiddenpowerfighting","healingwish","nastyplot","thunderbolt","encore"],
randomDoubleBattleMoves: ["fakeout","psychic","thunderwave","hiddenpowerfighting","healingwish","nastyplot","thunderbolt","encore","icywind","protect"],
tier: "LC"
},
mrmime: {
randomBattleMoves: ["batonpass","psychic","psyshock","focusblast","healingwish","nastyplot","thunderbolt","encore","dazzlinggleam"],
randomDoubleBattleMoves: ["fakeout","psychic","thunderwave","hiddenpowerfighting","healingwish","nastyplot","thunderbolt","encore","icywind","protect","wideguard","dazzlinggleam"],
eventPokemon: [
{"generation":3,"level":42,"abilities":["soundproof"],"moves":["followme","psychic","encore","thunderpunch"]}
],
tier: "PU"
},
scyther: {
randomBattleMoves: ["swordsdance","roost","bugbite","quickattack","brickbreak","aerialace","batonpass","uturn","knockoff"],
randomDoubleBattleMoves: ["swordsdance","protect","bugbite","quickattack","brickbreak","aerialace","feint","uturn","knockoff"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["swarm"],"moves":["quickattack","leer","focusenergy"]},
{"generation":3,"level":40,"abilities":["swarm"],"moves":["morningsun","razorwind","silverwind","slash"]},
{"generation":5,"level":30,"isHidden":false,"moves":["agility","wingattack","furycutter","slash"],"pokeball":"cherishball"}
],
tier: "NU"
},
scizor: {
randomBattleMoves: ["swordsdance","roost","bulletpunch","bugbite","superpower","uturn","pursuit","defog","knockoff"],
randomDoubleBattleMoves: ["swordsdance","roost","bulletpunch","bugbite","superpower","uturn","protect","feint","knockoff"],
eventPokemon: [
{"generation":3,"level":50,"gender":"M","abilities":["swarm"],"moves":["furycutter","metalclaw","swordsdance","slash"]},
{"generation":4,"level":50,"gender":"M","nature":"Adamant","abilities":["swarm"],"moves":["xscissor","swordsdance","irondefense","agility"],"pokeball":"cherishball"},
{"generation":5,"level":100,"gender":"M","isHidden":false,"abilities":["technician"],"moves":["bulletpunch","bugbite","roost","swordsdance"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["leer","focusenergy","pursuit","steelwing"]},
{"generation":6,"level":50,"gender":"M","isHidden":false,"moves":["xscissor","nightslash","doublehit","ironhead"],"pokeball":"cherishball"},
{"generation":6,"level":25,"nature":"Adamant","isHidden":false,"abilities":["technician"],"moves":["aerialace","falseswipe","agility","furycutter"],"pokeball":"cherishball"},
{"generation":6,"level":25,"isHidden":false,"moves":["metalclaw","falseswipe","agility","furycutter"],"pokeball":"cherishball"},
{"generation":6,"level":50,"isHidden":false,"abilities":["technician"],"moves":["bulletpunch","swordsdance","roost","uturn"],"pokeball":"cherishball"}
],
tier: "OU"
},
scizormega: {
randomBattleMoves: ["swordsdance","roost","bulletpunch","bugbite","superpower","uturn","batonpass","pursuit","defog","knockoff"],
randomDoubleBattleMoves: ["swordsdance","roost","bulletpunch","bugbite","superpower","uturn","protect","feint","knockoff"],
requiredItem: "Scizorite"
},
smoochum: {
randomBattleMoves: ["icebeam","psychic","hiddenpowerfighting","trick","shadowball","grassknot"],
randomDoubleBattleMoves: ["icebeam","psychic","hiddenpowerfighting","trick","shadowball","grassknot","fakeout","protect"],
tier: "LC"
},
jynx: {
randomBattleMoves: ["icebeam","psychic","focusblast","trick","nastyplot","lovelykiss","substitute","psyshock"],
randomDoubleBattleMoves: ["icebeam","psychic","hiddenpowerfighting","shadowball","protect","lovelykiss","substitute","psyshock"],
tier: "NU"
},
elekid: {
randomBattleMoves: ["thunderbolt","crosschop","voltswitch","substitute","icepunch","psychic","hiddenpowergrass"],
randomDoubleBattleMoves: ["thunderbolt","crosschop","voltswitch","substitute","icepunch","psychic","hiddenpowergrass","protect"],
eventPokemon: [
{"generation":3,"level":20,"moves":["icepunch","firepunch","thunderpunch","crosschop"]}
],
tier: "LC"
},
electabuzz: {
randomBattleMoves: ["thunderbolt","voltswitch","substitute","hiddenpowerice","hiddenpowergrass","focusblast","psychic"],
randomDoubleBattleMoves: ["thunderbolt","crosschop","voltswitch","substitute","icepunch","psychic","hiddenpowergrass","protect","focusblast","discharge"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["quickattack","leer","thunderpunch"]},
{"generation":3,"level":43,"moves":["followme","crosschop","thunderwave","thunderbolt"]},
{"generation":4,"level":30,"gender":"M","nature":"Naughty","moves":["lowkick","shockwave","lightscreen","thunderpunch"]},
{"generation":5,"level":30,"isHidden":false,"moves":["lowkick","swift","shockwave","lightscreen"],"pokeball":"cherishball"},
{"generation":6,"level":30,"gender":"M","isHidden":true,"moves":["lowkick","shockwave","lightscreen","thunderpunch"],"pokeball":"cherishball"}
],
tier: "NFE"
},
electivire: {
randomBattleMoves: ["wildcharge","crosschop","icepunch","flamethrower","earthquake","voltswitch"],
randomDoubleBattleMoves: ["wildcharge","crosschop","icepunch","substitute","flamethrower","earthquake","protect","thunderbolt","followme"],
eventPokemon: [
{"generation":4,"level":50,"gender":"M","nature":"Adamant","moves":["thunderpunch","icepunch","crosschop","earthquake"]},
{"generation":4,"level":50,"gender":"M","nature":"Serious","moves":["lightscreen","thunderpunch","discharge","thunderbolt"],"pokeball":"cherishball"}
],
tier: "NU"
},
magby: {
randomBattleMoves: ["flareblitz","substitute","fireblast","hiddenpowergrass","hiddenpowerice","crosschop","thunderpunch","overheat"],
tier: "LC"
},
magmar: {
randomBattleMoves: ["flareblitz","substitute","fireblast","hiddenpowergrass","hiddenpowerice","crosschop","thunderpunch","focusblast"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["leer","smog","firepunch","leer"]},
{"generation":3,"level":36,"moves":["followme","fireblast","crosschop","thunderpunch"]},
{"generation":4,"level":30,"gender":"M","nature":"Quiet","moves":["smokescreen","firespin","confuseray","firepunch"]},
{"generation":5,"level":30,"isHidden":false,"moves":["smokescreen","feintattack","firespin","confuseray"],"pokeball":"cherishball"},
{"generation":6,"level":30,"gender":"M","isHidden":true,"moves":["smokescreen","firespin","confuseray","firepunch"],"pokeball":"cherishball"}
],
tier: "NFE"
},
magmortar: {
randomBattleMoves: ["fireblast","focusblast","hiddenpowergrass","hiddenpowerice","thunderbolt","earthquake","willowisp"],
randomDoubleBattleMoves: ["fireblast","taunt","focusblast","hiddenpowergrass","hiddenpowerice","thunderbolt","heatwave","willowisp","protect","followme"],
eventPokemon: [
{"generation":4,"level":50,"gender":"F","nature":"Modest","moves":["flamethrower","psychic","hyperbeam","solarbeam"]},
{"generation":4,"level":50,"gender":"M","nature":"Hardy","moves":["confuseray","firepunch","lavaplume","flamethrower"],"pokeball":"cherishball"}
],
tier: "NU"
},
pinsir: {
randomBattleMoves: ["earthquake","xscissor","closecombat","stoneedge","stealthrock","knockoff"],
randomDoubleBattleMoves: ["protect","swordsdance","xscissor","earthquake","closecombat","substitute","rockslide"],
eventPokemon: [
{"generation":3,"level":35,"abilities":["hypercutter"],"moves":["helpinghand","guillotine","falseswipe","submission"]},
{"generation":6,"level":50,"gender":"F","nature":"Adamant","isHidden":false,"moves":["xscissor","earthquake","stoneedge","return"],"pokeball":"cherishball"},
{"generation":6,"level":50,"nature":"Jolly","isHidden":true,"moves":["earthquake","swordsdance","feint","quickattack"],"pokeball":"cherishball"}
],
tier: "UU"
},
pinsirmega: {
randomBattleMoves: ["swordsdance","earthquake","closecombat","quickattack","return"],
randomDoubleBattleMoves: ["feint","protect","swordsdance","xscissor","earthquake","closecombat","substitute","quickattack","return","rockslide"],
requiredItem: "Pinsirite",
tier: "BL"
},
tauros: {
randomBattleMoves: ["rockclimb","earthquake","zenheadbutt","rockslide","pursuit","doubleedge"],
randomDoubleBattleMoves: ["rockclimb","earthquake","zenheadbutt","rockslide","protect","doubleedge"],
eventPokemon: [
{"generation":3,"level":25,"gender":"M","abilities":["intimidate"],"moves":["rage","hornattack","scaryface","pursuit"]},
{"generation":3,"level":10,"gender":"M","abilities":["intimidate"],"moves":["tackle","tailwhip","rage","hornattack"]},
{"generation":3,"level":46,"gender":"M","abilities":["intimidate"],"moves":["refresh","earthquake","tailwhip","bodyslam"]}
],
tier: "PU"
},
magikarp: {
randomBattleMoves: ["bounce","flail","tackle","hydropump"],
eventPokemon: [
{"generation":4,"level":5,"gender":"M","nature":"Relaxed","moves":["splash"]},
{"generation":4,"level":6,"gender":"F","nature":"Rash","moves":["splash"]},
{"generation":4,"level":7,"gender":"F","nature":"Hardy","moves":["splash"]},
{"generation":4,"level":5,"gender":"F","nature":"Lonely","moves":["splash"]},
{"generation":4,"level":4,"gender":"M","nature":"Modest","moves":["splash"]},
{"generation":5,"level":99,"shiny":true,"gender":"M","isHidden":false,"moves":["flail","hydropump","bounce","splash"],"pokeball":"cherishball"}
],
tier: "LC"
},
gyarados: {
randomBattleMoves: ["dragondance","waterfall","earthquake","bounce","rest","sleeptalk","dragontail","stoneedge","substitute","icefang"],
randomDoubleBattleMoves: ["dragondance","waterfall","earthquake","bounce","taunt","protect","thunderwave","stoneedge","substitute","icefang"],
eventPokemon: [
{"generation":6,"level":50,"isHidden":false,"moves":["waterfall","earthquake","icefang","dragondance"],"pokeball":"cherishball"}
],
tier: "OU"
},
gyaradosmega: {
randomBattleMoves: ["dragondance","waterfall","earthquake","stoneedge","substitute","icefang","crunch"],
randomDoubleBattleMoves: ["dragondance","waterfall","earthquake","bounce","taunt","protect","thunderwave","stoneedge","substitute","icefang"],
requiredItem: "Gyaradosite"
},
lapras: {
randomBattleMoves: ["icebeam","thunderbolt","healbell","toxic","surf","rest","sleeptalk"],
randomDoubleBattleMoves: ["icebeam","thunderbolt","healbell","hydropump","surf","substitute","protect","iceshard","icywind"],
eventPokemon: [
{"generation":3,"level":44,"moves":["hydropump","raindance","blizzard","healbell"]}
],
tier: "PU"
},
ditto: {
randomBattleMoves: ["transform"],
tier: "PU"
},
eevee: {
randomBattleMoves: ["quickattack","return","bite","batonpass","irontail","yawn","protect","wish"],
randomDoubleBattleMoves: ["quickattack","return","bite","helpinghand","irontail","yawn","protect","wish"],
eventPokemon: [
{"generation":4,"level":10,"gender":"F","nature":"Lonely","abilities":["adaptability"],"moves":["covet","bite","helpinghand","attract"],"pokeball":"cherishball"},
{"generation":4,"level":50,"shiny":true,"gender":"M","nature":"Hardy","abilities":["adaptability"],"moves":["irontail","trumpcard","flail","quickattack"],"pokeball":"cherishball"},
{"generation":5,"level":50,"gender":"F","nature":"Hardy","isHidden":false,"abilities":["adaptability"],"moves":["sing","return","echoedvoice","attract"],"pokeball":"cherishball"},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","sandattack","babydolleyes","swift"],"pokeball":"cherishball"}
],
tier: "LC"
},
vaporeon: {
randomBattleMoves: ["wish","protect","scald","roar","icebeam","toxic"],
randomDoubleBattleMoves: ["helpinghand","wish","protect","scald","muddywater","icebeam","toxic","hydropump"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","watergun"],"pokeball":"cherishball"}
],
tier: "UU"
},
jolteon: {
randomBattleMoves: ["thunderbolt","voltswitch","hiddenpowerice","batonpass","substitute","signalbeam"],
randomDoubleBattleMoves: ["thunderbolt","voltswitch","hiddenpowergrass","hiddenpowerice","helpinghand","protect","substitute","signalbeam"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","thundershock"],"pokeball":"cherishball"}
],
tier: "RU"
},
flareon: {
randomBattleMoves: ["flamecharge","facade","flareblitz","superpower","wish","protect","toxic"],
randomDoubleBattleMoves: ["flamecharge","facade","flareblitz","superpower","wish","protect","helpinghand"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","ember"],"pokeball":"cherishball"}
],
tier: "PU"
},
espeon: {
randomBattleMoves: ["psychic","psyshock","substitute","wish","shadowball","calmmind","morningsun","batonpass","dazzlinggleam"],
randomDoubleBattleMoves: ["psychic","psyshock","substitute","wish","shadowball","hiddenpowerfighting","helpinghand","protect","dazzlinggleam"],
eventPokemon: [
{"generation":3,"level":70,"moves":["psybeam","psychup","psychic","morningsun"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","confusion"],"pokeball":"cherishball"}
],
tier: "UU"
},
umbreon: {
randomBattleMoves: ["wish","protect","healbell","toxic","batonpass","foulplay"],
randomDoubleBattleMoves: ["moonlight","wish","protect","healbell","snarl","foulplay","helpinghand"],
eventPokemon: [
{"generation":3,"level":70,"moves":["feintattack","meanlook","screech","moonlight"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","pursuit"],"pokeball":"cherishball"}
],
tier: "UU"
},
leafeon: {
randomBattleMoves: ["swordsdance","leafblade","substitute","xscissor","synthesis","healbell","batonpass","knockoff"],
randomDoubleBattleMoves: ["swordsdance","leafblade","substitute","xscissor","protect","helpinghand","knockoff"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","razorleaf"],"pokeball":"cherishball"}
],
tier: "PU"
},
glaceon: {
randomBattleMoves: ["icebeam","hiddenpowerground","shadowball","wish","protect","healbell","batonpass"],
randomDoubleBattleMoves: ["icebeam","hiddenpowerground","shadowball","wish","protect","healbell","helpinghand"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","icywind"],"pokeball":"cherishball"}
],
tier: "PU"
},
porygon: {
randomBattleMoves: ["triattack","icebeam","recover","toxic","thunderwave","discharge","trick"],
eventPokemon: [
{"generation":5,"level":10,"isHidden":true,"moves":["tackle","conversion","sharpen","psybeam"]}
],
tier: "LC"
},
porygon2: {
randomBattleMoves: ["triattack","icebeam","recover","toxic","thunderwave","discharge","shadowball","trickroom"],
randomDoubleBattleMoves: ["triattack","icebeam","discharge","shadowball","trickroom","protect","recover"],
tier: "UU"
},
porygonz: {
randomBattleMoves: ["triattack","darkpulse","icebeam","thunderbolt","agility","trick","nastyplot"],
randomDoubleBattleMoves: ["protect","triattack","darkpulse","hiddenpowerfighting","agility","trick","nastyplot"],
tier: "UU"
},
omanyte: {
randomBattleMoves: ["shellsmash","surf","icebeam","earthpower","hiddenpowerelectric","spikes","toxicspikes","stealthrock","hydropump"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"abilities":["swiftswim"],"moves":["bubblebeam","supersonic","withdraw","bite"],"pokeball":"cherishball"}
],
tier: "LC"
},
omastar: {
randomBattleMoves: ["shellsmash","surf","icebeam","earthpower","spikes","toxicspikes","stealthrock","hydropump"],
randomDoubleBattleMoves: ["shellsmash","muddywater","icebeam","earthpower","hiddenpowerelectric","protect","toxicspikes","stealthrock","hydropump"],
tier: "RU"
},
kabuto: {
randomBattleMoves: ["aquajet","rockslide","rapidspin","stealthrock","honeclaws","waterfall","toxic"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"abilities":["battlearmor"],"moves":["confuseray","dig","scratch","harden"],"pokeball":"cherishball"}
],
tier: "LC"
},
kabutops: {
randomBattleMoves: ["aquajet","stoneedge","rapidspin","swordsdance","waterfall","knockoff"],
randomDoubleBattleMoves: ["aquajet","stoneedge","protect","rockslide","swordsdance","waterfall","superpower"],
tier: "RU"
},
aerodactyl: {
randomBattleMoves: ["stealthrock","taunt","stoneedge","earthquake","aquatail","roost","defog"],
randomDoubleBattleMoves: ["wideguard","taunt","stoneedge","rockslide","earthquake","aquatail","firefang","protect","icefang","skydrop","tailwind"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"abilities":["pressure"],"moves":["steelwing","icefang","firefang","thunderfang"],"pokeball":"cherishball"}
],
tier: "UU"
},
aerodactylmega: {
randomBattleMoves: ["stealthrock","defog","honeclaws","stoneedge","firefang","icefang","aerialace","roost"],
randomDoubleBattleMoves: ["wideguard","taunt","stoneedge","rockslide","earthquake","aquatail","firefang","protect","icefang","skydrop","tailwind"],
requiredItem: "Aerodactylite"
},
munchlax: {
randomBattleMoves: ["rest","curse","sleeptalk","bodyslam","earthquake","return","firepunch","icepunch","whirlwind","toxic"],
tier: "LC"
},
snorlax: {
randomBattleMoves: ["rest","curse","sleeptalk","bodyslam","earthquake","return","firepunch","crunch","pursuit","whirlwind"],
randomDoubleBattleMoves: ["curse","protect","bodyslam","earthquake","return","firepunch","icepunch","crunch","selfdestruct"],
eventPokemon: [
{"generation":3,"level":43,"moves":["refresh","fissure","curse","bodyslam"]}
],
tier: "UU"
},
articuno: {
randomBattleMoves: ["icebeam","roost","freezedry","toxic","substitute","hurricane"],
randomDoubleBattleMoves: ["freezedry","roost","protect","blizzard","substitute","hurricane","tailwind"],
eventPokemon: [
{"generation":3,"level":70,"moves":["agility","mindreader","icebeam","reflect"]},
{"generation":3,"level":50,"moves":["icebeam","healbell","extrasensory","haze"]}
],
unreleasedHidden: true,
tier: "PU"
},
zapdos: {
randomBattleMoves: ["thunderbolt","heatwave","hiddenpowergrass","hiddenpowerice","roost","toxic","substitute","defog"],
randomDoubleBattleMoves: ["thunderbolt","heatwave","hiddenpowergrass","hiddenpowerice","tailwind","protect","discharge"],
eventPokemon: [
{"generation":3,"level":70,"moves":["agility","detect","drillpeck","charge"]},
{"generation":3,"level":50,"moves":["thunderbolt","extrasensory","batonpass","metalsound"]}
],
unreleasedHidden: true,
tier: "OU"
},
moltres: {
randomBattleMoves: ["fireblast","hiddenpowergrass","roost","substitute","toxic","uturn","willowisp","hurricane"],
randomDoubleBattleMoves: ["fireblast","hiddenpowergrass","airslash","roost","substitute","protect","uturn","willowisp","hurricane","heatwave","tailwind"],
eventPokemon: [
{"generation":3,"level":70,"moves":["agility","endure","flamethrower","safeguard"]},
{"generation":3,"level":50,"moves":["extrasensory","morningsun","willowisp","flamethrower"]}
],
unreleasedHidden: true,
tier: "RU"
},
dratini: {
randomBattleMoves: ["dragondance","outrage","waterfall","fireblast","extremespeed","dracometeor","substitute","aquatail"],
tier: "LC"
},
dragonair: {
randomBattleMoves: ["dragondance","outrage","waterfall","fireblast","extremespeed","dracometeor","substitute","aquatail"],
tier: "NFE"
},
dragonite: {
randomBattleMoves: ["dragondance","outrage","firepunch","extremespeed","earthquake","roost"],
randomDoubleBattleMoves: ["dragondance","firepunch","extremespeed","dragonclaw","earthquake","roost","substitute","thunderwave","superpower","dracometeor","protect","skydrop"],
eventPokemon: [
{"generation":3,"level":70,"moves":["agility","safeguard","wingattack","outrage"]},
{"generation":3,"level":55,"moves":["healbell","hyperbeam","dragondance","earthquake"]},
{"generation":4,"level":50,"gender":"M","nature":"Mild","moves":["dracometeor","thunderbolt","outrage","dragondance"],"pokeball":"cherishball"},
{"generation":5,"level":100,"gender":"M","isHidden":true,"moves":["extremespeed","firepunch","dragondance","outrage"],"pokeball":"cherishball"},
{"generation":5,"level":55,"gender":"M","isHidden":true,"moves":["dragonrush","safeguard","wingattack","thunderpunch"]},
{"generation":5,"level":55,"gender":"M","isHidden":true,"moves":["dragonrush","safeguard","wingattack","extremespeed"]},
{"generation":5,"level":50,"gender":"M","nature":"Brave","isHidden":false,"abilities":["innerfocus"],"moves":["fireblast","safeguard","outrage","hyperbeam"],"pokeball":"cherishball"}
],
tier: "OU"
},
mewtwo: {
randomBattleMoves: ["psystrike","aurasphere","fireblast","icebeam","calmmind","substitute","recover","thunderbolt","willowisp"],
randomDoubleBattleMoves: ["psystrike","aurasphere","fireblast","icebeam","calmmind","substitute","recover","thunderbolt","willowisp","taunt","protect"],
eventPokemon: [
{"generation":5,"level":70,"isHidden":false,"moves":["psystrike","shadowball","aurasphere","electroball"],"pokeball":"cherishball"},
{"generation":5,"level":100,"nature":"Timid","isHidden":true,"moves":["psystrike","icebeam","healpulse","hurricane"],"pokeball":"cherishball"}
],
tier: "Uber"
},
mewtwomegax: {
randomBattleMoves: ["bulkup","drainpunch","earthquake","firepunch","icepunch","irontail","recover","stoneedge","substitute","thunderpunch","zenheadbutt"],
requiredItem: "Mewtwonite X"
},
mewtwomegay: {
randomBattleMoves: ["psystrike","aurasphere","fireblast","icebeam","calmmind","substitute","recover","thunderbolt","willowisp"],
requiredItem: "Mewtwonite Y"
},
mew: {
randomBattleMoves: ["taunt","willowisp","roost","psychic","nastyplot","aurasphere","fireblast","swordsdance","drainpunch","zenheadbutt","batonpass","substitute","toxic","icebeam","thunderbolt","knockoff","stealthrock","suckerpunch","defog"],
randomDoubleBattleMoves: ["taunt","willowisp","transform","roost","psyshock","nastyplot","aurasphere","fireblast","swordsdance","drainpunch","zenheadbutt","icebeam","thunderbolt","drillrun","suckerpunch","protect","fakeout","helpinghand","tailwind"],
eventPokemon: [
{"generation":3,"level":30,"moves":["pound","transform","megapunch","metronome"]},
{"generation":3,"level":10,"moves":["pound","transform"]},
{"generation":4,"level":50,"moves":["ancientpower","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["barrier","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["megapunch","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["amnesia","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["transform","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["psychic","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["synthesis","return","hypnosis","teleport"],"pokeball":"cherishball"},
{"generation":4,"level":5,"moves":["pound"],"pokeball":"cherishball"}
],
tier: "OU"
},
chikorita: {
randomBattleMoves: ["reflect","lightscreen","aromatherapy","grasswhistle","leechseed","toxic","gigadrain","synthesis"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","growl","razorleaf"]}
],
unreleasedHidden: true,
tier: "LC"
},
bayleef: {
randomBattleMoves: ["reflect","lightscreen","aromatherapy","grasswhistle","leechseed","toxic","gigadrain","synthesis"],
unreleasedHidden: true,
tier: "NFE"
},
meganium: {
randomBattleMoves: ["reflect","lightscreen","aromatherapy","leechseed","toxic","gigadrain","synthesis","dragontail"],
randomDoubleBattleMoves: ["reflect","lightscreen","aromatherapy","leechseed","hiddenpowerfire","gigadrain","synthesis","dragontail","healpulse","protect"],
unreleasedHidden: true,
tier: "PU"
},
cyndaquil: {
randomBattleMoves: ["eruption","fireblast","flamethrower","hiddenpowergrass","hiddenpowerice"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","leer","smokescreen"]}
],
unreleasedHidden: true,
tier: "LC"
},
quilava: {
randomBattleMoves: ["eruption","fireblast","flamethrower","hiddenpowergrass","hiddenpowerice"],
unreleasedHidden: true,
tier: "NFE"
},
typhlosion: {
randomBattleMoves: ["eruption","fireblast","hiddenpowergrass","hiddenpowerice","focusblast"],
randomDoubleBattleMoves: ["eruption","fireblast","hiddenpowergrass","hiddenpowerice","focusblast","heatwave","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["quickattack","flamewheel","swift","flamethrower"]}
],
unreleasedHidden: true,
tier: "NU"
},
totodile: {
randomBattleMoves: ["aquajet","waterfall","crunch","icepunch","superpower","dragondance","swordsdance"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["scratch","leer","rage"]}
],
unreleasedHidden: true,
tier: "LC"
},
croconaw: {
randomBattleMoves: ["aquajet","waterfall","crunch","icepunch","superpower","dragondance","swordsdance"],
unreleasedHidden: true,
tier: "NFE"
},
feraligatr: {
randomBattleMoves: ["aquajet","waterfall","crunch","icepunch","dragondance","swordsdance","earthquake"],
randomDoubleBattleMoves: ["aquajet","waterfall","crunch","icepunch","dragondance","swordsdance","earthquake","protect"],
unreleasedHidden: true,
tier: "NU"
},
sentret: {
randomBattleMoves: ["superfang","trick","toxic","uturn","knockoff"],
tier: "LC"
},
furret: {
randomBattleMoves: ["uturn","suckerpunch","trick","icepunch","firepunch","knockoff","doubleedge"],
randomDoubleBattleMoves: ["uturn","suckerpunch","trick","icepunch","firepunch","knockoff","doubleedge","followme","helpinghand","protect"],
tier: "PU"
},
hoothoot: {
randomBattleMoves: ["reflect","toxic","roost","whirlwind","nightshade","magiccoat"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","growl","foresight"]}
],
tier: "LC"
},
noctowl: {
randomBattleMoves: ["roost","whirlwind","airslash","nightshade","toxic","defog"],
randomDoubleBattleMoves: ["roost","tailwind","airslash","hypervoice","heatwave","protect","hypnosis"],
tier: "PU"
},
ledyba: {
randomBattleMoves: ["roost","agility","lightscreen","encore","reflect","knockoff","swordsdance","batonpass","toxic"],
eventPokemon: [
{"generation":3,"level":10,"moves":["refresh","psybeam","aerialace","supersonic"]}
],
tier: "LC"
},
ledian: {
randomBattleMoves: ["roost","lightscreen","encore","reflect","knockoff","toxic","uturn"],
randomDoubleBattleMoves: ["protect","lightscreen","encore","reflect","knockoff","bugbuzz","uturn","tailwind","stringshot","strugglebug"],
tier: "PU"
},
spinarak: {
randomBattleMoves: ["agility","toxic","xscissor","toxicspikes","poisonjab","batonpass","stickyweb"],
eventPokemon: [
{"generation":3,"level":14,"moves":["refresh","dig","signalbeam","nightshade"]}
],
tier: "LC"
},
ariados: {
randomBattleMoves: ["toxic","megahorn","toxicspikes","poisonjab","suckerpunch","stickyweb"],
randomDoubleBattleMoves: ["protect","megahorn","stringshot","poisonjab","stickyweb","ragepowder","strugglebug"],
tier: "PU"
},
chinchou: {
randomBattleMoves: ["voltswitch","thunderbolt","hiddenpowergrass","hydropump","icebeam","surf","thunderwave","scald","discharge","healbell"],
tier: "LC"
},
lanturn: {
randomBattleMoves: ["voltswitch","hiddenpowergrass","hydropump","icebeam","thunderwave","scald","discharge","healbell"],
randomDoubleBattleMoves: ["thunderbolt","hiddenpowergrass","hydropump","icebeam","thunderwave","scald","discharge","protect","surf"],
tier: "NU"
},
togepi: {
randomBattleMoves: ["protect","fireblast","toxic","thunderwave","softboiled","dazzlinggleam"],
eventPokemon: [
{"generation":3,"level":20,"gender":"F","abilities":["serenegrace"],"moves":["metronome","charm","sweetkiss","yawn"]},
{"generation":3,"level":25,"moves":["triattack","followme","ancientpower","helpinghand"]}
],
tier: "LC"
},
togetic: {
randomBattleMoves: ["nastyplot","dazzlinggleam","fireblast","batonpass","roost","encore","healbell","thunderwave"],
tier: "PU"
},
togekiss: {
randomBattleMoves: ["roost","thunderwave","nastyplot","airslash","aurasphere","batonpass","dazzlinggleam","fireblast"],
randomDoubleBattleMoves: ["roost","thunderwave","nastyplot","airslash","aurasphere","followme","dazzlinggleam","heatwave","tailwind","protect"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["extremespeed","aurasphere","airslash","present"]}
],
tier: "BL"
},
natu: {
randomBattleMoves: ["thunderwave","roost","toxic","reflect","lightscreen","uturn","wish","psychic","nightshade"],
eventPokemon: [
{"generation":3,"level":22,"moves":["batonpass","futuresight","nightshade","aerialace"]}
],
tier: "LC"
},
xatu: {
randomBattleMoves: ["thunderwave","toxic","roost","psychic","psyshock","uturn","reflect","lightscreen","grassknot","heatwave"],
randomDoubleBattleMoves: ["thunderwave","tailwind","roost","psychic","uturn","reflect","lightscreen","grassknot","heatwave","protect"],
tier: "NU"
},
mareep: {
randomBattleMoves: ["reflect","lightscreen","thunderbolt","discharge","thunderwave","toxic","hiddenpowerice","cottonguard","powergem"],
eventPokemon: [
{"generation":3,"level":37,"gender":"F","moves":["thunder","thundershock","thunderwave","cottonspore"]},
{"generation":3,"level":10,"gender":"M","moves":["tackle","growl","thundershock"]},
{"generation":3,"level":17,"moves":["healbell","thundershock","thunderwave","bodyslam"]}
],
tier: "LC"
},
flaaffy: {
randomBattleMoves: ["reflect","lightscreen","thunderbolt","discharge","thunderwave","toxic","hiddenpowerice","cottonguard","powergem"],
tier: "NFE"
},
ampharos: {
randomBattleMoves: ["voltswitch","reflect","lightscreen","focusblast","thunderbolt","toxic","healbell","hiddenpowerice"],
randomDoubleBattleMoves: ["focusblast","hiddenpowerice","hiddenpowergrass","thunderbolt","discharge","dragonpulse","protect"],
tier: "UU"
},
ampharosmega: {
randomBattleMoves: ["voltswitch","focusblast","agility","thunderbolt","healbell","dragonpulse"],
randomDoubleBattleMoves: ["focusblast","hiddenpowerice","hiddenpowergrass","thunderbolt","discharge","dragonpulse","protect"],
requiredItem: "Ampharosite"
},
azurill: {
randomBattleMoves: ["scald","return","bodyslam","encore","toxic","protect","knockoff"],
tier: "LC"
},
marill: {
randomBattleMoves: ["waterfall","knockoff","encore","toxic","aquajet","superpower","icepunch","protect","playrough","poweruppunch"],
tier: "NFE"
},
azumarill: {
randomBattleMoves: ["waterfall","aquajet","playrough","superpower","bellydrum","knockoff"],
randomDoubleBattleMoves: ["waterfall","aquajet","playrough","superpower","bellydrum","knockoff","protect"],
tier: "OU"
},
bonsly: {
randomBattleMoves: ["rockslide","brickbreak","doubleedge","toxic","stealthrock","suckerpunch","explosion"],
tier: "LC"
},
sudowoodo: {
randomBattleMoves: ["stoneedge","earthquake","suckerpunch","woodhammer","explosion","stealthrock"],
randomDoubleBattleMoves: ["stoneedge","earthquake","suckerpunch","woodhammer","explosion","stealthrock","rockslide","helpinghand","protect","taunt"],
tier: "PU"
},
hoppip: {
randomBattleMoves: ["encore","sleeppowder","uturn","toxic","leechseed","substitute","protect"],
tier: "LC"
},
skiploom: {
randomBattleMoves: ["encore","sleeppowder","uturn","toxic","leechseed","substitute","protect"],
tier: "NFE"
},
jumpluff: {
randomBattleMoves: ["encore","sleeppowder","uturn","toxic","leechseed","gigadrain","synthesis"],
randomDoubleBattleMoves: ["encore","sleeppowder","uturn","helpinghand","leechseed","gigadrain","ragepowder","protect"],
eventPokemon: [
{"generation":5,"level":27,"gender":"M","isHidden":true,"moves":["falseswipe","sleeppowder","bulletseed","leechseed"]}
],
tier: "PU"
},
aipom: {
randomBattleMoves: ["fakeout","return","brickbreak","seedbomb","knockoff","uturn","icepunch","irontail"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["scratch","tailwhip","sandattack"]}
],
tier: "LC"
},
ambipom: {
randomBattleMoves: ["fakeout","return","knockoff","uturn","switcheroo","seedbomb","icepunch","lowkick"],
randomDoubleBattleMoves: ["fakeout","return","knockoff","uturn","switcheroo","seedbomb","icepunch","lowkick","protect"],
tier: "RU"
},
sunkern: {
randomBattleMoves: ["sunnyday","gigadrain","solarbeam","hiddenpowerfire","toxic","earthpower","leechseed"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["chlorophyll"],"moves":["absorb","growth"]}
],
tier: "LC"
},
sunflora: {
randomBattleMoves: ["sunnyday","gigadrain","solarbeam","hiddenpowerfire","earthpower"],
randomDoubleBattleMoves: ["sunnyday","gigadrain","solarbeam","hiddenpowerfire","earthpower","protect"],
tier: "PU"
},
yanma: {
randomBattleMoves: ["bugbuzz","airslash","hiddenpowerground","uturn","protect","gigadrain","ancientpower"],
tier: "LC Uber"
},
yanmega: {
randomBattleMoves: ["bugbuzz","airslash","hiddenpowerground","uturn","protect","gigadrain"],
tier: "BL2"
},
wooper: {
randomBattleMoves: ["recover","earthquake","scald","toxic","stockpile","yawn","protect"],
tier: "LC"
},
quagsire: {
randomBattleMoves: ["recover","earthquake","waterfall","scald","toxic","curse","yawn","icepunch"],
randomDoubleBattleMoves: ["icywind","earthquake","waterfall","scald","rockslide","curse","yawn","icepunch","protect"],
tier: "NU"
},
murkrow: {
randomBattleMoves: ["substitute","suckerpunch","bravebird","heatwave","hiddenpowergrass","roost","darkpulse","thunderwave"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["insomnia"],"moves":["peck","astonish"]}
],
tier: "LC Uber"
},
honchkrow: {
randomBattleMoves: ["substitute","superpower","suckerpunch","bravebird","roost","heatwave","pursuit"],
randomDoubleBattleMoves: ["substitute","superpower","suckerpunch","bravebird","roost","heatwave","protect"],
tier: "UU"
},
misdreavus: {
randomBattleMoves: ["nastyplot","substitute","calmmind","willowisp","shadowball","thunderbolt","hiddenpowerfighting"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["growl","psywave","spite"]}
],
tier: "PU"
},
mismagius: {
randomBattleMoves: ["nastyplot","substitute","willowisp","shadowball","thunderbolt","dazzlinggleam","healbell","painsplit"],
randomDoubleBattleMoves: ["nastyplot","substitute","willowisp","shadowball","thunderbolt","dazzlinggleam","taunt","protect"],
tier: "NU"
},
unown: {
randomBattleMoves: ["hiddenpowerpsychic"],
tier: "PU"
},
wynaut: {
randomBattleMoves: ["destinybond","counter","mirrorcoat","encore"],
eventPokemon: [
{"generation":3,"level":5,"moves":["splash","charm","encore","tickle"]}
],
tier: "LC"
},
wobbuffet: {
randomBattleMoves: ["destinybond","counter","mirrorcoat","encore"],
eventPokemon: [
{"generation":3,"level":5,"moves":["counter","mirrorcoat","safeguard","destinybond"]},
{"generation":3,"level":10,"gender":"M","moves":["counter","mirrorcoat","safeguard","destinybond"]},
{"generation":6,"level":10,"gender":"M","isHidden":false,"moves":["counter"],"pokeball":"cherishball"},
{"generation":6,"level":15,"gender":"M","isHidden":false,"moves":["counter","mirrorcoat"],"pokeball":"cherishball"}
],
tier: "PU"
},
girafarig: {
randomBattleMoves: ["psychic","psyshock","thunderbolt","nastyplot","batonpass","agility","hypervoice"],
randomDoubleBattleMoves: ["psychic","psyshock","thunderbolt","nastyplot","protect","agility","hypervoice"],
tier: "PU"
},
pineco: {
randomBattleMoves: ["rapidspin","toxicspikes","spikes","bugbite","stealthrock"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","protect","selfdestruct"]},
{"generation":3,"level":22,"moves":["refresh","pinmissile","spikes","counter"]}
],
tier: "LC"
},
forretress: {
randomBattleMoves: ["rapidspin","toxicspikes","spikes","voltswitch","stealthrock","gyroball"],
randomDoubleBattleMoves: ["rockslide","drillrun","stringshot","voltswitch","stealthrock","gyroball","protect"],
tier: "UU"
},
dunsparce: {
randomBattleMoves: ["coil","rockslide","bite","headbutt","glare","bodyslam","roost"],
randomDoubleBattleMoves: ["coil","rockslide","bite","headbutt","glare","bodyslam","protect"],
tier: "PU"
},
gligar: {
randomBattleMoves: ["stealthrock","toxic","roost","taunt","earthquake","uturn","knockoff"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["poisonsting","sandattack"]}
],
tier: "UU"
},
gliscor: {
randomBattleMoves: ["uturn","roost","substitute","taunt","earthquake","protect","toxic","stealthrock","knockoff"],
randomDoubleBattleMoves: ["uturn","tailwind","substitute","taunt","earthquake","protect","stoneedge","knockoff"],
tier: "OU"
},
snubbull: {
randomBattleMoves: ["thunderwave","firepunch","crunch","closecombat","icepunch","earthquake","playrough"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","scaryface","tailwhip","charm"]}
],
tier: "LC"
},
granbull: {
randomBattleMoves: ["thunderwave","playrough","crunch","earthquake","healbell"],
randomDoubleBattleMoves: ["thunderwave","playrough","crunch","earthquake","snarl","rockslide","protect"],
tier: "NU"
},
qwilfish: {
randomBattleMoves: ["toxicspikes","waterfall","spikes","painsplit","thunderwave","taunt","destinybond"],
randomDoubleBattleMoves: ["poisonjab","waterfall","swordsdance","protect","thunderwave","taunt","destinybond"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","poisonsting","harden","minimize"]}
],
tier: "NU"
},
shuckle: {
randomBattleMoves: ["toxic","encore","stealthrock","knockoff","stickyweb","infestation"],
randomDoubleBattleMoves: ["encore","stealthrock","knockoff","stickyweb","guardsplit","helpinghand","stringshot"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["sturdy"],"moves":["constrict","withdraw","wrap"]},
{"generation":3,"level":20,"abilities":["sturdy"],"moves":["substitute","toxic","sludgebomb","encore"]}
],
tier: "BL2"
},
heracross: {
randomBattleMoves: ["closecombat","megahorn","stoneedge","swordsdance","knockoff","earthquake"],
randomDoubleBattleMoves: ["closecombat","megahorn","stoneedge","swordsdance","knockoff","earthquake","protect"],
eventPokemon: [
{"generation":6,"level":50,"gender":"F","nature":"Adamant","isHidden":false,"moves":["bulletseed","pinmissile","closecombat","megahorn"],"pokeball":"cherishball"},
{"generation":6,"level":50,"nature":"Adamant","isHidden":false,"abilities":["guts"],"moves":["pinmissile","bulletseed","earthquake","rockblast"],"pokeball":"cherishball"}
],
tier: "UU"
},
heracrossmega: {
randomBattleMoves: ["closecombat","pinmissile","rockblast","swordsdance","bulletseed","knockoff","earthquake"],
randomDoubleBattleMoves: ["closecombat","pinmissile","rockblast","swordsdance","bulletseed","knockoff","earthquake","protect"],
requiredItem: "Heracronite",
tier: "BL"
},
sneasel: {
randomBattleMoves: ["iceshard","iciclecrash","lowkick","pursuit","swordsdance","knockoff"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["scratch","leer","taunt","quickattack"]}
],
tier: "PU"
},
weavile: {
randomBattleMoves: ["iceshard","iciclecrash","knockoff","pursuit","swordsdance","lowkick"],
randomDoubleBattleMoves: ["iceshard","icepunch","knockoff","fakeout","swordsdance","lowkick","taunt","protect","feint"],
eventPokemon: [
{"generation":4,"level":30,"gender":"M","nature":"Jolly","moves":["fakeout","iceshard","nightslash","brickbreak"],"pokeball":"cherishball"}
],
tier: "BL"
},
teddiursa: {
randomBattleMoves: ["swordsdance","protect","facade","closecombat","firepunch","crunch","playrough","gunkshot"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["pickup"],"moves":["scratch","leer","lick"]},
{"generation":3,"level":11,"abilities":["pickup"],"moves":["refresh","metalclaw","leer","return"]}
],
tier: "LC"
},
ursaring: {
randomBattleMoves: ["swordsdance","facade","closecombat","earthquake","crunch","protect"],
randomDoubleBattleMoves: ["swordsdance","facade","closecombat","earthquake","crunch","protect"],
tier: "PU"
},
slugma: {
randomBattleMoves: ["stockpile","recover","lavaplume","willowisp","toxic","hiddenpowergrass","earthpower","memento"],
tier: "LC"
},
magcargo: {
randomBattleMoves: ["recover","lavaplume","toxic","hiddenpowergrass","stealthrock","fireblast","earthpower","shellsmash","ancientpower"],
randomDoubleBattleMoves: ["protect","heatwave","willowisp","shellsmash","hiddenpowergrass","hiddenpowerrock","stealthrock","fireblast","earthpower"],
eventPokemon: [
{"generation":3,"level":38,"moves":["refresh","heatwave","earthquake","flamethrower"]}
],
tier: "PU"
},
swinub: {
randomBattleMoves: ["earthquake","iciclecrash","iceshard","superpower","endeavor","stealthrock"],
eventPokemon: [
{"generation":3,"level":22,"abilities":["oblivious"],"moves":["charm","ancientpower","mist","mudshot"]}
],
tier: "LC"
},
piloswine: {
randomBattleMoves: ["earthquake","iciclecrash","iceshard","superpower","endeavor","stealthrock"],
tier: "PU"
},
mamoswine: {
randomBattleMoves: ["iceshard","earthquake","endeavor","iciclecrash","stealthrock","superpower","knockoff"],
randomDoubleBattleMoves: ["iceshard","earthquake","rockslide","iciclecrash","protect","superpower","knockoff"],
eventPokemon: [
{"generation":5,"level":34,"gender":"M","isHidden":true,"moves":["hail","icefang","takedown","doublehit"]},
{"generation":6,"level":50,"shiny":true,"gender":"M","nature":"Adamant","isHidden":true,"moves":["iciclespear","earthquake","iciclecrash","rockslide"]}
],
tier: "OU"
},
corsola: {
randomBattleMoves: ["recover","toxic","powergem","scald","stealthrock","earthpower","icebeam"],
randomDoubleBattleMoves: ["protect","icywind","powergem","scald","stealthrock","earthpower","icebeam"],
eventPokemon: [
{"generation":3,"level":5,"moves":["tackle","mudsport"]}
],
tier: "PU"
},
remoraid: {
randomBattleMoves: ["waterspout","hydropump","fireblast","hiddenpowerground","icebeam","seedbomb","rockblast"],
tier: "LC"
},
octillery: {
randomBattleMoves: ["hydropump","fireblast","icebeam","energyball","rockblast","waterspout"],
randomDoubleBattleMoves: ["hydropump","fireblast","icebeam","energyball","rockblast","waterspout","protect"],
eventPokemon: [
{"generation":4,"level":50,"gender":"F","nature":"Serious","abilities":["suctioncups"],"moves":["octazooka","icebeam","signalbeam","hyperbeam"],"pokeball":"cherishball"}
],
tier: "PU"
},
delibird: {
randomBattleMoves: ["rapidspin","iceshard","icepunch","freezedry","aerialace","spikes","destinybond"],
randomDoubleBattleMoves: ["fakeout","iceshard","icepunch","freezedry","aerialace","brickbreak","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["present"]}
],
tier: "PU"
},
mantyke: {
randomBattleMoves: ["raindance","hydropump","scald","airslash","icebeam","rest","sleeptalk","toxic"],
tier: "LC"
},
mantine: {
randomBattleMoves: ["raindance","hydropump","scald","airslash","icebeam","rest","sleeptalk","toxic","defog"],
randomDoubleBattleMoves: ["raindance","hydropump","scald","airslash","icebeam","tailwind","wideguard","helpinghand","protect","surf"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","bubble","supersonic"]}
],
tier: "NU"
},
skarmory: {
randomBattleMoves: ["whirlwind","bravebird","roost","spikes","stealthrock","defog"],
randomDoubleBattleMoves: ["skydrop","bravebird","tailwind","taunt","feint","protect","ironhead"],
tier: "OU"
},
houndour: {
randomBattleMoves: ["pursuit","suckerpunch","fireblast","darkpulse","hiddenpowerfighting","nastyplot"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["leer","ember","howl"]},
{"generation":3,"level":17,"moves":["charm","feintattack","ember","roar"]}
],
tier: "LC"
},
houndoom: {
randomBattleMoves: ["nastyplot","darkpulse","suckerpunch","fireblast","hiddenpowerfighting"],
randomDoubleBattleMoves: ["nastyplot","darkpulse","suckerpunch","heatwave","hiddenpowerfighting","protect"],
eventPokemon: [
{"generation":6,"level":50,"nature":"Timid","isHidden":false,"abilities":["flashfire"],"moves":["flamethrower","darkpulse","solarbeam","sludgebomb"],"pokeball":"cherishball"}
],
tier: "RU"
},
houndoommega: {
randomBattleMoves: ["nastyplot","darkpulse","suckerpunch","fireblast","hiddenpowerfighting"],
randomDoubleBattleMoves: ["nastyplot","darkpulse","suckerpunch","heatwave","hiddenpowerfighting","protect"],
requiredItem: "Houndoominite",
tier: "BL2"
},
phanpy: {
randomBattleMoves: ["stealthrock","earthquake","iceshard","headsmash","knockoff","seedbomb","superpower","playrough"],
tier: "LC"
},
donphan: {
randomBattleMoves: ["stealthrock","rapidspin","iceshard","earthquake","knockoff","stoneedge","playrough"],
randomDoubleBattleMoves: ["stealthrock","seedbomb","iceshard","earthquake","rockslide","playrough","protect"],
tier: "UU"
},
stantler: {
randomBattleMoves: ["return","megahorn","jumpkick","earthquake","suckerpunch"],
randomDoubleBattleMoves: ["return","megahorn","jumpkick","earthquake","suckerpunch","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["intimidate"],"moves":["tackle","leer"]}
],
tier: "PU"
},
smeargle: {
randomBattleMoves: ["spore","spikes","stealthrock","destinybond","whirlwind","stickyweb"],
randomDoubleBattleMoves: ["spore","fakeout","wideguard","helpinghand","followme","tailwind","kingsshield","transform"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["owntempo"],"moves":["sketch"]},
{"generation":5,"level":50,"gender":"F","nature":"Jolly","abilities":["technician"],"moves":["falseswipe","spore","odorsleuth","meanlook"],"pokeball":"cherishball"}
],
tier: "BL"
},
miltank: {
randomBattleMoves: ["milkdrink","stealthrock","bodyslam","healbell","curse","earthquake","thunderwave"],
randomDoubleBattleMoves: ["protect","helpinghand","bodyslam","healbell","curse","earthquake","thunderwave"],
tier: "NU"
},
raikou: {
randomBattleMoves: ["thunderbolt","hiddenpowerice","aurasphere","calmmind","substitute","voltswitch"],
randomDoubleBattleMoves: ["thunderbolt","hiddenpowerice","aurasphere","calmmind","substitute","snarl","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["quickattack","spark","reflect","crunch"]},
{"generation":4,"level":30,"shiny":true,"nature":"Rash","moves":["zapcannon","aurasphere","extremespeed","weatherball"],"pokeball":"cherishball"}
],
unreleasedHidden: true,
tier: "OU"
},
entei: {
randomBattleMoves: ["extremespeed","flareblitz","ironhead","stoneedge","sacredfire"],
randomDoubleBattleMoves: ["extremespeed","flareblitz","ironhead","stoneedge","sacredfire","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["firespin","stomp","flamethrower","swagger"]},
{"generation":4,"level":30,"shiny":true,"nature":"Adamant","moves":["flareblitz","howl","extremespeed","crushclaw"],"pokeball":"cherishball"}
],
unreleasedHidden: true,
tier: "UU"
},
suicune: {
randomBattleMoves: ["hydropump","icebeam","scald","hiddenpowergrass","hiddenpowerelectric","rest","sleeptalk","roar","calmmind"],
randomDoubleBattleMoves: ["hydropump","icebeam","scald","hiddenpowergrass","hiddenpowerelectric","snarl","tailwind","protect","calmmind"],
eventPokemon: [
{"generation":3,"level":70,"moves":["gust","aurorabeam","mist","mirrorcoat"]},
{"generation":4,"level":30,"shiny":true,"nature":"Relaxed","moves":["sheercold","airslash","extremespeed","aquaring"],"pokeball":"cherishball"}
],
unreleasedHidden: true,
tier: "UU"
},
larvitar: {
randomBattleMoves: ["earthquake","stoneedge","facade","dragondance","superpower","crunch"],
eventPokemon: [
{"generation":3,"level":20,"moves":["sandstorm","dragondance","bite","outrage"]},
{"generation":5,"level":5,"shiny":true,"gender":"M","isHidden":false,"moves":["bite","leer","sandstorm","superpower"],"pokeball":"cherishball"}
],
tier: "LC"
},
pupitar: {
randomBattleMoves: ["earthquake","stoneedge","crunch","dragondance","superpower","stealthrock"],
tier: "NFE"
},
tyranitar: {
randomBattleMoves: ["crunch","stoneedge","pursuit","superpower","fireblast","icebeam","stealthrock"],
randomDoubleBattleMoves: ["crunch","stoneedge","rockslide","lowkick","fireblast","icebeam","stealthrock","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["thrash","scaryface","crunch","earthquake"]},
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["fireblast","icebeam","stoneedge","crunch"],"pokeball":"cherishball"},
{"generation":5,"level":55,"gender":"M","isHidden":true,"moves":["payback","crunch","earthquake","seismictoss"]},
{"generation":6,"level":50,"isHidden":false,"moves":["stoneedge","crunch","earthquake","icepunch"],"pokeball":"cherishball"},
{"generation":6,"level":50,"nature":"Jolly","isHidden":false,"moves":["rockslide","earthquake","crunch","stoneedge"],"pokeball":"cherishball"}
],
tier: "OU"
},
tyranitarmega: {
randomBattleMoves: ["crunch","stoneedge","earthquake","icepunch","dragondance"],
randomDoubleBattleMoves: ["crunch","stoneedge","earthquake","icepunch","dragondance","rockslide","protect"],
requiredItem: "Tyranitarite"
},
lugia: {
randomBattleMoves: ["toxic","roost","substitute","whirlwind","icebeam","psychic","calmmind","aeroblast"],
randomDoubleBattleMoves: ["aeroblast","roost","substitute","tailwind","icebeam","psychic","calmmind","skydrop","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["swift","raindance","hydropump","recover"]},
{"generation":3,"level":70,"moves":["recover","hydropump","raindance","swift"]},
{"generation":3,"level":50,"moves":["psychoboost","recover","hydropump","featherdance"]}
],
dreamWorldPokeball: 'dreamball',
tier: "Uber"
},
hooh: {
randomBattleMoves: ["substitute","sacredfire","bravebird","earthquake","roost","willowisp","flamecharge","tailwind"],
randomDoubleBattleMoves: ["substitute","sacredfire","bravebird","earthquake","roost","willowisp","flamecharge","tailwind","skydrop","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["swift","sunnyday","fireblast","recover"]},
{"generation":3,"level":70,"moves":["recover","fireblast","sunnyday","swift"]}
],
dreamWorldPokeball: 'dreamball',
tier: "Uber"
},
celebi: {
randomBattleMoves: ["nastyplot","psychic","gigadrain","recover","healbell","batonpass","stealthrock","earthpower","hiddenpowerfire","hiddenpowerice","calmmind","leafstorm","uturn","thunderwave"],
randomDoubleBattleMoves: ["protect","psychic","gigadrain","recover","earthpower","hiddenpowerfire","hiddenpowerice","helpinghand","leafstorm","uturn","thunderwave"],
eventPokemon: [
{"generation":3,"level":10,"moves":["confusion","recover","healbell","safeguard"]},
{"generation":3,"level":70,"moves":["ancientpower","futuresight","batonpass","perishsong"]},
{"generation":3,"level":10,"moves":["leechseed","recover","healbell","safeguard"]},
{"generation":3,"level":30,"moves":["healbell","safeguard","ancientpower","futuresight"]},
{"generation":4,"level":50,"moves":["leafstorm","recover","nastyplot","healingwish"],"pokeball":"cherishball"},
{"generation":6,"level":10,"moves":["recover","healbell","safeguard","holdback"],"pokeball":"luxuryball"}
],
unobtainableShiny: true,
tier: "OU"
},
treecko: {
randomBattleMoves: ["substitute","leechseed","leafstorm","hiddenpowerice","hiddenpowerrock","endeavor"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["pound","leer","absorb"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["pound","leer","absorb"]}
],
tier: "LC"
},
grovyle: {
randomBattleMoves: ["substitute","leechseed","gigadrain","leafstorm","hiddenpowerice","hiddenpowerrock","endeavor"],
tier: "NFE"
},
sceptile: {
randomBattleMoves: ["substitute","gigadrain","leafstorm","hiddenpowerice","focusblast","hiddenpowerfire"],
randomDoubleBattleMoves: ["substitute","gigadrain","leafstorm","hiddenpowerice","focusblast","hiddenpowerfire","protect"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":false,"moves":["leafstorm","dragonpulse","focusblast","rockslide"],"pokeball":"cherishball"}
],
tier: "UU"
},
sceptilemega: {
randomBattleMoves: ["substitute","gigadrain","dragonpulse","focusblast","swordsdance","outrage","leafblade","earthquake","hiddenpowerfire"],
randomDoubleBattleMoves: ["substitute","gigadrain","leafstorm","hiddenpowerice","focusblast","dragonpulse","hiddenpowerfire","protect"],
requiredItem: "Sceptilite"
},
torchic: {
randomBattleMoves: ["protect","batonpass","substitute","hiddenpowergrass","swordsdance","firepledge"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["scratch","growl","focusenergy","ember"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["scratch","growl","focusenergy","ember"]},
{"generation":6,"level":10,"gender":"M","isHidden":true,"moves":["scratch","growl","focusenergy","ember"],"pokeball":"cherishball"}
],
tier: "LC"
},
combusken: {
randomBattleMoves: ["flareblitz","skyuppercut","protect","swordsdance","substitute","batonpass","shadowclaw"],
tier: "BL3"
},
blaziken: {
randomBattleMoves: ["flareblitz","highjumpkick","protect","swordsdance","substitute","batonpass","stoneedge","knockoff"],
eventPokemon: [
{"generation":3,"level":70,"moves":["blazekick","slash","mirrormove","skyuppercut"]},
{"generation":5,"level":50,"isHidden":false,"moves":["flareblitz","highjumpkick","thunderpunch","stoneedge"],"pokeball":"cherishball"}
],
tier: "Uber"
},
blazikenmega: {
randomBattleMoves: ["flareblitz","highjumpkick","protect","swordsdance","substitute","batonpass","stoneedge","knockoff"],
requiredItem: "Blazikenite"
},
mudkip: {
randomBattleMoves: ["hydropump","earthpower","hiddenpowerelectric","icebeam","sludgewave"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","growl","mudslap","watergun"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tackle","growl","mudslap","watergun"]}
],
tier: "LC"
},
marshtomp: {
randomBattleMoves: ["waterfall","earthquake","superpower","icepunch","rockslide","stealthrock"],
tier: "NFE"
},
swampert: {
randomBattleMoves: ["waterfall","earthquake","icebeam","stealthrock","roar","scald"],
randomDoubleBattleMoves: ["waterfall","earthquake","icebeam","stealthrock","wideguard","scald","rockslide","muddywater","protect","icywind"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":false,"moves":["earthquake","icebeam","hydropump","hammerarm"],"pokeball":"cherishball"}
],
tier: "UU"
},
swampertmega: {
randomBattleMoves: ["waterfall","earthquake","raindance","icepunch","superpower"],
randomDoubleBattleMoves: ["waterfall","earthquake","raindance","icepunch","superpower","protect"],
requiredItem: "Swampertite"
},
poochyena: {
randomBattleMoves: ["superfang","foulplay","suckerpunch","toxic","crunch","firefang","icefang","poisonfang"],
eventPokemon: [
{"generation":3,"level":10,"abilities":["runaway"],"moves":["healbell","dig","poisonfang","growl"]}
],
tier: "LC"
},
mightyena: {
randomBattleMoves: ["suckerpunch","crunch","playrough","firefang","taunt","irontail"],
randomDoubleBattleMoves: ["suckerpunch","crunch","playrough","firefang","taunt","protect"],
tier: "PU"
},
zigzagoon: {
randomBattleMoves: ["trick","thunderwave","icebeam","thunderbolt","gunkshot","lastresort"],
eventPokemon: [
{"generation":3,"level":5,"shiny":true,"abilities":["pickup"],"moves":["tackle","growl","tailwhip"]},
{"generation":3,"level":5,"abilities":["pickup"],"moves":["tackle","growl","extremespeed"]}
],
tier: "LC"
},
linoone: {
randomBattleMoves: ["bellydrum","extremespeed","seedbomb","substitute","shadowclaw"],
randomDoubleBattleMoves: ["bellydrum","extremespeed","seedbomb","protect","shadowclaw"],
eventPokemon: [
{"generation":6,"level":50,"isHidden":false,"moves":["extremespeed","helpinghand","babydolleyes","protect"],"pokeball":"cherishball"}
],
tier: "PU"
},
wurmple: {
randomBattleMoves: ["bugbite","poisonsting","tackle","electroweb"],
tier: "LC"
},
silcoon: {
randomBattleMoves: ["bugbite","poisonsting","tackle","electroweb"],
tier: "NFE"
},
beautifly: {
randomBattleMoves: ["quiverdance","bugbuzz","gigadrain","hiddenpowerground","psychic","substitute"],
randomDoubleBattleMoves: ["quiverdance","bugbuzz","gigadrain","hiddenpowerground","psychic","substitute","tailwind","stringshot","protect"],
tier: "PU"
},
cascoon: {
randomBattleMoves: ["bugbite","poisonsting","tackle","electroweb"],
tier: "NFE"
},
dustox: {
randomBattleMoves: ["toxic","roost","whirlwind","bugbuzz","protect","sludgebomb","quiverdance","shadowball"],
randomDoubleBattleMoves: ["tailwind","stringshot","strugglebug","bugbuzz","protect","sludgebomb","quiverdance","shadowball"],
tier: "PU"
},
lotad: {
randomBattleMoves: ["gigadrain","icebeam","scald","naturepower","raindance"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["astonish","growl","absorb"]}
],
tier: "LC"
},
lombre: {
randomBattleMoves: ["fakeout","swordsdance","waterfall","seedbomb","icepunch","firepunch","thunderpunch","poweruppunch","gigadrain","icebeam"],
tier: "NFE"
},
ludicolo: {
randomBattleMoves: ["raindance","hydropump","scald","gigadrain","icebeam","focusblast"],
randomDoubleBattleMoves: ["raindance","hydropump","surf","gigadrain","icebeam","fakeout","protect"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":false,"abilities":["swiftswim"],"moves":["fakeout","hydropump","icebeam","gigadrain"],"pokeball":"cherishball"},
{"generation":5,"level":30,"gender":"M","nature":"Calm","isHidden":false,"abilities":["swiftswim"],"moves":["scald","gigadrain","icebeam","sunnyday"]}
],
tier: "NU"
},
seedot: {
randomBattleMoves: ["defog","naturepower","seedbomb","explosion","foulplay"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["bide","harden","growth"]},
{"generation":3,"level":17,"moves":["refresh","gigadrain","bulletseed","secretpower"]}
],
tier: "LC"
},
nuzleaf: {
randomBattleMoves: ["suckerpunch","naturepower","seedbomb","explosion","swordsdance","rockslide","lowsweep"],
tier: "NFE"
},
shiftry: {
randomBattleMoves: ["leafstorm","swordsdance","leafblade","suckerpunch","defog","lowkick","knockoff"],
randomDoubleBattleMoves: ["leafstorm","swordsdance","leafblade","suckerpunch","knockoff","lowkick","fakeout","protect"],
tier: "RU"
},
taillow: {
randomBattleMoves: ["bravebird","facade","quickattack","uturn","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["peck","growl","focusenergy","featherdance"]}
],
tier: "LC"
},
swellow: {
randomBattleMoves: ["bravebird","facade","quickattack","uturn","endeavor"],
randomDoubleBattleMoves: ["bravebird","facade","quickattack","uturn","protect"],
eventPokemon: [
{"generation":3,"level":43,"moves":["batonpass","skyattack","agility","facade"]}
],
tier: "NU"
},
wingull: {
randomBattleMoves: ["scald","icebeam","tailwind","uturn","airslash","knockoff","defog"],
tier: "LC"
},
pelipper: {
randomBattleMoves: ["scald","uturn","hurricane","toxic","roost","defog","knockoff"],
randomDoubleBattleMoves: ["scald","surf","hurricane","wideguard","protect","tailwind","knockoff"],
tier: "PU"
},
ralts: {
randomBattleMoves: ["trickroom","destinybond","psychic","willowisp","hypnosis","dazzlinggleam","substitute","trick"],
eventPokemon: [
{"generation":3,"level":5,"moves":["growl","wish"]},
{"generation":3,"level":5,"moves":["growl","charm"]},
{"generation":3,"level":20,"moves":["sing","shockwave","reflect","confusion"]},
{"generation":6,"level":1,"isHidden":true,"moves":["growl","encore"]}
],
tier: "LC"
},
kirlia: {
randomBattleMoves: ["trick","dazzlinggleam","psychic","willowisp","signalbeam","thunderbolt","destinybond","substitute"],
tier: "NFE"
},
gardevoir: {
randomBattleMoves: ["psyshock","focusblast","shadowball","moonblast","calmmind","willowisp","thunderbolt","healingwish"],
randomDoubleBattleMoves: ["psyshock","focusblast","shadowball","moonblast","taunt","willowisp","thunderbolt","trickroom","helpinghand","protect","dazzlinggleam"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":false,"abilities":["trace"],"moves":["hypnosis","thunderbolt","focusblast","psychic"],"pokeball":"cherishball"}
],
tier: "OU"
},
gardevoirmega: {
randomBattleMoves: ["psyshock","focusblast","shadowball","calmmind","thunderbolt","hypervoice","healingwish"],
randomDoubleBattleMoves: ["psyshock","focusblast","shadowball","calmmind","thunderbolt","hypervoice","protect"],
requiredItem: "Gardevoirite"
},
gallade: {
randomBattleMoves: ["closecombat","trick","stoneedge","shadowsneak","drainpunch","icepunch","zenheadbutt","swordsdance","knockoff"],
randomDoubleBattleMoves: ["closecombat","trick","stoneedge","shadowsneak","drainpunch","icepunch","zenheadbutt","knockoff","trickroom","protect","helpinghand","healpulse"],
tier: "OU"
},
gallademega: {
randomBattleMoves: ["closecombat","stoneedge","drainpunch","icepunch","zenheadbutt","swordsdance","knockoff"],
randomDoubleBattleMoves: ["closecombat","stoneedge","drainpunch","icepunch","zenheadbutt","swordsdance","knockoff","protect"],
requiredItem: "Galladite"
},
surskit: {
randomBattleMoves: ["hydropump","signalbeam","hiddenpowerfire","stickyweb","gigadrain","powersplit"],
eventPokemon: [
{"generation":3,"level":5,"moves":["bubble","mudsport"]},
{"generation":3,"level":10,"gender":"M","moves":["bubble","quickattack"]}
],
tier: "LC"
},
masquerain: {
randomBattleMoves: ["hydropump","bugbuzz","airslash","quiverdance","substitute","batonpass","stickyweb","roost"],
randomDoubleBattleMoves: ["hydropump","bugbuzz","airslash","quiverdance","substitute","tailwind","stickyweb","roost","strugglebug","protect"],
tier: "PU"
},
shroomish: {
randomBattleMoves: ["spore","substitute","leechseed","gigadrain","protect","toxic","stunspore"],
eventPokemon: [
{"generation":3,"level":15,"abilities":["effectspore"],"moves":["refresh","falseswipe","megadrain","stunspore"]}
],
tier: "LC"
},
breloom: {
randomBattleMoves: ["spore","substitute","focuspunch","machpunch","bulletseed","rocktomb","swordsdance","drainpunch"],
randomDoubleBattleMoves: ["spore","helpinghand","machpunch","bulletseed","rocktomb","protect","drainpunch"],
tier: "OU"
},
slakoth: {
randomBattleMoves: ["doubleedge","hammerarm","firepunch","counter","retaliate","toxic"],
tier: "LC"
},
vigoroth: {
randomBattleMoves: ["bulkup","return","earthquake","firepunch","suckerpunch","slackoff","icepunch","lowkick"],
tier: "NFE"
},
slaking: {
randomBattleMoves: ["earthquake","pursuit","nightslash","doubleedge","retaliate"],
randomDoubleBattleMoves: ["earthquake","nightslash","doubleedge","retaliate","hammerarm","rockslide"],
eventPokemon: [
{"generation":4,"level":50,"gender":"M","nature":"Adamant","moves":["gigaimpact","return","shadowclaw","aerialace"],"pokeball":"cherishball"}
],
tier: "PU"
},
nincada: {
randomBattleMoves: ["xscissor","dig","aerialace","nightslash"],
tier: "LC"
},
ninjask: {
randomBattleMoves: ["batonpass","swordsdance","substitute","protect","xscissor"],
randomDoubleBattleMoves: ["batonpass","swordsdance","substitute","protect","xscissor","aerialace"],
tier: "PU"
},
shedinja: {
randomBattleMoves: ["swordsdance","willowisp","xscissor","shadowsneak","shadowclaw","protect"],
eventPokemon: [
{"generation":3,"level":50,"moves":["spite","confuseray","shadowball","grudge"]},
{"generation":3,"level":20,"moves":["doubleteam","furycutter","screech"]},
{"generation":3,"level":25,"moves":["swordsdance"]},
{"generation":3,"level":31,"moves":["slash"]},
{"generation":3,"level":38,"moves":["agility"]},
{"generation":3,"level":45,"moves":["batonpass"]},
{"generation":4,"level":52,"moves":["xscissor"]}
],
tier: "PU"
},
whismur: {
randomBattleMoves: ["hypervoice","fireblast","shadowball","icebeam","extrasensory"],
eventPokemon: [
{"generation":3,"level":5,"moves":["pound","uproar","teeterdance"]}
],
tier: "LC"
},
loudred: {
randomBattleMoves: ["hypervoice","fireblast","shadowball","icebeam","circlethrow","bodyslam"],
tier: "NFE"
},
exploud: {
randomBattleMoves: ["boomburst","fireblast","icebeam","surf","focusblast"],
randomDoubleBattleMoves: ["boomburst","fireblast","icebeam","surf","focusblast","protect","hypervoice"],
eventPokemon: [
{"generation":3,"level":100,"moves":["roar","rest","sleeptalk","hypervoice"]},
{"generation":3,"level":50,"moves":["stomp","screech","hyperbeam","roar"]}
],
tier: "RU"
},
makuhita: {
randomBattleMoves: ["crosschop","bulletpunch","closecombat","icepunch","bulkup","fakeout","earthquake"],
eventPokemon: [
{"generation":3,"level":18,"moves":["refresh","brickbreak","armthrust","rocktomb"]}
],
tier: "LC"
},
hariyama: {
randomBattleMoves: ["bulletpunch","closecombat","icepunch","stoneedge","bulkup","earthquake","knockoff"],
randomDoubleBattleMoves: ["bulletpunch","closecombat","icepunch","stoneedge","fakeout","knockoff","helpinghand","wideguard","protect"],
tier: "NU"
},
nosepass: {
randomBattleMoves: ["powergem","thunderwave","stealthrock","painsplit","explosion","voltswitch"],
eventPokemon: [
{"generation":3,"level":26,"moves":["helpinghand","thunderbolt","thunderwave","rockslide"]}
],
tier: "LC"
},
probopass: {
randomBattleMoves: ["stealthrock","thunderwave","toxic","earthpower","powergem","voltswitch","painsplit"],
randomDoubleBattleMoves: ["stealthrock","thunderwave","helpinghand","earthpower","powergem","wideguard","protect","voltswitch"],
tier: "PU"
},
skitty: {
randomBattleMoves: ["doubleedge","zenheadbutt","thunderwave","fakeout","playrough","healbell"],
eventPokemon: [
{"generation":3,"level":5,"abilities":["cutecharm"],"moves":["tackle","growl","tailwhip","payday"]},
{"generation":3,"level":5,"abilities":["cutecharm"],"moves":["growl","tackle","tailwhip","rollout"]},
{"generation":3,"level":10,"gender":"M","abilities":["cutecharm"],"moves":["growl","tackle","tailwhip","attract"]}
],
tier: "LC"
},
delcatty: {
randomBattleMoves: ["doubleedge","suckerpunch","playrough","wildcharge","fakeout","thunderwave","wish","healbell"],
randomDoubleBattleMoves: ["doubleedge","suckerpunch","playrough","wildcharge","fakeout","thunderwave","protect","helpinghand"],
eventPokemon: [
{"generation":3,"level":18,"abilities":["cutecharm"],"moves":["sweetkiss","secretpower","attract","shockwave"]}
],
tier: "PU"
},
sableye: {
randomBattleMoves: ["recover","willowisp","taunt","toxic","knockoff","foulplay"],
randomDoubleBattleMoves: ["recover","willowisp","taunt","fakeout","knockoff","foulplay","feint","helpinghand","snarl","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["keeneye"],"moves":["leer","scratch","foresight","nightshade"]},
{"generation":3,"level":33,"abilities":["keeneye"],"moves":["helpinghand","shadowball","feintattack","recover"]},
{"generation":5,"level":50,"gender":"M","isHidden":true,"moves":["foulplay","octazooka","tickle","trick"],"pokeball":"cherishball"}
],
tier: "OU"
},
sableyemega: {
randomBattleMoves: ["recover","willowisp","darkpulse","calmmind","shadowball"],
randomDoubleBattleMoves: ["fakeout","knockoff","darkpulse","shadowball","willowisp","protect"],
requiredItem: "Sablenite"
},
mawile: {
randomBattleMoves: ["swordsdance","ironhead","substitute","playrough","suckerpunch","batonpass"],
randomDoubleBattleMoves: ["swordsdance","ironhead","firefang","substitute","playrough","suckerpunch","knockoff","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["astonish","faketears"]},
{"generation":3,"level":22,"moves":["sing","falseswipe","vicegrip","irondefense"]},
{"generation":6,"level":50,"isHidden":false,"abilities":["intimidate"],"moves":["ironhead","playrough","firefang","suckerpunch"],"pokeball":"cherishball"}
],
tier: "NU"
},
mawilemega: {
randomBattleMoves: ["swordsdance","ironhead","firefang","substitute","playrough","suckerpunch","knockoff","focuspunch"],
randomDoubleBattleMoves: ["swordsdance","ironhead","firefang","substitute","playrough","suckerpunch","knockoff","protect"],
requiredItem: "Mawilite",
tier: "Uber"
},
aron: {
randomBattleMoves: ["headsmash","ironhead","earthquake","superpower","stealthrock","endeavor"],
tier: "LC"
},
lairon: {
randomBattleMoves: ["headsmash","ironhead","earthquake","superpower","stealthrock"],
tier: "NFE"
},
aggron: {
randomBattleMoves: ["autotomize","headsmash","earthquake","lowkick","heavyslam","aquatail","stealthrock"],
randomDoubleBattleMoves: ["rockslide","headsmash","earthquake","lowkick","heavyslam","aquatail","stealthrock","protect"],
eventPokemon: [
{"generation":3,"level":100,"moves":["irontail","protect","metalsound","doubleedge"]},
{"generation":3,"level":50,"moves":["takedown","irontail","protect","metalsound"]},
{"generation":6,"level":50,"nature":"Brave","isHidden":false,"abilities":["rockhead"],"moves":["ironhead","earthquake","headsmash","rockslide"],"pokeball":"cherishball"}
],
tier: "UU"
},
aggronmega: {
randomBattleMoves: ["earthquake","heavyslam","icepunch","stealthrock","thunderwave","roar","toxic"],
randomDoubleBattleMoves: ["rockslide","earthquake","lowkick","heavyslam","aquatail","protect"],
requiredItem: "Aggronite"
},
meditite: {
randomBattleMoves: ["highjumpkick","psychocut","icepunch","thunderpunch","trick","fakeout","bulletpunch","drainpunch","zenheadbutt"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["bide","meditate","confusion"]},
{"generation":3,"level":20,"moves":["dynamicpunch","confusion","shadowball","detect"]}
],
tier: "LC Uber"
},
medicham: {
randomBattleMoves: ["highjumpkick","drainpunch","zenheadbutt","icepunch","bulletpunch"],
randomDoubleBattleMoves: ["highjumpkick","drainpunch","zenheadbutt","icepunch","bulletpunch","protect","fakeout"],
tier: "UU"
},
medichammega: {
randomBattleMoves: ["highjumpkick","drainpunch","icepunch","bulletpunch","zenheadbutt","firepunch"],
randomDoubleBattleMoves: ["highjumpkick","drainpunch","zenheadbutt","icepunch","bulletpunch","protect","fakeout"],
requiredItem: "Medichamite",
tier: "BL"
},
electrike: {
randomBattleMoves: ["voltswitch","thunderbolt","hiddenpowerice","switcheroo","flamethrower","hiddenpowergrass"],
tier: "LC"
},
manectric: {
randomBattleMoves: ["voltswitch","thunderbolt","hiddenpowerice","hiddenpowergrass","overheat","flamethrower"],
randomDoubleBattleMoves: ["voltswitch","thunderbolt","hiddenpowerice","hiddenpowergrass","overheat","flamethrower","snarl","protect"],
eventPokemon: [
{"generation":3,"level":44,"moves":["refresh","thunder","raindance","bite"]},
{"generation":6,"level":50,"nature":"Timid","isHidden":false,"abilities":["lightningrod"],"moves":["overheat","thunderbolt","voltswitch","protect"],"pokeball":"cherishball"}
],
tier: "OU"
},
manectricmega: {
randomBattleMoves: ["voltswitch","thunderbolt","hiddenpowerice","hiddenpowergrass","overheat","flamethrower"],
randomDoubleBattleMoves: ["voltswitch","thunderbolt","hiddenpowerice","hiddenpowergrass","overheat","flamethrower","snarl","protect"],
requiredItem: "Manectite"
},
plusle: {
randomBattleMoves: ["nastyplot","thunderbolt","substitute","batonpass","hiddenpowerice","encore"],
randomDoubleBattleMoves: ["nastyplot","thunderbolt","substitute","protect","hiddenpowerice","encore","helpinghand"],
eventPokemon: [
{"generation":3,"level":5,"moves":["growl","thunderwave","mudsport"]},
{"generation":3,"level":10,"gender":"M","moves":["growl","thunderwave","quickattack"]}
],
tier: "PU"
},
minun: {
randomBattleMoves: ["nastyplot","thunderbolt","substitute","batonpass","hiddenpowerice","encore"],
randomDoubleBattleMoves: ["nastyplot","thunderbolt","substitute","protect","hiddenpowerice","encore","helpinghand"],
eventPokemon: [
{"generation":3,"level":5,"moves":["growl","thunderwave","watersport"]},
{"generation":3,"level":10,"gender":"M","moves":["growl","thunderwave","quickattack"]}
],
tier: "PU"
},
volbeat: {
randomBattleMoves: ["tailglow","batonpass","substitute","bugbuzz","thunderwave","encore","tailwind"],
randomDoubleBattleMoves: ["stringshot","strugglebug","helpinghand","bugbuzz","thunderwave","encore","tailwind","protect"],
tier: "PU"
},
illumise: {
randomBattleMoves: ["substitute","batonpass","wish","bugbuzz","encore","thunderbolt","tailwind","uturn","thunderwave"],
randomDoubleBattleMoves: ["protect","helpinghand","bugbuzz","encore","thunderbolt","tailwind","uturn"],
tier: "PU"
},
budew: {
randomBattleMoves: ["spikes","sludgebomb","sleeppowder","gigadrain","stunspore","rest"],
tier: "LC"
},
roselia: {
randomBattleMoves: ["spikes","toxicspikes","sleeppowder","gigadrain","stunspore","rest","sludgebomb","synthesis"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["absorb","growth","poisonsting"]},
{"generation":3,"level":22,"moves":["sweetkiss","magicalleaf","leechseed","grasswhistle"]}
],
tier: "PU"
},
roserade: {
randomBattleMoves: ["sludgebomb","gigadrain","sleeppowder","leafstorm","spikes","toxicspikes","rest","synthesis","hiddenpowerfire"],
randomDoubleBattleMoves: ["sludgebomb","gigadrain","sleeppowder","leafstorm","protect","hiddenpowerfire"],
tier: "UU"
},
gulpin: {
randomBattleMoves: ["stockpile","sludgebomb","sludgewave","icebeam","toxic","painsplit","yawn","encore"],
eventPokemon: [
{"generation":3,"level":17,"moves":["sing","shockwave","sludge","toxic"]}
],
tier: "LC"
},
swalot: {
randomBattleMoves: ["sludgebomb","icebeam","toxic","yawn","encore","painsplit","earthquake"],
randomDoubleBattleMoves: ["sludgebomb","icebeam","protect","yawn","encore","gunkshot","earthquake"],
tier: "PU"
},
carvanha: {
randomBattleMoves: ["protect","hydropump","surf","icebeam","waterfall","crunch","aquajet","destinybond"],
eventPokemon: [
{"generation":3,"level":15,"moves":["refresh","waterpulse","bite","scaryface"]},
{"generation":6,"level":1,"isHidden":true,"moves":["leer","bite","hydropump"]}
],
tier: "LC"
},
sharpedo: {
randomBattleMoves: ["protect","icebeam","crunch","earthquake","waterfall","aquajet","destinybond","zenheadbutt"],
randomDoubleBattleMoves: ["protect","hydropump","surf","icebeam","crunch","earthquake","waterfall","darkpulse","destinybond"],
tier: "UU"
},
sharpedomega: {
randomBattleMoves: ["protect","icefang","crunch","earthquake","waterfall","zenheadbutt"],
requiredItem: "Sharpedonite"
},
wailmer: {
randomBattleMoves: ["waterspout","surf","hydropump","icebeam","hiddenpowergrass","hiddenpowerelectric"],
tier: "LC"
},
wailord: {
randomBattleMoves: ["waterspout","hydropump","icebeam","hiddenpowergrass","hiddenpowerfire"],
randomDoubleBattleMoves: ["waterspout","hydropump","icebeam","hiddenpowergrass","hiddenpowerfire","protect"],
eventPokemon: [
{"generation":3,"level":100,"moves":["rest","waterspout","amnesia","hydropump"]},
{"generation":3,"level":50,"moves":["waterpulse","mist","rest","waterspout"]}
],
tier: "PU"
},
numel: {
randomBattleMoves: ["curse","earthquake","rockslide","fireblast","flamecharge","rest","sleeptalk","stockpile","hiddenpowerelectric","earthpower","lavaplume"],
eventPokemon: [
{"generation":3,"level":14,"abilities":["oblivious"],"moves":["charm","takedown","dig","ember"]},
{"generation":6,"level":1,"isHidden":false,"moves":["growl","tackle","ironhead"]}
],
tier: "LC"
},
camerupt: {
randomBattleMoves: ["rockpolish","fireblast","earthpower","lavaplume","stealthrock","hiddenpowergrass","roar"],
randomDoubleBattleMoves: ["rockpolish","fireblast","earthpower","heatwave","eruption","hiddenpowergrass","protect"],
tier: "NU"
},
cameruptmega: {
randomBattleMoves: ["stealthrock","fireblast","earthpower","rockslide","flashcannon"],
randomDoubleBattleMoves: ["fireblast","earthpower","heatwave","eruption","rockslide","protect"],
requiredItem: "Cameruptite"
},
torkoal: {
randomBattleMoves: ["rapidspin","stealthrock","yawn","lavaplume","earthpower","toxic","willowisp","shellsmash","fireblast"],
randomDoubleBattleMoves: ["protect","heatwave","earthpower","willowisp","shellsmash","fireblast","hiddenpowergrass"],
tier: "PU"
},
spoink: {
randomBattleMoves: ["psychic","reflect","lightscreen","thunderwave","trick","healbell","calmmind","hiddenpowerfighting","shadowball"],
eventPokemon: [
{"generation":3,"level":5,"abilities":["owntempo"],"moves":["splash","uproar"]}
],
tier: "LC"
},
grumpig: {
randomBattleMoves: ["psychic","psyshock","thunderwave","healbell","whirlwind","toxic","focusblast","reflect","lightscreen"],
randomDoubleBattleMoves: ["psychic","psyshock","thunderwave","trickroom","taunt","protect","focusblast","reflect","lightscreen"],
tier: "PU"
},
spinda: {
randomBattleMoves: ["doubleedge","return","superpower","suckerpunch","trickroom"],
randomDoubleBattleMoves: ["doubleedge","return","superpower","suckerpunch","trickroom","fakeout","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["tackle","uproar","sing"]}
],
tier: "PU"
},
trapinch: {
randomBattleMoves: ["earthquake","rockslide","crunch","quickattack","superpower"],
eventPokemon: [
{"generation":5,"level":1,"shiny":true,"isHidden":false,"moves":["bite"]}
],
tier: "LC"
},
vibrava: {
randomBattleMoves: ["substitute","earthquake","outrage","roost","uturn","superpower","defog"],
tier: "NFE"
},
flygon: {
randomBattleMoves: ["earthquake","outrage","dragonclaw","uturn","roost","stoneedge","firepunch","fireblast","defog"],
randomDoubleBattleMoves: ["earthquake","protect","dragonclaw","uturn","rockslide","firepunch","fireblast","tailwind","feint"],
eventPokemon: [
{"generation":3,"level":45,"moves":["sandtomb","crunch","dragonbreath","screech"]},
{"generation":4,"level":50,"gender":"M","nature":"Naive","moves":["dracometeor","uturn","earthquake","dragonclaw"],"pokeball":"cherishball"}
],
tier: "UU"
},
cacnea: {
randomBattleMoves: ["swordsdance","spikes","suckerpunch","seedbomb","drainpunch"],
eventPokemon: [
{"generation":3,"level":5,"moves":["poisonsting","leer","absorb","encore"]}
],
tier: "LC"
},
cacturne: {
randomBattleMoves: ["swordsdance","spikes","suckerpunch","seedbomb","drainpunch","substitute","focuspunch","destinybond"],
randomDoubleBattleMoves: ["darkpulse","spikyshield","suckerpunch","seedbomb","drainpunch","gigadrain"],
eventPokemon: [
{"generation":3,"level":45,"moves":["ingrain","feintattack","spikes","needlearm"]}
],
tier: "NU"
},
swablu: {
randomBattleMoves: ["roost","toxic","cottonguard","pluck","hypervoice","return"],
eventPokemon: [
{"generation":3,"level":5,"moves":["peck","growl","falseswipe"]},
{"generation":5,"level":1,"shiny":true,"isHidden":false,"moves":["peck","growl"]},
{"generation":6,"level":1,"isHidden":true,"moves":["peck","growl","hypervoice"]}
],
tier: "LC"
},
altaria: {
randomBattleMoves: ["dragondance","dracometeor","outrage","dragonclaw","earthquake","roost","fireblast","healbell"],
randomDoubleBattleMoves: ["dragondance","dracometeor","protect","dragonclaw","earthquake","fireblast","tailwind"],
eventPokemon: [
{"generation":3,"level":45,"moves":["takedown","dragonbreath","dragondance","refresh"]},
{"generation":3,"level":36,"moves":["healbell","dragonbreath","solarbeam","aerialace"]},
{"generation":5,"level":35,"gender":"M","isHidden":true,"moves":["takedown","naturalgift","dragonbreath","falseswipe"]}
],
tier: "OU"
},
altariamega: {
randomBattleMoves: ["dragondance","return","outrage","dragonclaw","earthquake","roost","dracometeor","fireblast"],
randomDoubleBattleMoves: ["dragondance","return","doubleedge","dragonclaw","earthquake","protect","fireblast"],
requiredItem: "Altarianite"
},
zangoose: {
randomBattleMoves: ["swordsdance","closecombat","knockoff","quickattack","facade"],
randomDoubleBattleMoves: ["protect","closecombat","knockoff","quickattack","facade"],
eventPokemon: [
{"generation":3,"level":18,"moves":["leer","quickattack","swordsdance","furycutter"]},
{"generation":3,"level":10,"gender":"M","moves":["scratch","leer","quickattack","swordsdance"]},
{"generation":3,"level":28,"moves":["refresh","brickbreak","counter","crushclaw"]}
],
tier: "NU"
},
seviper: {
randomBattleMoves: ["flamethrower","gigadrain","earthquake","suckerpunch","aquatail","coil","glare","poisonjab","sludgewave"],
randomDoubleBattleMoves: ["flamethrower","gigadrain","earthquake","suckerpunch","aquatail","protect","glare","poisonjab","sludgewave"],
eventPokemon: [
{"generation":3,"level":18,"moves":["wrap","lick","bite","poisontail"]},
{"generation":3,"level":30,"moves":["poisontail","screech","glare","crunch"]},
{"generation":3,"level":10,"gender":"M","moves":["wrap","lick","bite"]}
],
tier: "PU"
},
lunatone: {
randomBattleMoves: ["psychic","earthpower","stealthrock","rockpolish","batonpass","calmmind","icebeam","hiddenpowerrock","moonlight","trickroom","explosion"],
randomDoubleBattleMoves: ["psychic","earthpower","rockpolish","calmmind","helpinghand","icebeam","hiddenpowerrock","moonlight","trickroom","protect"],
eventPokemon: [
{"generation":3,"level":10,"moves":["tackle","harden","confusion"]},
{"generation":3,"level":25,"moves":["batonpass","psychic","raindance","rocktomb"]}
],
tier: "PU"
},
solrock: {
randomBattleMoves: ["stealthrock","explosion","stoneedge","zenheadbutt","willowisp","morningsun","earthquake"],
randomDoubleBattleMoves: ["protect","helpinghand","stoneedge","zenheadbutt","willowisp","trickroom","rockslide"],
eventPokemon: [
{"generation":3,"level":10,"moves":["tackle","harden","confusion"]},
{"generation":3,"level":41,"moves":["batonpass","psychic","sunnyday","cosmicpower"]}
],
tier: "PU"
},
barboach: {
randomBattleMoves: ["dragondance","waterfall","earthquake","return","bounce"],
tier: "LC"
},
whiscash: {
randomBattleMoves: ["dragondance","waterfall","earthquake","stoneedge","zenheadbutt"],
randomDoubleBattleMoves: ["dragondance","waterfall","earthquake","stoneedge","zenheadbutt","protect"],
eventPokemon: [
{"generation":4,"level":51,"gender":"F","nature":"Gentle","abilities":["oblivious"],"moves":["earthquake","aquatail","zenheadbutt","gigaimpact"],"pokeball":"cherishball"}
],
tier: "PU"
},
corphish: {
randomBattleMoves: ["dragondance","waterfall","crunch","superpower","swordsdance","knockoff","aquajet"],
eventPokemon: [
{"generation":3,"level":5,"moves":["bubble","watersport"]}
],
tier: "LC"
},
crawdaunt: {
randomBattleMoves: ["dragondance","crabhammer","superpower","swordsdance","knockoff","aquajet"],
randomDoubleBattleMoves: ["dragondance","crabhammer","crunch","superpower","swordsdance","knockoff","aquajet","protect"],
eventPokemon: [
{"generation":3,"level":100,"moves":["taunt","crabhammer","swordsdance","guillotine"]},
{"generation":3,"level":50,"moves":["knockoff","taunt","crabhammer","swordsdance"]}
],
tier: "BL"
},
baltoy: {
randomBattleMoves: ["stealthrock","earthquake","toxic","psychic","reflect","lightscreen","icebeam","rapidspin"],
eventPokemon: [
{"generation":3,"level":17,"moves":["refresh","rocktomb","mudslap","psybeam"]}
],
tier: "LC"
},
claydol: {
randomBattleMoves: ["stealthrock","toxic","psychic","icebeam","earthquake","rapidspin"],
randomDoubleBattleMoves: ["earthpower","trickroom","psychic","icebeam","earthquake","protect"],
tier: "NU"
},
lileep: {
randomBattleMoves: ["stealthrock","recover","ancientpower","hiddenpowerfire","gigadrain","stockpile"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"moves":["recover","rockslide","constrict","acid"],"pokeball":"cherishball"}
],
tier: "LC"
},
cradily: {
randomBattleMoves: ["stealthrock","recover","seedbomb","rockslide","earthquake","curse","swordsdance"],
randomDoubleBattleMoves: ["protect","recover","seedbomb","rockslide","earthquake","curse","swordsdance"],
tier: "NU"
},
anorith: {
randomBattleMoves: ["stealthrock","brickbreak","toxic","xscissor","rockslide","swordsdance","rockpolish"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"moves":["harden","mudsport","watergun","crosspoison"],"pokeball":"cherishball"}
],
tier: "LC"
},
armaldo: {
randomBattleMoves: ["stealthrock","stoneedge","toxic","xscissor","swordsdance","knockoff","rapidspin"],
randomDoubleBattleMoves: ["rockslide","stoneedge","stringshot","xscissor","swordsdance","knockoff","protect"],
tier: "PU"
},
feebas: {
randomBattleMoves: ["protect","confuseray","hypnosis","scald","toxic"],
tier: "LC"
},
milotic: {
randomBattleMoves: ["recover","scald","toxic","icebeam","dragontail","rest","sleeptalk","hiddenpowergrass"],
randomDoubleBattleMoves: ["recover","scald","hydropump","icebeam","dragontail","hypnosis","protect","hiddenpowergrass"],
eventPokemon: [
{"generation":3,"level":35,"moves":["waterpulse","twister","recover","raindance"]},
{"generation":4,"level":50,"gender":"F","nature":"Bold","moves":["recover","raindance","icebeam","hydropump"],"pokeball":"cherishball"},
{"generation":4,"level":50,"shiny":true,"gender":"M","nature":"Timid","moves":["raindance","recover","hydropump","icywind"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["recover","hydropump","icebeam","mirrorcoat"],"pokeball":"cherishball"},
{"generation":5,"level":58,"gender":"M","nature":"Lax","isHidden":false,"moves":["recover","surf","icebeam","toxic"],"pokeball":"cherishball"}
],
tier: "UU"
},
castform: {
randomBattleMoves: ["sunnyday","raindance","fireblast","hydropump","thunder","icebeam","solarbeam","weatherball","hurricane"],
randomDoubleBattleMoves: ["sunnyday","raindance","fireblast","hydropump","thunder","icebeam","solarbeam","weatherball","hurricane","protect"],
tier: "PU"
},
kecleon: {
randomBattleMoves: ["drainpunch","toxic","stealthrock","recover","return","thunderwave","suckerpunch","shadowsneak","knockoff"],
randomDoubleBattleMoves: ["knockoff","fakeout","trickroom","recover","return","thunderwave","suckerpunch","shadowsneak","protect","feint"],
tier: "PU"
},
shuppet: {
randomBattleMoves: ["trickroom","destinybond","taunt","shadowsneak","suckerpunch","willowisp"],
eventPokemon: [
{"generation":3,"level":45,"abilities":["insomnia"],"moves":["spite","willowisp","feintattack","shadowball"]}
],
tier: "LC"
},
banette: {
randomBattleMoves: ["destinybond","taunt","shadowclaw","suckerpunch","willowisp","shadowsneak","knockoff"],
randomDoubleBattleMoves: ["destinybond","taunt","shadowclaw","suckerpunch","willowisp","shadowsneak","knockoff","protect"],
eventPokemon: [
{"generation":3,"level":37,"abilities":["insomnia"],"moves":["helpinghand","feintattack","shadowball","curse"]},
{"generation":5,"level":37,"gender":"F","isHidden":true,"moves":["feintattack","hex","shadowball","cottonguard"]}
],
tier: "RU"
},
banettemega: {
randomBattleMoves: ["destinybond","taunt","shadowclaw","suckerpunch","willowisp","shadowsneak","knockoff"],
randomDoubleBattleMoves: ["destinybond","taunt","shadowclaw","suckerpunch","willowisp","shadowsneak","knockoff","protect"],
requiredItem: "Banettite"
},
duskull: {
randomBattleMoves: ["willowisp","shadowsneak","icebeam","painsplit","substitute","nightshade"],
eventPokemon: [
{"generation":3,"level":45,"moves":["pursuit","curse","willowisp","meanlook"]},
{"generation":3,"level":19,"moves":["helpinghand","shadowball","astonish","confuseray"]}
],
tier: "LC"
},
dusclops: {
randomBattleMoves: ["willowisp","shadowsneak","icebeam","painsplit","substitute","seismictoss","toxic","trickroom"],
tier: "NFE"
},
dusknoir: {
randomBattleMoves: ["willowisp","shadowsneak","icepunch","painsplit","substitute","earthquake","focuspunch","trickroom"],
randomDoubleBattleMoves: ["willowisp","shadowsneak","icepunch","painsplit","protect","earthquake","helpinghand","trickroom"],
tier: "PU"
},
tropius: {
randomBattleMoves: ["leechseed","substitute","airslash","gigadrain","toxic","protect"],
randomDoubleBattleMoves: ["leechseed","protect","airslash","gigadrain","earthquake","hiddenpowerfire","tailwind","sunnyday","roost"],
eventPokemon: [
{"generation":4,"level":53,"gender":"F","nature":"Jolly","abilities":["chlorophyll"],"moves":["airslash","synthesis","sunnyday","solarbeam"],"pokeball":"cherishball"}
],
tier: "PU"
},
chingling: {
randomBattleMoves: ["hypnosis","reflect","lightscreen","toxic","recover","psychic","signalbeam","healbell"],
tier: "LC"
},
chimecho: {
randomBattleMoves: ["toxic","psychic","thunderwave","recover","calmmind","shadowball","dazzlinggleam","healingwish","healbell","taunt"],
randomDoubleBattleMoves: ["protect","psychic","thunderwave","recover","shadowball","dazzlinggleam","trickroom","helpinghand","taunt"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["wrap","growl","astonish"]}
],
tier: "PU"
},
absol: {
randomBattleMoves: ["swordsdance","suckerpunch","knockoff","superpower","pursuit","playrough"],
randomDoubleBattleMoves: ["swordsdance","suckerpunch","knockoff","fireblast","superpower","protect","playrough"],
eventPokemon: [
{"generation":3,"level":5,"abilities":["pressure"],"moves":["scratch","leer","wish"]},
{"generation":3,"level":5,"abilities":["pressure"],"moves":["scratch","leer","spite"]},
{"generation":3,"level":35,"abilities":["pressure"],"moves":["razorwind","bite","swordsdance","spite"]},
{"generation":3,"level":70,"abilities":["pressure"],"moves":["doubleteam","slash","futuresight","perishsong"]}
],
tier: "UU"
},
absolmega: {
randomBattleMoves: ["swordsdance","suckerpunch","knockoff","fireblast","superpower","pursuit","playrough","icebeam"],
randomDoubleBattleMoves: ["swordsdance","suckerpunch","knockoff","fireblast","superpower","protect","playrough"],
requiredItem: "Absolite"
},
snorunt: {
randomBattleMoves: ["spikes","icebeam","hiddenpowerground","iceshard","crunch","switcheroo"],
eventPokemon: [
{"generation":3,"level":22,"abilities":["innerfocus"],"moves":["sing","waterpulse","bite","icywind"]}
],
tier: "LC"
},
glalie: {
randomBattleMoves: ["spikes","icebeam","iceshard","taunt","earthquake","explosion"],
randomDoubleBattleMoves: ["icebeam","iceshard","taunt","earthquake","protect","encore"],
tier: "RU"
},
glaliemega: {
randomBattleMoves: ["crunch","iceshard","taunt","earthquake","explosion","return","spikes"],
randomDoubleBattleMoves: ["crunch","iceshard","taunt","earthquake","explosion","protect","encore","return"],
requiredItem: "Glalitite"
},
froslass: {
randomBattleMoves: ["icebeam","spikes","destinybond","shadowball","taunt","thunderwave"],
randomDoubleBattleMoves: ["icebeam","protect","destinybond","shadowball","taunt","thunderwave"],
tier: "BL2"
},
spheal: {
randomBattleMoves: ["substitute","protect","toxic","surf","icebeam","yawn","superfang"],
eventPokemon: [
{"generation":3,"level":17,"abilities":["thickfat"],"moves":["charm","aurorabeam","watergun","mudslap"]}
],
tier: "LC"
},
sealeo: {
randomBattleMoves: ["substitute","protect","toxic","surf","icebeam","yawn","superfang"],
tier: "NFE"
},
walrein: {
randomBattleMoves: ["substitute","protect","toxic","surf","icebeam","roar"],
randomDoubleBattleMoves: ["hydropump","protect","icywind","surf","icebeam"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":false,"abilities":["thickfat"],"moves":["icebeam","surf","hail","sheercold"],"pokeball":"cherishball"}
],
tier: "PU"
},
clamperl: {
randomBattleMoves: ["shellsmash","icebeam","surf","hiddenpowergrass","hiddenpowerelectric","substitute"],
tier: "LC"
},
huntail: {
randomBattleMoves: ["shellsmash","waterfall","icebeam","batonpass","suckerpunch"],
randomDoubleBattleMoves: ["shellsmash","return","hydropump","batonpass","suckerpunch","protect"],
tier: "PU"
},
gorebyss: {
randomBattleMoves: ["shellsmash","batonpass","hydropump","icebeam","hiddenpowergrass","substitute"],
randomDoubleBattleMoves: ["shellsmash","batonpass","surf","icebeam","hiddenpowergrass","substitute","protect"],
tier: "NU"
},
relicanth: {
randomBattleMoves: ["headsmash","waterfall","earthquake","doubleedge","stealthrock","toxic"],
randomDoubleBattleMoves: ["headsmash","waterfall","earthquake","doubleedge","rockslide","protect"],
tier: "PU"
},
luvdisc: {
randomBattleMoves: ["surf","icebeam","toxic","sweetkiss","protect","scald"],
tier: "PU"
},
bagon: {
randomBattleMoves: ["outrage","dragondance","firefang","rockslide","dragonclaw"],
eventPokemon: [
{"generation":3,"level":5,"moves":["rage","bite","wish"]},
{"generation":3,"level":5,"moves":["rage","bite","irondefense"]},
{"generation":5,"level":1,"shiny":true,"isHidden":false,"moves":["rage"]},
{"generation":6,"level":1,"isHidden":false,"moves":["rage","thrash"]}
],
tier: "LC"
},
shelgon: {
randomBattleMoves: ["outrage","brickbreak","dragonclaw","dragondance","crunch","zenheadbutt"],
tier: "NFE"
},
salamence: {
randomBattleMoves: ["outrage","fireblast","earthquake","dracometeor","roost","dragondance","dragonclaw","hydropump","stoneedge"],
randomDoubleBattleMoves: ["protect","fireblast","earthquake","dracometeor","tailwind","dragondance","dragonclaw","hydropump","rockslide"],
eventPokemon: [
{"generation":3,"level":50,"moves":["protect","dragonbreath","scaryface","fly"]},
{"generation":3,"level":50,"moves":["refresh","dragonclaw","dragondance","aerialace"]},
{"generation":4,"level":50,"gender":"M","nature":"Naughty","moves":["hydropump","stoneedge","fireblast","dragonclaw"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["dragondance","dragonclaw","outrage","aerialace"],"pokeball":"cherishball"}
],
tier: "UU"
},
salamencemega: {
randomBattleMoves: ["doubleedge","return","fireblast","earthquake","dracometeor","roost","dragondance","dragonclaw"],
randomDoubleBattleMoves: ["doubleedge","return","fireblast","earthquake","dracometeor","protect","dragondance","dragonclaw"],
requiredItem: "Salamencite",
tier: "Uber"
},
beldum: {
randomBattleMoves: ["ironhead","zenheadbutt","headbutt","irondefense"],
eventPokemon: [
{"generation":6,"level":5,"shiny":true,"isHidden":false,"moves":["holdback","ironhead","zenheadbutt","irondefense"],"pokeball":"cherishball"}
],
tier: "LC"
},
metang: {
randomBattleMoves: ["stealthrock","meteormash","toxic","earthquake","bulletpunch","zenheadbutt"],
eventPokemon: [
{"generation":3,"level":30,"moves":["takedown","confusion","metalclaw","refresh"]}
],
tier: "NFE"
},
metagross: {
randomBattleMoves: ["meteormash","earthquake","agility","stealthrock","zenheadbutt","bulletpunch","thunderpunch","explosion","icepunch"],
randomDoubleBattleMoves: ["meteormash","earthquake","protect","zenheadbutt","bulletpunch","thunderpunch","explosion","icepunch","hammerarm"],
eventPokemon: [
{"generation":4,"level":62,"nature":"Brave","moves":["bulletpunch","meteormash","hammerarm","zenheadbutt"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["meteormash","earthquake","bulletpunch","hammerarm"],"pokeball":"cherishball"},
{"generation":5,"level":100,"isHidden":false,"moves":["bulletpunch","zenheadbutt","hammerarm","icepunch"],"pokeball":"cherishball"},
{"generation":5,"level":45,"isHidden":false,"moves":["earthquake","zenheadbutt","protect","meteormash"]},
{"generation":5,"level":45,"isHidden":true,"moves":["irondefense","agility","hammerarm","doubleedge"]},
{"generation":5,"level":45,"isHidden":true,"moves":["psychic","meteormash","hammerarm","doubleedge"]},
{"generation":5,"level":58,"nature":"Serious","isHidden":false,"moves":["earthquake","hyperbeam","psychic","meteormash"],"pokeball":"cherishball"}
],
tier: "OU"
},
metagrossmega: {
randomBattleMoves: ["meteormash","earthquake","agility","zenheadbutt","thunderpunch","icepunch"],
randomDoubleBattleMoves: ["meteormash","earthquake","protect","zenheadbutt","thunderpunch","icepunch"],
requiredItem: "Metagrossite"
},
regirock: {
randomBattleMoves: ["stealthrock","thunderwave","stoneedge","drainpunch","curse","rest","sleeptalk","rockslide","toxic"],
randomDoubleBattleMoves: ["stealthrock","thunderwave","stoneedge","drainpunch","curse","rockslide","protect"],
eventPokemon: [
{"generation":3,"level":40,"moves":["curse","superpower","ancientpower","hyperbeam"]}
],
unreleasedHidden: true,
tier: "NU"
},
regice: {
randomBattleMoves: ["thunderwave","icebeam","thunderbolt","rest","sleeptalk","focusblast","rockpolish"],
randomDoubleBattleMoves: ["thunderwave","icebeam","thunderbolt","icywind","protect","focusblast","rockpolish"],
eventPokemon: [
{"generation":3,"level":40,"moves":["curse","superpower","ancientpower","hyperbeam"]}
],
unreleasedHidden: true,
tier: "PU"
},
registeel: {
randomBattleMoves: ["stealthrock","ironhead","curse","rest","thunderwave","toxic","seismictoss"],
randomDoubleBattleMoves: ["stealthrock","ironhead","curse","rest","thunderwave","protect","seismictoss"],
eventPokemon: [
{"generation":3,"level":40,"moves":["curse","superpower","ancientpower","hyperbeam"]}
],
unreleasedHidden: true,
tier: "RU"
},
latias: {
randomBattleMoves: ["dragonpulse","surf","thunderbolt","roost","calmmind","healingwish","defog"],
randomDoubleBattleMoves: ["dragonpulse","psychic","tailwind","helpinghand","healpulse","lightscreen","reflect","protect"],
eventPokemon: [
{"generation":3,"level":50,"gender":"F","moves":["charm","recover","psychic","mistball"]},
{"generation":3,"level":70,"gender":"F","moves":["mistball","psychic","recover","charm"]},
{"generation":4,"level":40,"gender":"F","moves":["watersport","refresh","mistball","zenheadbutt"]}
],
tier: "OU"
},
latiasmega: {
randomBattleMoves: ["dragonpulse","surf","thunderbolt","roost","calmmind","healingwish","defog"],
randomDoubleBattleMoves: ["dragonpulse","psychic","tailwind","helpinghand","healpulse","lightscreen","reflect","protect"],
requiredItem: "Latiasite"
},
latios: {
randomBattleMoves: ["dracometeor","dragonpulse","surf","thunderbolt","psyshock","roost","trick","calmmind","defog"],
randomDoubleBattleMoves: ["dracometeor","dragonpulse","surf","thunderbolt","psyshock","substitute","trick","tailwind","protect","hiddenpowerfire"],
eventPokemon: [
{"generation":3,"level":50,"gender":"M","moves":["dragondance","recover","psychic","lusterpurge"]},
{"generation":3,"level":70,"gender":"M","moves":["lusterpurge","psychic","recover","dragondance"]},
{"generation":4,"level":40,"gender":"M","moves":["protect","refresh","lusterpurge","zenheadbutt"]}
],
tier: "OU"
},
latiosmega: {
randomBattleMoves: ["dracometeor","dragonpulse","surf","thunderbolt","psyshock","roost","calmmind","defog"],
randomDoubleBattleMoves: ["dracometeor","dragonpulse","surf","thunderbolt","psyshock","substitute","trick","tailwind","protect","hiddenpowerfire"],
requiredItem: "Latiosite"
},
kyogre: {
randomBattleMoves: ["waterspout","originpulse","scald","thunder","icebeam","calmmind","rest","sleeptalk","roar"],
randomDoubleBattleMoves: ["waterspout","muddywater","originpulse","thunder","icebeam","calmmind","rest","sleeptalk","protect"],
eventPokemon: [
{"generation":5,"level":80,"moves":["icebeam","ancientpower","waterspout","thunder"],"pokeball":"cherishball"},
{"generation":5,"level":100,"moves":["waterspout","thunder","icebeam","sheercold"],"pokeball":"cherishball"}
],
tier: "Uber"
},
kyogreprimal: {
randomBattleMoves: ["waterspout","originpulse","scald","thunder","icebeam","calmmind","rest","sleeptalk","roar"],
randomDoubleBattleMoves: ["waterspout","originpulse","muddywater","thunder","icebeam","calmmind","rest","sleeptalk","protect"],
requiredItem: "Blue Orb"
},
groudon: {
randomBattleMoves: ["earthquake","roar","stealthrock","stoneedge","swordsdance","rockpolish","thunderwave","firepunch"],
randomDoubleBattleMoves: ["earthquake","rockslide","protect","stoneedge","swordsdance","rockpolish","dragonclaw","firepunch"],
eventPokemon: [
{"generation":5,"level":80,"moves":["earthquake","ancientpower","eruption","solarbeam"],"pokeball":"cherishball"},
{"generation":5,"level":100,"moves":["eruption","hammerarm","earthpower","solarbeam"],"pokeball":"cherishball"}
],
tier: "Uber"
},
groudonprimal: {
randomBattleMoves: ["earthquake","lavaplume","stealthrock","stoneedge","swordsdance","overheat","rockpolish","firepunch"],
randomDoubleBattleMoves: ["earthquake","lavaplume","rockslide","stoneedge","swordsdance","overheat","rockpolish","firepunch","protect"],
requiredItem: "Red Orb"
},
rayquaza: {
randomBattleMoves: ["outrage","vcreate","extremespeed","dragondance","earthquake","dracometeor","dragonclaw"],
randomDoubleBattleMoves: ["tailwind","vcreate","extremespeed","dragondance","earthquake","dracometeor","dragonclaw","protect"],
eventPokemon: [
{"generation":5,"level":70,"shiny":true,"moves":["dragonpulse","ancientpower","outrage","dragondance"],"pokeball":"cherishball"},
{"generation":5,"level":100,"moves":["extremespeed","hyperbeam","dragonpulse","vcreate"],"pokeball":"cherishball"},
{"generation":6,"level":70,"shiny":true,"moves":["dragonpulse","thunder","twister","extremespeed"],"pokeball":"cherishball"}
],
tier: "Uber"
},
rayquazamega: {
randomBattleMoves: ["vcreate","extremespeed","swordsdance","earthquake","dragonascent","dragonclaw","dragondance"],
randomDoubleBattleMoves: ["vcreate","extremespeed","swordsdance","earthquake","dragonascent","dragonclaw","dragondance","protect"],
requiredMove: "Dragon Ascent"
},
jirachi: {
randomBattleMoves: ["bodyslam","ironhead","firepunch","thunderwave","stealthrock","wish","uturn","calmmind","psychic","thunderbolt","icepunch","trick"],
randomDoubleBattleMoves: ["bodyslam","ironhead","icywind","thunderwave","helpinghand","trickroom","uturn","followme","psychic","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["wish","confusion","rest"]},
{"generation":3,"level":30,"moves":["helpinghand","psychic","refresh","rest"]},
{"generation":4,"level":5,"moves":["wish","confusion","rest"],"pokeball":"cherishball"},
{"generation":4,"level":5,"moves":["wish","confusion","rest","dracometeor"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["healingwish","psychic","swift","meteormash"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["dracometeor","meteormash","wish","followme"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["wish","healingwish","cosmicpower","meteormash"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["wish","healingwish","swift","return"],"pokeball":"cherishball"},
{"generation":6,"level":10,"shiny":true,"moves":["wish","swift","healingwish","moonblast"],"pokeball":"cherishball"},
{"generation":6,"level":15,"shiny":true,"moves":["wish","confusion","helpinghand","return"],"pokeball":"cherishball"}
],
tier: "OU"
},
deoxys: {
randomBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","spikes","stealthrock","knockoff"],
randomDoubleBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","protect","knockoff","psyshock"],
eventPokemon: [
{"generation":3,"level":30,"moves":["snatch","psychic","spikes","knockoff"]},
{"generation":3,"level":30,"moves":["superpower","psychic","pursuit","taunt"]},
{"generation":3,"level":30,"moves":["swift","psychic","pursuit","knockoff"]},
{"generation":3,"level":70,"moves":["cosmicpower","recover","psychoboost","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","zapcannon","irondefense","extremespeed"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["psychoboost","swift","doubleteam","extremespeed"]},
{"generation":4,"level":50,"moves":["psychoboost","detect","counter","mirrorcoat"]},
{"generation":4,"level":50,"moves":["psychoboost","meteormash","superpower","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","leer","wrap","nightshade"]},
{"generation":5,"level":100,"moves":["nastyplot","darkpulse","recover","psychoboost"],"pokeball":"duskball"}
],
tier: "Uber"
},
deoxysattack: {
randomBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","spikes","stealthrock","knockoff"],
randomDoubleBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","protect","knockoff"],
eventPokemon: [
{"generation":3,"level":30,"moves":["snatch","psychic","spikes","knockoff"]},
{"generation":3,"level":30,"moves":["superpower","psychic","pursuit","taunt"]},
{"generation":3,"level":30,"moves":["swift","psychic","pursuit","knockoff"]},
{"generation":3,"level":70,"moves":["cosmicpower","recover","psychoboost","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","zapcannon","irondefense","extremespeed"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["psychoboost","swift","doubleteam","extremespeed"]},
{"generation":4,"level":50,"moves":["psychoboost","detect","counter","mirrorcoat"]},
{"generation":4,"level":50,"moves":["psychoboost","meteormash","superpower","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","leer","wrap","nightshade"]},
{"generation":5,"level":100,"moves":["nastyplot","darkpulse","recover","psychoboost"],"pokeball":"duskball"}
],
tier: "Uber"
},
deoxysdefense: {
randomBattleMoves: ["spikes","stealthrock","recover","taunt","toxic","seismictoss","magiccoat"],
randomDoubleBattleMoves: ["protect","stealthrock","recover","taunt","reflect","seismictoss","lightscreen","trickroom"],
eventPokemon: [
{"generation":3,"level":30,"moves":["snatch","psychic","spikes","knockoff"]},
{"generation":3,"level":30,"moves":["superpower","psychic","pursuit","taunt"]},
{"generation":3,"level":30,"moves":["swift","psychic","pursuit","knockoff"]},
{"generation":3,"level":70,"moves":["cosmicpower","recover","psychoboost","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","zapcannon","irondefense","extremespeed"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["psychoboost","swift","doubleteam","extremespeed"]},
{"generation":4,"level":50,"moves":["psychoboost","detect","counter","mirrorcoat"]},
{"generation":4,"level":50,"moves":["psychoboost","meteormash","superpower","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","leer","wrap","nightshade"]},
{"generation":5,"level":100,"moves":["nastyplot","darkpulse","recover","psychoboost"],"pokeball":"duskball"}
],
tier: "Uber"
},
deoxysspeed: {
randomBattleMoves: ["spikes","stealthrock","superpower","icebeam","psychoboost","taunt","lightscreen","reflect","magiccoat","knockoff"],
randomDoubleBattleMoves: ["superpower","icebeam","psychoboost","taunt","lightscreen","reflect","protect","knockoff"],
eventPokemon: [
{"generation":3,"level":30,"moves":["snatch","psychic","spikes","knockoff"]},
{"generation":3,"level":30,"moves":["superpower","psychic","pursuit","taunt"]},
{"generation":3,"level":30,"moves":["swift","psychic","pursuit","knockoff"]},
{"generation":3,"level":70,"moves":["cosmicpower","recover","psychoboost","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","zapcannon","irondefense","extremespeed"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["psychoboost","swift","doubleteam","extremespeed"]},
{"generation":4,"level":50,"moves":["psychoboost","detect","counter","mirrorcoat"]},
{"generation":4,"level":50,"moves":["psychoboost","meteormash","superpower","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","leer","wrap","nightshade"]},
{"generation":5,"level":100,"moves":["nastyplot","darkpulse","recover","psychoboost"],"pokeball":"duskball"}
],
tier: "Uber"
},
turtwig: {
randomBattleMoves: ["reflect","lightscreen","stealthrock","seedbomb","substitute","leechseed","toxic"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tackle","withdraw","absorb"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tackle","withdraw","absorb","stockpile"]}
],
tier: "LC"
},
grotle: {
randomBattleMoves: ["reflect","lightscreen","stealthrock","seedbomb","substitute","leechseed","toxic"],
tier: "NFE"
},
torterra: {
randomBattleMoves: ["stealthrock","earthquake","woodhammer","stoneedge","synthesis","leechseed","rockpolish"],
randomDoubleBattleMoves: ["protect","earthquake","woodhammer","stoneedge","rockslide","wideguard","rockpolish"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["woodhammer","earthquake","outrage","stoneedge"],"pokeball":"cherishball"}
],
tier: "PU"
},
chimchar: {
randomBattleMoves: ["stealthrock","overheat","hiddenpowergrass","fakeout","uturn","gunkshot"],
eventPokemon: [
{"generation":4,"level":40,"gender":"M","nature":"Mild","moves":["flamethrower","thunderpunch","grassknot","helpinghand"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["scratch","leer","ember","taunt"]},
{"generation":4,"level":40,"gender":"M","nature":"Hardy","moves":["flamethrower","thunderpunch","grassknot","helpinghand"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["leer","ember","taunt","fakeout"]}
],
tier: "LC"
},
monferno: {
randomBattleMoves: ["stealthrock","overheat","hiddenpowergrass","fakeout","vacuumwave","uturn","gunkshot"],
tier: "PU"
},
infernape: {
randomBattleMoves: ["stealthrock","fireblast","closecombat","uturn","grassknot","stoneedge","machpunch","swordsdance","nastyplot","flareblitz","hiddenpowerice","thunderpunch"],
randomDoubleBattleMoves: ["fakeout","heatwave","closecombat","uturn","grassknot","stoneedge","machpunch","feint","taunt","flareblitz","hiddenpowerice","thunderpunch","protect"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["fireblast","closecombat","uturn","grassknot"],"pokeball":"cherishball"}
],
tier: "UU"
},
piplup: {
randomBattleMoves: ["stealthrock","hydropump","scald","icebeam","hiddenpowerelectric","hiddenpowerfire","yawn","defog"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["pound","growl","bubble"]},
{"generation":5,"level":15,"isHidden":false,"moves":["hydropump","featherdance","watersport","peck"],"pokeball":"cherishball"},
{"generation":5,"level":15,"gender":"M","isHidden":false,"moves":["sing","round","featherdance","peck"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["pound","growl","bubble","featherdance"]},
{"generation":6,"level":7,"isHidden":false,"moves":["pound","growl","return"],"pokeball":"cherishball"}
],
tier: "LC"
},
prinplup: {
randomBattleMoves: ["stealthrock","hydropump","scald","icebeam","hiddenpowerelectric","hiddenpowerfire","yawn","defog"],
tier: "NFE"
},
empoleon: {
randomBattleMoves: ["stealthrock","hydropump","scald","icebeam","roar","grassknot","flashcannon","defog","agility"],
randomDoubleBattleMoves: ["icywind","hydropump","scald","icebeam","hiddenpowerelectric","protect","grassknot","flashcannon"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["hydropump","icebeam","aquajet","grassknot"],"pokeball":"cherishball"}
],
tier: "UU"
},
starly: {
randomBattleMoves: ["bravebird","return","uturn","pursuit"],
eventPokemon: [
{"generation":4,"level":1,"gender":"M","nature":"Mild","moves":["tackle","growl"]}
],
tier: "LC"
},
staravia: {
randomBattleMoves: ["bravebird","return","uturn","pursuit","defog"],
tier: "NFE"
},
staraptor: {
randomBattleMoves: ["bravebird","closecombat","uturn","quickattack","roost","doubleedge"],
randomDoubleBattleMoves: ["bravebird","closecombat","uturn","quickattack","doubleedge","tailwind","protect"],
tier: "BL"
},
bidoof: {
randomBattleMoves: ["return","aquatail","curse","quickattack","stealthrock","superfang"],
eventPokemon: [
{"generation":4,"level":1,"gender":"M","nature":"Lonely","abilities":["simple"],"moves":["tackle"]}
],
tier: "LC"
},
bibarel: {
randomBattleMoves: ["return","waterfall","curse","quickattack","stealthrock","rest"],
randomDoubleBattleMoves: ["return","waterfall","curse","quickattack","protect","rest"],
tier: "PU"
},
kricketot: {
randomBattleMoves: ["endeavor","mudslap","bugbite","strugglebug"],
tier: "LC"
},
kricketune: {
randomBattleMoves: ["xscissor","endeavor","taunt","toxic","stickyweb","knockoff"],
randomDoubleBattleMoves: ["bugbite","protect","taunt","stickyweb","knockoff"],
tier: "PU"
},
shinx: {
randomBattleMoves: ["wildcharge","icefang","firefang","crunch"],
tier: "LC"
},
luxio: {
randomBattleMoves: ["wildcharge","icefang","firefang","crunch"],
tier: "NFE"
},
luxray: {
randomBattleMoves: ["wildcharge","icefang","voltswitch","crunch","superpower","facade"],
randomDoubleBattleMoves: ["wildcharge","icefang","voltswitch","crunch","superpower","facade","protect"],
tier: "PU"
},
cranidos: {
randomBattleMoves: ["headsmash","rockslide","earthquake","zenheadbutt","firepunch","rockpolish","crunch"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"moves":["pursuit","takedown","crunch","headbutt"],"pokeball":"cherishball"}
],
tier: "LC"
},
rampardos: {
randomBattleMoves: ["headsmash","earthquake","zenheadbutt","rockpolish","crunch","stoneedge"],
randomDoubleBattleMoves: ["headsmash","earthquake","zenheadbutt","rockslide","crunch","stoneedge","protect"],
tier: "PU"
},
shieldon: {
randomBattleMoves: ["stealthrock","metalburst","fireblast","icebeam","protect","toxic","roar"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"moves":["metalsound","takedown","bodyslam","protect"],"pokeball":"cherishball"}
],
tier: "LC"
},
bastiodon: {
randomBattleMoves: ["stealthrock","rockblast","metalburst","protect","toxic","roar"],
randomDoubleBattleMoves: ["stealthrock","stoneedge","metalburst","protect","wideguard","guardsplit"],
tier: "PU"
},
burmy: {
randomBattleMoves: ["bugbite","hiddenpowerice","electroweb","protect"],
tier: "LC"
},
wormadam: {
randomBattleMoves: ["leafstorm","gigadrain","signalbeam","hiddenpowerice","hiddenpowerrock","toxic","synthesis"],
randomDoubleBattleMoves: ["leafstorm","gigadrain","signalbeam","hiddenpowerice","hiddenpowerrock","stringshot","protect"],
tier: "PU"
},
wormadamsandy: {
randomBattleMoves: ["earthquake","toxic","rockblast","protect","stealthrock"],
randomDoubleBattleMoves: ["earthquake","suckerpunch","rockblast","protect","stringshot"],
tier: "PU"
},
wormadamtrash: {
randomBattleMoves: ["stealthrock","toxic","gyroball","protect"],
randomDoubleBattleMoves: ["strugglebug","stringshot","gyroball","protect"],
tier: "PU"
},
mothim: {
randomBattleMoves: ["quiverdance","bugbuzz","airslash","gigadrain","roost"],
randomDoubleBattleMoves: ["quiverdance","bugbuzz","airslash","gigadrain","roost","protect"],
tier: "PU"
},
combee: {
randomBattleMoves: ["bugbuzz","aircutter","endeavor","ominouswind","tailwind"],
tier: "LC"
},
vespiquen: {
randomBattleMoves: ["substitute","healorder","toxic","attackorder","defendorder","infestation"],
randomDoubleBattleMoves: ["tailwind","healorder","stringshot","attackorder","strugglebug","protect"],
tier: "PU"
},
pachirisu: {
randomBattleMoves: ["nuzzle","thunderbolt","superfang","toxic","uturn"],
randomDoubleBattleMoves: ["nuzzle","thunderbolt","superfang","followme","uturn","helpinghand","protect"],
eventPokemon: [
{"generation":6,"level":50,"nature":"Impish","isHidden":true,"moves":["nuzzle","superfang","followme","protect"],"pokeball":"cherishball"}
],
tier: "PU"
},
buizel: {
randomBattleMoves: ["waterfall","aquajet","switcheroo","brickbreak","bulkup","batonpass","icepunch"],
tier: "LC"
},
floatzel: {
randomBattleMoves: ["waterfall","aquajet","switcheroo","bulkup","batonpass","icepunch","crunch"],
randomDoubleBattleMoves: ["waterfall","aquajet","switcheroo","raindance","protect","icepunch","crunch","taunt"],
tier: "PU"
},
cherubi: {
randomBattleMoves: ["sunnyday","solarbeam","weatherball","hiddenpowerice","aromatherapy","dazzlinggleam"],
tier: "LC"
},
cherrim: {
randomBattleMoves: ["sunnyday","solarbeam","weatherball","hiddenpowerice","energyball","synthesis"],
randomDoubleBattleMoves: ["sunnyday","solarbeam","weatherball","hiddenpowerice","protect"],
tier: "PU"
},
shellos: {
randomBattleMoves: ["scald","clearsmog","recover","toxic","icebeam","stockpile"],
tier: "LC"
},
gastrodon: {
randomBattleMoves: ["earthquake","icebeam","scald","toxic","recover"],
randomDoubleBattleMoves: ["earthpower","icebeam","scald","muddywater","recover","icywind","protect"],
tier: "RU"
},
drifloon: {
randomBattleMoves: ["shadowball","substitute","calmmind","hypnosis","hiddenpowerfighting","thunderbolt","destinybond","willowisp","stockpile","batonpass","disable"],
tier: "LC"
},
drifblim: {
randomBattleMoves: ["shadowball","substitute","calmmind","hiddenpowerfighting","thunderbolt","destinybond","willowisp","batonpass"],
randomDoubleBattleMoves: ["shadowball","substitute","hypnosis","hiddenpowerfighting","thunderbolt","destinybond","willowisp","protect"],
tier: "PU"
},
buneary: {
randomBattleMoves: ["fakeout","return","switcheroo","thunderpunch","highjumpkick","firepunch","icepunch","healingwish"],
tier: "LC"
},
lopunny: {
randomBattleMoves: ["return","switcheroo","highjumpkick","firepunch","icepunch","healingwish"],
randomDoubleBattleMoves: ["return","switcheroo","highjumpkick","firepunch","icepunch","fakeout","protect","encore"],
tier: "OU"
},
lopunnymega: {
randomBattleMoves: ["return","highjumpkick","poweruppunch","fakeout","icepunch"],
randomDoubleBattleMoves: ["return","highjumpkick","protect","fakeout","icepunch","encore"],
requiredItem: "Lopunnite"
},
glameow: {
randomBattleMoves: ["fakeout","uturn","suckerpunch","hypnosis","quickattack","return","foulplay"],
tier: "LC"
},
purugly: {
randomBattleMoves: ["fakeout","uturn","suckerpunch","quickattack","return","knockoff"],
randomDoubleBattleMoves: ["fakeout","uturn","suckerpunch","quickattack","return","knockoff","protect"],
tier: "PU"
},
stunky: {
randomBattleMoves: ["pursuit","suckerpunch","crunch","fireblast","explosion","taunt","poisonjab","playrough","defog"],
tier: "LC"
},
skuntank: {
randomBattleMoves: ["pursuit","suckerpunch","crunch","fireblast","taunt","poisonjab","playrough","defog"],
randomDoubleBattleMoves: ["protect","suckerpunch","crunch","fireblast","taunt","poisonjab","playrough","snarl","feint"],
tier: "RU"
},
bronzor: {
randomBattleMoves: ["stealthrock","psychic","toxic","hypnosis","reflect","lightscreen","trickroom","trick"],
tier: "LC"
},
bronzong: {
randomBattleMoves: ["stealthrock","earthquake","toxic","reflect","lightscreen","trickroom","explosion","gyroball"],
randomDoubleBattleMoves: ["earthquake","protect","reflect","lightscreen","trickroom","explosion","gyroball"],
tier: "RU"
},
chatot: {
randomBattleMoves: ["nastyplot","boomburst","heatwave","encore","substitute","chatter","uturn"],
randomDoubleBattleMoves: ["nastyplot","heatwave","encore","substitute","chatter","uturn","protect","hypervoice","boomburst"],
eventPokemon: [
{"generation":4,"level":25,"gender":"M","nature":"Jolly","abilities":["keeneye"],"moves":["mirrormove","furyattack","chatter","taunt"]}
],
tier: "PU"
},
spiritomb: {
randomBattleMoves: ["shadowsneak","suckerpunch","pursuit","willowisp","calmmind","darkpulse","rest","sleeptalk","foulplay","painsplit"],
randomDoubleBattleMoves: ["shadowsneak","suckerpunch","icywind","willowisp","snarl","darkpulse","protect","foulplay","painsplit"],
eventPokemon: [
{"generation":5,"level":61,"gender":"F","nature":"Quiet","isHidden":false,"moves":["darkpulse","psychic","silverwind","embargo"],"pokeball":"cherishball"}
],
tier: "RU"
},
gible: {
randomBattleMoves: ["outrage","dragonclaw","earthquake","fireblast","stoneedge","stealthrock"],
tier: "LC"
},
gabite: {
randomBattleMoves: ["outrage","dragonclaw","earthquake","fireblast","stoneedge","stealthrock"],
tier: "NFE"
},
garchomp: {
randomBattleMoves: ["outrage","dragonclaw","earthquake","stoneedge","fireblast","swordsdance","stealthrock","firefang"],
randomDoubleBattleMoves: ["substitute","dragonclaw","earthquake","stoneedge","rockslide","swordsdance","protect"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["outrage","earthquake","swordsdance","stoneedge"],"pokeball":"cherishball"},
{"generation":5,"level":48,"gender":"M","isHidden":true,"moves":["dragonclaw","dig","crunch","outrage"]},
{"generation":6,"level":48,"gender":"M","isHidden":false,"moves":["dracometeor","dragonclaw","dig","crunch"],"pokeball":"cherishball"},
{"generation":6,"level":50,"gender":"M","isHidden":false,"moves":["slash","dragonclaw","dig","crunch"],"pokeball":"cherishball"}
],
tier: "OU"
},
garchompmega: {
randomBattleMoves: ["outrage","dracometeor","earthquake","stoneedge","fireblast","stealthrock"],
randomDoubleBattleMoves: ["substitute","dragonclaw","earthquake","stoneedge","rockslide","swordsdance","protect","fireblast"],
requiredItem: "Garchompite"
},
riolu: {
randomBattleMoves: ["crunch","rockslide","copycat","drainpunch","highjumpkick","icepunch","swordsdance"],
eventPokemon: [
{"generation":4,"level":30,"gender":"M","nature":"Serious","abilities":["steadfast"],"moves":["aurasphere","shadowclaw","bulletpunch","drainpunch"]}
],
tier: "LC"
},
lucario: {
randomBattleMoves: ["swordsdance","closecombat","crunch","extremespeed","icepunch","bulletpunch","nastyplot","aurasphere","darkpulse","vacuumwave","flashcannon"],
randomDoubleBattleMoves: ["followme","closecombat","crunch","extremespeed","icepunch","bulletpunch","aurasphere","darkpulse","vacuumwave","flashcannon","protect"],
eventPokemon: [
{"generation":4,"level":50,"gender":"M","nature":"Modest","abilities":["steadfast"],"moves":["aurasphere","darkpulse","dragonpulse","waterpulse"],"pokeball":"cherishball"},
{"generation":4,"level":30,"gender":"M","nature":"Adamant","abilities":["innerfocus"],"moves":["forcepalm","bonerush","sunnyday","blazekick"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["detect","metalclaw","counter","bulletpunch"]},
{"generation":5,"level":50,"gender":"M","nature":"Naughty","isHidden":true,"moves":["bulletpunch","closecombat","stoneedge","shadowclaw"],"pokeball":"cherishball"}
],
tier: "UU"
},
lucariomega: {
randomBattleMoves: ["swordsdance","closecombat","crunch","extremespeed","icepunch","bulletpunch","nastyplot","aurasphere","darkpulse","vacuumwave","flashcannon"],
randomDoubleBattleMoves: ["followme","closecombat","crunch","extremespeed","icepunch","bulletpunch","aurasphere","darkpulse","vacuumwave","flashcannon","protect"],
requiredItem: "Lucarionite",
tier: "Uber"
},
hippopotas: {
randomBattleMoves: ["earthquake","slackoff","whirlwind","stealthrock","protect","toxic","stockpile"],
tier: "LC"
},
hippowdon: {
randomBattleMoves: ["earthquake","slackoff","whirlwind","stealthrock","toxic","rockslide"],
randomDoubleBattleMoves: ["earthquake","slackoff","rockslide","stealthrock","protect","stoneedge"],
tier: "UU"
},
skorupi: {
randomBattleMoves: ["toxicspikes","xscissor","poisonjab","knockoff","pinmissile","whirlwind"],
tier: "LC"
},
drapion: {
randomBattleMoves: ["whirlwind","toxicspikes","pursuit","earthquake","aquatail","swordsdance","poisonjab","knockoff"],
randomDoubleBattleMoves: ["snarl","taunt","protect","earthquake","aquatail","swordsdance","poisonjab","knockoff"],
tier: "RU"
},
croagunk: {
randomBattleMoves: ["fakeout","vacuumwave","suckerpunch","drainpunch","darkpulse","knockoff","gunkshot","toxic"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["astonish","mudslap","poisonsting","taunt"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["mudslap","poisonsting","taunt","poisonjab"]}
],
tier: "LC"
},
toxicroak: {
randomBattleMoves: ["suckerpunch","drainpunch","substitute","swordsdance","knockoff","icepunch","gunkshot"],
randomDoubleBattleMoves: ["suckerpunch","drainpunch","substitute","swordsdance","knockoff","icepunch","gunkshot","fakeout","protect"],
tier: "UU"
},
carnivine: {
randomBattleMoves: ["swordsdance","powerwhip","return","sleeppowder","substitute","leechseed","knockoff"],
randomDoubleBattleMoves: ["swordsdance","powerwhip","return","sleeppowder","substitute","leechseed","knockoff","ragepowder","protect"],
tier: "PU"
},
finneon: {
randomBattleMoves: ["surf","uturn","icebeam","hiddenpowerelectric","hiddenpowergrass","raindance"],
tier: "LC"
},
lumineon: {
randomBattleMoves: ["surf","uturn","icebeam","hiddenpowerelectric","hiddenpowergrass","raindance"],
randomDoubleBattleMoves: ["surf","uturn","icebeam","hiddenpowerelectric","hiddenpowergrass","raindance","tailwind","protect"],
tier: "PU"
},
snover: {
randomBattleMoves: ["blizzard","iceshard","gigadrain","leechseed","substitute","woodhammer"],
tier: "LC"
},
abomasnow: {
randomBattleMoves: ["blizzard","iceshard","gigadrain","leechseed","substitute","focusblast","woodhammer","earthquake"],
randomDoubleBattleMoves: ["blizzard","iceshard","gigadrain","protect","focusblast","woodhammer","earthquake"],
tier: "RU"
},
abomasnowmega: {
randomBattleMoves: ["blizzard","iceshard","gigadrain","leechseed","substitute","focusblast","woodhammer","earthquake"],
randomDoubleBattleMoves: ["blizzard","iceshard","gigadrain","protect","focusblast","woodhammer","earthquake"],
requiredItem: "Abomasite"
},
rotom: {
randomBattleMoves: ["thunderbolt","voltswitch","shadowball","substitute","painsplit","hiddenpowerice","trick","willowisp"],
randomDoubleBattleMoves: ["thunderbolt","voltswitch","shadowball","substitute","painsplit","hiddenpowerice","trick","willowisp","electroweb","protect"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "NU"
},
rotomheat: {
randomBattleMoves: ["overheat","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","trick"],
randomDoubleBattleMoves: ["overheat","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","trick","electroweb","protect"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "UU"
},
rotomwash: {
randomBattleMoves: ["hydropump","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","trick"],
randomDoubleBattleMoves: ["hydropump","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","trick","electroweb","protect","hiddenpowergrass"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "OU"
},
rotomfrost: {
randomBattleMoves: ["blizzard","thunderbolt","voltswitch","substitute","painsplit","willowisp","trick"],
randomDoubleBattleMoves: ["blizzard","thunderbolt","voltswitch","substitute","painsplit","willowisp","trick","electroweb","protect"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "PU"
},
rotomfan: {
randomBattleMoves: ["airslash","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","trick"],
randomDoubleBattleMoves: ["airslash","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","electroweb","discharge","protect"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "NU"
},
rotommow: {
randomBattleMoves: ["leafstorm","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerfire","willowisp","trick"],
randomDoubleBattleMoves: ["leafstorm","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerfire","willowisp","trick","electroweb","protect"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "RU"
},
uxie: {
randomBattleMoves: ["uturn","psyshock","yawn","healbell","stealthrock","toxic","thunderbolt","substitute","calmmind"],
randomDoubleBattleMoves: ["uturn","psyshock","yawn","healbell","stealthrock","thunderbolt","protect","helpinghand","thunderwave","skillswap"],
tier: "NU"
},
mesprit: {
randomBattleMoves: ["calmmind","psyshock","thunderbolt","icebeam","substitute","uturn","trick","stealthrock","knockoff","psychic","healingwish"],
randomDoubleBattleMoves: ["calmmind","psychic","thunderbolt","icebeam","substitute","uturn","trick","protect","knockoff","psychic","helpinghand"],
tier: "NU"
},
azelf: {
randomBattleMoves: ["nastyplot","psychic","fireblast","thunderbolt","icepunch","knockoff","zenheadbutt","uturn","trick","taunt","stealthrock","explosion"],
randomDoubleBattleMoves: ["nastyplot","psychic","fireblast","thunderbolt","icepunch","knockoff","zenheadbutt","uturn","trick","taunt","protect","dazzlinggleam"],
tier: "UU"
},
dialga: {
randomBattleMoves: ["stealthrock","dracometeor","dragonpulse","roar","thunderbolt","flashcannon","outrage","fireblast","aurasphere"],
randomDoubleBattleMoves: ["dracometeor","dragonpulse","protect","thunderbolt","flashcannon","earthpower","fireblast","aurasphere"],
eventPokemon: [
{"generation":5,"level":100,"shiny":true,"isHidden":false,"moves":["dragonpulse","dracometeor","aurasphere","roaroftime"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'dreamball',
tier: "Uber"
},
palkia: {
randomBattleMoves: ["spacialrend","dracometeor","surf","hydropump","thunderbolt","outrage","fireblast"],
randomDoubleBattleMoves: ["spacialrend","dracometeor","surf","hydropump","thunderbolt","fireblast","protect"],
eventPokemon: [
{"generation":5,"level":100,"shiny":true,"isHidden":false,"moves":["hydropump","dracometeor","spacialrend","aurasphere"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'dreamball',
tier: "Uber"
},
heatran: {
randomBattleMoves: ["substitute","fireblast","lavaplume","willowisp","stealthrock","earthpower","hiddenpowerice","protect","toxic","roar"],
randomDoubleBattleMoves: ["heatwave","substitute","earthpower","protect","eruption","willowisp"],
eventPokemon: [
{"generation":4,"level":50,"nature":"Quiet","moves":["eruption","magmastorm","earthpower","ancientpower"]}
],
unreleasedHidden: true,
tier: "OU"
},
regigigas: {
randomBattleMoves: ["thunderwave","substitute","return","drainpunch","earthquake","confuseray"],
randomDoubleBattleMoves: ["thunderwave","substitute","return","icywind","rockslide","earthquake","knockoff","wideguard"],
eventPokemon: [
{"generation":4,"level":100,"moves":["ironhead","rockslide","icywind","crushgrip"],"pokeball":"cherishball"}
],
tier: "PU"
},
giratina: {
randomBattleMoves: ["rest","sleeptalk","dragontail","roar","willowisp","shadowball","dragonpulse"],
randomDoubleBattleMoves: ["tailwind","icywind","protect","dragontail","willowisp","calmmind","dragonpulse","shadowball"],
eventPokemon: [
{"generation":5,"level":100,"shiny":true,"isHidden":false,"moves":["dragonpulse","dragonclaw","aurasphere","shadowforce"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'dreamball',
tier: "Uber"
},
giratinaorigin: {
randomBattleMoves: ["dracometeor","shadowsneak","dragontail","willowisp","defog","toxic","shadowball","stoneedge","earthquake"],
randomDoubleBattleMoves: ["dracometeor","shadowsneak","tailwind","hiddenpowerfire","willowisp","calmmind","substitute","dragonpulse","shadowball","aurasphere","protect","earthquake"],
requiredItem: "Griseous Orb",
tier: "Uber"
},
cresselia: {
randomBattleMoves: ["moonlight","psychic","icebeam","thunderwave","toxic","lunardance","rest","sleeptalk","calmmind"],
randomDoubleBattleMoves: ["psyshock","icywind","thunderwave","trickroom","moonblast","moonlight","skillswap","reflect","lightscreen","icebeam","protect","helpinghand"],
eventPokemon: [
{"generation":5,"level":68,"gender":"F","nature":"Modest","moves":["icebeam","psyshock","energyball","hiddenpower"]}
],
tier: "RU"
},
phione: {
randomBattleMoves: ["raindance","scald","uturn","rest","icebeam"],
randomDoubleBattleMoves: ["raindance","scald","uturn","rest","icebeam","helpinghand","icywind","protect"],
eventPokemon: [
{"generation":4,"level":50,"abilities":["hydration"],"moves":["grassknot","raindance","rest","surf"],"pokeball":"cherishball"}
],
tier: "PU"
},
manaphy: {
randomBattleMoves: ["tailglow","surf","icebeam","energyball","psychic"],
randomDoubleBattleMoves: ["tailglow","surf","icebeam","energyball","protect","scald","icywind","helpinghand"],
eventPokemon: [
{"generation":4,"level":5,"moves":["tailglow","bubble","watersport"]},
{"generation":4,"level":1,"moves":["tailglow","bubble","watersport"]},
{"generation":4,"level":50,"moves":["acidarmor","whirlpool","waterpulse","heartswap"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["heartswap","waterpulse","whirlpool","acidarmor"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["heartswap","whirlpool","waterpulse","acidarmor"],"pokeball":"cherishball"},
{"generation":4,"level":50,"nature":"Impish","moves":["aquaring","waterpulse","watersport","heartswap"],"pokeball":"cherishball"}
],
tier: "OU"
},
darkrai: {
randomBattleMoves: ["darkvoid","darkpulse","focusblast","nastyplot","substitute","trick","sludgebomb"],
randomDoubleBattleMoves: ["darkpulse","focusblast","nastyplot","substitute","snarl","protect"],
eventPokemon: [
{"generation":4,"level":50,"moves":["roaroftime","spacialrend","nightmare","hypnosis"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["darkvoid","darkpulse","shadowball","doubleteam"]},
{"generation":4,"level":50,"moves":["nightmare","hypnosis","roaroftime","spacialrend"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["doubleteam","nightmare","feintattack","hypnosis"]},
{"generation":5,"level":50,"moves":["darkvoid","ominouswind","feintattack","nightmare"],"pokeball":"cherishball"},
{"generation":6,"level":50,"moves":["darkvoid","darkpulse","phantomforce","dreameater"],"pokeball":"cherishball"}
],
tier: "Uber"
},
shaymin: {
randomBattleMoves: ["seedflare","earthpower","airslash","hiddenpowerfire","rest","substitute","leechseed"],
randomDoubleBattleMoves: ["seedflare","earthpower","airslash","hiddenpowerfire","rest","substitute","leechseed","tailwind","protect"],
eventPokemon: [
{"generation":4,"level":50,"moves":["seedflare","aromatherapy","substitute","energyball"],"pokeball":"cherishball"},
{"generation":4,"level":30,"moves":["synthesis","leechseed","magicalleaf","growth"]},
{"generation":4,"level":30,"moves":["growth","magicalleaf","leechseed","synthesis"]},
{"generation":5,"level":50,"moves":["seedflare","leechseed","synthesis","sweetscent"],"pokeball":"cherishball"},
{"generation":6,"level":15,"moves":["growth","magicalleaf","seedflare","airslash"],"pokeball":"cherishball"}
],
tier: "UU"
},
shayminsky: {
randomBattleMoves: ["seedflare","earthpower","airslash","hiddenpowerice","hiddenpowerfire","substitute","leechseed"],
randomDoubleBattleMoves: ["seedflare","earthpower","airslash","hiddenpowerfire","rest","substitute","leechseed","tailwind","protect","hiddenpowerice"],
tier: "Uber"
},
arceus: {
randomBattleMoves: ["swordsdance","extremespeed","shadowclaw","earthquake","recover"],
randomDoubleBattleMoves: ["swordsdance","extremespeed","shadowclaw","earthquake","recover","protect"],
eventPokemon: [
{"generation":4,"level":100,"moves":["judgment","roaroftime","spacialrend","shadowforce"],"pokeball":"cherishball"},
{"generation":5,"level":100,"moves":["recover","hyperbeam","perishsong","judgment"]}
],
unobtainableShiny: true,
tier: "Uber"
},
arceusbug: {
randomBattleMoves: ["swordsdance","xscissor","stoneedge","recover","earthquake","ironhead"],
randomDoubleBattleMoves: ["swordsdance","xscissor","stoneedge","recover","earthquake","ironhead","protect"],
requiredItem: "Insect Plate"
},
arceusdark: {
randomBattleMoves: ["calmmind","judgment","recover","fireblast","thunderbolt"],
randomDoubleBattleMoves: ["calmmind","judgment","recover","focusblast","safeguard","snarl","willowisp","protect"],
requiredItem: "Dread Plate"
},
arceusdragon: {
randomBattleMoves: ["swordsdance","outrage","extremespeed","earthquake","recover","calmmind","judgment","fireblast"],
randomDoubleBattleMoves: ["swordsdance","dragonclaw","extremespeed","earthquake","recover","protect"],
requiredItem: "Draco Plate"
},
arceuselectric: {
randomBattleMoves: ["calmmind","judgment","recover","icebeam","grassknot","fireblast","willowisp"],
randomDoubleBattleMoves: ["calmmind","judgment","recover","icebeam","protect"],
requiredItem: "Zap Plate"
},
arceusfairy: {
randomBattleMoves: ["calmmind","judgment","recover","willowisp","defog","thunderbolt","toxic","fireblast"],
randomDoubleBattleMoves: ["calmmind","judgment","recover","willowisp","protect","earthpower","thunderbolt"],
requiredItem: "Pixie Plate",
gen: 6
},
arceusfighting: {
randomBattleMoves: ["calmmind","judgment","stoneedge","shadowball","recover","toxic","defog"],
randomDoubleBattleMoves: ["calmmind","judgment","icebeam","shadowball","recover","willowisp","protect"],
requiredItem: "Fist Plate"
},
arceusfire: {
randomBattleMoves: ["calmmind","judgment","grassknot","thunderbolt","icebeam","recover"],
randomDoubleBattleMoves: ["calmmind","judgment","thunderbolt","recover","heatwave","protect","willowisp"],
requiredItem: "Flame Plate"
},
arceusflying: {
randomBattleMoves: ["calmmind","judgment","earthpower","fireblast","substitute","recover"],
randomDoubleBattleMoves: ["calmmind","judgment","safeguard","recover","substitute","tailwind","protect"],
requiredItem: "Sky Plate"
},
arceusghost: {
randomBattleMoves: ["calmmind","judgment","focusblast","recover","swordsdance","shadowforce","brickbreak","willowisp","roar","defog"],
randomDoubleBattleMoves: ["calmmind","judgment","focusblast","recover","swordsdance","shadowforce","brickbreak","willowisp","protect"],
requiredItem: "Spooky Plate"
},
arceusgrass: {
randomBattleMoves: ["judgment","recover","calmmind","icebeam","fireblast"],
randomDoubleBattleMoves: ["calmmind","icebeam","judgment","earthpower","recover","safeguard","thunderwave","protect"],
requiredItem: "Meadow Plate"
},
arceusground: {
randomBattleMoves: ["swordsdance","earthquake","stoneedge","recover","extremespeed","icebeam"],
randomDoubleBattleMoves: ["swordsdance","earthquake","stoneedge","recover","calmmind","judgment","icebeam","rockslide","protect"],
requiredItem: "Earth Plate"
},
arceusice: {
randomBattleMoves: ["calmmind","judgment","thunderbolt","fireblast","recover"],
randomDoubleBattleMoves: ["calmmind","judgment","thunderbolt","focusblast","recover","protect","icywind"],
requiredItem: "Icicle Plate"
},
arceuspoison: {
randomBattleMoves: ["calmmind","sludgebomb","fireblast","recover","willowisp","defog","thunderwave"],
randomDoubleBattleMoves: ["calmmind","judgment","sludgebomb","heatwave","recover","willowisp","protect","earthpower"],
requiredItem: "Toxic Plate"
},
arceuspsychic: {
randomBattleMoves: ["judgment","calmmind","focusblast","recover","defog","thunderbolt","willowisp"],
randomDoubleBattleMoves: ["calmmind","psyshock","focusblast","recover","willowisp","judgment","protect"],
requiredItem: "Mind Plate"
},
arceusrock: {
randomBattleMoves: ["recover","swordsdance","earthquake","stoneedge","extremespeed"],
randomDoubleBattleMoves: ["swordsdance","stoneedge","recover","rockslide","earthquake","protect"],
requiredItem: "Stone Plate"
},
arceussteel: {
randomBattleMoves: ["calmmind","judgment","recover","willowisp","thunderbolt","swordsdance","ironhead","earthquake","stoneedge"],
randomDoubleBattleMoves: ["calmmind","judgment","recover","protect","willowisp"],
requiredItem: "Iron Plate"
},
arceuswater: {
randomBattleMoves: ["recover","calmmind","judgment","substitute","willowisp","thunderbolt"],
randomDoubleBattleMoves: ["recover","calmmind","judgment","icebeam","fireblast","icywind","surf","protect"],
requiredItem: "Splash Plate"
},
victini: {
randomBattleMoves: ["vcreate","boltstrike","uturn","psychic","focusblast","blueflare"],
randomDoubleBattleMoves: ["vcreate","boltstrike","uturn","psychic","focusblast","blueflare","protect"],
eventPokemon: [
{"generation":5,"level":15,"moves":["incinerate","quickattack","endure","confusion"]},
{"generation":5,"level":50,"moves":["vcreate","fusionflare","fusionbolt","searingshot"],"pokeball":"cherishball"},
{"generation":5,"level":100,"moves":["vcreate","blueflare","boltstrike","glaciate"],"pokeball":"cherishball"},
{"generation":6,"level":15,"moves":["confusion","quickattack","vcreate","searingshot"],"pokeball":"cherishball"}
],
unobtainableShiny: true,
tier: "BL"
},
snivy: {
randomBattleMoves: ["leafstorm","hiddenpowerfire","substitute","leechseed","hiddenpowerice","gigadrain"],
eventPokemon: [
{"generation":5,"level":5,"gender":"M","nature":"Hardy","isHidden":false,"moves":["growth","synthesis","energyball","aromatherapy"],"pokeball":"cherishball"}
],
tier: "LC"
},
servine: {
randomBattleMoves: ["leafstorm","hiddenpowerfire","substitute","leechseed","hiddenpowerice","gigadrain"],
tier: "NFE"
},
serperior: {
randomBattleMoves: ["leafstorm","hiddenpowerfire","substitute","leechseed","dragonpulse","gigadrain"],
randomDoubleBattleMoves: ["leafstorm","hiddenpowerfire","substitute","taunt","dragonpulse","gigadrain","protect"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["leafstorm","substitute","gigadrain","leechseed"],"pokeball":"cherishball"},
{"generation":6,"level":50,"isHidden":true,"moves":["leafstorm","holdback","wringout","gigadrain"],"pokeball":"cherishball"}
],
tier: "UU"
},
tepig: {
randomBattleMoves: ["flamecharge","flareblitz","wildcharge","superpower","headsmash"],
tier: "LC"
},
pignite: {
randomBattleMoves: ["flamecharge","flareblitz","wildcharge","superpower","headsmash"],
tier: "NFE"
},
emboar: {
randomBattleMoves: ["flareblitz","superpower","flamecharge","wildcharge","headsmash","suckerpunch","fireblast"],
randomDoubleBattleMoves: ["flareblitz","superpower","flamecharge","wildcharge","headsmash","protect","heatwave","rockslide"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["flareblitz","hammerarm","wildcharge","headsmash"],"pokeball":"cherishball"},
{"generation":6,"level":50,"isHidden":true,"moves":["flareblitz","holdback","headsmash","takedown"],"pokeball":"cherishball"}
],
tier: "RU"
},
oshawott: {
randomBattleMoves: ["swordsdance","waterfall","aquajet","xscissor"],
tier: "LC"
},
dewott: {
randomBattleMoves: ["swordsdance","waterfall","aquajet","xscissor"],
tier: "NFE"
},
samurott: {
randomBattleMoves: ["swordsdance","aquajet","waterfall","megahorn","superpower"],
randomDoubleBattleMoves: ["hydropump","aquajet","icebeam","scald","hiddenpowergrass","taunt","helpinghand","protect"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["hydropump","icebeam","megahorn","superpower"],"pokeball":"cherishball"},
{"generation":6,"level":50,"isHidden":true,"moves":["razorshell","holdback","confide","hydropump"],"pokeball":"cherishball"}
],
tier: "NU"
},
patrat: {
randomBattleMoves: ["swordsdance","batonpass","substitute","hypnosis","return","superfang"],
tier: "LC"
},
watchog: {
randomBattleMoves: ["swordsdance","batonpass","substitute","hypnosis","return","superfang"],
randomDoubleBattleMoves: ["swordsdance","knockoff","substitute","hypnosis","return","superfang","protect"],
tier: "PU"
},
lillipup: {
randomBattleMoves: ["return","wildcharge","firefang","crunch","icefang"],
tier: "LC"
},
herdier: {
randomBattleMoves: ["return","wildcharge","firefang","crunch","icefang"],
tier: "NFE"
},
stoutland: {
randomBattleMoves: ["return","wildcharge","superpower","crunch","icefang"],
randomDoubleBattleMoves: ["return","wildcharge","superpower","crunch","icefang","protect"],
tier: "PU"
},
purrloin: {
randomBattleMoves: ["encore","suckerpunch","playrough","uturn","knockoff"],
tier: "LC"
},
liepard: {
randomBattleMoves: ["encore","thunderwave","substitute","knockoff","playrough","uturn","suckerpunch"],
randomDoubleBattleMoves: ["encore","thunderwave","substitute","knockoff","playrough","uturn","suckerpunch","fakeout","protect"],
eventPokemon: [
{"generation":5,"level":20,"gender":"F","nature":"Jolly","isHidden":true,"moves":["fakeout","foulplay","encore","swagger"]}
],
tier: "NU"
},
pansage: {
randomBattleMoves: ["leafstorm","hiddenpowerfire","hiddenpowerice","gigadrain","nastyplot","substitute","leechseed"],
eventPokemon: [
{"generation":5,"level":1,"gender":"M","nature":"Brave","isHidden":false,"moves":["bulletseed","bite","solarbeam","dig"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["leer","lick","vinewhip","leafstorm"]},
{"generation":5,"level":30,"gender":"M","nature":"Serious","isHidden":false,"moves":["seedbomb","solarbeam","rocktomb","dig"],"pokeball":"cherishball"}
],
tier: "LC"
},
simisage: {
randomBattleMoves: ["nastyplot","leafstorm","hiddenpowerfire","hiddenpowerice","gigadrain","focusblast","substitute","leechseed","synthesis"],
randomDoubleBattleMoves: ["nastyplot","leafstorm","hiddenpowerfire","hiddenpowerice","gigadrain","focusblast","substitute","taunt","synthesis","helpinghand","protect"],
tier: "PU"
},
pansear: {
randomBattleMoves: ["nastyplot","fireblast","hiddenpowerelectric","hiddenpowerground","sunnyday","solarbeam","overheat"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["leer","lick","incinerate","heatwave"]}
],
tier: "LC"
},
simisear: {
randomBattleMoves: ["nastyplot","fireblast","focusblast","grassknot","hiddenpowerground","substitute","flamethrower","overheat"],
randomDoubleBattleMoves: ["nastyplot","fireblast","focusblast","grassknot","hiddenpowerground","substitute","heatwave","taunt","protect"],
tier: "PU"
},
panpour: {
randomBattleMoves: ["nastyplot","hydropump","hiddenpowergrass","substitute","surf","icebeam"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["leer","lick","watergun","hydropump"]}
],
tier: "LC"
},
simipour: {
randomBattleMoves: ["nastyplot","hydropump","icebeam","substitute","grassknot","surf"],
randomDoubleBattleMoves: ["nastyplot","hydropump","icebeam","substitute","grassknot","surf","taunt","helpinghand","protect"],
tier: "PU"
},
munna: {
randomBattleMoves: ["psychic","hiddenpowerfighting","hypnosis","calmmind","moonlight","thunderwave","batonpass","psyshock","healbell","signalbeam"],
tier: "LC"
},
musharna: {
randomBattleMoves: ["calmmind","thunderwave","moonlight","psychic","hiddenpowerfighting","batonpass","psyshock","healbell","signalbeam"],
randomDoubleBattleMoves: ["trickroom","thunderwave","moonlight","psychic","hiddenpowerfighting","helpinghand","psyshock","healbell","signalbeam","protect"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":true,"moves":["defensecurl","luckychant","psybeam","hypnosis"]}
],
tier: "NU"
},
pidove: {
randomBattleMoves: ["pluck","uturn","return","detect","roost","wish"],
eventPokemon: [
{"generation":5,"level":1,"gender":"F","nature":"Hardy","isHidden":false,"abilities":["superluck"],"moves":["gust","quickattack","aircutter"]}
],
tier: "LC"
},
tranquill: {
randomBattleMoves: ["pluck","uturn","return","detect","roost","wish"],
tier: "NFE"
},
unfezant: {
randomBattleMoves: ["pluck","uturn","return","detect","roost","wish"],
randomDoubleBattleMoves: ["pluck","uturn","return","protect","tailwind","taunt","wish"],
tier: "PU"
},
blitzle: {
randomBattleMoves: ["voltswitch","hiddenpowergrass","wildcharge","mefirst"],
tier: "LC"
},
zebstrika: {
randomBattleMoves: ["voltswitch","hiddenpowergrass","overheat","wildcharge","thunderbolt"],
randomDoubleBattleMoves: ["voltswitch","hiddenpowergrass","overheat","wildcharge","protect"],
tier: "PU"
},
roggenrola: {
randomBattleMoves: ["autotomize","stoneedge","stealthrock","rockblast","earthquake","explosion"],
tier: "LC"
},
boldore: {
randomBattleMoves: ["autotomize","stoneedge","stealthrock","rockblast","earthquake","explosion"],
tier: "NFE"
},
gigalith: {
randomBattleMoves: ["stealthrock","rockblast","earthquake","explosion","stoneedge","autotomize","superpower"],
randomDoubleBattleMoves: ["stealthrock","rockslide","earthquake","explosion","stoneedge","autotomize","superpower","wideguard","protect"],
tier: "PU"
},
woobat: {
randomBattleMoves: ["calmmind","psychic","airslash","gigadrain","roost","heatwave","storedpower"],
tier: "LC"
},
swoobat: {
randomBattleMoves: ["calmmind","psychic","airslash","gigadrain","roost","heatwave","storedpower"],
randomDoubleBattleMoves: ["calmmind","psychic","airslash","gigadrain","protect","heatwave","tailwind"],
tier: "PU"
},
drilbur: {
randomBattleMoves: ["swordsdance","rapidspin","earthquake","rockslide","shadowclaw","return","xscissor"],
tier: "LC"
},
excadrill: {
randomBattleMoves: ["swordsdance","rapidspin","earthquake","rockslide","ironhead"],
randomDoubleBattleMoves: ["swordsdance","drillrun","earthquake","rockslide","ironhead","substitute","protect"],
tier: "OU"
},
audino: {
randomBattleMoves: ["wish","protect","healbell","toxic","thunderwave","reflect","lightscreen","return"],
randomDoubleBattleMoves: ["healpulse","protect","healbell","trickroom","thunderwave","reflect","lightscreen","return","helpinghand"],
eventPokemon: [
{"generation":5,"level":30,"gender":"F","nature":"Calm","isHidden":false,"abilities":["healer"],"moves":["healpulse","helpinghand","refresh","doubleslap"],"pokeball":"cherishball"},
{"generation":5,"level":30,"gender":"F","nature":"Serious","isHidden":false,"abilities":["healer"],"moves":["healpulse","helpinghand","refresh","present"],"pokeball":"cherishball"}
],
tier: "NU"
},
audinomega: {
randomBattleMoves: ["wish","protect","healbell","toxic","thunderwave","reflect","lightscreen","return"],
randomDoubleBattleMoves: ["healpulse","protect","healbell","trickroom","thunderwave","reflect","lightscreen","hypervoice","helpinghand","dazzlinggleam"],
requiredItem: "Audinite"
},
timburr: {
randomBattleMoves: ["machpunch","bulkup","drainpunch","icepunch","knockoff"],
tier: "LC"
},
gurdurr: {
randomBattleMoves: ["bulkup","machpunch","drainpunch","icepunch","knockoff"],
tier: "NU"
},
conkeldurr: {
randomBattleMoves: ["bulkup","machpunch","drainpunch","icepunch","knockoff"],
randomDoubleBattleMoves: ["wideguard","machpunch","drainpunch","icepunch","knockoff","protect"],
tier: "OU"
},
tympole: {
randomBattleMoves: ["hydropump","surf","sludgewave","earthpower","hiddenpowerelectric"],
tier: "LC"
},
palpitoad: {
randomBattleMoves: ["hydropump","surf","sludgewave","earthpower","hiddenpowerelectric","stealthrock"],
tier: "NFE"
},
seismitoad: {
randomBattleMoves: ["hydropump","surf","sludgewave","earthpower","hiddenpowerelectric","stealthrock"],
randomDoubleBattleMoves: ["hydropump","muddywater","sludgebomb","earthpower","hiddenpowerelectric","icywind","protect"],
tier: "NU"
},
throh: {
randomBattleMoves: ["bulkup","circlethrow","icepunch","stormthrow","rest","sleeptalk","knockoff"],
randomDoubleBattleMoves: ["helpinghand","circlethrow","icepunch","stormthrow","wideguard","knockoff","protect"],
tier: "PU"
},
sawk: {
randomBattleMoves: ["closecombat","earthquake","icepunch","stoneedge","bulkup","knockoff"],
randomDoubleBattleMoves: ["closecombat","knockoff","icepunch","rockslide","protect"],
tier: "NU"
},
sewaddle: {
randomBattleMoves: ["calmmind","gigadrain","bugbuzz","hiddenpowerfire","hiddenpowerice","airslash"],
tier: "LC"
},
swadloon: {
randomBattleMoves: ["calmmind","gigadrain","bugbuzz","hiddenpowerfire","hiddenpowerice","airslash","stickyweb"],
tier: "NFE"
},
leavanny: {
randomBattleMoves: ["swordsdance","leafblade","xscissor","batonpass","stickyweb","poisonjab"],
randomDoubleBattleMoves: ["swordsdance","leafblade","xscissor","protect","stickyweb","poisonjab"],
tier: "PU"
},
venipede: {
randomBattleMoves: ["toxicspikes","steamroller","spikes","poisonjab"],
tier: "LC"
},
whirlipede: {
randomBattleMoves: ["toxicspikes","steamroller","spikes","poisonjab"],
tier: "NFE"
},
scolipede: {
randomBattleMoves: ["spikes","toxicspikes","megahorn","rockslide","earthquake","swordsdance","batonpass","aquatail","superpower"],
randomDoubleBattleMoves: ["substitute","protect","megahorn","rockslide","poisonjab","swordsdance","batonpass","aquatail","superpower"],
tier: "BL"
},
cottonee: {
randomBattleMoves: ["encore","taunt","substitute","leechseed","toxic","stunspore"],
tier: "LC"
},
whimsicott: {
randomBattleMoves: ["encore","taunt","substitute","leechseed","uturn","toxic","stunspore","memento","tailwind","moonblast"],
randomDoubleBattleMoves: ["encore","taunt","substitute","leechseed","uturn","helpinghand","stunspore","moonblast","tailwind","dazzlinggleam","gigadrain","protect"],
eventPokemon: [
{"generation":5,"level":50,"gender":"F","nature":"Timid","isHidden":false,"abilities":["prankster"],"moves":["swagger","gigadrain","beatup","helpinghand"],"pokeball":"cherishball"}
],
tier: "RU"
},
petilil: {
randomBattleMoves: ["sunnyday","sleeppowder","solarbeam","hiddenpowerfire","hiddenpowerice","healingwish"],
tier: "LC"
},
lilligant: {
randomBattleMoves: ["quiverdance","gigadrain","sleeppowder","hiddenpowerice","hiddenpowerfire","hiddenpowerrock","petaldance"],
randomDoubleBattleMoves: ["quiverdance","gigadrain","sleeppowder","hiddenpowerice","hiddenpowerfire","hiddenpowerrock","petaldance","helpinghand","protect"],
tier: "NU"
},
basculin: {
randomBattleMoves: ["waterfall","aquajet","superpower","crunch","doubleedge"],
randomDoubleBattleMoves: ["waterfall","aquajet","superpower","crunch","doubleedge","protect"],
tier: "PU"
},
basculinbluestriped: {
randomBattleMoves: ["waterfall","aquajet","superpower","crunch","doubleedge"],
randomDoubleBattleMoves: ["waterfall","aquajet","superpower","crunch","doubleedge","protect"],
tier: "PU"
},
sandile: {
randomBattleMoves: ["earthquake","stoneedge","pursuit","crunch"],
tier: "LC"
},
krokorok: {
randomBattleMoves: ["earthquake","stoneedge","pursuit","crunch"],
tier: "NFE"
},
krookodile: {
randomBattleMoves: ["earthquake","stoneedge","pursuit","knockoff","bulkup","superpower"],
randomDoubleBattleMoves: ["earthquake","stoneedge","protect","knockoff","bulkup","superpower"],
tier: "UU"
},
darumaka: {
randomBattleMoves: ["uturn","flareblitz","firepunch","rockslide","superpower"],
tier: "LC"
},
darmanitan: {
randomBattleMoves: ["uturn","flareblitz","firepunch","rockslide","earthquake","superpower"],
randomDoubleBattleMoves: ["uturn","flareblitz","firepunch","rockslide","earthquake","superpower","protect"],
eventPokemon: [
{"generation":5,"level":35,"isHidden":true,"moves":["thrash","bellydrum","flareblitz","hammerarm"]}
],
tier: "UU"
},
maractus: {
randomBattleMoves: ["spikes","gigadrain","leechseed","hiddenpowerfire","toxic","suckerpunch","spikyshield"],
randomDoubleBattleMoves: ["grassyterrain","gigadrain","leechseed","hiddenpowerfire","helpinghand","suckerpunch","spikyshield"],
tier: "PU"
},
dwebble: {
randomBattleMoves: ["stealthrock","spikes","shellsmash","earthquake","rockblast","xscissor","stoneedge"],
tier: "LC"
},
crustle: {
randomBattleMoves: ["stealthrock","spikes","shellsmash","earthquake","rockblast","xscissor","stoneedge"],
randomDoubleBattleMoves: ["protect","shellsmash","earthquake","rockslide","xscissor","stoneedge"],
tier: "NU"
},
scraggy: {
randomBattleMoves: ["dragondance","icepunch","highjumpkick","drainpunch","rest","bulkup","crunch","knockoff"],
eventPokemon: [
{"generation":5,"level":1,"gender":"M","nature":"Adamant","isHidden":false,"abilities":["moxie"],"moves":["headbutt","leer","highjumpkick","lowkick"],"pokeball":"cherishball"}
],
tier: "LC"
},
scrafty: {
randomBattleMoves: ["dragondance","icepunch","highjumpkick","drainpunch","rest","bulkup","knockoff"],
randomDoubleBattleMoves: ["fakeout","drainpunch","knockoff","icepunch","stoneedge", "protect"],
eventPokemon: [
{"generation":5,"level":50,"gender":"M","nature":"Brave","isHidden":false,"abilities":["moxie"],"moves":["firepunch","payback","drainpunch","substitute"],"pokeball":"cherishball"}
],
tier: "UU"
},
sigilyph: {
randomBattleMoves: ["cosmicpower","roost","storedpower","psychoshift"],
randomDoubleBattleMoves: ["psyshock","heatwave","icebeam","airslash","energyball","shadowball","tailwind","protect"],
tier: "BL3"
},
yamask: {
randomBattleMoves: ["nastyplot","trickroom","shadowball","hiddenpowerfighting","willowisp","haze","rest","sleeptalk","painsplit"],
tier: "LC"
},
cofagrigus: {
randomBattleMoves: ["nastyplot","trickroom","shadowball","hiddenpowerfighting","willowisp","haze","rest","sleeptalk","painsplit"],
randomDoubleBattleMoves: ["nastyplot","trickroom","shadowball","hiddenpowerfighting","willowisp","protect","painsplit"],
tier: "RU"
},
tirtouga: {
randomBattleMoves: ["shellsmash","aquajet","waterfall","stoneedge","earthquake","stealthrock"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"abilities":["sturdy"],"moves":["bite","protect","aquajet","bodyslam"],"pokeball":"cherishball"}
],
tier: "LC"
},
carracosta: {
randomBattleMoves: ["shellsmash","aquajet","waterfall","stoneedge","earthquake","stealthrock"],
randomDoubleBattleMoves: ["shellsmash","aquajet","waterfall","stoneedge","earthquake","protect","wideguard","rockslide"],
tier: "PU"
},
archen: {
randomBattleMoves: ["stoneedge","rockslide","earthquake","uturn","pluck","headsmash"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","moves":["headsmash","wingattack","doubleteam","scaryface"],"pokeball":"cherishball"}
],
tier: "LC"
},
archeops: {
randomBattleMoves: ["stoneedge","rockslide","earthquake","uturn","pluck","headsmash"],
randomDoubleBattleMoves: ["stoneedge","rockslide","earthquake","uturn","pluck","tailwind","taunt","protect"],
tier: "NU"
},
trubbish: {
randomBattleMoves: ["clearsmog","toxicspikes","spikes","gunkshot","painsplit","toxic"],
tier: "LC"
},
garbodor: {
randomBattleMoves: ["spikes","toxicspikes","gunkshot","haze","painsplit","toxic","rockblast"],
randomDoubleBattleMoves: ["protect","painsplit","gunkshot","seedbomb","drainpunch","explosion","rockblast"],
tier: "NU"
},
zorua: {
randomBattleMoves: ["suckerpunch","extrasensory","darkpulse","hiddenpowerfighting","uturn","knockoff"],
tier: "LC"
},
zoroark: {
randomBattleMoves: ["suckerpunch","darkpulse","focusblast","flamethrower","uturn","nastyplot","knockoff"],
randomDoubleBattleMoves: ["suckerpunch","darkpulse","focusblast","flamethrower","uturn","nastyplot","knockoff","protect"],
eventPokemon: [
{"generation":5,"level":50,"gender":"M","nature":"Quirky","moves":["agility","embargo","punishment","snarl"],"pokeball":"cherishball"}
],
tier: "BL2"
},
minccino: {
randomBattleMoves: ["return","tailslap","wakeupslap","uturn","aquatail"],
tier: "LC"
},
cinccino: {
randomBattleMoves: ["return","tailslap","wakeupslap","uturn","aquatail","bulletseed","rockblast"],
randomDoubleBattleMoves: ["return","tailslap","wakeupslap","uturn","aquatail","bulletseed","rockblast","protect"],
tier: "RU"
},
gothita: {
randomBattleMoves: ["psychic","thunderbolt","hiddenpowerfighting","shadowball","substitute","calmmind","reflect","lightscreen","trick","grassknot","signalbeam"],
tier: "LC"
},
gothorita: {
randomBattleMoves: ["psychic","thunderbolt","hiddenpowerfighting","shadowball","substitute","calmmind","reflect","lightscreen","trick","grassknot","signalbeam"],
eventPokemon: [
{"generation":5,"level":32,"gender":"M","isHidden":true,"moves":["psyshock","flatter","futuresight","mirrorcoat"]},
{"generation":5,"level":32,"gender":"M","isHidden":true,"moves":["psyshock","flatter","futuresight","imprison"]}
],
tier: "NFE"
},
gothitelle: {
randomBattleMoves: ["psychic","thunderbolt","hiddenpowerfighting","shadowball","substitute","calmmind","reflect","lightscreen","trick","psyshock","grassknot","signalbeam"],
randomDoubleBattleMoves: ["psychic","thunderbolt","hiddenpowerfighting","shadowball","calmmind","reflect","lightscreen","trick","psyshock","grassknot","signalbeam","trickroom","taunt","helpinghand","healpulse","protect"],
tier: "OU"
},
solosis: {
randomBattleMoves: ["calmmind","recover","psychic","hiddenpowerfighting","shadowball","trickroom","psyshock"],
tier: "LC"
},
duosion: {
randomBattleMoves: ["calmmind","recover","psychic","hiddenpowerfighting","shadowball","trickroom","psyshock"],
tier: "NFE"
},
reuniclus: {
randomBattleMoves: ["calmmind","recover","psychic","focusblast","shadowball","trickroom","psyshock","hiddenpowerfire"],
randomDoubleBattleMoves: ["calmmind","recover","psychic","focusblast","shadowball","trickroom","psyshock","hiddenpowerfire","protect"],
tier: "RU"
},
ducklett: {
randomBattleMoves: ["scald","airslash","roost","hurricane","icebeam","hiddenpowergrass","bravebird","defog"],
tier: "LC"
},
swanna: {
randomBattleMoves: ["airslash","roost","hurricane","surf","icebeam","raindance","defog","scald"],
randomDoubleBattleMoves: ["airslash","roost","hurricane","surf","icebeam","raindance","tailwind","scald","protect"],
tier: "PU"
},
vanillite: {
randomBattleMoves: ["icebeam","explosion","hiddenpowerelectric","hiddenpowerfighting","autotomize"],
tier: "LC"
},
vanillish: {
randomBattleMoves: ["icebeam","explosion","hiddenpowerelectric","hiddenpowerfighting","autotomize"],
tier: "NFE"
},
vanilluxe: {
randomBattleMoves: ["icebeam","explosion","hiddenpowerelectric","hiddenpowerfighting","autotomize"],
randomDoubleBattleMoves: ["icebeam","taunt","hiddenpowerelectric","hiddenpowerfighting","autotomize","protect","freezedry"],
tier: "PU"
},
deerling: {
randomBattleMoves: ["agility","batonpass","seedbomb","jumpkick","synthesis","return","thunderwave"],
eventPokemon: [
{"generation":5,"level":30,"gender":"F","isHidden":true,"moves":["feintattack","takedown","jumpkick","aromatherapy"]}
],
tier: "LC"
},
sawsbuck: {
randomBattleMoves: ["swordsdance","hornleech","jumpkick","return","substitute","synthesis","batonpass"],
randomDoubleBattleMoves: ["swordsdance","hornleech","jumpkick","return","substitute","synthesis","protect"],
tier: "PU"
},
emolga: {
randomBattleMoves: ["agility","chargebeam","batonpass","substitute","thunderbolt","airslash","roost"],
randomDoubleBattleMoves: ["helpinghand","tailwind","encore","substitute","thunderbolt","airslash","roost","protect"],
tier: "PU"
},
karrablast: {
randomBattleMoves: ["swordsdance","megahorn","return","substitute"],
eventPokemon: [
{"generation":5,"level":30,"isHidden":false,"moves":["furyattack","headbutt","falseswipe","bugbuzz"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["megahorn","takedown","xscissor","flail"],"pokeball":"cherishball"}
],
tier: "LC"
},
escavalier: {
randomBattleMoves: ["megahorn","pursuit","ironhead","knockoff","swordsdance","drillrun"],
randomDoubleBattleMoves: ["megahorn","protect","ironhead","knockoff","swordsdance","drillrun"],
tier: "RU"
},
foongus: {
randomBattleMoves: ["spore","stunspore","gigadrain","clearsmog","hiddenpowerfire","synthesis","sludgebomb"],
tier: "LC"
},
amoonguss: {
randomBattleMoves: ["spore","stunspore","gigadrain","clearsmog","hiddenpowerfire","synthesis","sludgebomb"],
randomDoubleBattleMoves: ["spore","stunspore","gigadrain","ragepowder","hiddenpowerfire","synthesis","sludgebomb","protect"],
tier: "RU"
},
frillish: {
randomBattleMoves: ["scald","willowisp","recover","toxic","shadowball","taunt"],
tier: "LC"
},
jellicent: {
randomBattleMoves: ["scald","willowisp","recover","toxic","shadowball","icebeam","gigadrain","taunt"],
randomDoubleBattleMoves: ["scald","willowisp","recover","trickroom","shadowball","icebeam","gigadrain","waterspout","icywind","protect"],
eventPokemon: [
{"generation":5,"level":40,"isHidden":true,"moves":["waterpulse","ominouswind","brine","raindance"]}
],
tier: "RU"
},
alomomola: {
randomBattleMoves: ["wish","protect","waterfall","toxic","scald"],
randomDoubleBattleMoves: ["wish","protect","waterfall","icywind","scald","helpinghand","wideguard"],
tier: "RU"
},
joltik: {
randomBattleMoves: ["thunderbolt","bugbuzz","hiddenpowerice","gigadrain","voltswitch","stickyweb"],
tier: "LC"
},
galvantula: {
randomBattleMoves: ["thunder","hiddenpowerice","gigadrain","bugbuzz","voltswitch","stickyweb"],
randomDoubleBattleMoves: ["thunder","hiddenpowerice","gigadrain","bugbuzz","voltswitch","stickyweb",'protect'],
tier: "UU"
},
ferroseed: {
randomBattleMoves: ["spikes","stealthrock","leechseed","seedbomb","protect","thunderwave","gyroball"],
tier: "NU"
},
ferrothorn: {
randomBattleMoves: ["spikes","stealthrock","leechseed","powerwhip","thunderwave","protect","knockoff","gyroball"],
randomDoubleBattleMoves: ["gyroball","stealthrock","leechseed","powerwhip","thunderwave","protect"],
tier: "OU"
},
klink: {
randomBattleMoves: ["shiftgear","return","geargrind","wildcharge","substitute"],
tier: "LC"
},
klang: {
randomBattleMoves: ["shiftgear","return","geargrind","wildcharge","substitute"],
tier: "NFE"
},
klinklang: {
randomBattleMoves: ["shiftgear","return","geargrind","wildcharge","substitute"],
randomDoubleBattleMoves: ["shiftgear","return","geargrind","wildcharge","protect"],
tier: "NU"
},
tynamo: {
randomBattleMoves: ["spark","chargebeam","thunderwave","tackle"],
tier: "LC"
},
eelektrik: {
randomBattleMoves: ["uturn","voltswitch","acidspray","wildcharge","thunderbolt","gigadrain","aquatail","coil"],
tier: "NFE"
},
eelektross: {
randomBattleMoves: ["thunderbolt","flamethrower","uturn","voltswitch","acidspray","wildcharge","drainpunch","superpower","gigadrain","aquatail","coil"],
randomDoubleBattleMoves: ["thunderbolt","flamethrower","uturn","voltswitch","thunderwave","wildcharge","drainpunch","superpower","gigadrain","aquatail","protect"],
tier: "RU"
},
elgyem: {
randomBattleMoves: ["nastyplot","psychic","thunderbolt","hiddenpowerfighting","substitute","calmmind","recover","trick", "trickroom", "signalbeam"],
tier: "LC"
},
beheeyem: {
randomBattleMoves: ["nastyplot","psychic","psyshock","thunderbolt","hiddenpowerfighting","substitute","calmmind","recover","trick","trickroom", "signalbeam"],
randomDoubleBattleMoves: ["nastyplot","psychic","thunderbolt","hiddenpowerfighting","recover","trick","trickroom", "signalbeam","protect"],
tier: "PU"
},
litwick: {
randomBattleMoves: ["calmmind","shadowball","energyball","fireblast","overheat","hiddenpowerfighting","hiddenpowerground","hiddenpowerrock","trick","substitute", "painsplit"],
tier: "LC"
},
lampent: {
randomBattleMoves: ["calmmind","shadowball","energyball","fireblast","overheat","hiddenpowerfighting","hiddenpowerground","hiddenpowerrock","trick","substitute", "painsplit"],
tier: "NFE"
},
chandelure: {
randomBattleMoves: ["shadowball","energyball","fireblast","overheat","hiddenpowerfighting","hiddenpowerground","trick","substitute","painsplit"],
randomDoubleBattleMoves: ["shadowball","energyball","fireblast","heatwave","hiddenpowerfighting","hiddenpowerground","trick","substitute","protect"],
eventPokemon: [
{"generation":5,"level":50,"gender":"F","nature":"Modest","isHidden":false,"abilities":["flashfire"],"moves":["heatwave","shadowball","energyball","psychic"],"pokeball":"cherishball"}
],
tier: "UU"
},
axew: {
randomBattleMoves: ["dragondance","outrage","dragonclaw","swordsdance","aquatail","superpower","poisonjab","taunt", "substitute"],
eventPokemon: [
{"generation":5,"level":1,"gender":"M","nature":"Naive","isHidden":false,"abilities":["moldbreaker"],"moves":["scratch","dragonrage"]},
{"generation":5,"level":10,"gender":"F","isHidden":false,"abilities":["moldbreaker"],"moves":["dragonrage","return","endure","dragonclaw"],"pokeball":"cherishball"},
{"generation":5,"level":30,"gender":"M","nature":"Naive","isHidden":false,"abilities":["rivalry"],"moves":["dragonrage","scratch","outrage","gigaimpact"],"pokeball":"cherishball"}
],
tier: "LC"
},
fraxure: {
randomBattleMoves: ["dragondance","swordsdance","outrage","dragonclaw","aquatail","superpower","poisonjab","taunt", "substitute"],
tier: "NFE"
},
haxorus: {
randomBattleMoves: ["dragondance","swordsdance","outrage","dragonclaw","earthquake","lowkick","poisonjab","taunt", "substitute"],
randomDoubleBattleMoves: ["dragondance","swordsdance","protect","dragonclaw","earthquake","lowkick","poisonjab","taunt", "substitute"],
eventPokemon: [
{"generation":5,"level":59,"gender":"F","nature":"Naive","isHidden":false,"abilities":["moldbreaker"],"moves":["earthquake","dualchop","xscissor","dragondance"],"pokeball":"cherishball"}
],
tier: "UU"
},
cubchoo: {
randomBattleMoves: ["icebeam","surf","hiddenpowergrass","superpower"],
eventPokemon: [
{"generation":5,"level":15,"isHidden":false,"moves":["powdersnow","growl","bide","icywind"],"pokeball":"cherishball"}
],
tier: "LC"
},
beartic: {
randomBattleMoves: ["iciclecrash","superpower","nightslash","stoneedge","swordsdance","aquajet"],
randomDoubleBattleMoves: ["iciclecrash","superpower","nightslash","stoneedge","swordsdance","aquajet","protect"],
tier: "PU"
},
cryogonal: {
randomBattleMoves: ["icebeam","recover","toxic","rapidspin","reflect","freezedry","hiddenpowerfire"],
randomDoubleBattleMoves: ["icebeam","recover","icywind","protect","reflect","freezedry","hiddenpowerfire"],
tier: "NU"
},
shelmet: {
randomBattleMoves: ["spikes","yawn","substitute","acidarmor","batonpass","recover","toxic","bugbuzz","infestation"],
eventPokemon: [
{"generation":5,"level":30,"isHidden":false,"moves":["strugglebug","megadrain","yawn","protect"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["encore","gigadrain","bodyslam","bugbuzz"],"pokeball":"cherishball"}
],
tier: "LC"
},
accelgor: {
randomBattleMoves: ["spikes","yawn","bugbuzz","focusblast","gigadrain","hiddenpowerrock","encore","sludgebomb"],
randomDoubleBattleMoves: ["protect","yawn","bugbuzz","focusblast","gigadrain","hiddenpowerrock","encore","sludgebomb"],
tier: "RU"
},
stunfisk: {
randomBattleMoves: ["discharge","thunderbolt","earthpower","scald","toxic","rest","sleeptalk","stealthrock"],
randomDoubleBattleMoves: ["discharge","thunderbolt","earthpower","scald","electroweb","protect","stealthrock"],
tier: "PU"
},
mienfoo: {
randomBattleMoves: ["uturn","drainpunch","stoneedge","swordsdance","batonpass","highjumpkick","fakeout","knockoff"],
tier: "LC"
},
mienshao: {
randomBattleMoves: ["uturn","fakeout","highjumpkick","stoneedge","drainpunch","swordsdance","batonpass","knockoff"],
randomDoubleBattleMoves: ["uturn","fakeout","highjumpkick","stoneedge","drainpunch","swordsdance","wideguard","knockoff","feint","protect"],
tier: "UU"
},
druddigon: {
randomBattleMoves: ["outrage","superpower","earthquake","suckerpunch","dragonclaw","dragontail","substitute","glare","stealthrock","firepunch","thunderpunch"],
randomDoubleBattleMoves: ["superpower","earthquake","suckerpunch","dragonclaw","glare","protect","firepunch","thunderpunch"],
eventPokemon: [
{"generation":5,"level":1,"shiny":true,"isHidden":false,"moves":["leer","scratch"]}
],
tier: "RU"
},
golett: {
randomBattleMoves: ["earthquake","shadowpunch","dynamicpunch","icepunch","stealthrock","rockpolish"],
tier: "LC"
},
golurk: {
randomBattleMoves: ["earthquake","shadowpunch","dynamicpunch","icepunch","stoneedge","stealthrock","rockpolish"],
randomDoubleBattleMoves: ["earthquake","shadowpunch","dynamicpunch","icepunch","stoneedge","protect","rockpolish"],
eventPokemon: [
{"generation":5,"level":70,"shiny":true,"isHidden":false,"abilities":["ironfist"],"moves":["shadowpunch","hyperbeam","gyroball","hammerarm"],"pokeball":"cherishball"}
],
tier: "NU"
},
pawniard: {
randomBattleMoves: ["swordsdance","substitute","suckerpunch","ironhead","brickbreak","knockoff"],
tier: "PU"
},
bisharp: {
randomBattleMoves: ["swordsdance","substitute","suckerpunch","ironhead","brickbreak","knockoff"],
randomDoubleBattleMoves: ["swordsdance","substitute","suckerpunch","ironhead","brickbreak","knockoff","protect"],
tier: "OU"
},
bouffalant: {
randomBattleMoves: ["headcharge","earthquake","stoneedge","megahorn","swordsdance","superpower"],
randomDoubleBattleMoves: ["headcharge","earthquake","stoneedge","megahorn","swordsdance","superpower","protect"],
tier: "NU"
},
rufflet: {
randomBattleMoves: ["bravebird","rockslide","return","uturn","substitute","bulkup","roost"],
tier: "LC"
},
braviary: {
randomBattleMoves: ["bravebird","superpower","return","uturn","substitute","rockslide","bulkup","roost"],
randomDoubleBattleMoves: ["bravebird","superpower","return","uturn","tailwind","rockslide","bulkup","roost","skydrop","protect"],
eventPokemon: [
{"generation":5,"level":25,"gender":"M","isHidden":true,"moves":["wingattack","honeclaws","scaryface","aerialace"]}
],
tier: "RU"
},
vullaby: {
randomBattleMoves: ["knockoff","roost","taunt","whirlwind","toxic","defog","uturn","bravebird"],
tier: "LC"
},
mandibuzz: {
randomBattleMoves: ["knockoff","roost","taunt","whirlwind","toxic","uturn","bravebird","defog"],
randomDoubleBattleMoves: ["knockoff","roost","taunt","tailwind","snarl","uturn","bravebird","protect"],
eventPokemon: [
{"generation":5,"level":25,"gender":"F","isHidden":true,"moves":["pluck","nastyplot","flatter","feintattack"]}
],
tier: "OU"
},
heatmor: {
randomBattleMoves: ["fireblast","suckerpunch","focusblast","gigadrain"],
randomDoubleBattleMoves: ["fireblast","suckerpunch","focusblast","gigadrain","heatwave","protect"],
tier: "PU"
},
durant: {
randomBattleMoves: ["honeclaws","ironhead","xscissor","stoneedge","batonpass","superpower"],
randomDoubleBattleMoves: ["honeclaws","ironhead","xscissor","rockslide","protect","superpower"],
tier: "RU"
},
deino: {
randomBattleMoves: ["outrage","crunch","firefang","dragontail","thunderwave","superpower"],
eventPokemon: [
{"generation":5,"level":1,"shiny":true,"moves":["tackle","dragonrage"]}
],
tier: "LC"
},
zweilous: {
randomBattleMoves: ["outrage","crunch","firefang","dragontail","thunderwave","superpower"],
tier: "NFE"
},
hydreigon: {
randomBattleMoves: ["uturn","dracometeor","dragonpulse","earthpower","fireblast","darkpulse","roost","flashcannon","superpower"],
randomDoubleBattleMoves: ["uturn","dracometeor","dragonpulse","earthpower","fireblast","darkpulse","roost","flashcannon","superpower","tailwind","protect"],
eventPokemon: [
{"generation":5,"level":70,"shiny":true,"gender":"M","moves":["hypervoice","dragonbreath","flamethrower","focusblast"],"pokeball":"cherishball"}
],
tier: "UU"
},
larvesta: {
randomBattleMoves: ["flareblitz","uturn","wildcharge","zenheadbutt","morningsun","willowisp"],
tier: "LC"
},
volcarona: {
randomBattleMoves: ["quiverdance","fierydance","fireblast","bugbuzz","roost","gigadrain","hiddenpowerice"],
randomDoubleBattleMoves: ["quiverdance","fierydance","fireblast","bugbuzz","roost","gigadrain","hiddenpowerice","heatwave","willowisp","ragepowder","tailwind","protect"],
eventPokemon: [
{"generation":5,"level":35,"isHidden":false,"moves":["stringshot","leechlife","gust","firespin"]},
{"generation":5,"level":77,"gender":"M","nature":"Calm","isHidden":false,"moves":["bugbuzz","overheat","hyperbeam","quiverdance"],"pokeball":"cherishball"}
],
tier: "BL"
},
cobalion: {
randomBattleMoves: ["closecombat","ironhead","swordsdance","substitute","stoneedge","voltswitch","hiddenpowerice","thunderwave","stealthrock"],
randomDoubleBattleMoves: ["closecombat","ironhead","swordsdance","substitute","stoneedge","voltswitch","hiddenpowerice","thunderwave","protect","helpinghand"],
tier: "RU"
},
terrakion: {
randomBattleMoves: ["stoneedge","closecombat","swordsdance","rockpolish","substitute","stealthrock","earthquake"],
randomDoubleBattleMoves: ["stoneedge","closecombat","substitute","rockslide","earthquake","protect"],
tier: "UU"
},
virizion: {
randomBattleMoves: ["swordsdance","calmmind","closecombat","focusblast","hiddenpowerice","stoneedge","leafblade","gigadrain","substitute","synthesis"],
randomDoubleBattleMoves: ["taunt","closecombat","focusblast","hiddenpowerice","stoneedge","leafblade","gigadrain","substitute","synthesis","protect","helpinghand"],
tier: "NU"
},
tornadus: {
randomBattleMoves: ["hurricane","airslash","uturn","superpower","focusblast","taunt","substitute","heatwave","tailwind"],
randomDoubleBattleMoves: ["hurricane","airslash","uturn","superpower","focusblast","taunt","substitute","heatwave","tailwind","protect","skydrop"],
eventPokemon: [
{"generation":5,"level":70,"gender":"M","isHidden":false,"moves":["hurricane","hammerarm","airslash","hiddenpower"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'dreamball',
tier: "BL2"
},
tornadustherian: {
randomBattleMoves: ["hurricane","airslash","focusblast","uturn","heatwave","knockoff"],
randomDoubleBattleMoves: ["hurricane","airslash","focusblast","uturn","heatwave","skydrop","tailwind","taunt","protect"],
eventPokemon: [
{"generation":5,"level":70,"gender":"M","isHidden":false,"moves":["hurricane","hammerarm","airslash","hiddenpower"],"pokeball":"cherishball"}
],
tier: "BL"
},
thundurus: {
randomBattleMoves: ["thunderwave","nastyplot","thunderbolt","hiddenpowerice","focusblast","grassknot","substitute"],
randomDoubleBattleMoves: ["thunderwave","nastyplot","thunderbolt","hiddenpowerice","focusblast","grassknot","substitute","taunt","protect"],
eventPokemon: [
{"generation":5,"level":70,"gender":"M","isHidden":false,"moves":["thunder","hammerarm","focusblast","wildcharge"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'dreamball',
tier: "OU"
},
thundurustherian: {
randomBattleMoves: ["nastyplot","agility","thunderbolt","hiddenpowerice","focusblast","grassknot","superpower"],
randomDoubleBattleMoves: ["nastyplot","agility","thunderbolt","hiddenpowerice","focusblast","grassknot","superpower","protect"],
eventPokemon: [
{"generation":5,"level":70,"gender":"M","isHidden":false,"moves":["thunder","hammerarm","focusblast","wildcharge"],"pokeball":"cherishball"}
],
tier: "BL"
},
reshiram: {
randomBattleMoves: ["blueflare","dracometeor","dragonpulse","flamethrower","flamecharge","roost"],
randomDoubleBattleMoves: ["blueflare","dracometeor","dragonpulse","heatwave","flamecharge","roost","protect","tailwind"],
eventPokemon: [
{"generation":5,"level":100,"moves":["blueflare","fusionflare","mist","dracometeor"],"pokeball":"cherishball"}
],
tier: "Uber"
},
zekrom: {
randomBattleMoves: ["voltswitch","outrage","dragonclaw","boltstrike","honeclaws","substitute","dracometeor","fusionbolt","roost"],
randomDoubleBattleMoves: ["voltswitch","protect","dragonclaw","boltstrike","honeclaws","substitute","dracometeor","fusionbolt","roost","tailwind"],
eventPokemon: [
{"generation":5,"level":100,"moves":["boltstrike","fusionbolt","haze","outrage"],"pokeball":"cherishball"}
],
tier: "Uber"
},
landorus: {
randomBattleMoves: ["earthpower","focusblast","rockpolish","hiddenpowerice","psychic","sludgewave"],
randomDoubleBattleMoves: ["earthpower","focusblast","rockpolish","hiddenpowerice","psychic","sludgebomb","protect"],
dreamWorldPokeball: 'dreamball',
tier: "OU"
},
landorustherian: {
randomBattleMoves: ["rockpolish","earthquake","stoneedge","uturn","superpower","stealthrock","swordsdance"],
randomDoubleBattleMoves: ["rockslide","earthquake","stoneedge","uturn","superpower","knockoff","protect"],
tier: "OU"
},
kyurem: {
randomBattleMoves: ["substitute","icebeam","dracometeor","dragonpulse","focusblast","outrage","earthpower","roost"],
randomDoubleBattleMoves: ["substitute","icebeam","dracometeor","dragonpulse","focusblast","glaciate","earthpower","roost","protect"],
tier: "BL2"
},
kyuremblack: {
randomBattleMoves: ["outrage","fusionbolt","icebeam","roost","substitute","honeclaws","earthpower","dragonclaw"],
randomDoubleBattleMoves: ["protect","fusionbolt","icebeam","roost","substitute","honeclaws","earthpower","dragonclaw"],
tier: "OU"
},
kyuremwhite: {
randomBattleMoves: ["dracometeor","dragonpulse","icebeam","fusionflare","earthpower","focusblast","roost"],
randomDoubleBattleMoves: ["dracometeor","dragonpulse","icebeam","fusionflare","earthpower","focusblast","roost","protect"],
tier: "Uber"
},
keldeo: {
randomBattleMoves: ["hydropump","secretsword","calmmind","hiddenpowerghost","hiddenpowerelectric","substitute","scald","icywind"],
randomDoubleBattleMoves: ["hydropump","secretsword","protect","hiddenpowerghost","hiddenpowerelectric","substitute","surf","icywind","taunt"],
eventPokemon: [
{"generation":5,"level":15,"moves":["aquajet","leer","doublekick","bubblebeam"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["sacredsword","hydropump","aquajet","swordsdance"],"pokeball":"cherishball"},
{"generation":6,"level":15,"moves":["aquajet","leer","doublekick","hydropump"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'cherishball',
unobtainableShiny: true,
tier: "OU"
},
keldeoresolute: {},
meloetta: {
randomBattleMoves: ["relicsong","closecombat","calmmind","psychic","thunderbolt","hypervoice","uturn"],
randomDoubleBattleMoves: ["relicsong","closecombat","calmmind","psychic","thunderbolt","hypervoice","uturn","protect"],
eventPokemon: [
{"generation":5,"level":15,"moves":["quickattack","confusion","round"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["round","teeterdance","psychic","closecombat"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'cherishball',
unobtainableShiny: true,
tier: "RU"
},
genesect: {
randomBattleMoves: ["uturn","bugbuzz","icebeam","flamethrower","thunderbolt","ironhead","shiftgear","extremespeed","blazekick"],
randomDoubleBattleMoves: ["uturn","bugbuzz","icebeam","flamethrower","thunderbolt","ironhead","shiftgear","extremespeed","blazekick","protect"],
eventPokemon: [
{"generation":5,"level":50,"moves":["technoblast","magnetbomb","solarbeam","signalbeam"],"pokeball":"cherishball"},
{"generation":5,"level":15,"moves":["technoblast","magnetbomb","solarbeam","signalbeam"],"pokeball":"cherishball"},
{"generation":5,"level":100,"shiny":true,"nature":"Hasty","moves":["extremespeed","technoblast","blazekick","shiftgear"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'cherishball',
tier: "Uber"
},
genesectburn: {
randomBattleMoves: ["uturn","bugbuzz","icebeam","technoblast","thunderbolt","ironhead","shiftgear","extremespeed"],
randomDoubleBattleMoves: ["uturn","bugbuzz","icebeam","technoblast","thunderbolt","ironhead","shiftgear","extremespeed","blazekick","protect"],
dreamWorldPokeball: 'cherishball',
requiredItem: "Burn Drive"
},
genesectchill: {
randomBattleMoves: ["uturn","bugbuzz","technoblast","flamethrower","thunderbolt","ironhead","shiftgear","extremespeed","blazekick"],
randomDoubleBattleMoves: ["uturn","bugbuzz","icebeam","technoblast","thunderbolt","ironhead","shiftgear","extremespeed","blazekick","protect"],
dreamWorldPokeball: 'cherishball',
requiredItem: "Chill Drive"
},
genesectdouse: {
randomBattleMoves: ["uturn","bugbuzz","icebeam","flamethrower","thunderbolt","technoblast","ironhead","shiftgear","extremespeed","blazekick"],
randomDoubleBattleMoves: ["uturn","bugbuzz","icebeam","technoblast","thunderbolt","ironhead","shiftgear","extremespeed","blazekick","protect"],
dreamWorldPokeball: 'cherishball',
requiredItem: "Douse Drive"
},
genesectshock: {
randomBattleMoves: ["uturn","bugbuzz","icebeam","flamethrower","technoblast","ironhead","shiftgear","extremespeed","blazekick"],
randomDoubleBattleMoves: ["uturn","bugbuzz","icebeam","technoblast","thunderbolt","ironhead","shiftgear","extremespeed","blazekick","protect"],
dreamWorldPokeball: 'cherishball',
requiredItem: "Shock Drive"
},
chespin: {
randomBattleMoves: ["curse","gyroball","seedbomb","stoneedge","spikes","synthesis"],
tier: "LC"
},
quilladin: {
randomBattleMoves: ["curse","gyroball","seedbomb","stoneedge","spikes","synthesis"],
tier: "NFE"
},
chesnaught: {
randomBattleMoves: ["leechseed","synthesis","spikes","drainpunch","spikyshield","woodhammer"],
randomDoubleBattleMoves: ["leechseed","synthesis","hammerarm","spikyshield","stoneedge","woodhammer","rockslide"],
tier: "UU"
},
fennekin: {
randomBattleMoves: ["fireblast","psychic","psyshock","grassknot","willowisp","hypnosis","hiddenpowerrock","flamecharge","dazzlinggleam"],
tier: "LC"
},
braixen: {
randomBattleMoves: ["fireblast","flamethrower","psychic","psyshock","grassknot","willowisp","hiddenpowerrock","dazzlinggleam"],
tier: "NFE"
},
delphox: {
randomBattleMoves: ["calmmind","fireblast","flamethrower","psyshock","grassknot","switcheroo","shadowball","dazzlinggleam"],
randomDoubleBattleMoves: ["calmmind","fireblast","flamethrower","psyshock","grassknot","switcheroo","shadowball","heatwave","dazzlinggleam","protect"],
tier: "RU"
},
froakie: {
randomBattleMoves: ["quickattack","hydropump","icebeam","waterfall","toxicspikes","poweruppunch","uturn"],
eventPokemon: [
{"generation":6,"level":7,"isHidden":false,"moves":["pound","growl","bubble","return"],"pokeball":"cherishball"}
],
tier: "LC"
},
frogadier: {
randomBattleMoves: ["hydropump","surf","icebeam","uturn","taunt","toxicspikes"],
tier: "NFE"
},
greninja: {
randomBattleMoves: ["hydropump","uturn","surf","icebeam","spikes","taunt","darkpulse","toxicspikes","hiddenpowerfire","gunkshot"],
randomDoubleBattleMoves: ["hydropump","uturn","surf","icebeam","matblock","taunt","darkpulse","protect","hiddenpowerfire"],
eventPokemon: [
{"generation":6,"level":36,"isHidden":true,"moves":["watershuriken","shadowsneak","hydropump","substitute"],"pokeball":"cherishball"}
],
tier: "Uber"
},
bunnelby: {
randomBattleMoves: ["agility","earthquake","return","quickattack","uturn","stoneedge","spikes","bounce"],
tier: "LC"
},
diggersby: {
randomBattleMoves: ["earthquake","uturn","return","wildcharge","swordsdance","quickattack","agility","knockoff"],
randomDoubleBattleMoves: ["earthquake","uturn","return","wildcharge","protect","quickattack"],
tier: "BL"
},
fletchling: {
randomBattleMoves: ["roost","swordsdance","uturn","return","overheat","flamecharge","tailwind"],
tier: "LC"
},
fletchinder: {
randomBattleMoves: ["roost","swordsdance","uturn","return","overheat","flamecharge","tailwind","acrobatics"],
tier: "RU"
},
talonflame: {
randomBattleMoves: ["bravebird","flareblitz","roost","swordsdance","uturn","willowisp","tailwind"],
randomDoubleBattleMoves: ["bravebird","flareblitz","roost","swordsdance","uturn","willowisp","tailwind","taunt","protect"],
tier: "OU"
},
scatterbug: {
randomBattleMoves: ["tackle","stringshot","stunspore","bugbite","poisonpowder"],
tier: "LC"
},
spewpa: {
randomBattleMoves: ["tackle","stringshot","stunspore","bugbite","poisonpowder"],
tier: "NFE"
},
vivillon: {
randomBattleMoves: ["sleeppowder","quiverdance","hurricane","bugbuzz","roost"],
randomDoubleBattleMoves: ["sleeppowder","quiverdance","hurricane","bugbuzz","roost","protect"],
eventPokemon: [
// Poké Ball pattern
{"generation":6,"level":12,"gender":"M","isHidden":false,"moves":["stunspore","gust","lightscreen","strugglebug"],"pokeball":"cherishball"},
// Fancy pattern
{"generation":6,"level":12,"isHidden":false,"moves":["gust","lightscreen","strugglebug","holdhands"],"pokeball":"cherishball"}
],
tier: "NU"
},
litleo: {
randomBattleMoves: ["hypervoice","fireblast","willowisp","bulldoze","yawn"],
tier: "LC"
},
pyroar: {
randomBattleMoves: ["hypervoice","fireblast","willowisp","bulldoze","sunnyday","solarbeam"],
randomDoubleBattleMoves: ["hypervoice","fireblast","willowisp","protect","sunnyday","solarbeam"],
tier: "NU"
},
flabebe: {
randomBattleMoves: ["moonblast","toxic","wish","psychic","aromatherapy","protect","calmmind"],
tier: "LC"
},
floette: {
randomBattleMoves: ["moonblast","toxic","wish","psychic","aromatherapy","protect","calmmind"],
tier: "NFE"
},
floetteeternalflower: {
randomBattleMoves: ["lightofruin","psychic","hiddenpowerfire","hiddenpowerground","moonblast"],
randomDoubleBattleMoves: ["lightofruin","dazzlinggleam","wish","psychic","aromatherapy","protect","calmmind"],
isUnreleased: true,
tier: "Unreleased"
},
florges: {
randomBattleMoves: ["moonblast","toxic","wish","psychic","aromatherapy","protect","calmmind"],
randomDoubleBattleMoves: ["moonblast","dazzlinggleam","wish","psychic","aromatherapy","protect","calmmind"],
tier: "UU"
},
skiddo: {
randomBattleMoves: ["hornleech","earthquake","brickbreak","bulkup","leechseed","milkdrink","rockslide"],
tier: "LC"
},
gogoat: {
randomBattleMoves: ["hornleech","earthquake","brickbreak","bulkup","leechseed","milkdrink","rockslide"],
randomDoubleBattleMoves: ["hornleech","earthquake","brickbreak","bulkup","leechseed","milkdrink","rockslide","protect"],
tier: "PU"
},
pancham: {
randomBattleMoves: ["partingshot","skyuppercut","crunch","stoneedge","bulldoze","shadowclaw","bulkup"],
tier: "LC"
},
pangoro: {
randomBattleMoves: ["partingshot","superpower","knockoff","drainpunch","icepunch","earthquake","gunkshot"],
randomDoubleBattleMoves: ["partingshot","hammerarm","crunch","circlethrow","icepunch","earthquake","poisonjab","protect"],
tier: "RU"
},
furfrou: {
randomBattleMoves: ["return","cottonguard","uturn","thunderwave","suckerpunch","roar","wildcharge","rest","sleeptalk"],
randomDoubleBattleMoves: ["return","cottonguard","uturn","thunderwave","suckerpunch","snarl","wildcharge","protect"],
tier: "PU"
},
espurr: {
randomBattleMoves: ["fakeout","yawn","thunderwave","psyshock","trick","darkpulse"],
tier: "LC"
},
meowstic: {
randomBattleMoves: ["toxic","yawn","thunderwave","psyshock","trick","psychic","reflect","lightscreen","healbell"],
randomDoubleBattleMoves: ["fakeout","thunderwave","psyshock","psychic","reflect","lightscreen","safeguard","protect"],
tier: "PU"
},
meowsticf: {
randomBattleMoves: ["psyshock","darkpulse","calmmind","energyball","signalbeam","thunderbolt"],
randomDoubleBattleMoves: ["psyshock","darkpulse","fakeout","energyball","signalbeam","thunderbolt","protect","helpinghand"],
tier: "PU"
},
honedge: {
randomBattleMoves: ["swordsdance","shadowclaw","shadowsneak","ironhead","rockslide","aerialace","destinybond"],
tier: "LC"
},
doublade: {
randomBattleMoves: ["swordsdance","shadowclaw","shadowsneak","ironhead","sacredsword"],
randomDoubleBattleMoves: ["swordsdance","shadowclaw","shadowsneak","ironhead","sacredsword","rockslide","protect"],
tier: "RU"
},
aegislash: {
randomBattleMoves: ["kingsshield","swordsdance","shadowclaw","sacredsword","ironhead","shadowsneak","hiddenpowerice","shadowball","flashcannon"],
randomDoubleBattleMoves: ["kingsshield","swordsdance","shadowclaw","sacredsword","ironhead","shadowsneak","wideguard","hiddenpowerice","shadowball","flashcannon"],
eventPokemon: [
{"generation":6,"level":50,"gender":"F","nature":"Quiet","moves":["wideguard","kingsshield","shadowball","flashcannon"],"pokeball":"cherishball"}
],
tier: "Uber"
},
spritzee: {
randomBattleMoves: ["calmmind","drainingkiss","moonblast","psychic","aromatherapy","wish","trickroom","thunderbolt"],
tier: "LC"
},
aromatisse: {
randomBattleMoves: ["calmmind","moonblast","psychic","aromatherapy","wish","trickroom","thunderbolt"],
randomDoubleBattleMoves: ["moonblast","aromatherapy","wish","trickroom","thunderbolt","protect","healpulse"],
tier: "RU"
},
swirlix: {
randomBattleMoves: ["calmmind","drainingkiss","dazzlinggleam","surf","psychic","flamethrower","bellydrum","thunderbolt","return","thief","cottonguard"],
tier: "LC Uber"
},
slurpuff: {
randomBattleMoves: ["calmmind","dazzlinggleam","surf","psychic","flamethrower","thunderbolt"],
randomDoubleBattleMoves: ["calmmind","dazzlinggleam","surf","psychic","flamethrower","thunderbolt","protect"],
tier: "RU"
},
inkay: {
randomBattleMoves: ["topsyturvy","switcheroo","superpower","psychocut","flamethrower","rockslide","trickroom"],
eventPokemon: [
{"generation":6,"level":10,"isHidden":false,"moves":["happyhour","foulplay","hypnosis","topsyturvy"],"pokeball":"cherishball"}
],
tier: "LC"
},
malamar: {
randomBattleMoves: ["switcheroo","superpower","psychocut","rockslide","trickroom","knockoff"],
randomDoubleBattleMoves: ["switcheroo","superpower","psychocut","rockslide","trickroom","knockoff","protect"],
tier: "NU"
},
binacle: {
randomBattleMoves: ["shellsmash","razorshell","stoneedge","earthquake","crosschop","poisonjab","xscissor","rockslide"],
tier: "LC"
},
barbaracle: {
randomBattleMoves: ["shellsmash","razorshell","stoneedge","earthquake","crosschop","poisonjab","xscissor","rockslide"],
randomDoubleBattleMoves: ["shellsmash","razorshell","stoneedge","earthquake","crosschop","poisonjab","xscissor","rockslide","protect"],
tier: "PU"
},
skrelp: {
randomBattleMoves: ["scald","sludgebomb","thunderbolt","shadowball","toxicspikes","hydropump"],
tier: "LC"
},
dragalge: {
randomBattleMoves: ["scald","sludgebomb","thunderbolt","toxicspikes","hydropump","focusblast","dracometeor","dragontail","substitute"],
randomDoubleBattleMoves: ["scald","sludgebomb","thunderbolt","protect","hydropump","focusblast","dracometeor","dragonpulse","substitute"],
tier: "BL2"
},
clauncher: {
randomBattleMoves: ["waterpulse","flashcannon","uturn","darkpulse","crabhammer","aquajet","sludgebomb"],
tier: "LC"
},
clawitzer: {
randomBattleMoves: ["waterpulse","icebeam","uturn","darkpulse","dragonpulse","aurasphere"],
randomDoubleBattleMoves: ["waterpulse","icebeam","uturn","darkpulse","dragonpulse","aurasphere","muddywater","helpinghand","protect"],
tier: "RU"
},
helioptile: {
randomBattleMoves: ["surf","voltswitch","hiddenpowerice","raindance","thunder","darkpulse","thunderbolt"],
tier: "LC"
},
heliolisk: {
randomBattleMoves: ["surf","voltswitch","hiddenpowerice","raindance","thunder","darkpulse","thunderbolt"],
randomDoubleBattleMoves: ["surf","voltswitch","hiddenpowerice","raindance","thunder","darkpulse","thunderbolt","electricterrain","protect"],
tier: "NU"
},
tyrunt: {
randomBattleMoves: ["stealthrock","dragondance","stoneedge","dragonclaw","earthquake","icefang","firefang"],
unreleasedHidden: true,
tier: "LC"
},
tyrantrum: {
randomBattleMoves: ["stealthrock","dragondance","stoneedge","dragonclaw","earthquake","firefang","outrage"],
randomDoubleBattleMoves: ["rockslide","dragondance","stoneedge","dragonclaw","earthquake","icefang","firefang","protect"],
unreleasedHidden: true,
tier: "RU"
},
amaura: {
randomBattleMoves: ["naturepower","hypervoice","ancientpower","thunderbolt","darkpulse","thunderwave","dragontail","flashcannon"],
unreleasedHidden: true,
tier: "LC"
},
aurorus: {
randomBattleMoves: ["naturepower","ancientpower","thunderbolt","encore","thunderwave","earthpower","freezedry","hypervoice","stealthrock"],
randomDoubleBattleMoves: ["hypervoice","ancientpower","thunderbolt","encore","thunderwave","flashcannon","freezedry","icywind","protect"],
unreleasedHidden: true,
tier: "PU"
},
sylveon: {
randomBattleMoves: ["hypervoice","calmmind","wish","protect","psyshock","batonpass","shadowball"],
randomDoubleBattleMoves: ["hypervoice","calmmind","wish","protect","psyshock","helpinghand","shadowball","hiddenpowerground"],
eventPokemon: [
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","helpinghand","sandattack","fairywind"],"pokeball":"cherishball"},
{"generation":6,"level":10,"gender":"F","isHidden":false,"moves":["disarmingvoice","babydolleyes","quickattack","drainingkiss"],"pokeball":"cherishball"}
],
tier: "OU"
},
hawlucha: {
randomBattleMoves: ["swordsdance","highjumpkick","acrobatics","roost","thunderpunch","substitute"],
randomDoubleBattleMoves: ["swordsdance","highjumpkick","uturn","stoneedge","skydrop","encore","protect"],
tier: "BL"
},
dedenne: {
randomBattleMoves: ["voltswitch","thunderbolt","nuzzle","grassknot","hiddenpowerice","uturn","toxic"],
randomDoubleBattleMoves: ["voltswitch","thunderbolt","nuzzle","grassknot","hiddenpowerice","uturn","helpinghand","protect"],
tier: "PU"
},
carbink: {
randomBattleMoves: ["stealthrock","lightscreen","reflect","explosion","powergem","moonblast"],
randomDoubleBattleMoves: ["trickroom","lightscreen","reflect","explosion","powergem","moonblast","protect"],
tier: "PU"
},
goomy: {
randomBattleMoves: ["sludgebomb","thunderbolt","toxic","protect","infestation"],
tier: "LC"
},
sliggoo: {
randomBattleMoves: ["sludgebomb","thunderbolt","toxic","protect","infestation","icebeam"],
tier: "NFE"
},
goodra: {
randomBattleMoves: ["thunderbolt","toxic","icebeam","dragonpulse","fireblast","dragontail","dracometeor","focusblast"],
randomDoubleBattleMoves: ["thunderbolt","feint","icebeam","dragonpulse","fireblast","muddywater","dracometeor","focusblast","protect"],
tier: "UU"
},
klefki: {
randomBattleMoves: ["reflect","lightscreen","spikes","torment","substitute","thunderwave","drainingkiss","flashcannon","dazzlinggleam"],
randomDoubleBattleMoves: ["reflect","lightscreen","safeguard","playrough","substitute","thunderwave","protect","flashcannon","dazzlinggleam"],
tier: "BL"
},
phantump: {
randomBattleMoves: ["hornleech","leechseed","phantomforce","substitute","willowisp","curse","bulldoze","rockslide","poisonjab"],
tier: "LC"
},
trevenant: {
randomBattleMoves: ["hornleech","leechseed","shadowclaw","substitute","willowisp","rest","phantomforce"],
randomDoubleBattleMoves: ["hornleech","woodhammer","leechseed","shadowclaw","willowisp","trickroom","earthquake","rockslide","protect"],
tier: "UU"
},
pumpkaboo: {
randomBattleMoves: ["willowisp","shadowsneak","fireblast","synthesis","seedbomb"],
tier: "LC"
},
pumpkaboosmall: {
randomBattleMoves: ["willowisp","shadowsneak","fireblast","synthesis","seedbomb"],
unreleasedHidden: true,
tier: "LC"
},
pumpkaboolarge: {
randomBattleMoves: ["willowisp","shadowsneak","fireblast","synthesis","seedbomb"],
unreleasedHidden: true,
tier: "LC"
},
pumpkaboosuper: {
randomBattleMoves: ["willowisp","shadowsneak","fireblast","synthesis","seedbomb"],
eventPokemon: [
{"generation":6,"level":50,"moves":["trickortreat","astonish","scaryface","shadowsneak"],"pokeball":"cherishball"}
],
tier: "LC"
},
gourgeist: {
randomBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion"],
randomDoubleBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion","protect"],
tier: "PU"
},
gourgeistsmall: {
randomBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion"],
randomDoubleBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion","protect"],
unreleasedHidden: true,
tier: "PU"
},
gourgeistlarge: {
randomBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion"],
randomDoubleBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion","protect","trickroom"],
unreleasedHidden: true,
tier: "PU"
},
gourgeistsuper: {
randomBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion"],
randomDoubleBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion","protect","trickroom"],
tier: "PU"
},
bergmite: {
randomBattleMoves: ["avalanche","recover","stoneedge","curse","gyroball","rapidspin"],
tier: "LC"
},
avalugg: {
randomBattleMoves: ["avalanche","recover","stoneedge","curse","gyroball","rapidspin","roar","earthquake"],
randomDoubleBattleMoves: ["avalanche","recover","stoneedge","protect","gyroball","earthquake","curse"],
tier: "PU"
},
noibat: {
randomBattleMoves: ["airslash","hurricane","dracometeor","uturn","roost","switcheroo"],
tier: "LC"
},
noivern: {
randomBattleMoves: ["airslash","hurricane","dragonpulse","dracometeor","focusblast","flamethrower","uturn","roost","boomburst","switcheroo"],
randomDoubleBattleMoves: ["airslash","hurricane","dragonpulse","dracometeor","focusblast","flamethrower","uturn","roost","boomburst","switcheroo","tailwind","taunt","protect"],
tier: "UU"
},
xerneas: {
randomBattleMoves: ["geomancy","moonblast","thunder","focusblast"],
randomDoubleBattleMoves: ["geomancy","dazzlinggleam","thunder","focusblast","protect"],
unobtainableShiny: true,
tier: "Uber"
},
yveltal: {
randomBattleMoves: ["darkpulse","oblivionwing","taunt","focusblast","hurricane","roost","suckerpunch"],
randomDoubleBattleMoves: ["darkpulse","oblivionwing","taunt","focusblast","hurricane","roost","suckerpunch","snarl","skydrop","protect"],
unobtainableShiny: true,
tier: "Uber"
},
zygarde: {
randomBattleMoves: ["dragondance","earthquake","extremespeed","outrage","coil","stoneedge"],
randomDoubleBattleMoves: ["dragondance","landswrath","extremespeed","rockslide","coil","stoneedge","glare","protect"],
unobtainableShiny: true,
tier: "BL"
},
diancie: {
randomBattleMoves: ["diamondstorm","moonblast","reflect","lightscreen","substitute","calmmind","psychic","stealthrock"],
randomDoubleBattleMoves: ["diamondstorm","moonblast","reflect","lightscreen","safeguard","substitute","calmmind","psychic","dazzlinggleam","protect"],
eventPokemon: [
{"generation":6,"level":50,"moves":["diamondstorm","reflect","return","moonblast"],"pokeball":"cherishball"}
],
unobtainableShiny: true,
tier: "OU"
},
dianciemega: {
randomBattleMoves: ["diamondstorm","moonblast","calmmind","psyshock","earthpower","hiddenpowerfire"],
randomDoubleBattleMoves: ["diamondstorm","moonblast","calmmind","psyshock","earthpower","hiddenpowerfire","dazzlinggleam","protect"],
requiredItem: "Diancite"
},
hoopa: {
isUnreleased: true,
randomBattleMoves: ["nastyplot","psyshock","shadowball","focusblast","trick"],
randomDoubleBattleMoves: ["hyperspacehole","shadowball","focusblast","protect","psychic"],
tier: "Unreleased"
},
hoopaunbound: {
isUnreleased: true,
randomBattleMoves: ["nastyplot","psyshock","darkpulse","focusblast","hyperspacefury","zenheadbutt","icepunch","drainpunch","knockoff","trick"],
randomDoubleBattleMoves: ["psychic","darkpulse","focusblast","protect","hyperspacefury","zenheadbutt","icepunch","drainpunch"],
tier: "Unreleased"
},
volcanion: {
isUnreleased: true,
randomBattleMoves: ["substitute","steameruption","fireblast","sludgewave","hiddenpowerice","earthpower","superpower"],
randomDoubleBattleMoves: ["substitute","steameruption","heatwave","sludgewave","rockslide","earthquake","protect"],
tier: "Unreleased"
},
missingno: {
randomBattleMoves: ["watergun","skyattack","doubleedge","metronome"],
isNonstandard: true,
tier: ""
},
tomohawk: {
randomBattleMoves: ["aurasphere","roost","stealthrock","rapidspin","hurricane","airslash","taunt","substitute","toxic","naturepower","earthpower"],
isNonstandard: true,
tier: "CAP"
},
necturna: {
randomBattleMoves: ["powerwhip","hornleech","willowisp","shadowsneak","stoneedge","sacredfire","boltstrike","vcreate","extremespeed","closecombat","shellsmash","spore","milkdrink","batonpass","stickyweb"],
isNonstandard: true,
tier: "CAP"
},
mollux: {
randomBattleMoves: ["fireblast","thunderbolt","sludgebomb","thunderwave","willowisp","recover","rapidspin","trick","stealthrock","toxicspikes","lavaplume"],
isNonstandard: true,
tier: "CAP"
},
aurumoth: {
randomBattleMoves: ["dragondance","quiverdance","closecombat","bugbuzz","hydropump","megahorn","psychic","blizzard","thunder","focusblast","zenheadbutt"],
isNonstandard: true,
tier: "CAP"
},
malaconda: {
randomBattleMoves: ["powerwhip","glare","toxic","suckerpunch","rest","substitute","uturn","synthesis","rapidspin","knockoff"],
isNonstandard: true,
tier: "CAP"
},
cawmodore: {
randomBattleMoves: ["bellydrum","bulletpunch","drainpunch","acrobatics","drillpeck","substitute","ironhead","quickattack"],
isNonstandard: true,
tier: "CAP"
},
volkraken: {
randomBattleMoves: ["scald","powergem","hydropump","memento","hiddenpowerice","fireblast","willowisp","uturn","substitute","flashcannon","surf"],
isNonstandard: true,
tier: "CAP"
},
plasmanta: {
randomBattleMoves: ["sludgebomb","thunderbolt","substitute","hiddenpowerice","psyshock","dazzlinggleam","flashcannon"],
isNonstandard: true,
tier: "CAP"
},
syclant: {
randomBattleMoves: ["bugbuzz","icebeam","blizzard","earthpower","spikes","superpower","tailglow","uturn","focusblast"],
isNonstandard: true,
tier: "CAP"
},
revenankh: {
randomBattleMoves: ["bulkup","shadowsneak","drainpunch","rest","moonlight","icepunch","glare"],
isNonstandard: true,
tier: "CAP"
},
pyroak: {
randomBattleMoves: ["leechseed","lavaplume","substitute","protect","gigadrain"],
isNonstandard: true,
tier: "CAP"
},
fidgit: {
randomBattleMoves: ["spikes","stealthrock","toxicspikes","wish","rapidspin","encore","uturn","sludgebomb","earthpower"],
isNonstandard: true,
tier: "CAP"
},
stratagem: {
randomBattleMoves: ["paleowave","earthpower","fireblast","gigadrain","calmmind","substitute"],
isNonstandard: true,
tier: "CAP"
},
arghonaut: {
randomBattleMoves: ["recover","bulkup","waterfall","drainpunch","crosschop","stoneedge","thunderpunch","aquajet","machpunch"],
isNonstandard: true,
tier: "CAP"
},
kitsunoh: {
randomBattleMoves: ["shadowstrike","earthquake","superpower","meteormash","uturn","icepunch","trick","willowisp"],
isNonstandard: true,
tier: "CAP"
},
cyclohm: {
randomBattleMoves: ["slackoff","dracometeor","dragonpulse","fireblast","thunderbolt","hydropump","discharge","healbell"],
isNonstandard: true,
tier: "CAP"
},
colossoil: {
randomBattleMoves: ["earthquake","crunch","suckerpunch","uturn","rapidspin","encore","pursuit","knockoff"],
isNonstandard: true,
tier: "CAP"
},
krilowatt: {
randomBattleMoves: ["surf","thunderbolt","icebeam","earthpower"],
isNonstandard: true,
tier: "CAP"
},
voodoom: {
randomBattleMoves: ["aurasphere","darkpulse","taunt","painsplit","substitute","hiddenpowerice","vacuumwave"],
isNonstandard: true,
tier: "CAP"
}
};
| data/formats-data.js | exports.BattleFormatsData = {
bulbasaur: {
randomBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","leechseed","synthesis"],
randomDoubleBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["sweetscent","growth","solarbeam","synthesis"]},
{"generation":3,"level":10,"gender":"M","moves":["tackle","growl","leechseed","vinewhip"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tackle","growl","leechseed","vinewhip"]},
{"generation":5,"level":1,"isHidden":false,"moves":["falseswipe","block","frenzyplant","weatherball"]}
],
tier: "LC"
},
ivysaur: {
randomBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","leechseed","synthesis"],
randomDoubleBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","protect"],
tier: "NFE"
},
venusaur: {
randomBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","knockoff","leechseed","synthesis","earthquake"],
randomDoubleBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","protect"],
tier: "OU"
},
venusaurmega: {
randomBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","swordsdance","powerwhip","leechseed","synthesis","earthquake"],
randomDoubleBattleMoves: ["sleeppowder","gigadrain","hiddenpowerfire","hiddenpowerice","sludgebomb","powerwhip","protect"],
requiredItem: "Venusaurite"
},
charmander: {
randomBattleMoves: ["flamethrower","overheat","dragonpulse","hiddenpowergrass","fireblast"],
randomDoubleBattleMoves: ["heatwave","dragonpulse","hiddenpowergrass","fireblast","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["scratch","growl","ember"]},
{"generation":4,"level":40,"gender":"M","nature":"Mild","moves":["return","hiddenpower","quickattack","howl"]},
{"generation":4,"level":40,"gender":"M","nature":"Naive","moves":["return","hiddenpower","quickattack","howl"]},
{"generation":4,"level":40,"gender":"M","nature":"Naughty","moves":["return","hiddenpower","quickattack","howl"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["scratch","growl","ember","smokescreen"]},
{"generation":4,"level":40,"gender":"M","nature":"Hardy","moves":["return","hiddenpower","quickattack","howl"],"pokeball":"cherishball"},
{"generation":5,"level":1,"isHidden":false,"moves":["falseswipe","block","blastburn","acrobatics"]}
],
tier: "LC"
},
charmeleon: {
randomBattleMoves: ["flamethrower","overheat","dragonpulse","hiddenpowergrass","fireblast","dragondance","flareblitz","shadowclaw","dragonclaw"],
randomDoubleBattleMoves: ["heatwave","dragonpulse","hiddenpowergrass","fireblast","protect"],
tier: "NFE"
},
charizard: {
randomBattleMoves: ["fireblast","focusblast","airslash","roost","dragondance","flareblitz","dragonclaw","earthquake"],
randomDoubleBattleMoves: ["heatwave","fireblast","airslash","dragondance","flareblitz","dragonclaw","earthquake","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["wingattack","slash","dragonrage","firespin"]},
{"generation":6,"level":36,"gender":"M","isHidden":false,"moves":["firefang","flameburst","airslash","inferno"],"pokeball":"cherishball"},
{"generation":6,"level":36,"gender":"M","isHidden":false,"moves":["firefang","airslash","dragonclaw","dragonrage"],"pokeball":"cherishball"},
{"generation":6,"level":36,"shiny":true,"gender":"M","isHidden":false,"moves":["overheat","solarbeam","focusblast","holdhands"],"pokeball":"cherishball"}
],
tier: "OU"
},
charizardmegax: {
randomBattleMoves: ["dragondance","flareblitz","dragonclaw","earthquake","roost","substitute"],
randomDoubleBattleMoves: ["dragondance","flareblitz","dragonclaw","earthquake","rockslide","roost","substitute"],
requiredItem: "Charizardite X"
},
charizardmegay: {
randomBattleMoves: ["flamethrower","fireblast","airslash","roost","solarbeam","focusblast"],
randomDoubleBattleMoves: ["heatwave","fireblast","airslash","roost","solarbeam","focusblast","protect"],
requiredItem: "Charizardite Y"
},
squirtle: {
randomBattleMoves: ["icebeam","hydropump","rapidspin","scald","aquajet","toxic"],
randomDoubleBattleMoves: ["muddywater","icebeam","hydropump","fakeout","scald","followme","icywind","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","tailwhip","bubble","withdraw"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tackle","tailwhip","bubble","withdraw"]},
{"generation":5,"level":1,"isHidden":false,"moves":["falseswipe","block","hydrocannon","followme"]}
],
tier: "LC"
},
wartortle: {
randomBattleMoves: ["icebeam","hydropump","rapidspin","scald","aquajet","toxic"],
randomDoubleBattleMoves: ["muddywater","icebeam","hydropump","fakeout","scald","followme","icywind","protect"],
tier: "NFE"
},
blastoise: {
randomBattleMoves: ["icebeam","hydropump","rapidspin","scald","toxic","darkpulse","aurasphere"],
randomDoubleBattleMoves: ["muddywater","icebeam","hydropump","fakeout","scald","darkpulse","aurasphere","followme","icywind","protect","waterspout"],
eventPokemon: [
{"generation":3,"level":70,"moves":["protect","raindance","skullbash","hydropump"]}
],
tier: "UU"
},
blastoisemega: {
randomBattleMoves: ["icebeam","hydropump","rapidspin","scald","aquajet","toxic","dragontail","darkpulse","aurasphere"],
randomDoubleBattleMoves: ["muddywater","icebeam","hydropump","fakeout","scald","darkpulse","aurasphere","followme","icywind","protect"],
requiredItem: "Blastoisinite"
},
caterpie: {
randomBattleMoves: ["bugbite","snore","tackle","electroweb"],
tier: "LC"
},
metapod: {
randomBattleMoves: ["snore","bugbite","tackle","electroweb"],
tier: "NFE"
},
butterfree: {
randomBattleMoves: ["quiverdance","roost","bugbuzz","substitute","sleeppowder","gigadrain","psychic","shadowball"],
randomDoubleBattleMoves: ["quiverdance","bugbuzz","substitute","sleeppowder","gigadrain","psychic","shadowball","protect"],
eventPokemon: [
{"generation":3,"level":30,"moves":["morningsun","psychic","sleeppowder","aerialace"]}
],
tier: "PU"
},
weedle: {
randomBattleMoves: ["bugbite","stringshot","poisonsting","electroweb"],
tier: "LC"
},
kakuna: {
randomBattleMoves: ["electroweb","bugbite","irondefense","poisonsting"],
tier: "NFE"
},
beedrill: {
randomBattleMoves: ["toxicspikes","xscissor","swordsdance","uturn","endeavor","poisonjab","drillrun","knockoff"],
randomDoubleBattleMoves: ["xscissor","uturn","poisonjab","drillrun","brickbreak","knockoff","protect","stringshot"],
eventPokemon: [
{"generation":3,"level":30,"moves":["batonpass","sludgebomb","twineedle","swordsdance"]}
],
tier: "UU"
},
beedrillmega: {
randomBattleMoves: ["toxicspikes","xscissor","swordsdance","uturn","endeavor","poisonjab","drillrun","knockoff"],
randomDoubleBattleMoves: ["xscissor","uturn","substitute","poisonjab","drillrun","knockoff","protect"],
requiredItem: "Beedrillite"
},
pidgey: {
randomBattleMoves: ["roost","bravebird","heatwave","return","workup","uturn","thief"],
randomDoubleBattleMoves: ["bravebird","heatwave","return","uturn","tailwind","protect"],
tier: "LC"
},
pidgeotto: {
randomBattleMoves: ["roost","bravebird","heatwave","return","workup","uturn","thief"],
randomDoubleBattleMoves: ["bravebird","heatwave","return","uturn","tailwind","protect"],
eventPokemon: [
{"generation":3,"level":30,"abilities":["keeneye"],"moves":["refresh","wingattack","steelwing","featherdance"]}
],
tier: "NFE"
},
pidgeot: {
randomBattleMoves: ["roost","bravebird","pursuit","heatwave","return","uturn","hurricane"],
randomDoubleBattleMoves: ["bravebird","heatwave","return","uturn","tailwind","protect"],
eventPokemon: [
{"generation":5,"level":61,"gender":"M","nature":"Naughty","isHidden":false,"abilities":["keeneye"],"moves":["whirlwind","wingattack","skyattack","mirrormove"],"pokeball":"cherishball"}
],
tier: "UU"
},
pidgeotmega: {
randomBattleMoves: ["roost","heatwave","uturn","hurricane","defog"],
randomDoubleBattleMoves: ["tailwind","heatwave","uturn","hurricane","protect"],
requiredItem: "Pidgeotite"
},
rattata: {
randomBattleMoves: ["facade","flamewheel","suckerpunch","uturn","wildcharge","thunderwave","crunch","revenge"],
randomDoubleBattleMoves: ["facade","flamewheel","suckerpunch","uturn","wildcharge","superfang","crunch","protect"],
tier: "LC"
},
raticate: {
randomBattleMoves: ["facade","flamewheel","suckerpunch","uturn","wildcharge","crunch"],
randomDoubleBattleMoves: ["facade","flamewheel","suckerpunch","uturn","wildcharge","superfang","crunch","protect"],
eventPokemon: [
{"generation":3,"level":34,"moves":["refresh","superfang","scaryface","hyperfang"]}
],
tier: "PU"
},
spearow: {
randomBattleMoves: ["return","drillpeck","doubleedge","uturn","quickattack","pursuit","drillrun","featherdance"],
randomDoubleBattleMoves: ["return","drillpeck","doubleedge","uturn","quickattack","drillrun","protect"],
eventPokemon: [
{"generation":3,"level":22,"moves":["batonpass","falseswipe","leer","aerialace"]}
],
tier: "LC"
},
fearow: {
randomBattleMoves: ["return","drillpeck","doubleedge","uturn","quickattack","pursuit","drillrun","roost"],
randomDoubleBattleMoves: ["return","drillpeck","doubleedge","uturn","quickattack","drillrun","protect"],
tier: "PU"
},
ekans: {
randomBattleMoves: ["coil","gunkshot","seedbomb","glare","suckerpunch","aquatail","earthquake","rest","rockslide"],
randomDoubleBattleMoves: ["gunkshot","seedbomb","suckerpunch","aquatail","earthquake","rest","rockslide","protect"],
eventPokemon: [
{"generation":3,"level":14,"abilities":["shedskin"],"moves":["leer","wrap","poisonsting","bite"]},
{"generation":3,"level":10,"gender":"M","moves":["wrap","leer","poisonsting"]}
],
tier: "LC"
},
arbok: {
randomBattleMoves: ["coil","gunkshot","suckerpunch","aquatail","earthquake","rest"],
randomDoubleBattleMoves: ["gunkshot","seedbomb","suckerpunch","aquatail","crunch","earthquake","rest","rockslide","protect"],
eventPokemon: [
{"generation":3,"level":33,"moves":["refresh","sludgebomb","glare","bite"]}
],
tier: "PU"
},
pichu: {
randomBattleMoves: ["fakeout","volttackle","encore","irontail","toxic","thunderbolt"],
randomDoubleBattleMoves: ["fakeout","volttackle","encore","irontail","protect","thunderbolt","discharge"],
eventPokemon: [
{"generation":3,"level":5,"moves":["thundershock","charm","surf"]},
{"generation":3,"level":5,"moves":["thundershock","charm","wish"]},
{"generation":3,"level":5,"moves":["thundershock","charm","teeterdance"]},
{"generation":3,"level":5,"moves":["thundershock","charm","followme"]},
{"generation":4,"level":1,"moves":["volttackle","thunderbolt","grassknot","return"]},
{"generation":4,"level":30,"shiny":true,"gender":"M","nature":"Jolly","moves":["charge","volttackle","endeavor","endure"],"pokeball":"cherishball"},
{"generation":4,"level":30,"shiny":true,"gender":"M","nature":"Jolly","moves":["volttackle","charge","endeavor","endure"],"pokeball":"cherishball"}
],
tier: "LC"
},
pichuspikyeared: {
eventPokemon: [
{"generation":4,"level":30,"gender":"F","nature":"Naughty","moves":["helpinghand","volttackle","swagger","painsplit"]}
],
tier: ""
},
pikachu: {
randomBattleMoves: ["thunderbolt","volttackle","voltswitch","grassknot","hiddenpowerice","brickbreak","extremespeed","encore","substitute","knockoff"],
randomDoubleBattleMoves: ["fakeout","thunderbolt","volttackle","voltswitch","feint","grassknot","hiddenpowerice","brickbreak","extremespeed","encore","substitute","knockoff","protect","discharge"],
eventPokemon: [
{"generation":3,"level":50,"moves":["thunderbolt","agility","thunder","lightscreen"]},
{"generation":3,"level":10,"moves":["thundershock","growl","tailwhip","thunderwave"]},
{"generation":3,"level":10,"moves":["fly","tailwhip","growl","thunderwave"]},
{"generation":3,"level":5,"moves":["surf","growl","tailwhip","thunderwave"]},
{"generation":3,"level":10,"moves":["fly","growl","tailwhip","thunderwave"]},
{"generation":3,"level":10,"moves":["thundershock","growl","thunderwave","surf"]},
{"generation":3,"level":70,"moves":["thunderbolt","thunder","lightscreen","fly"]},
{"generation":3,"level":70,"moves":["thunderbolt","thunder","lightscreen","surf"]},
{"generation":3,"level":70,"moves":["thunderbolt","thunder","lightscreen","agility"]},
{"generation":4,"level":10,"gender":"F","nature":"Hardy","moves":["surf","volttackle","tailwhip","thunderwave"]},
{"generation":3,"level":10,"gender":"M","moves":["thundershock","growl","tailwhip","thunderwave"]},
{"generation":4,"level":50,"gender":"M","nature":"Hardy","moves":["surf","thunderbolt","lightscreen","quickattack"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"F","nature":"Bashful","moves":["present","quickattack","thundershock","tailwhip"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"M","nature":"Jolly","moves":["grassknot","thunderbolt","flash","doubleteam"],"pokeball":"cherishball"},
{"generation":4,"level":40,"gender":"M","nature":"Modest","moves":["surf","thunder","protect"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"F","nature":"Bashful","moves":["quickattack","thundershock","tailwhip","present"],"pokeball":"cherishball"},
{"generation":4,"level":40,"gender":"M","nature":"Mild","moves":["surf","thunder","protect"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"F","nature":"Bashful","moves":["present","quickattack","thunderwave","tailwhip"],"pokeball":"cherishball"},
{"generation":4,"level":30,"gender":"M","moves":["lastresort","present","thunderbolt","quickattack"],"pokeball":"cherishball"},
{"generation":4,"level":50,"gender":"M","nature":"Relaxed","moves":["rest","sleeptalk","yawn","snore"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"M","nature":"Docile","moves":["present","quickattack","thundershock","tailwhip"],"pokeball":"cherishball"},
{"generation":4,"level":50,"gender":"M","nature":"Naughty","moves":["volttackle","irontail","quickattack","thunderbolt"],"pokeball":"cherishball"},
{"generation":4,"level":20,"gender":"M","nature":"Bashful","moves":["present","quickattack","thundershock","tailwhip"],"pokeball":"cherishball"},
{"generation":5,"level":30,"gender":"F","isHidden":true,"moves":["sing","teeterdance","encore","electroball"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["fly","irontail","electroball","quickattack"],"pokeball":"cherishball"},
{"generation":5,"level":100,"gender":"F","isHidden":false,"moves":["thunder","volttackle","grassknot","quickattack"],"pokeball":"cherishball"},
{"generation":5,"level":50,"gender":"F","isHidden":false,"moves":["extremespeed","thunderbolt","grassknot","brickbreak"],"pokeball":"cherishball"},
{"generation":5,"level":50,"gender":"F","isHidden":true,"moves":["fly","thunderbolt","grassknot","protect"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["thundershock","tailwhip","thunderwave","headbutt"]},
{"generation":5,"level":100,"gender":"M","isHidden":true,"moves":["volttackle","quickattack","feint","voltswitch"],"pokeball":"cherishball"},
{"generation":5,"level":50,"gender":"M","nature":"Brave","isHidden":false,"moves":["thunderbolt","quickattack","irontail","electroball"],"pokeball":"cherishball"},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","growl","playnice","quickattack"],"pokeball":"cherishball"},
{"generation":6,"level":22,"isHidden":false,"moves":["quickattack","electroball","doubleteam","megakick"],"pokeball":"cherishball"},
{"generation":6,"level":10,"gender":"M","isHidden":false,"moves":["thunderbolt","quickattack","surf","holdhands"],"pokeball":"cherishball"},
{"generation":6,"level":10,"gender":"F","isHidden":false,"moves":["thunderbolt","quickattack","heartstamp","holdhands"],"pokeball":"healball"},
{"generation":6,"level":36,"shiny":true,"isHidden":true,"moves":["thunder","substitute","playnice","holdhands"],"pokeball":"cherishball"},
{"generation":6,"level":10,"gender":"F","isHidden":false,"moves":["playnice","charm","nuzzle","sweetkiss"],"pokeball":"cherishball"}
],
tier: "NFE"
},
pikachucosplay: {
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
pikachurockstar: {
randomBattleMoves: ["meteormash","wildcharge","knockoff","brickbreak"],
randomDoubleBattleMoves: ["meteormash","discharge","hiddenpowerice","protect"],
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
pikachubelle: {
randomBattleMoves: ["iciclecrash","thunderbolt","knockoff","brickbreak"],
randomDoubleBattleMoves: ["iciclecrash","discharge","protect","brickbreak"],
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
pikachupopstar: {
randomBattleMoves: ["drainingkiss","thunderbolt","hiddenpowerice","knockoff"],
randomDoubleBattleMoves: ["drainingkiss","discharge","hiddenpowerice","protect"],
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
pikachuphd: {
randomBattleMoves: ["electricterrain","thunderbolt","hiddenpowerice","knockoff"],
randomDoubleBattleMoves: ["electricterrain","discharge","hiddenpowerice","protect"],
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
pikachulibre: {
randomBattleMoves: ["flyingpress","thunderbolt","knockoff","grassknot"],
randomDoubleBattleMoves: ["flyingpress","discharge","knockoff","protect"],
gen: 6,
unobtainableShiny: true,
tier: "PU"
},
raichu: {
randomBattleMoves: ["nastyplot","encore","thunderbolt","grassknot","hiddenpowerice","focusblast","substitute"],
randomDoubleBattleMoves: ["fakeout","encore","thunderbolt","grassknot","hiddenpowerice","focusblast","substitute","extremespeed","knockoff","feint","protect"],
tier: "PU"
},
sandshrew: {
randomBattleMoves: ["earthquake","rockslide","swordsdance","rapidspin","xscissor","stealthrock","toxic","knockoff"],
randomDoubleBattleMoves: ["earthquake","rockslide","swordsdance","xscissor","knockoff","protect"],
eventPokemon: [
{"generation":3,"level":12,"moves":["scratch","defensecurl","sandattack","poisonsting"]}
],
tier: "LC"
},
sandslash: {
randomBattleMoves: ["earthquake","stoneedge","swordsdance","rapidspin","xscissor","stealthrock","knockoff"],
randomDoubleBattleMoves: ["earthquake","rockslide","stoneedge","swordsdance","xscissor","knockoff","protect"],
tier: "NU"
},
nidoranf: {
randomBattleMoves: ["toxicspikes","crunch","poisonjab","honeclaws"],
randomDoubleBattleMoves: ["helpinghand","crunch","poisonjab","protect"],
tier: "LC"
},
nidorina: {
randomBattleMoves: ["toxicspikes","crunch","poisonjab","honeclaws","icebeam","thunderbolt","shadowclaw"],
randomDoubleBattleMoves: ["helpinghand","crunch","poisonjab","protect","icebeam","thunderbolt","shadowclaw"],
tier: "NFE"
},
nidoqueen: {
randomBattleMoves: ["toxicspikes","stealthrock","fireblast","thunderbolt","icebeam","earthpower","sludgewave","focusblast"],
randomDoubleBattleMoves: ["helpinghand","protect","fireblast","thunderbolt","icebeam","earthpower","sludgebomb","focusblast"],
tier: "UU"
},
nidoranm: {
randomBattleMoves: ["suckerpunch","poisonjab","headsmash","honeclaws","shadowclaw"],
randomDoubleBattleMoves: ["suckerpunch","poisonjab","shadowclaw","helpinghand","protect"],
tier: "LC"
},
nidorino: {
randomBattleMoves: ["suckerpunch","poisonjab","headsmash","honeclaws","shadowclaw"],
randomDoubleBattleMoves: ["suckerpunch","poisonjab","shadowclaw","helpinghand","protect"],
tier: "NFE"
},
nidoking: {
randomBattleMoves: ["substitute","fireblast","thunderbolt","icebeam","earthpower","sludgewave","focusblast"],
randomDoubleBattleMoves: ["helpinghand","protect","fireblast","thunderbolt","icebeam","earthpower","sludgebomb","focusblast"],
tier: "UU"
},
cleffa: {
randomBattleMoves: ["reflect","thunderwave","lightscreen","toxic","fireblast","encore","wish","protect","aromatherapy","moonblast"],
randomDoubleBattleMoves: ["reflect","thunderwave","lightscreen","safeguard","fireblast","protect","moonblast"],
tier: "LC"
},
clefairy: {
randomBattleMoves: ["healingwish","reflect","thunderwave","lightscreen","toxic","fireblast","encore","wish","protect","aromatherapy","stealthrock","moonblast","knockoff","moonlight"],
randomDoubleBattleMoves: ["reflect","thunderwave","lightscreen","safeguard","fireblast","followme","protect","moonblast"],
tier: "NFE"
},
clefable: {
randomBattleMoves: ["calmmind","softboiled","fireblast","thunderbolt","icebeam","moonblast"],
randomDoubleBattleMoves: ["reflect","thunderwave","lightscreen","safeguard","fireblast","followme","protect","moonblast","softboiled"],
tier: "OU"
},
vulpix: {
randomBattleMoves: ["flamethrower","fireblast","willowisp","energyball","substitute","toxic","hypnosis","painsplit"],
randomDoubleBattleMoves: ["heatwave","fireblast","willowisp","energyball","substitute","protect"],
eventPokemon: [
{"generation":3,"level":18,"moves":["tailwhip","roar","quickattack","willowisp"]},
{"generation":3,"level":18,"moves":["charm","heatwave","ember","dig"]}
],
tier: "LC"
},
ninetales: {
randomBattleMoves: ["flamethrower","fireblast","willowisp","solarbeam","nastyplot","substitute","toxic","painsplit"],
randomDoubleBattleMoves: ["heatwave","fireblast","willowisp","solarbeam","substitute","protect"],
eventPokemon: [
{"generation":5,"level":50,"gender":"M","nature":"Bold","isHidden":true,"moves":["heatwave","solarbeam","psyshock","willowisp"],"pokeball":"cherishball"}
],
tier: "PU"
},
igglybuff: {
randomBattleMoves: ["wish","thunderwave","reflect","lightscreen","healbell","seismictoss","counter","protect","knockoff","dazzlinggleam"],
randomDoubleBattleMoves: ["wish","thunderwave","reflect","lightscreen","seismictoss","protect","knockoff","dazzlinggleam"],
eventPokemon: [
{"generation":3,"level":5,"abilities":["cutecharm"],"moves":["sing","charm","defensecurl","tickle"]}
],
tier: "LC"
},
jigglypuff: {
randomBattleMoves: ["wish","thunderwave","reflect","lightscreen","healbell","seismictoss","counter","stealthrock","protect","knockoff","dazzlinggleam"],
randomDoubleBattleMoves: ["wish","thunderwave","reflect","lightscreen","seismictoss","protect","knockoff","dazzlinggleam"],
tier: "NFE"
},
wigglytuff: {
randomBattleMoves: ["wish","thunderwave","healbell","fireblast","stealthrock","dazzlinggleam","hypervoice"],
randomDoubleBattleMoves: ["thunderwave","reflect","lightscreen","seismictoss","protect","knockoff","dazzlinggleam","fireblast","icebeam","hypervoice"],
tier: "PU"
},
zubat: {
randomBattleMoves: ["bravebird","roost","toxic","taunt","nastyplot","gigadrain","sludgebomb","airslash","uturn","whirlwind","heatwave","superfang"],
randomDoubleBattleMoves: ["bravebird","taunt","nastyplot","gigadrain","sludgebomb","airslash","uturn","protect","heatwave","superfang"],
tier: "LC"
},
golbat: {
randomBattleMoves: ["bravebird","roost","toxic","taunt","defog","superfang","uturn"],
randomDoubleBattleMoves: ["bravebird","taunt","nastyplot","gigadrain","sludgebomb","airslash","uturn","protect","heatwave","superfang"],
tier: "RU"
},
crobat: {
randomBattleMoves: ["bravebird","roost","toxic","taunt","defog","uturn","superfang"],
randomDoubleBattleMoves: ["bravebird","taunt","tailwind","gigadrain","sludgebomb","airslash","uturn","protect","heatwave","superfang"],
eventPokemon: [
{"generation":4,"level":30,"gender":"M","nature":"Timid","moves":["heatwave","airslash","sludgebomb","superfang"],"pokeball":"cherishball"}
],
tier: "UU"
},
oddish: {
randomBattleMoves: ["gigadrain","sludgebomb","synthesis","sleeppowder","stunspore","toxic","hiddenpowerfire","leechseed","dazzlinggleam","sunnyday"],
randomDoubleBattleMoves: ["gigadrain","sludgebomb","sleeppowder","stunspore","protect","hiddenpowerfire","leechseed","dazzlinggleam","sunnyday"],
eventPokemon: [
{"generation":3,"level":26,"moves":["poisonpowder","stunspore","sleeppowder","acid"]},
{"generation":3,"level":5,"moves":["absorb","leechseed"]}
],
tier: "LC"
},
gloom: {
randomBattleMoves: ["gigadrain","sludgebomb","synthesis","sleeppowder","stunspore","toxic","hiddenpowerfire","leechseed","dazzlinggleam","sunnyday"],
randomDoubleBattleMoves: ["gigadrain","sludgebomb","sleeppowder","stunspore","protect","hiddenpowerfire","leechseed","dazzlinggleam","sunnyday"],
eventPokemon: [
{"generation":3,"level":50,"moves":["sleeppowder","acid","moonlight","petaldance"]}
],
tier: "NFE"
},
vileplume: {
randomBattleMoves: ["gigadrain","sludgebomb","synthesis","sleeppowder","stunspore","toxic","hiddenpowerfire","leechseed","aromatherapy"],
randomDoubleBattleMoves: ["gigadrain","sludgebomb","sleeppowder","stunspore","protect","hiddenpowerfire","leechseed","dazzlinggleam","aromatherapy"],
tier: "NU"
},
bellossom: {
randomBattleMoves: ["gigadrain","sludgebomb","synthesis","sleeppowder","hiddenpowerfire","leafstorm","sunnyday"],
randomDoubleBattleMoves: ["gigadrain","sludgebomb","sleeppowder","stunspore","protect","hiddenpowerfire","leechseed","dazzlinggleam","sunnyday","leafstorm"],
tier: "PU"
},
paras: {
randomBattleMoves: ["spore","stunspore","xscissor","seedbomb","synthesis","leechseed","aromatherapy","knockoff"],
randomDoubleBattleMoves: ["spore","stunspore","xscissor","seedbomb","ragepowder","leechseed","protect","knockoff","wideguard"],
eventPokemon: [
{"generation":3,"level":28,"abilities":["effectspore"],"moves":["refresh","spore","slash","falseswipe"]}
],
tier: "LC"
},
parasect: {
randomBattleMoves: ["spore","stunspore","xscissor","seedbomb","synthesis","leechseed","aromatherapy","knockoff"],
randomDoubleBattleMoves: ["spore","stunspore","xscissor","seedbomb","ragepowder","leechseed","protect","knockoff","wideguard"],
tier: "PU"
},
venonat: {
randomBattleMoves: ["sleeppowder","morningsun","toxicspikes","sludgebomb","signalbeam","stunspore","psychic"],
randomDoubleBattleMoves: ["sleeppowder","morningsun","ragepowder","sludgebomb","signalbeam","stunspore","psychic","protect"],
tier: "LC"
},
venomoth: {
randomBattleMoves: ["sleeppowder","roost","quiverdance","batonpass","bugbuzz","sludgebomb","substitute"],
randomDoubleBattleMoves: ["sleeppowder","roost","ragepowder","quiverdance","protect","bugbuzz","sludgebomb","gigadrain","substitute","psychic"],
eventPokemon: [
{"generation":3,"level":32,"abilities":["shielddust"],"moves":["refresh","silverwind","substitute","psychic"]}
],
tier: "BL"
},
diglett: {
randomBattleMoves: ["earthquake","rockslide","stealthrock","suckerpunch","reversal","substitute","shadowclaw"],
randomDoubleBattleMoves: ["earthquake","rockslide","protect","suckerpunch","shadowclaw"],
tier: "LC"
},
dugtrio: {
randomBattleMoves: ["earthquake","stoneedge","stealthrock","suckerpunch","reversal","substitute"],
randomDoubleBattleMoves: ["earthquake","rockslide","protect","suckerpunch","shadowclaw","stoneedge"],
eventPokemon: [
{"generation":3,"level":40,"moves":["charm","earthquake","sandstorm","triattack"]}
],
tier: "RU"
},
meowth: {
randomBattleMoves: ["fakeout","uturn","thief","taunt","return","hypnosis"],
randomDoubleBattleMoves: ["fakeout","uturn","nightslash","taunt","return","hypnosis","feint","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["scratch","growl","petaldance"]},
{"generation":3,"level":5,"moves":["scratch","growl"]},
{"generation":3,"level":10,"gender":"M","moves":["scratch","growl","bite"]},
{"generation":3,"level":22,"moves":["sing","slash","payday","bite"]},
{"generation":4,"level":21,"gender":"F","nature":"Jolly","abilities":["pickup"],"moves":["bite","fakeout","furyswipes","screech"],"pokeball":"cherishball"},
{"generation":4,"level":10,"gender":"M","nature":"Jolly","abilities":["pickup"],"moves":["fakeout","payday","assist","scratch"],"pokeball":"cherishball"},
{"generation":5,"level":15,"gender":"M","isHidden":false,"abilities":["pickup"],"moves":["furyswipes","sing","nastyplot","snatch"],"pokeball":"cherishball"}
],
tier: "LC"
},
persian: {
randomBattleMoves: ["fakeout","uturn","taunt","return","knockoff"],
randomDoubleBattleMoves: ["fakeout","uturn","nightslash","taunt","return","hypnosis","feint","protect"],
tier: "PU"
},
psyduck: {
randomBattleMoves: ["hydropump","scald","icebeam","hiddenpowergrass","crosschop","encore","psychic","signalbeam"],
randomDoubleBattleMoves: ["hydropump","scald","icebeam","hiddenpowergrass","crosschop","encore","psychic","signalbeam","surf","icywind","protect"],
eventPokemon: [
{"generation":3,"level":27,"abilities":["damp"],"moves":["tailwhip","confusion","disable"]},
{"generation":3,"level":5,"moves":["watersport","scratch","tailwhip","mudsport"]}
],
tier: "LC"
},
golduck: {
randomBattleMoves: ["hydropump","scald","icebeam","hiddenpowergrass","encore","focusblast","calmmind"],
randomDoubleBattleMoves: ["hydropump","scald","icebeam","hiddenpowergrass","focusblast","encore","psychic","signalbeam","surf","icywind","protect"],
eventPokemon: [
{"generation":3,"level":33,"moves":["charm","waterfall","psychup","brickbreak"]}
],
tier: "PU"
},
mankey: {
randomBattleMoves: ["closecombat","uturn","icepunch","rockslide","punishment","earthquake","poisonjab"],
randomDoubleBattleMoves: ["closecombat","uturn","icepunch","rockslide","punishment","earthquake","poisonjab","protect"],
tier: "LC"
},
primeape: {
randomBattleMoves: ["closecombat","uturn","icepunch","stoneedge","encore","earthquake","gunkshot"],
randomDoubleBattleMoves: ["closecombat","uturn","icepunch","rockslide","punishment","earthquake","poisonjab","protect","taunt","stoneedge"],
eventPokemon: [
{"generation":3,"level":34,"abilities":["vitalspirit"],"moves":["helpinghand","crosschop","focusenergy","reversal"]}
],
tier: "NU"
},
growlithe: {
randomBattleMoves: ["flareblitz","wildcharge","hiddenpowergrass","closecombat","morningsun","willowisp","toxic","flamethrower"],
randomDoubleBattleMoves: ["flareblitz","wildcharge","hiddenpowergrass","closecombat","willowisp","snarl","heatwave","helpinghand","protect"],
eventPokemon: [
{"generation":3,"level":32,"abilities":["intimidate"],"moves":["leer","odorsleuth","takedown","flamewheel"]},
{"generation":3,"level":10,"gender":"M","moves":["bite","roar","ember"]},
{"generation":3,"level":28,"moves":["charm","flamethrower","bite","takedown"]}
],
tier: "LC"
},
arcanine: {
randomBattleMoves: ["flareblitz","wildcharge","extremespeed","closecombat","morningsun","willowisp","toxic"],
randomDoubleBattleMoves: ["flareblitz","wildcharge","hiddenpowergrass","closecombat","willowisp","snarl","heatwave","helpinghand","protect","extremespeed"],
tier: "UU"
},
poliwag: {
randomBattleMoves: ["hydropump","icebeam","encore","bellydrum","hypnosis","waterfall","return"],
randomDoubleBattleMoves: ["hydropump","icebeam","encore","icywind","hypnosis","waterfall","return","protect","helpinghand"],
eventPokemon: [
{"generation":3,"level":5,"moves":["bubble","sweetkiss"]}
],
tier: "LC"
},
poliwhirl: {
randomBattleMoves: ["hydropump","icebeam","encore","bellydrum","hypnosis","waterfall","return","earthquake"],
randomDoubleBattleMoves: ["hydropump","icebeam","encore","icywind","hypnosis","waterfall","return","protect","helpinghand","earthquake"],
tier: "NFE"
},
poliwrath: {
randomBattleMoves: ["substitute","focuspunch","bulkup","encore","waterfall","toxic","rest","sleeptalk","protect","scald","earthquake","circlethrow"],
randomDoubleBattleMoves: ["substitute","helpinghand","icywind","encore","waterfall","protect","icepunch","poisonjab","earthquake","brickbreak"],
eventPokemon: [
{"generation":3,"level":42,"moves":["helpinghand","hydropump","raindance","brickbreak"]}
],
tier: "PU"
},
politoed: {
randomBattleMoves: ["scald","toxic","encore","perishsong","protect","icebeam","focusblast","hydropump","hiddenpowergrass"],
randomDoubleBattleMoves: ["scald","hypnosis","icywind","encore","helpinghand","protect","icebeam","focusblast","hydropump","hiddenpowergrass"],
eventPokemon: [
{"generation":5,"level":50,"gender":"M","nature":"Calm","isHidden":true,"moves":["scald","icebeam","perishsong","protect"],"pokeball":"cherishball"}
],
tier: "PU"
},
abra: {
randomBattleMoves: ["calmmind","psychic","psyshock","hiddenpowerfighting","shadowball","encore","substitute"],
randomDoubleBattleMoves: ["protect","psychic","psyshock","hiddenpowerfighting","shadowball","encore","substitute"],
tier: "LC"
},
kadabra: {
randomBattleMoves: ["calmmind","psychic","psyshock","hiddenpowerfighting","shadowball","encore","substitute"],
randomDoubleBattleMoves: ["protect","psychic","psyshock","hiddenpowerfighting","shadowball","encore","substitute"],
tier: "PU"
},
alakazam: {
randomBattleMoves: ["psyshock","psychic","focusblast","shadowball","hiddenpowerice","hiddenpowerfire"],
randomDoubleBattleMoves: ["protect","psychic","psyshock","focusblast","shadowball","encore","substitute","energyball"],
eventPokemon: [
{"generation":3,"level":70,"moves":["futuresight","calmmind","psychic","trick"]}
],
tier: "UU"
},
alakazammega: {
randomBattleMoves: ["calmmind","psyshock","focusblast","shadowball","encore","substitute"],
randomDoubleBattleMoves: ["protect","psychic","psyshock","focusblast","shadowball","encore","substitute","energyball"],
requiredItem: "Alakazite",
tier: "BL"
},
machop: {
randomBattleMoves: ["dynamicpunch","bulkup","icepunch","rockslide","bulletpunch","knockoff"],
randomDoubleBattleMoves: ["dynamicpunch","protect","icepunch","rockslide","bulletpunch","knockoff"],
tier: "LC"
},
machoke: {
randomBattleMoves: ["dynamicpunch","bulkup","icepunch","rockslide","bulletpunch","poweruppunch","knockoff"],
randomDoubleBattleMoves: ["dynamicpunch","protect","icepunch","rockslide","bulletpunch","knockoff"],
eventPokemon: [
{"generation":3,"level":38,"abilities":["guts"],"moves":["seismictoss","foresight","revenge","vitalthrow"]},
{"generation":5,"level":30,"isHidden":false,"moves":["lowsweep","foresight","seismictoss","revenge"],"pokeball":"cherishball"}
],
tier: "NFE"
},
machamp: {
randomBattleMoves: ["dynamicpunch","bulkup","icepunch","stoneedge","bulletpunch","earthquake","knockoff"],
randomDoubleBattleMoves: ["dynamicpunch","helpinghand","protect","icepunch","rockslide","bulletpunch","knockoff","wideguard"],
tier: "UU"
},
bellsprout: {
randomBattleMoves: ["swordsdance","sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","seedbomb"],
randomDoubleBattleMoves: ["swordsdance","sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","seedbomb","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["vinewhip","teeterdance"]},
{"generation":3,"level":10,"gender":"M","moves":["vinewhip","growth"]}
],
tier: "LC"
},
weepinbell: {
randomBattleMoves: ["swordsdance","sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","seedbomb","knockoff"],
randomDoubleBattleMoves: ["swordsdance","sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","seedbomb","protect","knockoff"],
eventPokemon: [
{"generation":3,"level":32,"moves":["morningsun","magicalleaf","sludgebomb","sweetscent"]}
],
tier: "NFE"
},
victreebel: {
randomBattleMoves: ["sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","powerwhip","knockoff"],
randomDoubleBattleMoves: ["swordsdance","sleeppowder","sunnyday","growth","solarbeam","gigadrain","sludgebomb","weatherball","suckerpunch","powerwhip","protect","knockoff"],
tier: "PU"
},
tentacool: {
randomBattleMoves: ["toxicspikes","rapidspin","scald","sludgebomb","icebeam","knockoff","gigadrain","toxic","dazzlinggleam"],
randomDoubleBattleMoves: ["muddywater","scald","sludgebomb","icebeam","knockoff","gigadrain","protect","dazzlinggleam"],
tier: "LC"
},
tentacruel: {
randomBattleMoves: ["toxicspikes","rapidspin","scald","sludgebomb","icebeam","toxic","substitute"],
randomDoubleBattleMoves: ["muddywater","scald","sludgebomb","icebeam","knockoff","gigadrain","protect","dazzlinggleam"],
tier: "UU"
},
geodude: {
randomBattleMoves: ["stealthrock","earthquake","stoneedge","suckerpunch","hammerarm","firepunch","rockblast"],
randomDoubleBattleMoves: ["rockslide","earthquake","stoneedge","suckerpunch","hammerarm","firepunch","rockblast","protect"],
tier: "LC"
},
graveler: {
randomBattleMoves: ["stealthrock","earthquake","stoneedge","suckerpunch","hammerarm","firepunch","rockblast"],
randomDoubleBattleMoves: ["rockslide","earthquake","stoneedge","suckerpunch","hammerarm","firepunch","rockblast","protect"],
tier: "NFE"
},
golem: {
randomBattleMoves: ["stealthrock","earthquake","stoneedge","suckerpunch","toxic","rockblast"],
randomDoubleBattleMoves: ["rockslide","earthquake","stoneedge","suckerpunch","hammerarm","firepunch","rockblast","protect"],
tier: "PU"
},
ponyta: {
randomBattleMoves: ["flareblitz","wildcharge","morningsun","hypnosis","flamecharge"],
randomDoubleBattleMoves: ["flareblitz","wildcharge","protect","hypnosis","flamecharge"],
tier: "LC"
},
rapidash: {
randomBattleMoves: ["flareblitz","wildcharge","morningsun","megahorn","drillrun","willowisp","sunnyday","solarbeam"],
randomDoubleBattleMoves: ["flareblitz","wildcharge","protect","hypnosis","flamecharge","megahorn","drillrun","willowisp","sunnyday","solarbeam"],
eventPokemon: [
{"generation":3,"level":40,"moves":["batonpass","solarbeam","sunnyday","flamethrower"]}
],
tier: "PU"
},
slowpoke: {
randomBattleMoves: ["scald","aquatail","zenheadbutt","thunderwave","toxic","slackoff","trickroom"],
randomDoubleBattleMoves: ["scald","aquatail","zenheadbutt","thunderwave","slackoff","trickroom","protect"],
eventPokemon: [
{"generation":3,"level":31,"abilities":["oblivious"],"moves":["watergun","confusion","disable","headbutt"]},
{"generation":3,"level":10,"gender":"M","moves":["curse","yawn","tackle","growl"]},
{"generation":5,"level":30,"isHidden":false,"moves":["confusion","disable","headbutt","waterpulse"],"pokeball":"cherishball"}
],
tier: "LC"
},
slowbro: {
randomBattleMoves: ["scald","fireblast","icebeam","psychic","grassknot","calmmind","thunderwave","toxic","slackoff","trickroom","psyshock"],
randomDoubleBattleMoves: ["scald","fireblast","icebeam","psychic","grassknot","thunderwave","slackoff","trickroom","protect","psyshock"],
tier: "OU"
},
slowbromega: {
randomBattleMoves: ["scald","fireblast","icebeam","calmmind","psyshock","rest","sleeptalk"],
randomDoubleBattleMoves: ["scald","fireblast","icebeam","psychic","grassknot","thunderwave","slackoff","trickroom","protect","psyshock"],
requiredItem: "Slowbronite"
},
slowking: {
randomBattleMoves: ["scald","fireblast","icebeam","psychic","grassknot","calmmind","thunderwave","toxic","slackoff","trickroom","nastyplot","dragontail","psyshock"],
randomDoubleBattleMoves: ["scald","fireblast","icebeam","psychic","grassknot","thunderwave","slackoff","trickroom","protect","psyshock"],
tier: "RU"
},
magnemite: {
randomBattleMoves: ["thunderbolt","thunderwave","magnetrise","substitute","flashcannon","hiddenpowerice","voltswitch"],
randomDoubleBattleMoves: ["thunderbolt","thunderwave","magnetrise","substitute","flashcannon","hiddenpowerice","voltswitch","protect","electroweb","discharge"],
tier: "LC"
},
magneton: {
randomBattleMoves: ["thunderbolt","substitute","flashcannon","hiddenpowerice","voltswitch","chargebeam","hiddenpowerfire"],
randomDoubleBattleMoves: ["thunderbolt","thunderwave","magnetrise","substitute","flashcannon","hiddenpowerice","voltswitch","protect","electroweb","discharge","hiddenpowerfire"],
eventPokemon: [
{"generation":3,"level":30,"moves":["refresh","doubleedge","raindance","thunder"]}
],
tier: "RU"
},
magnezone: {
randomBattleMoves: ["thunderbolt","substitute","flashcannon","hiddenpowerice","voltswitch","chargebeam","hiddenpowerfire"],
randomDoubleBattleMoves: ["thunderbolt","thunderwave","magnetrise","substitute","flashcannon","hiddenpowerice","voltswitch","protect","electroweb","discharge","hiddenpowerfire"],
tier: "OU"
},
farfetchd: {
randomBattleMoves: ["bravebird","swordsdance","return","leafblade","roost","nightslash"],
randomDoubleBattleMoves: ["bravebird","swordsdance","return","leafblade","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["yawn","wish"]},
{"generation":3,"level":36,"moves":["batonpass","slash","swordsdance","aerialace"]}
],
tier: "PU"
},
doduo: {
randomBattleMoves: ["bravebird","return","doubleedge","roost","quickattack","pursuit"],
randomDoubleBattleMoves: ["bravebird","return","doubleedge","quickattack","protect"],
tier: "LC"
},
dodrio: {
randomBattleMoves: ["bravebird","return","doubleedge","roost","quickattack","knockoff"],
randomDoubleBattleMoves: ["bravebird","return","doubleedge","quickattack","protect"],
eventPokemon: [
{"generation":3,"level":34,"moves":["batonpass","drillpeck","agility","triattack"]}
],
tier: "PU"
},
seel: {
randomBattleMoves: ["surf","icebeam","aquajet","protect","rest","toxic","drillrun"],
randomDoubleBattleMoves: ["surf","icebeam","aquajet","protect","rest","fakeout","drillrun","icywind"],
eventPokemon: [
{"generation":3,"level":23,"abilities":["thickfat"],"moves":["helpinghand","surf","safeguard","icebeam"]}
],
tier: "LC"
},
dewgong: {
randomBattleMoves: ["surf","icebeam","aquajet","iceshard","toxic","drillrun","encore"],
randomDoubleBattleMoves: ["surf","icebeam","aquajet","protect","rest","fakeout","drillrun","icywind"],
tier: "PU"
},
grimer: {
randomBattleMoves: ["curse","gunkshot","poisonjab","shadowsneak","painsplit","icepunch","firepunch","memento"],
randomDoubleBattleMoves: ["gunkshot","poisonjab","shadowsneak","protect","icepunch","firepunch"],
eventPokemon: [
{"generation":3,"level":23,"moves":["helpinghand","sludgebomb","shadowpunch","minimize"]}
],
tier: "LC"
},
muk: {
randomBattleMoves: ["curse","gunkshot","poisonjab","shadowsneak","icepunch","firepunch","memento"],
randomDoubleBattleMoves: ["gunkshot","poisonjab","shadowsneak","protect","icepunch","firepunch","brickbreak"],
tier: "NU"
},
shellder: {
randomBattleMoves: ["shellsmash","hydropump","razorshell","rockblast","iciclespear","rapidspin"],
randomDoubleBattleMoves: ["shellsmash","hydropump","razorshell","rockblast","iciclespear","protect"],
eventPokemon: [
{"generation":3,"level":24,"abilities":["shellarmor"],"moves":["withdraw","iciclespear","supersonic","aurorabeam"]},
{"generation":3,"level":10,"gender":"M","abilities":["shellarmor"],"moves":["tackle","withdraw","iciclespear"]},
{"generation":3,"level":29,"abilities":["shellarmor"],"moves":["refresh","takedown","surf","aurorabeam"]}
],
tier: "LC"
},
cloyster: {
randomBattleMoves: ["shellsmash","hydropump","razorshell","rockblast","iciclespear","iceshard","rapidspin","spikes","toxicspikes"],
randomDoubleBattleMoves: ["shellsmash","hydropump","razorshell","rockblast","iciclespear","protect"],
eventPokemon: [
{"generation":5,"level":30,"gender":"M","nature":"Naughty","isHidden":false,"abilities":["skilllink"],"moves":["iciclespear","rockblast","hiddenpower","razorshell"]}
],
tier: "UU"
},
gastly: {
randomBattleMoves: ["shadowball","sludgebomb","hiddenpowerfighting","thunderbolt","substitute","disable","painsplit","hypnosis","gigadrain","trick","dazzlinggleam"],
randomDoubleBattleMoves: ["shadowball","sludgebomb","hiddenpowerfighting","thunderbolt","substitute","disable","taunt","hypnosis","gigadrain","trick","dazzlinggleam","protect"],
tier: "LC"
},
haunter: {
randomBattleMoves: ["shadowball","sludgebomb","hiddenpowerfighting","thunderbolt","substitute","disable","painsplit","hypnosis","gigadrain","trick"],
randomDoubleBattleMoves: ["shadowball","sludgebomb","hiddenpowerfighting","thunderbolt","substitute","disable","taunt","hypnosis","gigadrain","trick","dazzlinggleam","protect"],
eventPokemon: [
{"generation":3,"level":23,"moves":["spite","curse","nightshade","confuseray"]},
{"generation":5,"level":30,"moves":["confuseray","suckerpunch","shadowpunch","payback"],"pokeball":"cherishball"}
],
tier: "PU"
},
gengar: {
randomBattleMoves: ["shadowball","sludgebomb","focusblast","thunderbolt","substitute","disable","painsplit"],
randomDoubleBattleMoves: ["shadowball","sludgebomb","focusblast","thunderbolt","substitute","disable","taunt","hypnosis","gigadrain","trick","dazzlinggleam","protect"],
eventPokemon: [
{"generation":6,"level":25,"nature":"Timid","moves":["psychic","confuseray","suckerpunch","shadowpunch"],"pokeball":"cherishball"},
{"generation":6,"level":25,"moves":["nightshade","confuseray","suckerpunch","shadowpunch"],"pokeball":"cherishball"},
{"generation":6,"level":50,"moves":["shadowball","sludgebomb","willowisp","destinybond"],"pokeball":"cherishball"},
{"generation":6,"level":25,"shiny":true,"moves":["shadowball","sludgewave","confuseray","astonish"],"pokeball":"duskball"}
],
tier: "OU"
},
gengarmega: {
randomBattleMoves: ["shadowball","sludgebomb","focusblast","thunderbolt","substitute","disable","painsplit","hypnosis","gigadrain"],
randomDoubleBattleMoves: ["shadowball","sludgebomb","focusblast","thunderbolt","substitute","disable","taunt","hypnosis","gigadrain","trick","dazzlinggleam","protect"],
requiredItem: "Gengarite",
tier: "Uber"
},
onix: {
randomBattleMoves: ["stealthrock","earthquake","stoneedge","dragontail","curse"],
randomDoubleBattleMoves: ["stealthrock","earthquake","stoneedge","rockslide","protect","explosion"],
tier: "LC"
},
steelix: {
randomBattleMoves: ["stealthrock","earthquake","ironhead","roar","toxic","rockslide"],
randomDoubleBattleMoves: ["stealthrock","earthquake","ironhead","rockslide","protect","explosion","icefang","firefang"],
tier: "NU"
},
steelixmega: {
randomBattleMoves: ["stealthrock","earthquake","heavyslam","roar","toxic"],
randomDoubleBattleMoves: ["stealthrock","earthquake","heavyslam","rockslide","protect","explosion"],
requiredItem: "Steelixite"
},
drowzee: {
randomBattleMoves: ["psychic","seismictoss","thunderwave","wish","protect","toxic","shadowball","trickroom","calmmind","dazzlinggleam"],
randomDoubleBattleMoves: ["psychic","seismictoss","thunderwave","wish","protect","hypnosis","shadowball","trickroom","calmmind","dazzlinggleam","toxic"],
eventPokemon: [
{"generation":3,"level":5,"abilities":["insomnia"],"moves":["bellydrum","wish"]}
],
tier: "LC"
},
hypno: {
randomBattleMoves: ["psychic","seismictoss","thunderwave","wish","protect","batonpass","toxic"],
randomDoubleBattleMoves: ["psychic","seismictoss","thunderwave","wish","protect","hypnosis","shadowball","trickroom","calmmind","dazzlinggleam","firepunch"],
eventPokemon: [
{"generation":3,"level":34,"abilities":["insomnia"],"moves":["batonpass","psychic","meditate","shadowball"]}
],
tier: "PU"
},
krabby: {
randomBattleMoves: ["crabhammer","swordsdance","agility","rockslide","substitute","xscissor","superpower","knockoff"],
randomDoubleBattleMoves: ["crabhammer","swordsdance","rockslide","substitute","xscissor","superpower","knockoff","protect"],
tier: "LC"
},
kingler: {
randomBattleMoves: ["crabhammer","xscissor","rockslide","swordsdance","agility","superpower","knockoff"],
randomDoubleBattleMoves: ["crabhammer","xscissor","rockslide","substitute","xscissor","superpower","knockoff","protect","wideguard"],
tier: "PU"
},
voltorb: {
randomBattleMoves: ["voltswitch","thunderbolt","taunt","foulplay","hiddenpowerice"],
randomDoubleBattleMoves: ["voltswitch","thunderbolt","taunt","foulplay","hiddenpowerice","protect","thunderwave"],
eventPokemon: [
{"generation":3,"level":19,"moves":["refresh","mirrorcoat","spark","swift"]}
],
tier: "LC"
},
electrode: {
randomBattleMoves: ["voltswitch","thunderbolt","taunt","foulplay","hiddenpowerice"],
randomDoubleBattleMoves: ["voltswitch","discharge","taunt","foulplay","hiddenpowerice","protect","thunderwave"],
tier: "PU"
},
exeggcute: {
randomBattleMoves: ["substitute","leechseed","gigadrain","psychic","sleeppowder","stunspore","hiddenpowerfire","synthesis"],
randomDoubleBattleMoves: ["substitute","leechseed","gigadrain","psychic","sleeppowder","stunspore","hiddenpowerfire","protect","trickroom"],
eventPokemon: [
{"generation":3,"level":5,"moves":["sweetscent","wish"]}
],
tier: "LC"
},
exeggutor: {
randomBattleMoves: ["substitute","leechseed","gigadrain","leafstorm","psychic","sleeppowder","hiddenpowerfire","trickroom","psyshock"],
randomDoubleBattleMoves: ["substitute","leechseed","gigadrain","leafstorm","psychic","sleeppowder","stunspore","hiddenpowerfire","protect","sludgebomb","trickroom","psyshock"],
eventPokemon: [
{"generation":3,"level":46,"moves":["refresh","psychic","hypnosis","ancientpower"]}
],
tier: "NU"
},
cubone: {
randomBattleMoves: ["substitute","bonemerang","doubleedge","rockslide","firepunch","earthquake"],
randomDoubleBattleMoves: ["substitute","bonemerang","doubleedge","rockslide","firepunch","earthquake","protect"],
tier: "LC"
},
marowak: {
randomBattleMoves: ["stealthrock","doubleedge","stoneedge","swordsdance","bonemerang","earthquake","knockoff","substitute"],
randomDoubleBattleMoves: ["substitute","bonemerang","doubleedge","rockslide","firepunch","earthquake","protect","swordsdance"],
eventPokemon: [
{"generation":3,"level":44,"moves":["sing","earthquake","swordsdance","rockslide"]}
],
tier: "PU"
},
tyrogue: {
randomBattleMoves: ["highjumpkick","rapidspin","fakeout","bulletpunch","machpunch","toxic","counter"],
randomDoubleBattleMoves: ["highjumpkick","fakeout","bulletpunch","machpunch","helpinghand","protect"],
tier: "LC"
},
hitmonlee: {
randomBattleMoves: ["highjumpkick","suckerpunch","stoneedge","machpunch","rapidspin","knockoff","poisonjab","fakeout"],
randomDoubleBattleMoves: ["helpinghand","suckerpunch","rockslide","machpunch","substitute","fakeout","closecombat","earthquake","blazekick","wideguard","protect"],
eventPokemon: [
{"generation":3,"level":38,"abilities":["limber"],"moves":["refresh","highjumpkick","mindreader","megakick"]}
],
tier: "RU"
},
hitmonchan: {
randomBattleMoves: ["bulkup","drainpunch","icepunch","firepunch","machpunch","substitute","rapidspin"],
randomDoubleBattleMoves: ["fakeout","drainpunch","icepunch","firepunch","machpunch","substitute","earthquake","rockslide","protect","helpinghand"],
eventPokemon: [
{"generation":3,"level":38,"abilities":["keeneye"],"moves":["helpinghand","skyuppercut","mindreader","megapunch"]}
],
tier: "RU"
},
hitmontop: {
randomBattleMoves: ["suckerpunch","machpunch","rapidspin","closecombat","toxic"],
randomDoubleBattleMoves: ["fakeout","feint","suckerpunch","closecombat","helpinghand","machpunch","wideguard"],
eventPokemon: [
{"generation":5,"level":55,"gender":"M","nature":"Adamant","isHidden":false,"abilities":["intimidate"],"moves":["fakeout","closecombat","suckerpunch","helpinghand"]}
],
tier: "RU"
},
lickitung: {
randomBattleMoves: ["wish","protect","dragontail","curse","bodyslam","return","powerwhip","swordsdance","earthquake","toxic","healbell"],
randomDoubleBattleMoves: ["wish","protect","dragontail","knockoff","bodyslam","return","powerwhip","swordsdance","earthquake","toxic","healbell"],
eventPokemon: [
{"generation":3,"level":5,"moves":["healbell","wish"]},
{"generation":3,"level":38,"moves":["helpinghand","doubleedge","defensecurl","rollout"]}
],
tier: "LC"
},
lickilicky: {
randomBattleMoves: ["wish","protect","dragontail","bodyslam","return","powerwhip","swordsdance","earthquake","toxic","healbell","explosion","knockoff"],
randomDoubleBattleMoves: ["wish","protect","dragontail","knockoff","bodyslam","return","powerwhip","swordsdance","earthquake","toxic","healbell","explosion"],
tier: "PU"
},
koffing: {
randomBattleMoves: ["painsplit","sludgebomb","willowisp","fireblast","toxic","clearsmog","rest","sleeptalk","thunderbolt"],
randomDoubleBattleMoves: ["protect","sludgebomb","willowisp","fireblast","toxic","rest","sleeptalk","thunderbolt"],
tier: "LC"
},
weezing: {
randomBattleMoves: ["painsplit","sludgebomb","willowisp","fireblast","toxic","clearsmog","toxicspikes"],
randomDoubleBattleMoves: ["protect","sludgebomb","willowisp","fireblast","toxic","rest","sleeptalk","thunderbolt","explosion"],
tier: "NU"
},
rhyhorn: {
randomBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockblast","rockpolish"],
randomDoubleBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockslide","protect"],
tier: "LC"
},
rhydon: {
randomBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockblast","rockpolish"],
randomDoubleBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockslide","protect"],
eventPokemon: [
{"generation":3,"level":46,"moves":["helpinghand","megahorn","scaryface","earthquake"]}
],
tier: "NU"
},
rhyperior: {
randomBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockblast","rockpolish","dragontail"],
randomDoubleBattleMoves: ["stoneedge","earthquake","aquatail","megahorn","stealthrock","rockslide","protect"],
tier: "RU"
},
happiny: {
randomBattleMoves: ["aromatherapy","toxic","thunderwave","counter","endeavor","lightscreen","fireblast"],
randomDoubleBattleMoves: ["aromatherapy","toxic","thunderwave","helpinghand","swagger","lightscreen","fireblast","protect"],
tier: "LC"
},
chansey: {
randomBattleMoves: ["wish","softboiled","protect","toxic","aromatherapy","seismictoss","counter","thunderwave","stealthrock","fireblast","icebeam"],
randomDoubleBattleMoves: ["aromatherapy","toxic","thunderwave","helpinghand","softboiled","lightscreen","seismictoss","protect","wish"],
eventPokemon: [
{"generation":3,"level":5,"gender":"F","moves":["sweetscent","wish"]},
{"generation":3,"level":10,"gender":"F","moves":["pound","growl","tailwhip","refresh"]},
{"generation":3,"level":39,"gender":"F","moves":["sweetkiss","thunderbolt","softboiled","skillswap"]}
],
tier: "OU"
},
blissey: {
randomBattleMoves: ["wish","softboiled","protect","toxic","healbell","seismictoss","counter","thunderwave","stealthrock","flamethrower","icebeam"],
randomDoubleBattleMoves: ["wish","softboiled","protect","toxic","aromatherapy","seismictoss","helpinghand","thunderwave","flamethrower","icebeam"],
eventPokemon: [
{"generation":5,"level":10,"gender":"F","isHidden":true,"moves":["pound","growl","tailwhip","refresh"]}
],
tier: "UU"
},
tangela: {
randomBattleMoves: ["gigadrain","sleeppowder","hiddenpowerfire","hiddenpowerice","leechseed","knockoff","leafstorm","sludgebomb","synthesis"],
randomDoubleBattleMoves: ["gigadrain","sleeppowder","hiddenpowerrock","hiddenpowerice","leechseed","knockoff","leafstorm","stunspore","protect","hiddenpowerfire"],
eventPokemon: [
{"generation":3,"level":30,"abilities":["chlorophyll"],"moves":["morningsun","solarbeam","sunnyday","ingrain"]}
],
tier: "PU"
},
tangrowth: {
randomBattleMoves: ["gigadrain","sleeppowder","hiddenpowerice","leechseed","knockoff","leafstorm","focusblast","synthesis","powerwhip","earthquake"],
randomDoubleBattleMoves: ["gigadrain","sleeppowder","hiddenpowerice","leechseed","knockoff","leafstorm","stunspore","focusblast","protect","powerwhip","earthquake"],
tier: "RU"
},
kangaskhan: {
randomBattleMoves: ["return","suckerpunch","earthquake","poweruppunch","drainpunch","crunch","fakeout"],
randomDoubleBattleMoves: ["fakeout","return","suckerpunch","earthquake","doubleedge","poweruppunch","drainpunch","crunch","protect"],
eventPokemon: [
{"generation":3,"level":5,"gender":"F","abilities":["earlybird"],"moves":["yawn","wish"]},
{"generation":3,"level":10,"gender":"F","abilities":["earlybird"],"moves":["cometpunch","leer","bite"]},
{"generation":3,"level":36,"gender":"F","abilities":["earlybird"],"moves":["sing","earthquake","tailwhip","dizzypunch"]},
{"generation":6,"level":50,"gender":"F","isHidden":false,"abilities":["scrappy"],"moves":["fakeout","return","earthquake","suckerpunch"],"pokeball":"cherishball"}
],
tier: "NU"
},
kangaskhanmega: {
randomBattleMoves: ["fakeout","return","suckerpunch","earthquake","poweruppunch","drainpunch","crunch"],
randomDoubleBattleMoves: ["fakeout","return","suckerpunch","earthquake","doubleedge","poweruppunch","drainpunch","crunch","protect"],
requiredItem: "Kangaskhanite",
tier: "Uber"
},
horsea: {
randomBattleMoves: ["hydropump","icebeam","substitute","hiddenpowergrass","raindance"],
randomDoubleBattleMoves: ["hydropump","icebeam","substitute","hiddenpowergrass","raindance","muddywater","protect"],
eventPokemon: [
{"generation":5,"level":1,"shiny":true,"isHidden":false,"moves":["bubble"]}
],
tier: "LC"
},
seadra: {
randomBattleMoves: ["hydropump","icebeam","agility","substitute","hiddenpowergrass"],
randomDoubleBattleMoves: ["hydropump","icebeam","substitute","hiddenpowergrass","agility","muddywater","protect"],
eventPokemon: [
{"generation":3,"level":45,"abilities":["poisonpoint"],"moves":["leer","watergun","twister","agility"]}
],
tier: "NFE"
},
kingdra: {
randomBattleMoves: ["hydropump","dragondance","substitute","outrage","dracometeor","waterfall","dragonpulse","scald"],
randomDoubleBattleMoves: ["hydropump","icebeam","dragondance","substitute","outrage","dracometeor","waterfall","dragonpulse","muddywater","protect"],
eventPokemon: [
{"generation":3,"level":50,"abilities":["swiftswim"],"moves":["leer","watergun","twister","agility"]},
{"generation":5,"level":50,"gender":"M","nature":"Timid","isHidden":false,"abilities":["swiftswim"],"moves":["dracometeor","muddywater","dragonpulse","protect"],"pokeball":"cherishball"}
],
tier: "UU"
},
goldeen: {
randomBattleMoves: ["waterfall","megahorn","knockoff","drillrun","icebeam"],
randomDoubleBattleMoves: ["waterfall","megahorn","knockoff","drillrun","icebeam","protect"],
tier: "LC"
},
seaking: {
randomBattleMoves: ["waterfall","scald","megahorn","knockoff","drillrun","icebeam"],
randomDoubleBattleMoves: ["waterfall","surf","megahorn","knockoff","drillrun","icebeam","icywind","protect"],
tier: "PU"
},
staryu: {
randomBattleMoves: ["scald","thunderbolt","icebeam","rapidspin","recover","dazzlinggleam","hydropump"],
randomDoubleBattleMoves: ["scald","thunderbolt","icebeam","protect","recover","dazzlinggleam","hydropump"],
eventPokemon: [
{"generation":3,"level":50,"moves":["minimize","lightscreen","cosmicpower","hydropump"]},
{"generation":3,"level":18,"abilities":["illuminate"],"moves":["tackle","watergun","rapidspin","recover"]}
],
tier: "LC"
},
starmie: {
randomBattleMoves: ["thunderbolt","icebeam","rapidspin","recover","psyshock","scald","hydropump"],
randomDoubleBattleMoves: ["surf","thunderbolt","icebeam","protect","recover","psychic","psyshock","scald","hydropump"],
eventPokemon: [
{"generation":3,"level":41,"moves":["refresh","waterfall","icebeam","recover"]}
],
tier: "OU"
},
mimejr: {
randomBattleMoves: ["batonpass","psychic","thunderwave","hiddenpowerfighting","healingwish","nastyplot","thunderbolt","encore"],
randomDoubleBattleMoves: ["fakeout","psychic","thunderwave","hiddenpowerfighting","healingwish","nastyplot","thunderbolt","encore","icywind","protect"],
tier: "LC"
},
mrmime: {
randomBattleMoves: ["psychic","psyshock","focusblast","healingwish","nastyplot","thunderbolt","encore","dazzlinggleam"],
randomDoubleBattleMoves: ["fakeout","psychic","thunderwave","hiddenpowerfighting","healingwish","nastyplot","thunderbolt","encore","icywind","protect","wideguard","dazzlinggleam"],
eventPokemon: [
{"generation":3,"level":42,"abilities":["soundproof"],"moves":["followme","psychic","encore","thunderpunch"]}
],
tier: "PU"
},
scyther: {
randomBattleMoves: ["swordsdance","roost","bugbite","quickattack","brickbreak","aerialace","batonpass","uturn","knockoff"],
randomDoubleBattleMoves: ["swordsdance","protect","bugbite","quickattack","brickbreak","aerialace","feint","uturn","knockoff"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["swarm"],"moves":["quickattack","leer","focusenergy"]},
{"generation":3,"level":40,"abilities":["swarm"],"moves":["morningsun","razorwind","silverwind","slash"]},
{"generation":5,"level":30,"isHidden":false,"moves":["agility","wingattack","furycutter","slash"],"pokeball":"cherishball"}
],
tier: "NU"
},
scizor: {
randomBattleMoves: ["swordsdance","roost","bulletpunch","bugbite","superpower","uturn","pursuit","defog","knockoff"],
randomDoubleBattleMoves: ["swordsdance","roost","bulletpunch","bugbite","superpower","uturn","protect","feint","knockoff"],
eventPokemon: [
{"generation":3,"level":50,"gender":"M","abilities":["swarm"],"moves":["furycutter","metalclaw","swordsdance","slash"]},
{"generation":4,"level":50,"gender":"M","nature":"Adamant","abilities":["swarm"],"moves":["xscissor","swordsdance","irondefense","agility"],"pokeball":"cherishball"},
{"generation":5,"level":100,"gender":"M","isHidden":false,"abilities":["technician"],"moves":["bulletpunch","bugbite","roost","swordsdance"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["leer","focusenergy","pursuit","steelwing"]},
{"generation":6,"level":50,"gender":"M","isHidden":false,"moves":["xscissor","nightslash","doublehit","ironhead"],"pokeball":"cherishball"},
{"generation":6,"level":25,"nature":"Adamant","isHidden":false,"abilities":["technician"],"moves":["aerialace","falseswipe","agility","furycutter"],"pokeball":"cherishball"},
{"generation":6,"level":25,"isHidden":false,"moves":["metalclaw","falseswipe","agility","furycutter"],"pokeball":"cherishball"},
{"generation":6,"level":50,"isHidden":false,"abilities":["technician"],"moves":["bulletpunch","swordsdance","roost","uturn"],"pokeball":"cherishball"}
],
tier: "OU"
},
scizormega: {
randomBattleMoves: ["swordsdance","roost","bulletpunch","bugbite","superpower","uturn","batonpass","pursuit","defog","knockoff"],
randomDoubleBattleMoves: ["swordsdance","roost","bulletpunch","bugbite","superpower","uturn","protect","feint","knockoff"],
requiredItem: "Scizorite"
},
smoochum: {
randomBattleMoves: ["icebeam","psychic","hiddenpowerfighting","trick","shadowball","grassknot"],
randomDoubleBattleMoves: ["icebeam","psychic","hiddenpowerfighting","trick","shadowball","grassknot","fakeout","protect"],
tier: "LC"
},
jynx: {
randomBattleMoves: ["icebeam","psychic","focusblast","trick","nastyplot","lovelykiss","substitute","psyshock"],
randomDoubleBattleMoves: ["icebeam","psychic","hiddenpowerfighting","shadowball","protect","lovelykiss","substitute","psyshock"],
tier: "NU"
},
elekid: {
randomBattleMoves: ["thunderbolt","crosschop","voltswitch","substitute","icepunch","psychic","hiddenpowergrass"],
randomDoubleBattleMoves: ["thunderbolt","crosschop","voltswitch","substitute","icepunch","psychic","hiddenpowergrass","protect"],
eventPokemon: [
{"generation":3,"level":20,"moves":["icepunch","firepunch","thunderpunch","crosschop"]}
],
tier: "LC"
},
electabuzz: {
randomBattleMoves: ["thunderbolt","voltswitch","substitute","hiddenpowerice","hiddenpowergrass","focusblast","psychic"],
randomDoubleBattleMoves: ["thunderbolt","crosschop","voltswitch","substitute","icepunch","psychic","hiddenpowergrass","protect","focusblast","discharge"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["quickattack","leer","thunderpunch"]},
{"generation":3,"level":43,"moves":["followme","crosschop","thunderwave","thunderbolt"]},
{"generation":4,"level":30,"gender":"M","nature":"Naughty","moves":["lowkick","shockwave","lightscreen","thunderpunch"]},
{"generation":5,"level":30,"isHidden":false,"moves":["lowkick","swift","shockwave","lightscreen"],"pokeball":"cherishball"},
{"generation":6,"level":30,"gender":"M","isHidden":true,"moves":["lowkick","shockwave","lightscreen","thunderpunch"],"pokeball":"cherishball"}
],
tier: "NFE"
},
electivire: {
randomBattleMoves: ["wildcharge","crosschop","icepunch","flamethrower","earthquake","voltswitch"],
randomDoubleBattleMoves: ["wildcharge","crosschop","icepunch","substitute","flamethrower","earthquake","protect","thunderbolt","followme"],
eventPokemon: [
{"generation":4,"level":50,"gender":"M","nature":"Adamant","moves":["thunderpunch","icepunch","crosschop","earthquake"]},
{"generation":4,"level":50,"gender":"M","nature":"Serious","moves":["lightscreen","thunderpunch","discharge","thunderbolt"],"pokeball":"cherishball"}
],
tier: "NU"
},
magby: {
randomBattleMoves: ["flareblitz","substitute","fireblast","hiddenpowergrass","hiddenpowerice","crosschop","thunderpunch","overheat"],
tier: "LC"
},
magmar: {
randomBattleMoves: ["flareblitz","substitute","fireblast","hiddenpowergrass","hiddenpowerice","crosschop","thunderpunch","focusblast"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["leer","smog","firepunch","leer"]},
{"generation":3,"level":36,"moves":["followme","fireblast","crosschop","thunderpunch"]},
{"generation":4,"level":30,"gender":"M","nature":"Quiet","moves":["smokescreen","firespin","confuseray","firepunch"]},
{"generation":5,"level":30,"isHidden":false,"moves":["smokescreen","feintattack","firespin","confuseray"],"pokeball":"cherishball"},
{"generation":6,"level":30,"gender":"M","isHidden":true,"moves":["smokescreen","firespin","confuseray","firepunch"],"pokeball":"cherishball"}
],
tier: "NFE"
},
magmortar: {
randomBattleMoves: ["fireblast","focusblast","hiddenpowergrass","hiddenpowerice","thunderbolt","earthquake","willowisp"],
randomDoubleBattleMoves: ["fireblast","taunt","focusblast","hiddenpowergrass","hiddenpowerice","thunderbolt","heatwave","willowisp","protect","followme"],
eventPokemon: [
{"generation":4,"level":50,"gender":"F","nature":"Modest","moves":["flamethrower","psychic","hyperbeam","solarbeam"]},
{"generation":4,"level":50,"gender":"M","nature":"Hardy","moves":["confuseray","firepunch","lavaplume","flamethrower"],"pokeball":"cherishball"}
],
tier: "NU"
},
pinsir: {
randomBattleMoves: ["earthquake","xscissor","closecombat","stoneedge","stealthrock","knockoff"],
randomDoubleBattleMoves: ["protect","swordsdance","xscissor","earthquake","closecombat","substitute","rockslide"],
eventPokemon: [
{"generation":3,"level":35,"abilities":["hypercutter"],"moves":["helpinghand","guillotine","falseswipe","submission"]},
{"generation":6,"level":50,"gender":"F","nature":"Adamant","isHidden":false,"moves":["xscissor","earthquake","stoneedge","return"],"pokeball":"cherishball"},
{"generation":6,"level":50,"nature":"Jolly","isHidden":true,"moves":["earthquake","swordsdance","feint","quickattack"],"pokeball":"cherishball"}
],
tier: "UU"
},
pinsirmega: {
randomBattleMoves: ["swordsdance","earthquake","closecombat","quickattack","return"],
randomDoubleBattleMoves: ["feint","protect","swordsdance","xscissor","earthquake","closecombat","substitute","quickattack","return","rockslide"],
requiredItem: "Pinsirite",
tier: "BL"
},
tauros: {
randomBattleMoves: ["rockclimb","earthquake","zenheadbutt","rockslide","pursuit","doubleedge"],
randomDoubleBattleMoves: ["rockclimb","earthquake","zenheadbutt","rockslide","protect","doubleedge"],
eventPokemon: [
{"generation":3,"level":25,"gender":"M","abilities":["intimidate"],"moves":["rage","hornattack","scaryface","pursuit"]},
{"generation":3,"level":10,"gender":"M","abilities":["intimidate"],"moves":["tackle","tailwhip","rage","hornattack"]},
{"generation":3,"level":46,"gender":"M","abilities":["intimidate"],"moves":["refresh","earthquake","tailwhip","bodyslam"]}
],
tier: "PU"
},
magikarp: {
randomBattleMoves: ["bounce","flail","tackle","hydropump"],
eventPokemon: [
{"generation":4,"level":5,"gender":"M","nature":"Relaxed","moves":["splash"]},
{"generation":4,"level":6,"gender":"F","nature":"Rash","moves":["splash"]},
{"generation":4,"level":7,"gender":"F","nature":"Hardy","moves":["splash"]},
{"generation":4,"level":5,"gender":"F","nature":"Lonely","moves":["splash"]},
{"generation":4,"level":4,"gender":"M","nature":"Modest","moves":["splash"]},
{"generation":5,"level":99,"shiny":true,"gender":"M","isHidden":false,"moves":["flail","hydropump","bounce","splash"],"pokeball":"cherishball"}
],
tier: "LC"
},
gyarados: {
randomBattleMoves: ["dragondance","waterfall","earthquake","bounce","rest","sleeptalk","dragontail","stoneedge","substitute","icefang"],
randomDoubleBattleMoves: ["dragondance","waterfall","earthquake","bounce","taunt","protect","thunderwave","stoneedge","substitute","icefang"],
eventPokemon: [
{"generation":6,"level":50,"isHidden":false,"moves":["waterfall","earthquake","icefang","dragondance"],"pokeball":"cherishball"}
],
tier: "OU"
},
gyaradosmega: {
randomBattleMoves: ["dragondance","waterfall","earthquake","stoneedge","substitute","icefang","crunch"],
randomDoubleBattleMoves: ["dragondance","waterfall","earthquake","bounce","taunt","protect","thunderwave","stoneedge","substitute","icefang"],
requiredItem: "Gyaradosite"
},
lapras: {
randomBattleMoves: ["icebeam","thunderbolt","healbell","toxic","surf","rest","sleeptalk"],
randomDoubleBattleMoves: ["icebeam","thunderbolt","healbell","hydropump","surf","substitute","protect","iceshard","icywind"],
eventPokemon: [
{"generation":3,"level":44,"moves":["hydropump","raindance","blizzard","healbell"]}
],
tier: "PU"
},
ditto: {
randomBattleMoves: ["transform"],
tier: "PU"
},
eevee: {
randomBattleMoves: ["quickattack","return","bite","batonpass","irontail","yawn","protect","wish"],
randomDoubleBattleMoves: ["quickattack","return","bite","helpinghand","irontail","yawn","protect","wish"],
eventPokemon: [
{"generation":4,"level":10,"gender":"F","nature":"Lonely","abilities":["adaptability"],"moves":["covet","bite","helpinghand","attract"],"pokeball":"cherishball"},
{"generation":4,"level":50,"shiny":true,"gender":"M","nature":"Hardy","abilities":["adaptability"],"moves":["irontail","trumpcard","flail","quickattack"],"pokeball":"cherishball"},
{"generation":5,"level":50,"gender":"F","nature":"Hardy","isHidden":false,"abilities":["adaptability"],"moves":["sing","return","echoedvoice","attract"],"pokeball":"cherishball"},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","sandattack","babydolleyes","swift"],"pokeball":"cherishball"}
],
tier: "LC"
},
vaporeon: {
randomBattleMoves: ["wish","protect","scald","roar","icebeam","toxic"],
randomDoubleBattleMoves: ["helpinghand","wish","protect","scald","muddywater","icebeam","toxic","hydropump"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","watergun"],"pokeball":"cherishball"}
],
tier: "UU"
},
jolteon: {
randomBattleMoves: ["thunderbolt","voltswitch","hiddenpowerice","batonpass","substitute","signalbeam"],
randomDoubleBattleMoves: ["thunderbolt","voltswitch","hiddenpowergrass","hiddenpowerice","helpinghand","protect","substitute","signalbeam"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","thundershock"],"pokeball":"cherishball"}
],
tier: "RU"
},
flareon: {
randomBattleMoves: ["flamecharge","facade","flareblitz","superpower","wish","protect","toxic"],
randomDoubleBattleMoves: ["flamecharge","facade","flareblitz","superpower","wish","protect","helpinghand"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","ember"],"pokeball":"cherishball"}
],
tier: "PU"
},
espeon: {
randomBattleMoves: ["psychic","psyshock","substitute","wish","shadowball","calmmind","morningsun","batonpass","dazzlinggleam"],
randomDoubleBattleMoves: ["psychic","psyshock","substitute","wish","shadowball","hiddenpowerfighting","helpinghand","protect","dazzlinggleam"],
eventPokemon: [
{"generation":3,"level":70,"moves":["psybeam","psychup","psychic","morningsun"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","confusion"],"pokeball":"cherishball"}
],
tier: "UU"
},
umbreon: {
randomBattleMoves: ["wish","protect","healbell","toxic","batonpass","foulplay"],
randomDoubleBattleMoves: ["moonlight","wish","protect","healbell","snarl","foulplay","helpinghand"],
eventPokemon: [
{"generation":3,"level":70,"moves":["feintattack","meanlook","screech","moonlight"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","pursuit"],"pokeball":"cherishball"}
],
tier: "UU"
},
leafeon: {
randomBattleMoves: ["swordsdance","leafblade","substitute","xscissor","synthesis","roar","healbell","batonpass","knockoff"],
randomDoubleBattleMoves: ["swordsdance","leafblade","substitute","xscissor","protect","helpinghand","knockoff"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","razorleaf"],"pokeball":"cherishball"}
],
tier: "PU"
},
glaceon: {
randomBattleMoves: ["icebeam","hiddenpowerground","shadowball","wish","protect","healbell","batonpass"],
randomDoubleBattleMoves: ["icebeam","hiddenpowerground","shadowball","wish","protect","healbell","helpinghand"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","tailwhip","sandattack","icywind"],"pokeball":"cherishball"}
],
tier: "PU"
},
porygon: {
randomBattleMoves: ["triattack","icebeam","recover","toxic","thunderwave","discharge","trick"],
eventPokemon: [
{"generation":5,"level":10,"isHidden":true,"moves":["tackle","conversion","sharpen","psybeam"]}
],
tier: "LC"
},
porygon2: {
randomBattleMoves: ["triattack","icebeam","recover","toxic","thunderwave","discharge","shadowball","trickroom"],
randomDoubleBattleMoves: ["triattack","icebeam","discharge","shadowball","trickroom","protect","recover"],
tier: "UU"
},
porygonz: {
randomBattleMoves: ["triattack","darkpulse","icebeam","thunderbolt","agility","trick","nastyplot"],
randomDoubleBattleMoves: ["protect","triattack","darkpulse","hiddenpowerfighting","agility","trick","nastyplot"],
tier: "UU"
},
omanyte: {
randomBattleMoves: ["shellsmash","surf","icebeam","earthpower","hiddenpowerelectric","spikes","toxicspikes","stealthrock","hydropump"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"abilities":["swiftswim"],"moves":["bubblebeam","supersonic","withdraw","bite"],"pokeball":"cherishball"}
],
tier: "LC"
},
omastar: {
randomBattleMoves: ["shellsmash","surf","icebeam","earthpower","spikes","toxicspikes","stealthrock","hydropump"],
randomDoubleBattleMoves: ["shellsmash","muddywater","icebeam","earthpower","hiddenpowerelectric","protect","toxicspikes","stealthrock","hydropump"],
tier: "RU"
},
kabuto: {
randomBattleMoves: ["aquajet","rockslide","rapidspin","stealthrock","honeclaws","waterfall","toxic"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"abilities":["battlearmor"],"moves":["confuseray","dig","scratch","harden"],"pokeball":"cherishball"}
],
tier: "LC"
},
kabutops: {
randomBattleMoves: ["aquajet","stoneedge","rapidspin","swordsdance","waterfall","knockoff"],
randomDoubleBattleMoves: ["aquajet","stoneedge","protect","rockslide","swordsdance","waterfall","superpower"],
tier: "RU"
},
aerodactyl: {
randomBattleMoves: ["stealthrock","taunt","stoneedge","earthquake","aquatail","roost","defog"],
randomDoubleBattleMoves: ["wideguard","taunt","stoneedge","rockslide","earthquake","aquatail","firefang","protect","icefang","skydrop","tailwind"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"abilities":["pressure"],"moves":["steelwing","icefang","firefang","thunderfang"],"pokeball":"cherishball"}
],
tier: "UU"
},
aerodactylmega: {
randomBattleMoves: ["stealthrock","defog","honeclaws","stoneedge","firefang","icefang","aerialace","roost"],
randomDoubleBattleMoves: ["wideguard","taunt","stoneedge","rockslide","earthquake","aquatail","firefang","protect","icefang","skydrop","tailwind"],
requiredItem: "Aerodactylite"
},
munchlax: {
randomBattleMoves: ["rest","curse","sleeptalk","bodyslam","earthquake","return","firepunch","icepunch","whirlwind","toxic"],
tier: "LC"
},
snorlax: {
randomBattleMoves: ["rest","curse","sleeptalk","bodyslam","earthquake","return","firepunch","crunch","pursuit","whirlwind"],
randomDoubleBattleMoves: ["curse","protect","bodyslam","earthquake","return","firepunch","icepunch","crunch","selfdestruct"],
eventPokemon: [
{"generation":3,"level":43,"moves":["refresh","fissure","curse","bodyslam"]}
],
tier: "UU"
},
articuno: {
randomBattleMoves: ["icebeam","roost","freezedry","toxic","substitute","hurricane"],
randomDoubleBattleMoves: ["freezedry","roost","protect","blizzard","substitute","hurricane","tailwind"],
eventPokemon: [
{"generation":3,"level":70,"moves":["agility","mindreader","icebeam","reflect"]},
{"generation":3,"level":50,"moves":["icebeam","healbell","extrasensory","haze"]}
],
unreleasedHidden: true,
tier: "PU"
},
zapdos: {
randomBattleMoves: ["thunderbolt","heatwave","hiddenpowergrass","hiddenpowerice","roost","toxic","substitute","defog"],
randomDoubleBattleMoves: ["thunderbolt","heatwave","hiddenpowergrass","hiddenpowerice","tailwind","protect","discharge"],
eventPokemon: [
{"generation":3,"level":70,"moves":["agility","detect","drillpeck","charge"]},
{"generation":3,"level":50,"moves":["thunderbolt","extrasensory","batonpass","metalsound"]}
],
unreleasedHidden: true,
tier: "OU"
},
moltres: {
randomBattleMoves: ["fireblast","hiddenpowergrass","roost","substitute","toxic","uturn","willowisp","hurricane"],
randomDoubleBattleMoves: ["fireblast","hiddenpowergrass","airslash","roost","substitute","protect","uturn","willowisp","hurricane","heatwave","tailwind"],
eventPokemon: [
{"generation":3,"level":70,"moves":["agility","endure","flamethrower","safeguard"]},
{"generation":3,"level":50,"moves":["extrasensory","morningsun","willowisp","flamethrower"]}
],
unreleasedHidden: true,
tier: "RU"
},
dratini: {
randomBattleMoves: ["dragondance","outrage","waterfall","fireblast","extremespeed","dracometeor","substitute","aquatail"],
tier: "LC"
},
dragonair: {
randomBattleMoves: ["dragondance","outrage","waterfall","fireblast","extremespeed","dracometeor","substitute","aquatail"],
tier: "NFE"
},
dragonite: {
randomBattleMoves: ["dragondance","outrage","firepunch","extremespeed","earthquake","roost"],
randomDoubleBattleMoves: ["dragondance","firepunch","extremespeed","dragonclaw","earthquake","roost","substitute","thunderwave","superpower","dracometeor","protect","skydrop"],
eventPokemon: [
{"generation":3,"level":70,"moves":["agility","safeguard","wingattack","outrage"]},
{"generation":3,"level":55,"moves":["healbell","hyperbeam","dragondance","earthquake"]},
{"generation":4,"level":50,"gender":"M","nature":"Mild","moves":["dracometeor","thunderbolt","outrage","dragondance"],"pokeball":"cherishball"},
{"generation":5,"level":100,"gender":"M","isHidden":true,"moves":["extremespeed","firepunch","dragondance","outrage"],"pokeball":"cherishball"},
{"generation":5,"level":55,"gender":"M","isHidden":true,"moves":["dragonrush","safeguard","wingattack","thunderpunch"]},
{"generation":5,"level":55,"gender":"M","isHidden":true,"moves":["dragonrush","safeguard","wingattack","extremespeed"]},
{"generation":5,"level":50,"gender":"M","nature":"Brave","isHidden":false,"abilities":["innerfocus"],"moves":["fireblast","safeguard","outrage","hyperbeam"],"pokeball":"cherishball"}
],
tier: "OU"
},
mewtwo: {
randomBattleMoves: ["psystrike","aurasphere","fireblast","icebeam","calmmind","substitute","recover","thunderbolt","willowisp"],
randomDoubleBattleMoves: ["psystrike","aurasphere","fireblast","icebeam","calmmind","substitute","recover","thunderbolt","willowisp","taunt","protect"],
eventPokemon: [
{"generation":5,"level":70,"isHidden":false,"moves":["psystrike","shadowball","aurasphere","electroball"],"pokeball":"cherishball"},
{"generation":5,"level":100,"nature":"Timid","isHidden":true,"moves":["psystrike","icebeam","healpulse","hurricane"],"pokeball":"cherishball"}
],
tier: "Uber"
},
mewtwomegax: {
randomBattleMoves: ["bulkup","drainpunch","earthquake","firepunch","icepunch","irontail","recover","stoneedge","substitute","thunderpunch","zenheadbutt"],
requiredItem: "Mewtwonite X"
},
mewtwomegay: {
randomBattleMoves: ["psystrike","aurasphere","fireblast","icebeam","calmmind","substitute","recover","thunderbolt","willowisp"],
requiredItem: "Mewtwonite Y"
},
mew: {
randomBattleMoves: ["taunt","willowisp","roost","psychic","nastyplot","aurasphere","fireblast","swordsdance","drainpunch","zenheadbutt","batonpass","substitute","toxic","icebeam","thunderbolt","knockoff","stealthrock","suckerpunch","defog"],
randomDoubleBattleMoves: ["taunt","willowisp","transform","roost","psyshock","nastyplot","aurasphere","fireblast","swordsdance","drainpunch","zenheadbutt","icebeam","thunderbolt","drillrun","suckerpunch","protect","fakeout","helpinghand","tailwind"],
eventPokemon: [
{"generation":3,"level":30,"moves":["pound","transform","megapunch","metronome"]},
{"generation":3,"level":10,"moves":["pound","transform"]},
{"generation":4,"level":50,"moves":["ancientpower","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["barrier","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["megapunch","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["amnesia","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["transform","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["psychic","metronome","teleport","aurasphere"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["synthesis","return","hypnosis","teleport"],"pokeball":"cherishball"},
{"generation":4,"level":5,"moves":["pound"],"pokeball":"cherishball"}
],
tier: "OU"
},
chikorita: {
randomBattleMoves: ["reflect","lightscreen","aromatherapy","grasswhistle","leechseed","toxic","gigadrain","synthesis"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","growl","razorleaf"]}
],
unreleasedHidden: true,
tier: "LC"
},
bayleef: {
randomBattleMoves: ["reflect","lightscreen","aromatherapy","grasswhistle","leechseed","toxic","gigadrain","synthesis"],
unreleasedHidden: true,
tier: "NFE"
},
meganium: {
randomBattleMoves: ["reflect","lightscreen","aromatherapy","leechseed","toxic","gigadrain","synthesis","dragontail"],
randomDoubleBattleMoves: ["reflect","lightscreen","aromatherapy","leechseed","hiddenpowerfire","gigadrain","synthesis","dragontail","healpulse","protect"],
unreleasedHidden: true,
tier: "PU"
},
cyndaquil: {
randomBattleMoves: ["eruption","fireblast","flamethrower","hiddenpowergrass","hiddenpowerice"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","leer","smokescreen"]}
],
unreleasedHidden: true,
tier: "LC"
},
quilava: {
randomBattleMoves: ["eruption","fireblast","flamethrower","hiddenpowergrass","hiddenpowerice"],
unreleasedHidden: true,
tier: "NFE"
},
typhlosion: {
randomBattleMoves: ["eruption","fireblast","hiddenpowergrass","hiddenpowerice","focusblast"],
randomDoubleBattleMoves: ["eruption","fireblast","hiddenpowergrass","hiddenpowerice","focusblast","heatwave","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["quickattack","flamewheel","swift","flamethrower"]}
],
unreleasedHidden: true,
tier: "NU"
},
totodile: {
randomBattleMoves: ["aquajet","waterfall","crunch","icepunch","superpower","dragondance","swordsdance"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["scratch","leer","rage"]}
],
unreleasedHidden: true,
tier: "LC"
},
croconaw: {
randomBattleMoves: ["aquajet","waterfall","crunch","icepunch","superpower","dragondance","swordsdance"],
unreleasedHidden: true,
tier: "NFE"
},
feraligatr: {
randomBattleMoves: ["aquajet","waterfall","crunch","icepunch","dragondance","swordsdance","earthquake"],
randomDoubleBattleMoves: ["aquajet","waterfall","crunch","icepunch","dragondance","swordsdance","earthquake","protect"],
unreleasedHidden: true,
tier: "NU"
},
sentret: {
randomBattleMoves: ["superfang","trick","toxic","uturn","knockoff"],
tier: "LC"
},
furret: {
randomBattleMoves: ["uturn","suckerpunch","trick","icepunch","firepunch","knockoff","doubleedge"],
randomDoubleBattleMoves: ["uturn","suckerpunch","trick","icepunch","firepunch","knockoff","doubleedge","followme","helpinghand","protect"],
tier: "PU"
},
hoothoot: {
randomBattleMoves: ["reflect","toxic","roost","whirlwind","nightshade","magiccoat"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","growl","foresight"]}
],
tier: "LC"
},
noctowl: {
randomBattleMoves: ["roost","whirlwind","airslash","nightshade","toxic","defog"],
randomDoubleBattleMoves: ["roost","tailwind","airslash","hypervoice","heatwave","protect","hypnosis"],
tier: "PU"
},
ledyba: {
randomBattleMoves: ["roost","agility","lightscreen","encore","reflect","knockoff","swordsdance","batonpass","toxic"],
eventPokemon: [
{"generation":3,"level":10,"moves":["refresh","psybeam","aerialace","supersonic"]}
],
tier: "LC"
},
ledian: {
randomBattleMoves: ["roost","lightscreen","encore","reflect","knockoff","toxic","uturn"],
randomDoubleBattleMoves: ["protect","lightscreen","encore","reflect","knockoff","bugbuzz","uturn","tailwind","stringshot","strugglebug"],
tier: "PU"
},
spinarak: {
randomBattleMoves: ["agility","toxic","xscissor","toxicspikes","poisonjab","batonpass","stickyweb"],
eventPokemon: [
{"generation":3,"level":14,"moves":["refresh","dig","signalbeam","nightshade"]}
],
tier: "LC"
},
ariados: {
randomBattleMoves: ["toxic","megahorn","toxicspikes","poisonjab","suckerpunch","stickyweb"],
randomDoubleBattleMoves: ["protect","megahorn","stringshot","poisonjab","stickyweb","ragepowder","strugglebug"],
tier: "PU"
},
chinchou: {
randomBattleMoves: ["voltswitch","thunderbolt","hiddenpowergrass","hydropump","icebeam","surf","thunderwave","scald","discharge","healbell"],
tier: "LC"
},
lanturn: {
randomBattleMoves: ["voltswitch","hiddenpowergrass","hydropump","icebeam","thunderwave","scald","discharge","healbell"],
randomDoubleBattleMoves: ["thunderbolt","hiddenpowergrass","hydropump","icebeam","thunderwave","scald","discharge","protect","surf"],
tier: "NU"
},
togepi: {
randomBattleMoves: ["protect","fireblast","toxic","thunderwave","softboiled","dazzlinggleam"],
eventPokemon: [
{"generation":3,"level":20,"gender":"F","abilities":["serenegrace"],"moves":["metronome","charm","sweetkiss","yawn"]},
{"generation":3,"level":25,"moves":["triattack","followme","ancientpower","helpinghand"]}
],
tier: "LC"
},
togetic: {
randomBattleMoves: ["nastyplot","dazzlinggleam","fireblast","batonpass","roost","encore","healbell","thunderwave"],
tier: "PU"
},
togekiss: {
randomBattleMoves: ["roost","thunderwave","nastyplot","airslash","aurasphere","batonpass","dazzlinggleam","fireblast"],
randomDoubleBattleMoves: ["roost","thunderwave","nastyplot","airslash","aurasphere","followme","dazzlinggleam","heatwave","tailwind","protect"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["extremespeed","aurasphere","airslash","present"]}
],
tier: "BL"
},
natu: {
randomBattleMoves: ["thunderwave","roost","toxic","reflect","lightscreen","uturn","wish","psychic","nightshade"],
eventPokemon: [
{"generation":3,"level":22,"moves":["batonpass","futuresight","nightshade","aerialace"]}
],
tier: "LC"
},
xatu: {
randomBattleMoves: ["thunderwave","toxic","roost","psychic","psyshock","uturn","reflect","lightscreen","grassknot","heatwave"],
randomDoubleBattleMoves: ["thunderwave","tailwind","roost","psychic","uturn","reflect","lightscreen","grassknot","heatwave","protect"],
tier: "NU"
},
mareep: {
randomBattleMoves: ["reflect","lightscreen","thunderbolt","discharge","thunderwave","toxic","hiddenpowerice","cottonguard","powergem"],
eventPokemon: [
{"generation":3,"level":37,"gender":"F","moves":["thunder","thundershock","thunderwave","cottonspore"]},
{"generation":3,"level":10,"gender":"M","moves":["tackle","growl","thundershock"]},
{"generation":3,"level":17,"moves":["healbell","thundershock","thunderwave","bodyslam"]}
],
tier: "LC"
},
flaaffy: {
randomBattleMoves: ["reflect","lightscreen","thunderbolt","discharge","thunderwave","toxic","hiddenpowerice","cottonguard","powergem"],
tier: "NFE"
},
ampharos: {
randomBattleMoves: ["voltswitch","reflect","lightscreen","focusblast","thunderbolt","toxic","healbell","hiddenpowerice"],
randomDoubleBattleMoves: ["focusblast","hiddenpowerice","hiddenpowergrass","thunderbolt","discharge","dragonpulse","protect"],
tier: "UU"
},
ampharosmega: {
randomBattleMoves: ["voltswitch","focusblast","agility","thunderbolt","healbell","dragonpulse","hiddenpowerice"],
randomDoubleBattleMoves: ["focusblast","hiddenpowerice","hiddenpowergrass","thunderbolt","discharge","dragonpulse","protect"],
requiredItem: "Ampharosite"
},
azurill: {
randomBattleMoves: ["scald","return","bodyslam","encore","toxic","protect","knockoff"],
tier: "LC"
},
marill: {
randomBattleMoves: ["waterfall","knockoff","encore","toxic","aquajet","superpower","icepunch","protect","playrough","poweruppunch"],
tier: "NFE"
},
azumarill: {
randomBattleMoves: ["waterfall","aquajet","playrough","superpower","bellydrum","knockoff"],
randomDoubleBattleMoves: ["waterfall","aquajet","playrough","superpower","bellydrum","knockoff","protect"],
tier: "OU"
},
bonsly: {
randomBattleMoves: ["rockslide","brickbreak","doubleedge","toxic","stealthrock","suckerpunch","explosion"],
tier: "LC"
},
sudowoodo: {
randomBattleMoves: ["stoneedge","earthquake","suckerpunch","woodhammer","explosion","stealthrock"],
randomDoubleBattleMoves: ["stoneedge","earthquake","suckerpunch","woodhammer","explosion","stealthrock","rockslide","helpinghand","protect","taunt"],
tier: "PU"
},
hoppip: {
randomBattleMoves: ["encore","sleeppowder","uturn","toxic","leechseed","substitute","protect"],
tier: "LC"
},
skiploom: {
randomBattleMoves: ["encore","sleeppowder","uturn","toxic","leechseed","substitute","protect"],
tier: "NFE"
},
jumpluff: {
randomBattleMoves: ["encore","sleeppowder","uturn","toxic","leechseed","gigadrain","synthesis"],
randomDoubleBattleMoves: ["encore","sleeppowder","uturn","helpinghand","leechseed","gigadrain","ragepowder","protect"],
eventPokemon: [
{"generation":5,"level":27,"gender":"M","isHidden":true,"moves":["falseswipe","sleeppowder","bulletseed","leechseed"]}
],
tier: "PU"
},
aipom: {
randomBattleMoves: ["fakeout","return","brickbreak","seedbomb","knockoff","uturn","icepunch","irontail"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["scratch","tailwhip","sandattack"]}
],
tier: "LC"
},
ambipom: {
randomBattleMoves: ["fakeout","return","knockoff","uturn","switcheroo","seedbomb","icepunch","lowkick"],
randomDoubleBattleMoves: ["fakeout","return","knockoff","uturn","switcheroo","seedbomb","icepunch","lowkick","protect"],
tier: "RU"
},
sunkern: {
randomBattleMoves: ["sunnyday","gigadrain","solarbeam","hiddenpowerfire","toxic","earthpower","leechseed"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["chlorophyll"],"moves":["absorb","growth"]}
],
tier: "LC"
},
sunflora: {
randomBattleMoves: ["sunnyday","gigadrain","solarbeam","hiddenpowerfire","earthpower"],
randomDoubleBattleMoves: ["sunnyday","gigadrain","solarbeam","hiddenpowerfire","earthpower","protect"],
tier: "PU"
},
yanma: {
randomBattleMoves: ["bugbuzz","airslash","hiddenpowerground","uturn","protect","gigadrain","ancientpower"],
tier: "LC Uber"
},
yanmega: {
randomBattleMoves: ["bugbuzz","airslash","hiddenpowerground","uturn","protect","gigadrain"],
tier: "BL2"
},
wooper: {
randomBattleMoves: ["recover","earthquake","scald","toxic","stockpile","yawn","protect"],
tier: "LC"
},
quagsire: {
randomBattleMoves: ["recover","earthquake","waterfall","scald","toxic","curse","yawn","icepunch"],
randomDoubleBattleMoves: ["icywind","earthquake","waterfall","scald","rockslide","curse","yawn","icepunch","protect"],
tier: "NU"
},
murkrow: {
randomBattleMoves: ["substitute","suckerpunch","bravebird","heatwave","hiddenpowergrass","roost","darkpulse","thunderwave"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["insomnia"],"moves":["peck","astonish"]}
],
tier: "LC Uber"
},
honchkrow: {
randomBattleMoves: ["substitute","superpower","suckerpunch","bravebird","roost","heatwave","pursuit"],
randomDoubleBattleMoves: ["substitute","superpower","suckerpunch","bravebird","roost","heatwave","protect"],
tier: "UU"
},
misdreavus: {
randomBattleMoves: ["nastyplot","substitute","calmmind","willowisp","shadowball","thunderbolt","hiddenpowerfighting"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["growl","psywave","spite"]}
],
tier: "PU"
},
mismagius: {
randomBattleMoves: ["nastyplot","substitute","willowisp","shadowball","thunderbolt","dazzlinggleam","healbell","painsplit"],
randomDoubleBattleMoves: ["nastyplot","substitute","willowisp","shadowball","thunderbolt","dazzlinggleam","taunt","protect"],
tier: "NU"
},
unown: {
randomBattleMoves: ["hiddenpowerpsychic"],
tier: "PU"
},
wynaut: {
randomBattleMoves: ["destinybond","counter","mirrorcoat","encore"],
eventPokemon: [
{"generation":3,"level":5,"moves":["splash","charm","encore","tickle"]}
],
tier: "LC"
},
wobbuffet: {
randomBattleMoves: ["destinybond","counter","mirrorcoat","encore"],
eventPokemon: [
{"generation":3,"level":5,"moves":["counter","mirrorcoat","safeguard","destinybond"]},
{"generation":3,"level":10,"gender":"M","moves":["counter","mirrorcoat","safeguard","destinybond"]},
{"generation":6,"level":10,"gender":"M","isHidden":false,"moves":["counter"],"pokeball":"cherishball"},
{"generation":6,"level":15,"gender":"M","isHidden":false,"moves":["counter","mirrorcoat"],"pokeball":"cherishball"}
],
tier: "PU"
},
girafarig: {
randomBattleMoves: ["psychic","psyshock","thunderbolt","nastyplot","batonpass","agility","hypervoice"],
randomDoubleBattleMoves: ["psychic","psyshock","thunderbolt","nastyplot","protect","agility","hypervoice"],
tier: "PU"
},
pineco: {
randomBattleMoves: ["rapidspin","toxicspikes","spikes","bugbite","stealthrock"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","protect","selfdestruct"]},
{"generation":3,"level":22,"moves":["refresh","pinmissile","spikes","counter"]}
],
tier: "LC"
},
forretress: {
randomBattleMoves: ["rapidspin","toxicspikes","spikes","voltswitch","stealthrock","gyroball"],
randomDoubleBattleMoves: ["rockslide","drillrun","stringshot","voltswitch","stealthrock","gyroball","protect"],
tier: "UU"
},
dunsparce: {
randomBattleMoves: ["coil","rockslide","bite","headbutt","glare","bodyslam","roost"],
randomDoubleBattleMoves: ["coil","rockslide","bite","headbutt","glare","bodyslam","protect"],
tier: "PU"
},
gligar: {
randomBattleMoves: ["stealthrock","toxic","roost","taunt","earthquake","uturn","knockoff"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["poisonsting","sandattack"]}
],
tier: "UU"
},
gliscor: {
randomBattleMoves: ["uturn","roost","substitute","taunt","earthquake","protect","toxic","stealthrock","knockoff"],
randomDoubleBattleMoves: ["uturn","tailwind","substitute","taunt","earthquake","protect","stoneedge","knockoff"],
tier: "OU"
},
snubbull: {
randomBattleMoves: ["thunderwave","firepunch","crunch","closecombat","icepunch","earthquake","playrough"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","scaryface","tailwhip","charm"]}
],
tier: "LC"
},
granbull: {
randomBattleMoves: ["thunderwave","playrough","crunch","earthquake","healbell"],
randomDoubleBattleMoves: ["thunderwave","playrough","crunch","earthquake","snarl","rockslide","protect"],
tier: "NU"
},
qwilfish: {
randomBattleMoves: ["toxicspikes","waterfall","spikes","painsplit","thunderwave","taunt","destinybond"],
randomDoubleBattleMoves: ["poisonjab","waterfall","swordsdance","protect","thunderwave","taunt","destinybond"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","poisonsting","harden","minimize"]}
],
tier: "NU"
},
shuckle: {
randomBattleMoves: ["toxic","encore","stealthrock","knockoff","stickyweb","infestation"],
randomDoubleBattleMoves: ["encore","stealthrock","knockoff","stickyweb","guardsplit","helpinghand","stringshot"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["sturdy"],"moves":["constrict","withdraw","wrap"]},
{"generation":3,"level":20,"abilities":["sturdy"],"moves":["substitute","toxic","sludgebomb","encore"]}
],
tier: "BL2"
},
heracross: {
randomBattleMoves: ["closecombat","megahorn","stoneedge","swordsdance","knockoff","earthquake"],
randomDoubleBattleMoves: ["closecombat","megahorn","stoneedge","swordsdance","knockoff","earthquake","protect"],
eventPokemon: [
{"generation":6,"level":50,"gender":"F","nature":"Adamant","isHidden":false,"moves":["bulletseed","pinmissile","closecombat","megahorn"],"pokeball":"cherishball"},
{"generation":6,"level":50,"nature":"Adamant","isHidden":false,"abilities":["guts"],"moves":["pinmissile","bulletseed","earthquake","rockblast"],"pokeball":"cherishball"}
],
tier: "UU"
},
heracrossmega: {
randomBattleMoves: ["closecombat","pinmissile","rockblast","swordsdance","bulletseed","knockoff","earthquake"],
randomDoubleBattleMoves: ["closecombat","pinmissile","rockblast","swordsdance","bulletseed","knockoff","earthquake","protect"],
requiredItem: "Heracronite",
tier: "BL"
},
sneasel: {
randomBattleMoves: ["iceshard","iciclecrash","lowkick","pursuit","swordsdance","knockoff"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["scratch","leer","taunt","quickattack"]}
],
tier: "PU"
},
weavile: {
randomBattleMoves: ["iceshard","iciclecrash","knockoff","pursuit","swordsdance","lowkick"],
randomDoubleBattleMoves: ["iceshard","icepunch","knockoff","fakeout","swordsdance","lowkick","taunt","protect","feint"],
eventPokemon: [
{"generation":4,"level":30,"gender":"M","nature":"Jolly","moves":["fakeout","iceshard","nightslash","brickbreak"],"pokeball":"cherishball"}
],
tier: "BL"
},
teddiursa: {
randomBattleMoves: ["swordsdance","protect","facade","closecombat","firepunch","crunch","playrough","gunkshot"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["pickup"],"moves":["scratch","leer","lick"]},
{"generation":3,"level":11,"abilities":["pickup"],"moves":["refresh","metalclaw","leer","return"]}
],
tier: "LC"
},
ursaring: {
randomBattleMoves: ["swordsdance","facade","closecombat","earthquake","crunch","protect"],
randomDoubleBattleMoves: ["swordsdance","facade","closecombat","earthquake","crunch","protect"],
tier: "PU"
},
slugma: {
randomBattleMoves: ["stockpile","recover","lavaplume","willowisp","toxic","hiddenpowergrass","earthpower","memento"],
tier: "LC"
},
magcargo: {
randomBattleMoves: ["recover","lavaplume","willowisp","toxic","hiddenpowergrass","hiddenpowerrock","stealthrock","fireblast","earthpower","shellsmash","ancientpower"],
randomDoubleBattleMoves: ["protect","heatwave","willowisp","shellsmash","hiddenpowergrass","hiddenpowerrock","stealthrock","fireblast","earthpower"],
eventPokemon: [
{"generation":3,"level":38,"moves":["refresh","heatwave","earthquake","flamethrower"]}
],
tier: "PU"
},
swinub: {
randomBattleMoves: ["earthquake","iciclecrash","iceshard","superpower","endeavor","stealthrock"],
eventPokemon: [
{"generation":3,"level":22,"abilities":["oblivious"],"moves":["charm","ancientpower","mist","mudshot"]}
],
tier: "LC"
},
piloswine: {
randomBattleMoves: ["earthquake","iciclecrash","iceshard","superpower","endeavor","stealthrock"],
tier: "PU"
},
mamoswine: {
randomBattleMoves: ["iceshard","earthquake","endeavor","iciclecrash","stealthrock","superpower","knockoff"],
randomDoubleBattleMoves: ["iceshard","earthquake","rockslide","iciclecrash","protect","superpower","knockoff"],
eventPokemon: [
{"generation":5,"level":34,"gender":"M","isHidden":true,"moves":["hail","icefang","takedown","doublehit"]},
{"generation":6,"level":50,"shiny":true,"gender":"M","nature":"Adamant","isHidden":true,"moves":["iciclespear","earthquake","iciclecrash","rockslide"]}
],
tier: "OU"
},
corsola: {
randomBattleMoves: ["recover","toxic","powergem","scald","stealthrock","earthpower","icebeam"],
randomDoubleBattleMoves: ["protect","icywind","powergem","scald","stealthrock","earthpower","icebeam"],
eventPokemon: [
{"generation":3,"level":5,"moves":["tackle","mudsport"]}
],
tier: "PU"
},
remoraid: {
randomBattleMoves: ["waterspout","hydropump","fireblast","hiddenpowerground","icebeam","seedbomb","rockblast"],
tier: "LC"
},
octillery: {
randomBattleMoves: ["hydropump","fireblast","icebeam","energyball","rockblast","waterspout"],
randomDoubleBattleMoves: ["hydropump","fireblast","icebeam","energyball","rockblast","waterspout","protect"],
eventPokemon: [
{"generation":4,"level":50,"gender":"F","nature":"Serious","abilities":["suctioncups"],"moves":["octazooka","icebeam","signalbeam","hyperbeam"],"pokeball":"cherishball"}
],
tier: "PU"
},
delibird: {
randomBattleMoves: ["fakeout","rapidspin","iceshard","icepunch","freezedry","aerialace","spikes","destinybond"],
randomDoubleBattleMoves: ["fakeout","iceshard","icepunch","freezedry","aerialace","brickbreak","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["present"]}
],
tier: "PU"
},
mantyke: {
randomBattleMoves: ["raindance","hydropump","scald","airslash","icebeam","rest","sleeptalk","toxic"],
tier: "LC"
},
mantine: {
randomBattleMoves: ["raindance","hydropump","scald","airslash","icebeam","rest","sleeptalk","toxic","defog"],
randomDoubleBattleMoves: ["raindance","hydropump","scald","airslash","icebeam","tailwind","wideguard","helpinghand","protect","surf"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","bubble","supersonic"]}
],
tier: "NU"
},
skarmory: {
randomBattleMoves: ["whirlwind","bravebird","roost","spikes","stealthrock","defog"],
randomDoubleBattleMoves: ["skydrop","bravebird","tailwind","taunt","feint","protect","ironhead"],
tier: "OU"
},
houndour: {
randomBattleMoves: ["pursuit","suckerpunch","fireblast","darkpulse","hiddenpowerfighting","nastyplot"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["leer","ember","howl"]},
{"generation":3,"level":17,"moves":["charm","feintattack","ember","roar"]}
],
tier: "LC"
},
houndoom: {
randomBattleMoves: ["nastyplot","darkpulse","suckerpunch","fireblast","hiddenpowerfighting"],
randomDoubleBattleMoves: ["nastyplot","darkpulse","suckerpunch","heatwave","hiddenpowerfighting","protect"],
eventPokemon: [
{"generation":6,"level":50,"nature":"Timid","isHidden":false,"abilities":["flashfire"],"moves":["flamethrower","darkpulse","solarbeam","sludgebomb"],"pokeball":"cherishball"}
],
tier: "RU"
},
houndoommega: {
randomBattleMoves: ["nastyplot","darkpulse","suckerpunch","fireblast","hiddenpowerfighting"],
randomDoubleBattleMoves: ["nastyplot","darkpulse","suckerpunch","heatwave","hiddenpowerfighting","protect"],
requiredItem: "Houndoominite",
tier: "BL2"
},
phanpy: {
randomBattleMoves: ["stealthrock","earthquake","iceshard","headsmash","knockoff","seedbomb","superpower","playrough"],
tier: "LC"
},
donphan: {
randomBattleMoves: ["stealthrock","rapidspin","iceshard","earthquake","knockoff","stoneedge","playrough"],
randomDoubleBattleMoves: ["stealthrock","seedbomb","iceshard","earthquake","rockslide","playrough","protect"],
tier: "UU"
},
stantler: {
randomBattleMoves: ["return","megahorn","jumpkick","earthquake","suckerpunch"],
randomDoubleBattleMoves: ["return","megahorn","jumpkick","earthquake","suckerpunch","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["intimidate"],"moves":["tackle","leer"]}
],
tier: "PU"
},
smeargle: {
randomBattleMoves: ["spore","spikes","stealthrock","destinybond","whirlwind","stickyweb"],
randomDoubleBattleMoves: ["spore","fakeout","wideguard","helpinghand","followme","tailwind","kingsshield","transform"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["owntempo"],"moves":["sketch"]},
{"generation":5,"level":50,"gender":"F","nature":"Jolly","abilities":["technician"],"moves":["falseswipe","spore","odorsleuth","meanlook"],"pokeball":"cherishball"}
],
tier: "BL"
},
miltank: {
randomBattleMoves: ["milkdrink","stealthrock","bodyslam","healbell","curse","earthquake","thunderwave"],
randomDoubleBattleMoves: ["protect","helpinghand","bodyslam","healbell","curse","earthquake","thunderwave"],
tier: "NU"
},
raikou: {
randomBattleMoves: ["thunderbolt","hiddenpowerice","aurasphere","calmmind","substitute","voltswitch"],
randomDoubleBattleMoves: ["thunderbolt","hiddenpowerice","aurasphere","calmmind","substitute","snarl","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["quickattack","spark","reflect","crunch"]},
{"generation":4,"level":30,"shiny":true,"nature":"Rash","moves":["zapcannon","aurasphere","extremespeed","weatherball"],"pokeball":"cherishball"}
],
unreleasedHidden: true,
tier: "OU"
},
entei: {
randomBattleMoves: ["extremespeed","flareblitz","ironhead","stoneedge","sacredfire"],
randomDoubleBattleMoves: ["extremespeed","flareblitz","ironhead","stoneedge","sacredfire","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["firespin","stomp","flamethrower","swagger"]},
{"generation":4,"level":30,"shiny":true,"nature":"Adamant","moves":["flareblitz","howl","extremespeed","crushclaw"],"pokeball":"cherishball"}
],
unreleasedHidden: true,
tier: "UU"
},
suicune: {
randomBattleMoves: ["hydropump","icebeam","scald","hiddenpowergrass","hiddenpowerelectric","rest","sleeptalk","roar","calmmind"],
randomDoubleBattleMoves: ["hydropump","icebeam","scald","hiddenpowergrass","hiddenpowerelectric","snarl","tailwind","protect","calmmind"],
eventPokemon: [
{"generation":3,"level":70,"moves":["gust","aurorabeam","mist","mirrorcoat"]},
{"generation":4,"level":30,"shiny":true,"nature":"Relaxed","moves":["sheercold","airslash","extremespeed","aquaring"],"pokeball":"cherishball"}
],
unreleasedHidden: true,
tier: "UU"
},
larvitar: {
randomBattleMoves: ["earthquake","stoneedge","facade","dragondance","superpower","crunch"],
eventPokemon: [
{"generation":3,"level":20,"moves":["sandstorm","dragondance","bite","outrage"]},
{"generation":5,"level":5,"shiny":true,"gender":"M","isHidden":false,"moves":["bite","leer","sandstorm","superpower"],"pokeball":"cherishball"}
],
tier: "LC"
},
pupitar: {
randomBattleMoves: ["earthquake","stoneedge","crunch","dragondance","superpower","stealthrock"],
tier: "NFE"
},
tyranitar: {
randomBattleMoves: ["crunch","stoneedge","pursuit","superpower","fireblast","icebeam","stealthrock"],
randomDoubleBattleMoves: ["crunch","stoneedge","rockslide","lowkick","fireblast","icebeam","stealthrock","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["thrash","scaryface","crunch","earthquake"]},
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["fireblast","icebeam","stoneedge","crunch"],"pokeball":"cherishball"},
{"generation":5,"level":55,"gender":"M","isHidden":true,"moves":["payback","crunch","earthquake","seismictoss"]},
{"generation":6,"level":50,"isHidden":false,"moves":["stoneedge","crunch","earthquake","icepunch"],"pokeball":"cherishball"},
{"generation":6,"level":50,"nature":"Jolly","isHidden":false,"moves":["rockslide","earthquake","crunch","stoneedge"],"pokeball":"cherishball"}
],
tier: "OU"
},
tyranitarmega: {
randomBattleMoves: ["crunch","stoneedge","earthquake","icepunch","dragondance"],
randomDoubleBattleMoves: ["crunch","stoneedge","earthquake","icepunch","dragondance","rockslide","protect"],
requiredItem: "Tyranitarite"
},
lugia: {
randomBattleMoves: ["toxic","roost","substitute","whirlwind","icebeam","psychic","calmmind","aeroblast"],
randomDoubleBattleMoves: ["aeroblast","roost","substitute","tailwind","icebeam","psychic","calmmind","skydrop","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["swift","raindance","hydropump","recover"]},
{"generation":3,"level":70,"moves":["recover","hydropump","raindance","swift"]},
{"generation":3,"level":50,"moves":["psychoboost","recover","hydropump","featherdance"]}
],
dreamWorldPokeball: 'dreamball',
tier: "Uber"
},
hooh: {
randomBattleMoves: ["substitute","sacredfire","bravebird","earthquake","roost","willowisp","flamecharge","tailwind"],
randomDoubleBattleMoves: ["substitute","sacredfire","bravebird","earthquake","roost","willowisp","flamecharge","tailwind","skydrop","protect"],
eventPokemon: [
{"generation":3,"level":70,"moves":["swift","sunnyday","fireblast","recover"]},
{"generation":3,"level":70,"moves":["recover","fireblast","sunnyday","swift"]}
],
dreamWorldPokeball: 'dreamball',
tier: "Uber"
},
celebi: {
randomBattleMoves: ["nastyplot","psychic","gigadrain","recover","healbell","batonpass","stealthrock","earthpower","hiddenpowerfire","hiddenpowerice","calmmind","leafstorm","uturn","thunderwave"],
randomDoubleBattleMoves: ["protect","psychic","gigadrain","recover","earthpower","hiddenpowerfire","hiddenpowerice","helpinghand","leafstorm","uturn","thunderwave"],
eventPokemon: [
{"generation":3,"level":10,"moves":["confusion","recover","healbell","safeguard"]},
{"generation":3,"level":70,"moves":["ancientpower","futuresight","batonpass","perishsong"]},
{"generation":3,"level":10,"moves":["leechseed","recover","healbell","safeguard"]},
{"generation":3,"level":30,"moves":["healbell","safeguard","ancientpower","futuresight"]},
{"generation":4,"level":50,"moves":["leafstorm","recover","nastyplot","healingwish"],"pokeball":"cherishball"},
{"generation":6,"level":10,"moves":["recover","healbell","safeguard","holdback"],"pokeball":"luxuryball"}
],
unobtainableShiny: true,
tier: "OU"
},
treecko: {
randomBattleMoves: ["substitute","leechseed","leafstorm","hiddenpowerice","hiddenpowerrock","endeavor"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["pound","leer","absorb"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["pound","leer","absorb"]}
],
tier: "LC"
},
grovyle: {
randomBattleMoves: ["substitute","leechseed","gigadrain","leafstorm","hiddenpowerice","hiddenpowerrock","endeavor"],
tier: "NFE"
},
sceptile: {
randomBattleMoves: ["substitute","gigadrain","leafstorm","hiddenpowerice","focusblast","hiddenpowerfire"],
randomDoubleBattleMoves: ["substitute","gigadrain","leafstorm","hiddenpowerice","focusblast","hiddenpowerfire","protect"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":false,"moves":["leafstorm","dragonpulse","focusblast","rockslide"],"pokeball":"cherishball"}
],
tier: "UU"
},
sceptilemega: {
randomBattleMoves: ["substitute","gigadrain","dragonpulse","focusblast","swordsdance","outrage","leafblade","earthquake","hiddenpowerfire"],
randomDoubleBattleMoves: ["substitute","gigadrain","leafstorm","hiddenpowerice","focusblast","dragonpulse","hiddenpowerfire","protect"],
requiredItem: "Sceptilite"
},
torchic: {
randomBattleMoves: ["protect","batonpass","substitute","hiddenpowergrass","swordsdance","firepledge"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["scratch","growl","focusenergy","ember"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["scratch","growl","focusenergy","ember"]},
{"generation":6,"level":10,"gender":"M","isHidden":true,"moves":["scratch","growl","focusenergy","ember"],"pokeball":"cherishball"}
],
tier: "LC"
},
combusken: {
randomBattleMoves: ["flareblitz","skyuppercut","protect","swordsdance","substitute","batonpass","shadowclaw"],
tier: "BL3"
},
blaziken: {
randomBattleMoves: ["flareblitz","highjumpkick","protect","swordsdance","substitute","batonpass","stoneedge","knockoff"],
eventPokemon: [
{"generation":3,"level":70,"moves":["blazekick","slash","mirrormove","skyuppercut"]},
{"generation":5,"level":50,"isHidden":false,"moves":["flareblitz","highjumpkick","thunderpunch","stoneedge"],"pokeball":"cherishball"}
],
tier: "Uber"
},
blazikenmega: {
randomBattleMoves: ["flareblitz","highjumpkick","protect","swordsdance","substitute","batonpass","stoneedge","knockoff"],
requiredItem: "Blazikenite"
},
mudkip: {
randomBattleMoves: ["hydropump","earthpower","hiddenpowerelectric","icebeam","sludgewave"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["tackle","growl","mudslap","watergun"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tackle","growl","mudslap","watergun"]}
],
tier: "LC"
},
marshtomp: {
randomBattleMoves: ["waterfall","earthquake","superpower","icepunch","rockslide","stealthrock"],
tier: "NFE"
},
swampert: {
randomBattleMoves: ["waterfall","earthquake","icebeam","stealthrock","roar","scald"],
randomDoubleBattleMoves: ["waterfall","earthquake","icebeam","stealthrock","wideguard","scald","rockslide","muddywater","protect","icywind"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":false,"moves":["earthquake","icebeam","hydropump","hammerarm"],"pokeball":"cherishball"}
],
tier: "UU"
},
swampertmega: {
randomBattleMoves: ["waterfall","earthquake","raindance","icepunch","superpower"],
randomDoubleBattleMoves: ["waterfall","earthquake","raindance","icepunch","superpower","protect"],
requiredItem: "Swampertite"
},
poochyena: {
randomBattleMoves: ["superfang","foulplay","suckerpunch","toxic","crunch","firefang","icefang","poisonfang"],
eventPokemon: [
{"generation":3,"level":10,"abilities":["runaway"],"moves":["healbell","dig","poisonfang","growl"]}
],
tier: "LC"
},
mightyena: {
randomBattleMoves: ["suckerpunch","crunch","playrough","firefang","taunt","irontail"],
randomDoubleBattleMoves: ["suckerpunch","crunch","playrough","firefang","taunt","protect"],
tier: "PU"
},
zigzagoon: {
randomBattleMoves: ["trick","thunderwave","icebeam","thunderbolt","gunkshot","lastresort"],
eventPokemon: [
{"generation":3,"level":5,"shiny":true,"abilities":["pickup"],"moves":["tackle","growl","tailwhip"]},
{"generation":3,"level":5,"abilities":["pickup"],"moves":["tackle","growl","extremespeed"]}
],
tier: "LC"
},
linoone: {
randomBattleMoves: ["bellydrum","extremespeed","seedbomb","substitute","shadowclaw"],
randomDoubleBattleMoves: ["bellydrum","extremespeed","seedbomb","protect","shadowclaw"],
eventPokemon: [
{"generation":6,"level":50,"isHidden":false,"moves":["extremespeed","helpinghand","babydolleyes","protect"],"pokeball":"cherishball"}
],
tier: "PU"
},
wurmple: {
randomBattleMoves: ["bugbite","poisonsting","tackle","electroweb"],
tier: "LC"
},
silcoon: {
randomBattleMoves: ["bugbite","poisonsting","tackle","electroweb"],
tier: "NFE"
},
beautifly: {
randomBattleMoves: ["quiverdance","bugbuzz","gigadrain","hiddenpowerground","psychic","substitute"],
randomDoubleBattleMoves: ["quiverdance","bugbuzz","gigadrain","hiddenpowerground","psychic","substitute","tailwind","stringshot","protect"],
tier: "PU"
},
cascoon: {
randomBattleMoves: ["bugbite","poisonsting","tackle","electroweb"],
tier: "NFE"
},
dustox: {
randomBattleMoves: ["toxic","roost","whirlwind","bugbuzz","protect","sludgebomb","quiverdance","shadowball"],
randomDoubleBattleMoves: ["tailwind","stringshot","strugglebug","bugbuzz","protect","sludgebomb","quiverdance","shadowball"],
tier: "PU"
},
lotad: {
randomBattleMoves: ["gigadrain","icebeam","scald","naturepower","raindance"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["astonish","growl","absorb"]}
],
tier: "LC"
},
lombre: {
randomBattleMoves: ["fakeout","swordsdance","waterfall","seedbomb","icepunch","firepunch","thunderpunch","poweruppunch","gigadrain","icebeam"],
tier: "NFE"
},
ludicolo: {
randomBattleMoves: ["raindance","hydropump","scald","gigadrain","icebeam","focusblast"],
randomDoubleBattleMoves: ["raindance","hydropump","surf","gigadrain","icebeam","fakeout","protect"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":false,"abilities":["swiftswim"],"moves":["fakeout","hydropump","icebeam","gigadrain"],"pokeball":"cherishball"},
{"generation":5,"level":30,"gender":"M","nature":"Calm","isHidden":false,"abilities":["swiftswim"],"moves":["scald","gigadrain","icebeam","sunnyday"]}
],
tier: "NU"
},
seedot: {
randomBattleMoves: ["defog","naturepower","seedbomb","explosion","foulplay"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["bide","harden","growth"]},
{"generation":3,"level":17,"moves":["refresh","gigadrain","bulletseed","secretpower"]}
],
tier: "LC"
},
nuzleaf: {
randomBattleMoves: ["suckerpunch","naturepower","seedbomb","explosion","swordsdance","rockslide","lowsweep"],
tier: "NFE"
},
shiftry: {
randomBattleMoves: ["leafstorm","swordsdance","leafblade","suckerpunch","defog","lowkick","knockoff"],
randomDoubleBattleMoves: ["leafstorm","swordsdance","leafblade","suckerpunch","knockoff","lowkick","fakeout","protect"],
tier: "RU"
},
taillow: {
randomBattleMoves: ["bravebird","facade","quickattack","uturn","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["peck","growl","focusenergy","featherdance"]}
],
tier: "LC"
},
swellow: {
randomBattleMoves: ["bravebird","facade","quickattack","uturn","endeavor"],
randomDoubleBattleMoves: ["bravebird","facade","quickattack","uturn","protect"],
eventPokemon: [
{"generation":3,"level":43,"moves":["batonpass","skyattack","agility","facade"]}
],
tier: "NU"
},
wingull: {
randomBattleMoves: ["scald","icebeam","tailwind","uturn","airslash","knockoff","defog"],
tier: "LC"
},
pelipper: {
randomBattleMoves: ["scald","uturn","hurricane","toxic","roost","defog","knockoff"],
randomDoubleBattleMoves: ["scald","surf","hurricane","wideguard","protect","tailwind","knockoff"],
tier: "PU"
},
ralts: {
randomBattleMoves: ["trickroom","destinybond","psychic","willowisp","hypnosis","dazzlinggleam","substitute","trick"],
eventPokemon: [
{"generation":3,"level":5,"moves":["growl","wish"]},
{"generation":3,"level":5,"moves":["growl","charm"]},
{"generation":3,"level":20,"moves":["sing","shockwave","reflect","confusion"]},
{"generation":6,"level":1,"isHidden":true,"moves":["growl","encore"]}
],
tier: "LC"
},
kirlia: {
randomBattleMoves: ["trick","dazzlinggleam","psychic","willowisp","signalbeam","thunderbolt","destinybond","substitute"],
tier: "NFE"
},
gardevoir: {
randomBattleMoves: ["psyshock","focusblast","shadowball","moonblast","calmmind","willowisp","thunderbolt","healingwish"],
randomDoubleBattleMoves: ["psyshock","focusblast","shadowball","moonblast","taunt","willowisp","thunderbolt","trickroom","helpinghand","protect","dazzlinggleam"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":false,"abilities":["trace"],"moves":["hypnosis","thunderbolt","focusblast","psychic"],"pokeball":"cherishball"}
],
tier: "OU"
},
gardevoirmega: {
randomBattleMoves: ["psyshock","focusblast","shadowball","calmmind","thunderbolt","hypervoice","healingwish"],
randomDoubleBattleMoves: ["psyshock","focusblast","shadowball","calmmind","thunderbolt","hypervoice","protect"],
requiredItem: "Gardevoirite"
},
gallade: {
randomBattleMoves: ["closecombat","trick","stoneedge","shadowsneak","drainpunch","icepunch","zenheadbutt","swordsdance","knockoff"],
randomDoubleBattleMoves: ["closecombat","trick","stoneedge","shadowsneak","drainpunch","icepunch","zenheadbutt","knockoff","trickroom","protect","helpinghand","healpulse"],
tier: "OU"
},
gallademega: {
randomBattleMoves: ["closecombat","stoneedge","drainpunch","icepunch","zenheadbutt","swordsdance","knockoff"],
randomDoubleBattleMoves: ["closecombat","stoneedge","drainpunch","icepunch","zenheadbutt","swordsdance","knockoff","protect"],
requiredItem: "Galladite"
},
surskit: {
randomBattleMoves: ["hydropump","signalbeam","hiddenpowerfire","stickyweb","gigadrain","powersplit"],
eventPokemon: [
{"generation":3,"level":5,"moves":["bubble","mudsport"]},
{"generation":3,"level":10,"gender":"M","moves":["bubble","quickattack"]}
],
tier: "LC"
},
masquerain: {
randomBattleMoves: ["hydropump","bugbuzz","airslash","quiverdance","substitute","batonpass","stickyweb","roost"],
randomDoubleBattleMoves: ["hydropump","bugbuzz","airslash","quiverdance","substitute","tailwind","stickyweb","roost","strugglebug","protect"],
tier: "PU"
},
shroomish: {
randomBattleMoves: ["spore","substitute","leechseed","gigadrain","protect","toxic","stunspore"],
eventPokemon: [
{"generation":3,"level":15,"abilities":["effectspore"],"moves":["refresh","falseswipe","megadrain","stunspore"]}
],
tier: "LC"
},
breloom: {
randomBattleMoves: ["spore","substitute","focuspunch","machpunch","bulletseed","rocktomb","swordsdance","drainpunch"],
randomDoubleBattleMoves: ["spore","helpinghand","machpunch","bulletseed","rocktomb","protect","drainpunch"],
tier: "OU"
},
slakoth: {
randomBattleMoves: ["doubleedge","hammerarm","firepunch","counter","retaliate","toxic"],
tier: "LC"
},
vigoroth: {
randomBattleMoves: ["bulkup","return","earthquake","firepunch","suckerpunch","slackoff","icepunch","lowkick"],
tier: "NFE"
},
slaking: {
randomBattleMoves: ["earthquake","pursuit","nightslash","doubleedge","retaliate"],
randomDoubleBattleMoves: ["earthquake","nightslash","doubleedge","retaliate","hammerarm","rockslide"],
eventPokemon: [
{"generation":4,"level":50,"gender":"M","nature":"Adamant","moves":["gigaimpact","return","shadowclaw","aerialace"],"pokeball":"cherishball"}
],
tier: "PU"
},
nincada: {
randomBattleMoves: ["xscissor","dig","aerialace","nightslash"],
tier: "LC"
},
ninjask: {
randomBattleMoves: ["batonpass","swordsdance","substitute","protect","xscissor"],
randomDoubleBattleMoves: ["batonpass","swordsdance","substitute","protect","xscissor","aerialace"],
tier: "PU"
},
shedinja: {
randomBattleMoves: ["swordsdance","willowisp","xscissor","shadowsneak","shadowclaw","protect"],
eventPokemon: [
{"generation":3,"level":50,"moves":["spite","confuseray","shadowball","grudge"]},
{"generation":3,"level":20,"moves":["doubleteam","furycutter","screech"]},
{"generation":3,"level":25,"moves":["swordsdance"]},
{"generation":3,"level":31,"moves":["slash"]},
{"generation":3,"level":38,"moves":["agility"]},
{"generation":3,"level":45,"moves":["batonpass"]},
{"generation":4,"level":52,"moves":["xscissor"]}
],
tier: "PU"
},
whismur: {
randomBattleMoves: ["hypervoice","fireblast","shadowball","icebeam","extrasensory"],
eventPokemon: [
{"generation":3,"level":5,"moves":["pound","uproar","teeterdance"]}
],
tier: "LC"
},
loudred: {
randomBattleMoves: ["hypervoice","fireblast","shadowball","icebeam","circlethrow","bodyslam"],
tier: "NFE"
},
exploud: {
randomBattleMoves: ["boomburst","fireblast","icebeam","surf","focusblast"],
randomDoubleBattleMoves: ["boomburst","fireblast","icebeam","surf","focusblast","protect","hypervoice"],
eventPokemon: [
{"generation":3,"level":100,"moves":["roar","rest","sleeptalk","hypervoice"]},
{"generation":3,"level":50,"moves":["stomp","screech","hyperbeam","roar"]}
],
tier: "RU"
},
makuhita: {
randomBattleMoves: ["crosschop","bulletpunch","closecombat","icepunch","bulkup","fakeout","earthquake"],
eventPokemon: [
{"generation":3,"level":18,"moves":["refresh","brickbreak","armthrust","rocktomb"]}
],
tier: "LC"
},
hariyama: {
randomBattleMoves: ["bulletpunch","closecombat","icepunch","stoneedge","bulkup","earthquake","knockoff"],
randomDoubleBattleMoves: ["bulletpunch","closecombat","icepunch","stoneedge","fakeout","knockoff","helpinghand","wideguard","protect"],
tier: "NU"
},
nosepass: {
randomBattleMoves: ["powergem","thunderwave","stealthrock","painsplit","explosion","voltswitch"],
eventPokemon: [
{"generation":3,"level":26,"moves":["helpinghand","thunderbolt","thunderwave","rockslide"]}
],
tier: "LC"
},
probopass: {
randomBattleMoves: ["stealthrock","thunderwave","toxic","earthpower","powergem","voltswitch","painsplit"],
randomDoubleBattleMoves: ["stealthrock","thunderwave","helpinghand","earthpower","powergem","wideguard","protect","voltswitch"],
tier: "PU"
},
skitty: {
randomBattleMoves: ["doubleedge","zenheadbutt","thunderwave","fakeout","playrough","healbell"],
eventPokemon: [
{"generation":3,"level":5,"abilities":["cutecharm"],"moves":["tackle","growl","tailwhip","payday"]},
{"generation":3,"level":5,"abilities":["cutecharm"],"moves":["growl","tackle","tailwhip","rollout"]},
{"generation":3,"level":10,"gender":"M","abilities":["cutecharm"],"moves":["growl","tackle","tailwhip","attract"]}
],
tier: "LC"
},
delcatty: {
randomBattleMoves: ["doubleedge","suckerpunch","playrough","wildcharge","fakeout","thunderwave","wish","healbell"],
randomDoubleBattleMoves: ["doubleedge","suckerpunch","playrough","wildcharge","fakeout","thunderwave","protect","helpinghand"],
eventPokemon: [
{"generation":3,"level":18,"abilities":["cutecharm"],"moves":["sweetkiss","secretpower","attract","shockwave"]}
],
tier: "PU"
},
sableye: {
randomBattleMoves: ["recover","willowisp","taunt","toxic","knockoff","foulplay"],
randomDoubleBattleMoves: ["recover","willowisp","taunt","fakeout","knockoff","foulplay","feint","helpinghand","snarl","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","abilities":["keeneye"],"moves":["leer","scratch","foresight","nightshade"]},
{"generation":3,"level":33,"abilities":["keeneye"],"moves":["helpinghand","shadowball","feintattack","recover"]},
{"generation":5,"level":50,"gender":"M","isHidden":true,"moves":["foulplay","octazooka","tickle","trick"],"pokeball":"cherishball"}
],
tier: "OU"
},
sableyemega: {
randomBattleMoves: ["recover","willowisp","darkpulse","calmmind","shadowball"],
randomDoubleBattleMoves: ["fakeout","knockoff","darkpulse","shadowball","willowisp","protect"],
requiredItem: "Sablenite"
},
mawile: {
randomBattleMoves: ["swordsdance","ironhead","substitute","playrough","suckerpunch","painsplit"],
randomDoubleBattleMoves: ["swordsdance","ironhead","firefang","substitute","playrough","suckerpunch","knockoff","protect"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["astonish","faketears"]},
{"generation":3,"level":22,"moves":["sing","falseswipe","vicegrip","irondefense"]},
{"generation":6,"level":50,"isHidden":false,"abilities":["intimidate"],"moves":["ironhead","playrough","firefang","suckerpunch"],"pokeball":"cherishball"}
],
tier: "NU"
},
mawilemega: {
randomBattleMoves: ["swordsdance","ironhead","firefang","substitute","playrough","suckerpunch","knockoff","focuspunch"],
randomDoubleBattleMoves: ["swordsdance","ironhead","firefang","substitute","playrough","suckerpunch","knockoff","protect"],
requiredItem: "Mawilite",
tier: "Uber"
},
aron: {
randomBattleMoves: ["headsmash","ironhead","earthquake","superpower","stealthrock","endeavor"],
tier: "LC"
},
lairon: {
randomBattleMoves: ["headsmash","ironhead","earthquake","superpower","stealthrock"],
tier: "NFE"
},
aggron: {
randomBattleMoves: ["autotomize","headsmash","earthquake","lowkick","heavyslam","aquatail","stealthrock"],
randomDoubleBattleMoves: ["rockslide","headsmash","earthquake","lowkick","heavyslam","aquatail","stealthrock","protect"],
eventPokemon: [
{"generation":3,"level":100,"moves":["irontail","protect","metalsound","doubleedge"]},
{"generation":3,"level":50,"moves":["takedown","irontail","protect","metalsound"]},
{"generation":6,"level":50,"nature":"Brave","isHidden":false,"abilities":["rockhead"],"moves":["ironhead","earthquake","headsmash","rockslide"],"pokeball":"cherishball"}
],
tier: "UU"
},
aggronmega: {
randomBattleMoves: ["earthquake","heavyslam","icepunch","stealthrock","thunderwave","roar","toxic"],
randomDoubleBattleMoves: ["rockslide","earthquake","lowkick","heavyslam","aquatail","protect"],
requiredItem: "Aggronite"
},
meditite: {
randomBattleMoves: ["highjumpkick","psychocut","icepunch","thunderpunch","trick","fakeout","bulletpunch","drainpunch","zenheadbutt"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["bide","meditate","confusion"]},
{"generation":3,"level":20,"moves":["dynamicpunch","confusion","shadowball","detect"]}
],
tier: "LC Uber"
},
medicham: {
randomBattleMoves: ["highjumpkick","drainpunch","zenheadbutt","icepunch","bulletpunch"],
randomDoubleBattleMoves: ["highjumpkick","drainpunch","zenheadbutt","icepunch","bulletpunch","protect","fakeout"],
tier: "UU"
},
medichammega: {
randomBattleMoves: ["highjumpkick","drainpunch","icepunch","bulletpunch","zenheadbutt","firepunch"],
randomDoubleBattleMoves: ["highjumpkick","drainpunch","zenheadbutt","icepunch","bulletpunch","protect","fakeout"],
requiredItem: "Medichamite",
tier: "BL"
},
electrike: {
randomBattleMoves: ["voltswitch","thunderbolt","hiddenpowerice","switcheroo","flamethrower","hiddenpowergrass"],
tier: "LC"
},
manectric: {
randomBattleMoves: ["voltswitch","thunderbolt","hiddenpowerice","hiddenpowergrass","overheat","flamethrower"],
randomDoubleBattleMoves: ["voltswitch","thunderbolt","hiddenpowerice","hiddenpowergrass","overheat","flamethrower","snarl","protect"],
eventPokemon: [
{"generation":3,"level":44,"moves":["refresh","thunder","raindance","bite"]},
{"generation":6,"level":50,"nature":"Timid","isHidden":false,"abilities":["lightningrod"],"moves":["overheat","thunderbolt","voltswitch","protect"],"pokeball":"cherishball"}
],
tier: "OU"
},
manectricmega: {
randomBattleMoves: ["voltswitch","thunderbolt","hiddenpowerice","hiddenpowergrass","overheat","flamethrower"],
randomDoubleBattleMoves: ["voltswitch","thunderbolt","hiddenpowerice","hiddenpowergrass","overheat","flamethrower","snarl","protect"],
requiredItem: "Manectite"
},
plusle: {
randomBattleMoves: ["nastyplot","thunderbolt","substitute","batonpass","hiddenpowerice","encore"],
randomDoubleBattleMoves: ["nastyplot","thunderbolt","substitute","protect","hiddenpowerice","encore","helpinghand"],
eventPokemon: [
{"generation":3,"level":5,"moves":["growl","thunderwave","mudsport"]},
{"generation":3,"level":10,"gender":"M","moves":["growl","thunderwave","quickattack"]}
],
tier: "PU"
},
minun: {
randomBattleMoves: ["nastyplot","thunderbolt","substitute","batonpass","hiddenpowerice","encore"],
randomDoubleBattleMoves: ["nastyplot","thunderbolt","substitute","protect","hiddenpowerice","encore","helpinghand"],
eventPokemon: [
{"generation":3,"level":5,"moves":["growl","thunderwave","watersport"]},
{"generation":3,"level":10,"gender":"M","moves":["growl","thunderwave","quickattack"]}
],
tier: "PU"
},
volbeat: {
randomBattleMoves: ["tailglow","batonpass","substitute","bugbuzz","thunderwave","encore","tailwind"],
randomDoubleBattleMoves: ["stringshot","strugglebug","helpinghand","bugbuzz","thunderwave","encore","tailwind","protect"],
tier: "PU"
},
illumise: {
randomBattleMoves: ["substitute","batonpass","wish","bugbuzz","encore","thunderbolt","tailwind","uturn","thunderwave"],
randomDoubleBattleMoves: ["protect","helpinghand","bugbuzz","encore","thunderbolt","tailwind","uturn"],
tier: "PU"
},
budew: {
randomBattleMoves: ["spikes","sludgebomb","sleeppowder","gigadrain","stunspore","rest"],
tier: "LC"
},
roselia: {
randomBattleMoves: ["spikes","toxicspikes","sleeppowder","gigadrain","stunspore","rest","sludgebomb","synthesis"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["absorb","growth","poisonsting"]},
{"generation":3,"level":22,"moves":["sweetkiss","magicalleaf","leechseed","grasswhistle"]}
],
tier: "PU"
},
roserade: {
randomBattleMoves: ["sludgebomb","gigadrain","sleeppowder","leafstorm","spikes","toxicspikes","rest","synthesis","hiddenpowerfire"],
randomDoubleBattleMoves: ["sludgebomb","gigadrain","sleeppowder","leafstorm","protect","hiddenpowerfire"],
tier: "UU"
},
gulpin: {
randomBattleMoves: ["stockpile","sludgebomb","sludgewave","icebeam","toxic","painsplit","yawn","encore"],
eventPokemon: [
{"generation":3,"level":17,"moves":["sing","shockwave","sludge","toxic"]}
],
tier: "LC"
},
swalot: {
randomBattleMoves: ["sludgebomb","icebeam","toxic","yawn","encore","painsplit","earthquake"],
randomDoubleBattleMoves: ["sludgebomb","icebeam","protect","yawn","encore","gunkshot","earthquake"],
tier: "PU"
},
carvanha: {
randomBattleMoves: ["protect","hydropump","surf","icebeam","waterfall","crunch","aquajet","destinybond"],
eventPokemon: [
{"generation":3,"level":15,"moves":["refresh","waterpulse","bite","scaryface"]},
{"generation":6,"level":1,"isHidden":true,"moves":["leer","bite","hydropump"]}
],
tier: "LC"
},
sharpedo: {
randomBattleMoves: ["protect","icebeam","crunch","earthquake","waterfall","aquajet","destinybond","zenheadbutt"],
randomDoubleBattleMoves: ["protect","hydropump","surf","icebeam","crunch","earthquake","waterfall","darkpulse","destinybond"],
tier: "UU"
},
sharpedomega: {
randomBattleMoves: ["protect","icefang","crunch","earthquake","waterfall","zenheadbutt"],
requiredItem: "Sharpedonite"
},
wailmer: {
randomBattleMoves: ["waterspout","surf","hydropump","icebeam","hiddenpowergrass","hiddenpowerelectric"],
tier: "LC"
},
wailord: {
randomBattleMoves: ["waterspout","hydropump","icebeam","hiddenpowergrass","hiddenpowerfire"],
randomDoubleBattleMoves: ["waterspout","hydropump","icebeam","hiddenpowergrass","hiddenpowerfire","protect"],
eventPokemon: [
{"generation":3,"level":100,"moves":["rest","waterspout","amnesia","hydropump"]},
{"generation":3,"level":50,"moves":["waterpulse","mist","rest","waterspout"]}
],
tier: "PU"
},
numel: {
randomBattleMoves: ["curse","earthquake","rockslide","fireblast","flamecharge","rest","sleeptalk","stockpile","hiddenpowerelectric","earthpower","lavaplume"],
eventPokemon: [
{"generation":3,"level":14,"abilities":["oblivious"],"moves":["charm","takedown","dig","ember"]},
{"generation":6,"level":1,"isHidden":false,"moves":["growl","tackle","ironhead"]}
],
tier: "LC"
},
camerupt: {
randomBattleMoves: ["rockpolish","fireblast","earthpower","lavaplume","stealthrock","hiddenpowergrass","roar"],
randomDoubleBattleMoves: ["rockpolish","fireblast","earthpower","heatwave","eruption","hiddenpowergrass","protect"],
tier: "NU"
},
cameruptmega: {
randomBattleMoves: ["stealthrock","fireblast","earthpower","rockslide","flashcannon"],
randomDoubleBattleMoves: ["fireblast","earthpower","heatwave","eruption","rockslide","protect"],
requiredItem: "Cameruptite"
},
torkoal: {
randomBattleMoves: ["rapidspin","stealthrock","yawn","lavaplume","earthpower","toxic","willowisp","shellsmash","fireblast"],
randomDoubleBattleMoves: ["protect","heatwave","earthpower","willowisp","shellsmash","fireblast","hiddenpowergrass"],
tier: "PU"
},
spoink: {
randomBattleMoves: ["psychic","reflect","lightscreen","thunderwave","trick","healbell","calmmind","hiddenpowerfighting","shadowball"],
eventPokemon: [
{"generation":3,"level":5,"abilities":["owntempo"],"moves":["splash","uproar"]}
],
tier: "LC"
},
grumpig: {
randomBattleMoves: ["psychic","psyshock","thunderwave","healbell","whirlwind","toxic","focusblast","reflect","lightscreen"],
randomDoubleBattleMoves: ["psychic","psyshock","thunderwave","trickroom","taunt","protect","focusblast","reflect","lightscreen"],
tier: "PU"
},
spinda: {
randomBattleMoves: ["doubleedge","return","superpower","suckerpunch","trickroom"],
randomDoubleBattleMoves: ["doubleedge","return","superpower","suckerpunch","trickroom","fakeout","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["tackle","uproar","sing"]}
],
tier: "PU"
},
trapinch: {
randomBattleMoves: ["earthquake","rockslide","crunch","quickattack","superpower"],
eventPokemon: [
{"generation":5,"level":1,"shiny":true,"isHidden":false,"moves":["bite"]}
],
tier: "LC"
},
vibrava: {
randomBattleMoves: ["substitute","earthquake","outrage","roost","uturn","superpower","defog"],
tier: "NFE"
},
flygon: {
randomBattleMoves: ["earthquake","outrage","dragonclaw","uturn","roost","stoneedge","firepunch","fireblast","defog"],
randomDoubleBattleMoves: ["earthquake","protect","dragonclaw","uturn","rockslide","firepunch","fireblast","tailwind","feint"],
eventPokemon: [
{"generation":3,"level":45,"moves":["sandtomb","crunch","dragonbreath","screech"]},
{"generation":4,"level":50,"gender":"M","nature":"Naive","moves":["dracometeor","uturn","earthquake","dragonclaw"],"pokeball":"cherishball"}
],
tier: "UU"
},
cacnea: {
randomBattleMoves: ["swordsdance","spikes","suckerpunch","seedbomb","drainpunch"],
eventPokemon: [
{"generation":3,"level":5,"moves":["poisonsting","leer","absorb","encore"]}
],
tier: "LC"
},
cacturne: {
randomBattleMoves: ["swordsdance","spikes","suckerpunch","seedbomb","drainpunch","substitute","focuspunch","destinybond"],
randomDoubleBattleMoves: ["darkpulse","spikyshield","suckerpunch","seedbomb","drainpunch","gigadrain"],
eventPokemon: [
{"generation":3,"level":45,"moves":["ingrain","feintattack","spikes","needlearm"]}
],
tier: "NU"
},
swablu: {
randomBattleMoves: ["roost","toxic","cottonguard","pluck","hypervoice","return"],
eventPokemon: [
{"generation":3,"level":5,"moves":["peck","growl","falseswipe"]},
{"generation":5,"level":1,"shiny":true,"isHidden":false,"moves":["peck","growl"]},
{"generation":6,"level":1,"isHidden":true,"moves":["peck","growl","hypervoice"]}
],
tier: "LC"
},
altaria: {
randomBattleMoves: ["dragondance","dracometeor","outrage","dragonclaw","earthquake","roost","fireblast","healbell"],
randomDoubleBattleMoves: ["dragondance","dracometeor","protect","dragonclaw","earthquake","fireblast","tailwind"],
eventPokemon: [
{"generation":3,"level":45,"moves":["takedown","dragonbreath","dragondance","refresh"]},
{"generation":3,"level":36,"moves":["healbell","dragonbreath","solarbeam","aerialace"]},
{"generation":5,"level":35,"gender":"M","isHidden":true,"moves":["takedown","naturalgift","dragonbreath","falseswipe"]}
],
tier: "OU"
},
altariamega: {
randomBattleMoves: ["dragondance","return","outrage","dragonclaw","earthquake","roost","dracometeor","fireblast"],
randomDoubleBattleMoves: ["dragondance","return","doubleedge","dragonclaw","earthquake","protect","fireblast"],
requiredItem: "Altarianite"
},
zangoose: {
randomBattleMoves: ["swordsdance","closecombat","knockoff","quickattack","facade"],
randomDoubleBattleMoves: ["protect","closecombat","knockoff","quickattack","facade"],
eventPokemon: [
{"generation":3,"level":18,"moves":["leer","quickattack","swordsdance","furycutter"]},
{"generation":3,"level":10,"gender":"M","moves":["scratch","leer","quickattack","swordsdance"]},
{"generation":3,"level":28,"moves":["refresh","brickbreak","counter","crushclaw"]}
],
tier: "NU"
},
seviper: {
randomBattleMoves: ["flamethrower","gigadrain","earthquake","suckerpunch","aquatail","coil","glare","poisonjab","sludgewave"],
randomDoubleBattleMoves: ["flamethrower","gigadrain","earthquake","suckerpunch","aquatail","protect","glare","poisonjab","sludgewave"],
eventPokemon: [
{"generation":3,"level":18,"moves":["wrap","lick","bite","poisontail"]},
{"generation":3,"level":30,"moves":["poisontail","screech","glare","crunch"]},
{"generation":3,"level":10,"gender":"M","moves":["wrap","lick","bite"]}
],
tier: "PU"
},
lunatone: {
randomBattleMoves: ["psychic","earthpower","stealthrock","rockpolish","batonpass","calmmind","icebeam","hiddenpowerrock","moonlight","trickroom","explosion"],
randomDoubleBattleMoves: ["psychic","earthpower","rockpolish","calmmind","helpinghand","icebeam","hiddenpowerrock","moonlight","trickroom","protect"],
eventPokemon: [
{"generation":3,"level":10,"moves":["tackle","harden","confusion"]},
{"generation":3,"level":25,"moves":["batonpass","psychic","raindance","rocktomb"]}
],
tier: "PU"
},
solrock: {
randomBattleMoves: ["stealthrock","explosion","stoneedge","zenheadbutt","willowisp","morningsun","earthquake"],
randomDoubleBattleMoves: ["protect","helpinghand","stoneedge","zenheadbutt","willowisp","trickroom","rockslide"],
eventPokemon: [
{"generation":3,"level":10,"moves":["tackle","harden","confusion"]},
{"generation":3,"level":41,"moves":["batonpass","psychic","sunnyday","cosmicpower"]}
],
tier: "PU"
},
barboach: {
randomBattleMoves: ["dragondance","waterfall","earthquake","return","bounce"],
tier: "LC"
},
whiscash: {
randomBattleMoves: ["dragondance","waterfall","earthquake","stoneedge","zenheadbutt"],
randomDoubleBattleMoves: ["dragondance","waterfall","earthquake","stoneedge","zenheadbutt","protect"],
eventPokemon: [
{"generation":4,"level":51,"gender":"F","nature":"Gentle","abilities":["oblivious"],"moves":["earthquake","aquatail","zenheadbutt","gigaimpact"],"pokeball":"cherishball"}
],
tier: "PU"
},
corphish: {
randomBattleMoves: ["dragondance","waterfall","crunch","superpower","swordsdance","knockoff","aquajet"],
eventPokemon: [
{"generation":3,"level":5,"moves":["bubble","watersport"]}
],
tier: "LC"
},
crawdaunt: {
randomBattleMoves: ["dragondance","crabhammer","superpower","swordsdance","knockoff","aquajet"],
randomDoubleBattleMoves: ["dragondance","crabhammer","crunch","superpower","swordsdance","knockoff","aquajet","protect"],
eventPokemon: [
{"generation":3,"level":100,"moves":["taunt","crabhammer","swordsdance","guillotine"]},
{"generation":3,"level":50,"moves":["knockoff","taunt","crabhammer","swordsdance"]}
],
tier: "BL"
},
baltoy: {
randomBattleMoves: ["stealthrock","earthquake","toxic","psychic","reflect","lightscreen","icebeam","rapidspin"],
eventPokemon: [
{"generation":3,"level":17,"moves":["refresh","rocktomb","mudslap","psybeam"]}
],
tier: "LC"
},
claydol: {
randomBattleMoves: ["stealthrock","toxic","psychic","icebeam","earthquake","rapidspin"],
randomDoubleBattleMoves: ["earthpower","trickroom","psychic","icebeam","earthquake","protect"],
tier: "NU"
},
lileep: {
randomBattleMoves: ["stealthrock","recover","ancientpower","hiddenpowerfire","gigadrain","stockpile"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"moves":["recover","rockslide","constrict","acid"],"pokeball":"cherishball"}
],
tier: "LC"
},
cradily: {
randomBattleMoves: ["stealthrock","recover","seedbomb","rockslide","earthquake","curse","swordsdance"],
randomDoubleBattleMoves: ["protect","recover","seedbomb","rockslide","earthquake","curse","swordsdance"],
tier: "NU"
},
anorith: {
randomBattleMoves: ["stealthrock","brickbreak","toxic","xscissor","rockslide","swordsdance","rockpolish"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"moves":["harden","mudsport","watergun","crosspoison"],"pokeball":"cherishball"}
],
tier: "LC"
},
armaldo: {
randomBattleMoves: ["stealthrock","stoneedge","toxic","xscissor","swordsdance","knockoff","rapidspin"],
randomDoubleBattleMoves: ["rockslide","stoneedge","stringshot","xscissor","swordsdance","knockoff","protect"],
tier: "PU"
},
feebas: {
randomBattleMoves: ["protect","confuseray","hypnosis","scald","toxic"],
tier: "LC"
},
milotic: {
randomBattleMoves: ["recover","scald","toxic","icebeam","dragontail","rest","sleeptalk","hiddenpowergrass"],
randomDoubleBattleMoves: ["recover","scald","hydropump","icebeam","dragontail","hypnosis","protect","hiddenpowergrass"],
eventPokemon: [
{"generation":3,"level":35,"moves":["waterpulse","twister","recover","raindance"]},
{"generation":4,"level":50,"gender":"F","nature":"Bold","moves":["recover","raindance","icebeam","hydropump"],"pokeball":"cherishball"},
{"generation":4,"level":50,"shiny":true,"gender":"M","nature":"Timid","moves":["raindance","recover","hydropump","icywind"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["recover","hydropump","icebeam","mirrorcoat"],"pokeball":"cherishball"},
{"generation":5,"level":58,"gender":"M","nature":"Lax","isHidden":false,"moves":["recover","surf","icebeam","toxic"],"pokeball":"cherishball"}
],
tier: "UU"
},
castform: {
randomBattleMoves: ["sunnyday","raindance","fireblast","hydropump","thunder","icebeam","solarbeam","weatherball","hurricane"],
randomDoubleBattleMoves: ["sunnyday","raindance","fireblast","hydropump","thunder","icebeam","solarbeam","weatherball","hurricane","protect"],
tier: "PU"
},
kecleon: {
randomBattleMoves: ["drainpunch","toxic","stealthrock","recover","return","thunderwave","suckerpunch","shadowsneak","knockoff"],
randomDoubleBattleMoves: ["knockoff","fakeout","trickroom","recover","return","thunderwave","suckerpunch","shadowsneak","protect","feint"],
tier: "PU"
},
shuppet: {
randomBattleMoves: ["trickroom","destinybond","taunt","shadowsneak","suckerpunch","willowisp"],
eventPokemon: [
{"generation":3,"level":45,"abilities":["insomnia"],"moves":["spite","willowisp","feintattack","shadowball"]}
],
tier: "LC"
},
banette: {
randomBattleMoves: ["destinybond","taunt","shadowclaw","suckerpunch","willowisp","shadowsneak","knockoff"],
randomDoubleBattleMoves: ["destinybond","taunt","shadowclaw","suckerpunch","willowisp","shadowsneak","knockoff","protect"],
eventPokemon: [
{"generation":3,"level":37,"abilities":["insomnia"],"moves":["helpinghand","feintattack","shadowball","curse"]},
{"generation":5,"level":37,"gender":"F","isHidden":true,"moves":["feintattack","hex","shadowball","cottonguard"]}
],
tier: "RU"
},
banettemega: {
randomBattleMoves: ["destinybond","taunt","shadowclaw","suckerpunch","willowisp","shadowsneak","knockoff"],
randomDoubleBattleMoves: ["destinybond","taunt","shadowclaw","suckerpunch","willowisp","shadowsneak","knockoff","protect"],
requiredItem: "Banettite"
},
duskull: {
randomBattleMoves: ["willowisp","shadowsneak","icebeam","painsplit","substitute","nightshade"],
eventPokemon: [
{"generation":3,"level":45,"moves":["pursuit","curse","willowisp","meanlook"]},
{"generation":3,"level":19,"moves":["helpinghand","shadowball","astonish","confuseray"]}
],
tier: "LC"
},
dusclops: {
randomBattleMoves: ["willowisp","shadowsneak","icebeam","painsplit","substitute","seismictoss","toxic","trickroom"],
tier: "NFE"
},
dusknoir: {
randomBattleMoves: ["willowisp","shadowsneak","icepunch","painsplit","substitute","earthquake","focuspunch","trickroom"],
randomDoubleBattleMoves: ["willowisp","shadowsneak","icepunch","painsplit","protect","earthquake","helpinghand","trickroom"],
tier: "PU"
},
tropius: {
randomBattleMoves: ["leechseed","substitute","airslash","gigadrain","toxic","protect"],
randomDoubleBattleMoves: ["leechseed","protect","airslash","gigadrain","earthquake","hiddenpowerfire","tailwind","sunnyday","roost"],
eventPokemon: [
{"generation":4,"level":53,"gender":"F","nature":"Jolly","abilities":["chlorophyll"],"moves":["airslash","synthesis","sunnyday","solarbeam"],"pokeball":"cherishball"}
],
tier: "PU"
},
chingling: {
randomBattleMoves: ["hypnosis","reflect","lightscreen","toxic","recover","psychic","signalbeam","healbell"],
tier: "LC"
},
chimecho: {
randomBattleMoves: ["toxic","psychic","thunderwave","recover","calmmind","shadowball","dazzlinggleam","healingwish","healbell","taunt"],
randomDoubleBattleMoves: ["protect","psychic","thunderwave","recover","shadowball","dazzlinggleam","trickroom","helpinghand","taunt"],
eventPokemon: [
{"generation":3,"level":10,"gender":"M","moves":["wrap","growl","astonish"]}
],
tier: "PU"
},
absol: {
randomBattleMoves: ["swordsdance","suckerpunch","knockoff","superpower","pursuit","playrough"],
randomDoubleBattleMoves: ["swordsdance","suckerpunch","knockoff","fireblast","superpower","protect","playrough"],
eventPokemon: [
{"generation":3,"level":5,"abilities":["pressure"],"moves":["scratch","leer","wish"]},
{"generation":3,"level":5,"abilities":["pressure"],"moves":["scratch","leer","spite"]},
{"generation":3,"level":35,"abilities":["pressure"],"moves":["razorwind","bite","swordsdance","spite"]},
{"generation":3,"level":70,"abilities":["pressure"],"moves":["doubleteam","slash","futuresight","perishsong"]}
],
tier: "UU"
},
absolmega: {
randomBattleMoves: ["swordsdance","suckerpunch","knockoff","fireblast","superpower","pursuit","playrough","icebeam"],
randomDoubleBattleMoves: ["swordsdance","suckerpunch","knockoff","fireblast","superpower","protect","playrough"],
requiredItem: "Absolite"
},
snorunt: {
randomBattleMoves: ["spikes","icebeam","hiddenpowerground","iceshard","crunch","switcheroo"],
eventPokemon: [
{"generation":3,"level":22,"abilities":["innerfocus"],"moves":["sing","waterpulse","bite","icywind"]}
],
tier: "LC"
},
glalie: {
randomBattleMoves: ["spikes","icebeam","iceshard","taunt","earthquake","explosion"],
randomDoubleBattleMoves: ["icebeam","iceshard","taunt","earthquake","protect","encore"],
tier: "RU"
},
glaliemega: {
randomBattleMoves: ["crunch","iceshard","taunt","earthquake","explosion","return","spikes"],
randomDoubleBattleMoves: ["crunch","iceshard","taunt","earthquake","explosion","protect","encore","return"],
requiredItem: "Glalitite"
},
froslass: {
randomBattleMoves: ["icebeam","spikes","destinybond","shadowball","taunt","thunderwave"],
randomDoubleBattleMoves: ["icebeam","protect","destinybond","shadowball","taunt","thunderwave"],
tier: "BL2"
},
spheal: {
randomBattleMoves: ["substitute","protect","toxic","surf","icebeam","yawn","superfang"],
eventPokemon: [
{"generation":3,"level":17,"abilities":["thickfat"],"moves":["charm","aurorabeam","watergun","mudslap"]}
],
tier: "LC"
},
sealeo: {
randomBattleMoves: ["substitute","protect","toxic","surf","icebeam","yawn","superfang"],
tier: "NFE"
},
walrein: {
randomBattleMoves: ["substitute","protect","toxic","surf","icebeam","roar"],
randomDoubleBattleMoves: ["hydropump","protect","icywind","surf","icebeam"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":false,"abilities":["thickfat"],"moves":["icebeam","surf","hail","sheercold"],"pokeball":"cherishball"}
],
tier: "PU"
},
clamperl: {
randomBattleMoves: ["shellsmash","icebeam","surf","hiddenpowergrass","hiddenpowerelectric","substitute"],
tier: "LC"
},
huntail: {
randomBattleMoves: ["shellsmash","waterfall","icebeam","batonpass","suckerpunch"],
randomDoubleBattleMoves: ["shellsmash","return","hydropump","batonpass","suckerpunch","protect"],
tier: "PU"
},
gorebyss: {
randomBattleMoves: ["shellsmash","batonpass","hydropump","icebeam","hiddenpowergrass","substitute"],
randomDoubleBattleMoves: ["shellsmash","batonpass","surf","icebeam","hiddenpowergrass","substitute","protect"],
tier: "NU"
},
relicanth: {
randomBattleMoves: ["headsmash","waterfall","earthquake","doubleedge","stealthrock","toxic"],
randomDoubleBattleMoves: ["headsmash","waterfall","earthquake","doubleedge","rockslide","protect"],
tier: "PU"
},
luvdisc: {
randomBattleMoves: ["surf","icebeam","toxic","sweetkiss","protect","scald"],
tier: "PU"
},
bagon: {
randomBattleMoves: ["outrage","dragondance","firefang","rockslide","dragonclaw"],
eventPokemon: [
{"generation":3,"level":5,"moves":["rage","bite","wish"]},
{"generation":3,"level":5,"moves":["rage","bite","irondefense"]},
{"generation":5,"level":1,"shiny":true,"isHidden":false,"moves":["rage"]},
{"generation":6,"level":1,"isHidden":false,"moves":["rage","thrash"]}
],
tier: "LC"
},
shelgon: {
randomBattleMoves: ["outrage","brickbreak","dragonclaw","dragondance","crunch","zenheadbutt"],
tier: "NFE"
},
salamence: {
randomBattleMoves: ["outrage","fireblast","earthquake","dracometeor","roost","dragondance","dragonclaw","hydropump","stoneedge"],
randomDoubleBattleMoves: ["protect","fireblast","earthquake","dracometeor","tailwind","dragondance","dragonclaw","hydropump","rockslide"],
eventPokemon: [
{"generation":3,"level":50,"moves":["protect","dragonbreath","scaryface","fly"]},
{"generation":3,"level":50,"moves":["refresh","dragonclaw","dragondance","aerialace"]},
{"generation":4,"level":50,"gender":"M","nature":"Naughty","moves":["hydropump","stoneedge","fireblast","dragonclaw"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["dragondance","dragonclaw","outrage","aerialace"],"pokeball":"cherishball"}
],
tier: "UU"
},
salamencemega: {
randomBattleMoves: ["doubleedge","return","fireblast","earthquake","dracometeor","roost","dragondance","dragonclaw"],
randomDoubleBattleMoves: ["doubleedge","return","fireblast","earthquake","dracometeor","protect","dragondance","dragonclaw"],
requiredItem: "Salamencite",
tier: "Uber"
},
beldum: {
randomBattleMoves: ["ironhead","zenheadbutt","headbutt","irondefense"],
eventPokemon: [
{"generation":6,"level":5,"shiny":true,"isHidden":false,"moves":["holdback","ironhead","zenheadbutt","irondefense"],"pokeball":"cherishball"}
],
tier: "LC"
},
metang: {
randomBattleMoves: ["stealthrock","meteormash","toxic","earthquake","bulletpunch","zenheadbutt"],
eventPokemon: [
{"generation":3,"level":30,"moves":["takedown","confusion","metalclaw","refresh"]}
],
tier: "NFE"
},
metagross: {
randomBattleMoves: ["meteormash","earthquake","agility","stealthrock","zenheadbutt","bulletpunch","thunderpunch","explosion","icepunch"],
randomDoubleBattleMoves: ["meteormash","earthquake","protect","zenheadbutt","bulletpunch","thunderpunch","explosion","icepunch","hammerarm"],
eventPokemon: [
{"generation":4,"level":62,"nature":"Brave","moves":["bulletpunch","meteormash","hammerarm","zenheadbutt"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["meteormash","earthquake","bulletpunch","hammerarm"],"pokeball":"cherishball"},
{"generation":5,"level":100,"isHidden":false,"moves":["bulletpunch","zenheadbutt","hammerarm","icepunch"],"pokeball":"cherishball"},
{"generation":5,"level":45,"isHidden":false,"moves":["earthquake","zenheadbutt","protect","meteormash"]},
{"generation":5,"level":45,"isHidden":true,"moves":["irondefense","agility","hammerarm","doubleedge"]},
{"generation":5,"level":45,"isHidden":true,"moves":["psychic","meteormash","hammerarm","doubleedge"]},
{"generation":5,"level":58,"nature":"Serious","isHidden":false,"moves":["earthquake","hyperbeam","psychic","meteormash"],"pokeball":"cherishball"}
],
tier: "OU"
},
metagrossmega: {
randomBattleMoves: ["meteormash","earthquake","agility","zenheadbutt","thunderpunch","icepunch"],
randomDoubleBattleMoves: ["meteormash","earthquake","protect","zenheadbutt","thunderpunch","icepunch"],
requiredItem: "Metagrossite"
},
regirock: {
randomBattleMoves: ["stealthrock","thunderwave","stoneedge","drainpunch","curse","rest","sleeptalk","rockslide","toxic"],
randomDoubleBattleMoves: ["stealthrock","thunderwave","stoneedge","drainpunch","curse","rockslide","protect"],
eventPokemon: [
{"generation":3,"level":40,"moves":["curse","superpower","ancientpower","hyperbeam"]}
],
unreleasedHidden: true,
tier: "NU"
},
regice: {
randomBattleMoves: ["thunderwave","icebeam","thunderbolt","rest","sleeptalk","focusblast","rockpolish"],
randomDoubleBattleMoves: ["thunderwave","icebeam","thunderbolt","icywind","protect","focusblast","rockpolish"],
eventPokemon: [
{"generation":3,"level":40,"moves":["curse","superpower","ancientpower","hyperbeam"]}
],
unreleasedHidden: true,
tier: "PU"
},
registeel: {
randomBattleMoves: ["stealthrock","ironhead","curse","rest","thunderwave","toxic","seismictoss"],
randomDoubleBattleMoves: ["stealthrock","ironhead","curse","rest","thunderwave","protect","seismictoss"],
eventPokemon: [
{"generation":3,"level":40,"moves":["curse","superpower","ancientpower","hyperbeam"]}
],
unreleasedHidden: true,
tier: "RU"
},
latias: {
randomBattleMoves: ["dragonpulse","surf","thunderbolt","roost","calmmind","healingwish","defog"],
randomDoubleBattleMoves: ["dragonpulse","psychic","tailwind","helpinghand","healpulse","lightscreen","reflect","protect"],
eventPokemon: [
{"generation":3,"level":50,"gender":"F","moves":["charm","recover","psychic","mistball"]},
{"generation":3,"level":70,"gender":"F","moves":["mistball","psychic","recover","charm"]},
{"generation":4,"level":40,"gender":"F","moves":["watersport","refresh","mistball","zenheadbutt"]}
],
tier: "OU"
},
latiasmega: {
randomBattleMoves: ["dragonpulse","surf","thunderbolt","roost","calmmind","healingwish","defog"],
randomDoubleBattleMoves: ["dragonpulse","psychic","tailwind","helpinghand","healpulse","lightscreen","reflect","protect"],
requiredItem: "Latiasite"
},
latios: {
randomBattleMoves: ["dracometeor","dragonpulse","surf","thunderbolt","psyshock","roost","trick","calmmind","defog"],
randomDoubleBattleMoves: ["dracometeor","dragonpulse","surf","thunderbolt","psyshock","substitute","trick","tailwind","protect","hiddenpowerfire"],
eventPokemon: [
{"generation":3,"level":50,"gender":"M","moves":["dragondance","recover","psychic","lusterpurge"]},
{"generation":3,"level":70,"gender":"M","moves":["lusterpurge","psychic","recover","dragondance"]},
{"generation":4,"level":40,"gender":"M","moves":["protect","refresh","lusterpurge","zenheadbutt"]}
],
tier: "OU"
},
latiosmega: {
randomBattleMoves: ["dracometeor","dragonpulse","surf","thunderbolt","psyshock","roost","calmmind","defog"],
randomDoubleBattleMoves: ["dracometeor","dragonpulse","surf","thunderbolt","psyshock","substitute","trick","tailwind","protect","hiddenpowerfire"],
requiredItem: "Latiosite"
},
kyogre: {
randomBattleMoves: ["waterspout","originpulse","scald","thunder","icebeam","calmmind","rest","sleeptalk","roar"],
randomDoubleBattleMoves: ["waterspout","muddywater","originpulse","thunder","icebeam","calmmind","rest","sleeptalk","protect"],
eventPokemon: [
{"generation":5,"level":80,"moves":["icebeam","ancientpower","waterspout","thunder"],"pokeball":"cherishball"},
{"generation":5,"level":100,"moves":["waterspout","thunder","icebeam","sheercold"],"pokeball":"cherishball"}
],
tier: "Uber"
},
kyogreprimal: {
randomBattleMoves: ["waterspout","originpulse","scald","thunder","icebeam","calmmind","rest","sleeptalk","roar"],
randomDoubleBattleMoves: ["waterspout","originpulse","muddywater","thunder","icebeam","calmmind","rest","sleeptalk","protect"],
requiredItem: "Blue Orb"
},
groudon: {
randomBattleMoves: ["earthquake","roar","stealthrock","stoneedge","swordsdance","rockpolish","thunderwave","firepunch"],
randomDoubleBattleMoves: ["earthquake","rockslide","protect","stoneedge","swordsdance","rockpolish","dragonclaw","firepunch"],
eventPokemon: [
{"generation":5,"level":80,"moves":["earthquake","ancientpower","eruption","solarbeam"],"pokeball":"cherishball"},
{"generation":5,"level":100,"moves":["eruption","hammerarm","earthpower","solarbeam"],"pokeball":"cherishball"}
],
tier: "Uber"
},
groudonprimal: {
randomBattleMoves: ["earthquake","lavaplume","stealthrock","stoneedge","swordsdance","overheat","rockpolish","firepunch"],
randomDoubleBattleMoves: ["earthquake","lavaplume","rockslide","stoneedge","swordsdance","overheat","rockpolish","firepunch","protect"],
requiredItem: "Red Orb"
},
rayquaza: {
randomBattleMoves: ["outrage","vcreate","extremespeed","dragondance","earthquake","dracometeor","dragonclaw"],
randomDoubleBattleMoves: ["tailwind","vcreate","extremespeed","dragondance","earthquake","dracometeor","dragonclaw","protect"],
eventPokemon: [
{"generation":5,"level":70,"shiny":true,"moves":["dragonpulse","ancientpower","outrage","dragondance"],"pokeball":"cherishball"},
{"generation":5,"level":100,"moves":["extremespeed","hyperbeam","dragonpulse","vcreate"],"pokeball":"cherishball"},
{"generation":6,"level":70,"shiny":true,"moves":["dragonpulse","thunder","twister","extremespeed"],"pokeball":"cherishball"}
],
tier: "Uber"
},
rayquazamega: {
randomBattleMoves: ["vcreate","extremespeed","swordsdance","earthquake","dragonascent","dragonclaw","dragondance"],
randomDoubleBattleMoves: ["vcreate","extremespeed","swordsdance","earthquake","dragonascent","dragonclaw","dragondance","protect"],
requiredMove: "Dragon Ascent"
},
jirachi: {
randomBattleMoves: ["bodyslam","ironhead","firepunch","thunderwave","stealthrock","wish","uturn","calmmind","psychic","thunderbolt","icepunch","trick"],
randomDoubleBattleMoves: ["bodyslam","ironhead","icywind","thunderwave","helpinghand","trickroom","uturn","followme","psychic","protect"],
eventPokemon: [
{"generation":3,"level":5,"moves":["wish","confusion","rest"]},
{"generation":3,"level":30,"moves":["helpinghand","psychic","refresh","rest"]},
{"generation":4,"level":5,"moves":["wish","confusion","rest"],"pokeball":"cherishball"},
{"generation":4,"level":5,"moves":["wish","confusion","rest","dracometeor"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["healingwish","psychic","swift","meteormash"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["dracometeor","meteormash","wish","followme"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["wish","healingwish","cosmicpower","meteormash"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["wish","healingwish","swift","return"],"pokeball":"cherishball"},
{"generation":6,"level":10,"shiny":true,"moves":["wish","swift","healingwish","moonblast"],"pokeball":"cherishball"},
{"generation":6,"level":15,"shiny":true,"moves":["wish","confusion","helpinghand","return"],"pokeball":"cherishball"}
],
tier: "OU"
},
deoxys: {
randomBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","spikes","stealthrock","knockoff","psyshock"],
randomDoubleBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","protect","knockoff","psyshock"],
eventPokemon: [
{"generation":3,"level":30,"moves":["snatch","psychic","spikes","knockoff"]},
{"generation":3,"level":30,"moves":["superpower","psychic","pursuit","taunt"]},
{"generation":3,"level":30,"moves":["swift","psychic","pursuit","knockoff"]},
{"generation":3,"level":70,"moves":["cosmicpower","recover","psychoboost","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","zapcannon","irondefense","extremespeed"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["psychoboost","swift","doubleteam","extremespeed"]},
{"generation":4,"level":50,"moves":["psychoboost","detect","counter","mirrorcoat"]},
{"generation":4,"level":50,"moves":["psychoboost","meteormash","superpower","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","leer","wrap","nightshade"]},
{"generation":5,"level":100,"moves":["nastyplot","darkpulse","recover","psychoboost"],"pokeball":"duskball"}
],
tier: "Uber"
},
deoxysattack: {
randomBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","spikes","stealthrock","knockoff"],
randomDoubleBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","protect","knockoff"],
eventPokemon: [
{"generation":3,"level":30,"moves":["snatch","psychic","spikes","knockoff"]},
{"generation":3,"level":30,"moves":["superpower","psychic","pursuit","taunt"]},
{"generation":3,"level":30,"moves":["swift","psychic","pursuit","knockoff"]},
{"generation":3,"level":70,"moves":["cosmicpower","recover","psychoboost","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","zapcannon","irondefense","extremespeed"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["psychoboost","swift","doubleteam","extremespeed"]},
{"generation":4,"level":50,"moves":["psychoboost","detect","counter","mirrorcoat"]},
{"generation":4,"level":50,"moves":["psychoboost","meteormash","superpower","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","leer","wrap","nightshade"]},
{"generation":5,"level":100,"moves":["nastyplot","darkpulse","recover","psychoboost"],"pokeball":"duskball"}
],
tier: "Uber"
},
deoxysdefense: {
randomBattleMoves: ["spikes","stealthrock","recover","taunt","toxic","seismictoss","magiccoat"],
randomDoubleBattleMoves: ["protect","stealthrock","recover","taunt","reflect","seismictoss","lightscreen","trickroom"],
eventPokemon: [
{"generation":3,"level":30,"moves":["snatch","psychic","spikes","knockoff"]},
{"generation":3,"level":30,"moves":["superpower","psychic","pursuit","taunt"]},
{"generation":3,"level":30,"moves":["swift","psychic","pursuit","knockoff"]},
{"generation":3,"level":70,"moves":["cosmicpower","recover","psychoboost","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","zapcannon","irondefense","extremespeed"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["psychoboost","swift","doubleteam","extremespeed"]},
{"generation":4,"level":50,"moves":["psychoboost","detect","counter","mirrorcoat"]},
{"generation":4,"level":50,"moves":["psychoboost","meteormash","superpower","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","leer","wrap","nightshade"]},
{"generation":5,"level":100,"moves":["nastyplot","darkpulse","recover","psychoboost"],"pokeball":"duskball"}
],
tier: "Uber"
},
deoxysspeed: {
randomBattleMoves: ["spikes","stealthrock","superpower","icebeam","psychoboost","taunt","lightscreen","reflect","magiccoat","knockoff"],
randomDoubleBattleMoves: ["superpower","icebeam","psychoboost","taunt","lightscreen","reflect","protect","knockoff"],
eventPokemon: [
{"generation":3,"level":30,"moves":["snatch","psychic","spikes","knockoff"]},
{"generation":3,"level":30,"moves":["superpower","psychic","pursuit","taunt"]},
{"generation":3,"level":30,"moves":["swift","psychic","pursuit","knockoff"]},
{"generation":3,"level":70,"moves":["cosmicpower","recover","psychoboost","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","zapcannon","irondefense","extremespeed"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["psychoboost","swift","doubleteam","extremespeed"]},
{"generation":4,"level":50,"moves":["psychoboost","detect","counter","mirrorcoat"]},
{"generation":4,"level":50,"moves":["psychoboost","meteormash","superpower","hyperbeam"]},
{"generation":4,"level":50,"moves":["psychoboost","leer","wrap","nightshade"]},
{"generation":5,"level":100,"moves":["nastyplot","darkpulse","recover","psychoboost"],"pokeball":"duskball"}
],
tier: "Uber"
},
turtwig: {
randomBattleMoves: ["reflect","lightscreen","stealthrock","seedbomb","substitute","leechseed","toxic"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tackle","withdraw","absorb"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tackle","withdraw","absorb","stockpile"]}
],
tier: "LC"
},
grotle: {
randomBattleMoves: ["reflect","lightscreen","stealthrock","seedbomb","substitute","leechseed","toxic"],
tier: "NFE"
},
torterra: {
randomBattleMoves: ["stealthrock","earthquake","woodhammer","stoneedge","synthesis","leechseed","rockpolish"],
randomDoubleBattleMoves: ["protect","earthquake","woodhammer","stoneedge","rockslide","wideguard","rockpolish"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["woodhammer","earthquake","outrage","stoneedge"],"pokeball":"cherishball"}
],
tier: "PU"
},
chimchar: {
randomBattleMoves: ["stealthrock","overheat","hiddenpowergrass","fakeout","uturn","gunkshot"],
eventPokemon: [
{"generation":4,"level":40,"gender":"M","nature":"Mild","moves":["flamethrower","thunderpunch","grassknot","helpinghand"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["scratch","leer","ember","taunt"]},
{"generation":4,"level":40,"gender":"M","nature":"Hardy","moves":["flamethrower","thunderpunch","grassknot","helpinghand"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["leer","ember","taunt","fakeout"]}
],
tier: "LC"
},
monferno: {
randomBattleMoves: ["stealthrock","overheat","hiddenpowergrass","fakeout","vacuumwave","uturn","gunkshot"],
tier: "PU"
},
infernape: {
randomBattleMoves: ["stealthrock","fireblast","closecombat","uturn","grassknot","stoneedge","machpunch","swordsdance","nastyplot","flareblitz","hiddenpowerice","thunderpunch"],
randomDoubleBattleMoves: ["fakeout","heatwave","closecombat","uturn","grassknot","stoneedge","machpunch","feint","taunt","flareblitz","hiddenpowerice","thunderpunch","protect"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["fireblast","closecombat","uturn","grassknot"],"pokeball":"cherishball"}
],
tier: "UU"
},
piplup: {
randomBattleMoves: ["stealthrock","hydropump","scald","icebeam","hiddenpowerelectric","hiddenpowerfire","yawn","defog"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["pound","growl","bubble"]},
{"generation":5,"level":15,"isHidden":false,"moves":["hydropump","featherdance","watersport","peck"],"pokeball":"cherishball"},
{"generation":5,"level":15,"gender":"M","isHidden":false,"moves":["sing","round","featherdance","peck"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["pound","growl","bubble","featherdance"]},
{"generation":6,"level":7,"isHidden":false,"moves":["pound","growl","return"],"pokeball":"cherishball"}
],
tier: "LC"
},
prinplup: {
randomBattleMoves: ["stealthrock","hydropump","scald","icebeam","hiddenpowerelectric","hiddenpowerfire","yawn","defog"],
tier: "NFE"
},
empoleon: {
randomBattleMoves: ["stealthrock","hydropump","scald","icebeam","roar","grassknot","flashcannon","defog","agility"],
randomDoubleBattleMoves: ["icywind","hydropump","scald","surf","icebeam","hiddenpowerelectric","protect","grassknot","flashcannon"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["hydropump","icebeam","aquajet","grassknot"],"pokeball":"cherishball"}
],
tier: "UU"
},
starly: {
randomBattleMoves: ["bravebird","return","uturn","pursuit"],
eventPokemon: [
{"generation":4,"level":1,"gender":"M","nature":"Mild","moves":["tackle","growl"]}
],
tier: "LC"
},
staravia: {
randomBattleMoves: ["bravebird","return","uturn","pursuit","defog"],
tier: "NFE"
},
staraptor: {
randomBattleMoves: ["bravebird","closecombat","uturn","quickattack","roost","doubleedge"],
randomDoubleBattleMoves: ["bravebird","closecombat","uturn","quickattack","doubleedge","tailwind","protect"],
tier: "BL"
},
bidoof: {
randomBattleMoves: ["return","aquatail","curse","quickattack","stealthrock","superfang"],
eventPokemon: [
{"generation":4,"level":1,"gender":"M","nature":"Lonely","abilities":["simple"],"moves":["tackle"]}
],
tier: "LC"
},
bibarel: {
randomBattleMoves: ["return","waterfall","curse","quickattack","stealthrock","rest"],
randomDoubleBattleMoves: ["return","waterfall","curse","quickattack","protect","rest"],
tier: "PU"
},
kricketot: {
randomBattleMoves: ["endeavor","mudslap","bugbite","strugglebug"],
tier: "LC"
},
kricketune: {
randomBattleMoves: ["xscissor","endeavor","taunt","toxic","stickyweb","knockoff"],
randomDoubleBattleMoves: ["bugbite","protect","taunt","stickyweb","knockoff"],
tier: "PU"
},
shinx: {
randomBattleMoves: ["wildcharge","icefang","firefang","crunch"],
tier: "LC"
},
luxio: {
randomBattleMoves: ["wildcharge","icefang","firefang","crunch"],
tier: "NFE"
},
luxray: {
randomBattleMoves: ["wildcharge","icefang","voltswitch","crunch","superpower","facade"],
randomDoubleBattleMoves: ["wildcharge","icefang","voltswitch","crunch","superpower","facade","protect"],
tier: "PU"
},
cranidos: {
randomBattleMoves: ["headsmash","rockslide","earthquake","zenheadbutt","firepunch","rockpolish","crunch"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"moves":["pursuit","takedown","crunch","headbutt"],"pokeball":"cherishball"}
],
tier: "LC"
},
rampardos: {
randomBattleMoves: ["headsmash","earthquake","zenheadbutt","rockpolish","crunch","stoneedge"],
randomDoubleBattleMoves: ["headsmash","earthquake","zenheadbutt","rockslide","crunch","stoneedge","protect"],
tier: "PU"
},
shieldon: {
randomBattleMoves: ["stealthrock","metalburst","fireblast","icebeam","protect","toxic","roar"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"moves":["metalsound","takedown","bodyslam","protect"],"pokeball":"cherishball"}
],
tier: "LC"
},
bastiodon: {
randomBattleMoves: ["stealthrock","rockblast","metalburst","protect","toxic","roar"],
randomDoubleBattleMoves: ["stealthrock","stoneedge","metalburst","protect","wideguard","guardsplit"],
tier: "PU"
},
burmy: {
randomBattleMoves: ["bugbite","hiddenpowerice","electroweb","protect"],
tier: "LC"
},
wormadam: {
randomBattleMoves: ["leafstorm","gigadrain","signalbeam","hiddenpowerice","hiddenpowerrock","toxic","synthesis"],
randomDoubleBattleMoves: ["leafstorm","gigadrain","signalbeam","hiddenpowerice","hiddenpowerrock","stringshot","protect"],
tier: "PU"
},
wormadamsandy: {
randomBattleMoves: ["earthquake","toxic","rockblast","protect","stealthrock"],
randomDoubleBattleMoves: ["earthquake","suckerpunch","rockblast","protect","stringshot"],
tier: "PU"
},
wormadamtrash: {
randomBattleMoves: ["stealthrock","toxic","gyroball","protect"],
randomDoubleBattleMoves: ["strugglebug","stringshot","gyroball","protect"],
tier: "PU"
},
mothim: {
randomBattleMoves: ["quiverdance","bugbuzz","airslash","gigadrain","roost"],
randomDoubleBattleMoves: ["quiverdance","bugbuzz","airslash","gigadrain","roost","protect"],
tier: "PU"
},
combee: {
randomBattleMoves: ["bugbuzz","aircutter","endeavor","ominouswind","tailwind"],
tier: "LC"
},
vespiquen: {
randomBattleMoves: ["substitute","healorder","toxic","attackorder","defendorder","infestation"],
randomDoubleBattleMoves: ["tailwind","healorder","stringshot","attackorder","strugglebug","protect"],
tier: "PU"
},
pachirisu: {
randomBattleMoves: ["nuzzle","thunderbolt","superfang","toxic","uturn"],
randomDoubleBattleMoves: ["nuzzle","thunderbolt","superfang","followme","uturn","helpinghand","protect"],
eventPokemon: [
{"generation":6,"level":50,"nature":"Impish","isHidden":true,"moves":["nuzzle","superfang","followme","protect"],"pokeball":"cherishball"}
],
tier: "PU"
},
buizel: {
randomBattleMoves: ["waterfall","aquajet","switcheroo","brickbreak","bulkup","batonpass","icepunch"],
tier: "LC"
},
floatzel: {
randomBattleMoves: ["waterfall","aquajet","switcheroo","bulkup","batonpass","icepunch","crunch"],
randomDoubleBattleMoves: ["waterfall","aquajet","switcheroo","raindance","protect","icepunch","crunch","taunt"],
tier: "PU"
},
cherubi: {
randomBattleMoves: ["sunnyday","solarbeam","weatherball","hiddenpowerice","aromatherapy","dazzlinggleam"],
tier: "LC"
},
cherrim: {
randomBattleMoves: ["sunnyday","solarbeam","weatherball","hiddenpowerice","energyball","synthesis"],
randomDoubleBattleMoves: ["sunnyday","solarbeam","weatherball","hiddenpowerice","protect"],
tier: "PU"
},
shellos: {
randomBattleMoves: ["scald","clearsmog","recover","toxic","icebeam","stockpile"],
tier: "LC"
},
gastrodon: {
randomBattleMoves: ["earthquake","icebeam","scald","toxic","recover"],
randomDoubleBattleMoves: ["earthpower","icebeam","scald","muddywater","recover","icywind","protect"],
tier: "RU"
},
drifloon: {
randomBattleMoves: ["shadowball","substitute","calmmind","hypnosis","hiddenpowerfighting","thunderbolt","destinybond","willowisp","stockpile","batonpass","disable"],
tier: "LC"
},
drifblim: {
randomBattleMoves: ["shadowball","substitute","calmmind","hiddenpowerfighting","thunderbolt","destinybond","willowisp","batonpass"],
randomDoubleBattleMoves: ["shadowball","substitute","hypnosis","hiddenpowerfighting","thunderbolt","destinybond","willowisp","protect"],
tier: "PU"
},
buneary: {
randomBattleMoves: ["fakeout","return","switcheroo","thunderpunch","highjumpkick","firepunch","icepunch","healingwish"],
tier: "LC"
},
lopunny: {
randomBattleMoves: ["return","switcheroo","highjumpkick","firepunch","icepunch","healingwish"],
randomDoubleBattleMoves: ["return","switcheroo","highjumpkick","firepunch","icepunch","fakeout","protect","encore"],
tier: "OU"
},
lopunnymega: {
randomBattleMoves: ["return","highjumpkick","poweruppunch","fakeout","icepunch"],
randomDoubleBattleMoves: ["return","highjumpkick","protect","fakeout","icepunch","encore"],
requiredItem: "Lopunnite"
},
glameow: {
randomBattleMoves: ["fakeout","uturn","suckerpunch","hypnosis","quickattack","return","foulplay"],
tier: "LC"
},
purugly: {
randomBattleMoves: ["fakeout","uturn","suckerpunch","quickattack","return","knockoff"],
randomDoubleBattleMoves: ["fakeout","uturn","suckerpunch","quickattack","return","knockoff","protect"],
tier: "PU"
},
stunky: {
randomBattleMoves: ["pursuit","suckerpunch","crunch","fireblast","explosion","taunt","poisonjab","playrough","defog"],
tier: "LC"
},
skuntank: {
randomBattleMoves: ["pursuit","suckerpunch","crunch","fireblast","taunt","poisonjab","playrough","defog"],
randomDoubleBattleMoves: ["protect","suckerpunch","crunch","fireblast","taunt","poisonjab","playrough","snarl","feint"],
tier: "RU"
},
bronzor: {
randomBattleMoves: ["stealthrock","psychic","toxic","hypnosis","reflect","lightscreen","trickroom","trick"],
tier: "LC"
},
bronzong: {
randomBattleMoves: ["stealthrock","earthquake","toxic","reflect","lightscreen","trickroom","explosion","gyroball"],
randomDoubleBattleMoves: ["earthquake","protect","reflect","lightscreen","trickroom","explosion","gyroball"],
tier: "RU"
},
chatot: {
randomBattleMoves: ["nastyplot","boomburst","heatwave","encore","substitute","chatter","uturn"],
randomDoubleBattleMoves: ["nastyplot","heatwave","encore","substitute","chatter","uturn","protect","hypervoice","boomburst"],
eventPokemon: [
{"generation":4,"level":25,"gender":"M","nature":"Jolly","abilities":["keeneye"],"moves":["mirrormove","furyattack","chatter","taunt"]}
],
tier: "PU"
},
spiritomb: {
randomBattleMoves: ["shadowsneak","suckerpunch","pursuit","willowisp","calmmind","darkpulse","rest","sleeptalk","foulplay","painsplit"],
randomDoubleBattleMoves: ["shadowsneak","suckerpunch","icywind","willowisp","snarl","darkpulse","protect","foulplay","painsplit"],
eventPokemon: [
{"generation":5,"level":61,"gender":"F","nature":"Quiet","isHidden":false,"moves":["darkpulse","psychic","silverwind","embargo"],"pokeball":"cherishball"}
],
tier: "RU"
},
gible: {
randomBattleMoves: ["outrage","dragonclaw","earthquake","fireblast","stoneedge","stealthrock"],
tier: "LC"
},
gabite: {
randomBattleMoves: ["outrage","dragonclaw","earthquake","fireblast","stoneedge","stealthrock"],
tier: "NFE"
},
garchomp: {
randomBattleMoves: ["outrage","dragonclaw","earthquake","stoneedge","fireblast","swordsdance","stealthrock","firefang"],
randomDoubleBattleMoves: ["substitute","dragonclaw","earthquake","stoneedge","rockslide","swordsdance","protect"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["outrage","earthquake","swordsdance","stoneedge"],"pokeball":"cherishball"},
{"generation":5,"level":48,"gender":"M","isHidden":true,"moves":["dragonclaw","dig","crunch","outrage"]},
{"generation":6,"level":48,"gender":"M","isHidden":false,"moves":["dracometeor","dragonclaw","dig","crunch"],"pokeball":"cherishball"},
{"generation":6,"level":50,"gender":"M","isHidden":false,"moves":["slash","dragonclaw","dig","crunch"],"pokeball":"cherishball"}
],
tier: "OU"
},
garchompmega: {
randomBattleMoves: ["outrage","dracometeor","earthquake","stoneedge","fireblast","stealthrock"],
randomDoubleBattleMoves: ["substitute","dragonclaw","earthquake","stoneedge","rockslide","swordsdance","protect","fireblast"],
requiredItem: "Garchompite"
},
riolu: {
randomBattleMoves: ["crunch","rockslide","copycat","drainpunch","highjumpkick","icepunch","swordsdance"],
eventPokemon: [
{"generation":4,"level":30,"gender":"M","nature":"Serious","abilities":["steadfast"],"moves":["aurasphere","shadowclaw","bulletpunch","drainpunch"]}
],
tier: "LC"
},
lucario: {
randomBattleMoves: ["swordsdance","closecombat","crunch","extremespeed","icepunch","bulletpunch","nastyplot","aurasphere","darkpulse","vacuumwave","flashcannon"],
randomDoubleBattleMoves: ["followme","closecombat","crunch","extremespeed","icepunch","bulletpunch","aurasphere","darkpulse","vacuumwave","flashcannon","protect"],
eventPokemon: [
{"generation":4,"level":50,"gender":"M","nature":"Modest","abilities":["steadfast"],"moves":["aurasphere","darkpulse","dragonpulse","waterpulse"],"pokeball":"cherishball"},
{"generation":4,"level":30,"gender":"M","nature":"Adamant","abilities":["innerfocus"],"moves":["forcepalm","bonerush","sunnyday","blazekick"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["detect","metalclaw","counter","bulletpunch"]},
{"generation":5,"level":50,"gender":"M","nature":"Naughty","isHidden":true,"moves":["bulletpunch","closecombat","stoneedge","shadowclaw"],"pokeball":"cherishball"}
],
tier: "UU"
},
lucariomega: {
randomBattleMoves: ["swordsdance","closecombat","crunch","extremespeed","icepunch","bulletpunch","nastyplot","aurasphere","darkpulse","vacuumwave","flashcannon"],
randomDoubleBattleMoves: ["followme","closecombat","crunch","extremespeed","icepunch","bulletpunch","aurasphere","darkpulse","vacuumwave","flashcannon","protect"],
requiredItem: "Lucarionite",
tier: "Uber"
},
hippopotas: {
randomBattleMoves: ["earthquake","slackoff","whirlwind","stealthrock","protect","toxic","stockpile"],
tier: "LC"
},
hippowdon: {
randomBattleMoves: ["earthquake","slackoff","whirlwind","stealthrock","toxic","rockslide"],
randomDoubleBattleMoves: ["earthquake","slackoff","rockslide","stealthrock","protect","stoneedge"],
tier: "UU"
},
skorupi: {
randomBattleMoves: ["toxicspikes","xscissor","poisonjab","knockoff","pinmissile","whirlwind"],
tier: "LC"
},
drapion: {
randomBattleMoves: ["whirlwind","toxicspikes","pursuit","earthquake","aquatail","swordsdance","poisonjab","knockoff"],
randomDoubleBattleMoves: ["snarl","taunt","protect","earthquake","aquatail","swordsdance","poisonjab","knockoff"],
tier: "RU"
},
croagunk: {
randomBattleMoves: ["fakeout","vacuumwave","suckerpunch","drainpunch","darkpulse","knockoff","gunkshot","toxic"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["astonish","mudslap","poisonsting","taunt"]},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["mudslap","poisonsting","taunt","poisonjab"]}
],
tier: "LC"
},
toxicroak: {
randomBattleMoves: ["suckerpunch","drainpunch","substitute","swordsdance","knockoff","icepunch","gunkshot"],
randomDoubleBattleMoves: ["suckerpunch","drainpunch","substitute","swordsdance","knockoff","icepunch","gunkshot","fakeout","protect"],
tier: "UU"
},
carnivine: {
randomBattleMoves: ["swordsdance","powerwhip","return","sleeppowder","substitute","leechseed","knockoff"],
randomDoubleBattleMoves: ["swordsdance","powerwhip","return","sleeppowder","substitute","leechseed","knockoff","ragepowder","protect"],
tier: "PU"
},
finneon: {
randomBattleMoves: ["surf","uturn","icebeam","hiddenpowerelectric","hiddenpowergrass","raindance"],
tier: "LC"
},
lumineon: {
randomBattleMoves: ["surf","uturn","icebeam","hiddenpowerelectric","hiddenpowergrass","raindance"],
randomDoubleBattleMoves: ["surf","uturn","icebeam","hiddenpowerelectric","hiddenpowergrass","raindance","tailwind","protect"],
tier: "PU"
},
snover: {
randomBattleMoves: ["blizzard","iceshard","gigadrain","leechseed","substitute","woodhammer"],
tier: "LC"
},
abomasnow: {
randomBattleMoves: ["blizzard","iceshard","gigadrain","leechseed","substitute","focusblast","woodhammer","earthquake"],
randomDoubleBattleMoves: ["blizzard","iceshard","gigadrain","protect","focusblast","woodhammer","earthquake"],
tier: "RU"
},
abomasnowmega: {
randomBattleMoves: ["blizzard","iceshard","gigadrain","leechseed","substitute","focusblast","woodhammer","earthquake"],
randomDoubleBattleMoves: ["blizzard","iceshard","gigadrain","protect","focusblast","woodhammer","earthquake"],
requiredItem: "Abomasite"
},
rotom: {
randomBattleMoves: ["thunderbolt","voltswitch","shadowball","substitute","painsplit","hiddenpowerice","trick","willowisp"],
randomDoubleBattleMoves: ["thunderbolt","voltswitch","shadowball","substitute","painsplit","hiddenpowerice","trick","willowisp","electroweb","protect"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "NU"
},
rotomheat: {
randomBattleMoves: ["overheat","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","trick"],
randomDoubleBattleMoves: ["overheat","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","trick","electroweb","protect"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "UU"
},
rotomwash: {
randomBattleMoves: ["hydropump","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","trick"],
randomDoubleBattleMoves: ["hydropump","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","trick","electroweb","protect","hiddenpowergrass"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "OU"
},
rotomfrost: {
randomBattleMoves: ["blizzard","thunderbolt","voltswitch","substitute","painsplit","willowisp","trick"],
randomDoubleBattleMoves: ["blizzard","thunderbolt","voltswitch","substitute","painsplit","willowisp","trick","electroweb","protect"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "PU"
},
rotomfan: {
randomBattleMoves: ["airslash","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","trick"],
randomDoubleBattleMoves: ["airslash","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerice","willowisp","electroweb","discharge","protect"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "NU"
},
rotommow: {
randomBattleMoves: ["leafstorm","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerfire","willowisp","trick"],
randomDoubleBattleMoves: ["leafstorm","thunderbolt","voltswitch","substitute","painsplit","hiddenpowerfire","willowisp","trick","electroweb","protect"],
eventPokemon: [
{"generation":5,"level":10,"nature":"Naughty","moves":["uproar","astonish","trick","thundershock"],"pokeball":"cherishball"},
{"generation":6,"level":10,"nature":"Quirky","moves":["shockwave","astonish","trick","thunderwave"],"pokeball":"cherishball"}
],
tier: "RU"
},
uxie: {
randomBattleMoves: ["uturn","psyshock","yawn","healbell","stealthrock","toxic","thunderbolt","substitute","calmmind"],
randomDoubleBattleMoves: ["uturn","psyshock","yawn","healbell","stealthrock","thunderbolt","protect","helpinghand","thunderwave","skillswap"],
tier: "NU"
},
mesprit: {
randomBattleMoves: ["calmmind","psyshock","thunderbolt","icebeam","substitute","uturn","trick","stealthrock","knockoff","psychic","healingwish"],
randomDoubleBattleMoves: ["calmmind","psychic","thunderbolt","icebeam","substitute","uturn","trick","protect","knockoff","psychic","helpinghand"],
tier: "NU"
},
azelf: {
randomBattleMoves: ["nastyplot","psychic","fireblast","thunderbolt","icepunch","knockoff","zenheadbutt","uturn","trick","taunt","stealthrock","explosion"],
randomDoubleBattleMoves: ["nastyplot","psychic","fireblast","thunderbolt","icepunch","knockoff","zenheadbutt","uturn","trick","taunt","protect","dazzlinggleam"],
tier: "UU"
},
dialga: {
randomBattleMoves: ["stealthrock","dracometeor","dragonpulse","roar","thunderbolt","flashcannon","outrage","fireblast","aurasphere"],
randomDoubleBattleMoves: ["dracometeor","dragonpulse","protect","thunderbolt","flashcannon","earthpower","fireblast","aurasphere"],
eventPokemon: [
{"generation":5,"level":100,"shiny":true,"isHidden":false,"moves":["dragonpulse","dracometeor","aurasphere","roaroftime"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'dreamball',
tier: "Uber"
},
palkia: {
randomBattleMoves: ["spacialrend","dracometeor","surf","hydropump","thunderbolt","outrage","fireblast"],
randomDoubleBattleMoves: ["spacialrend","dracometeor","surf","hydropump","thunderbolt","fireblast","protect"],
eventPokemon: [
{"generation":5,"level":100,"shiny":true,"isHidden":false,"moves":["hydropump","dracometeor","spacialrend","aurasphere"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'dreamball',
tier: "Uber"
},
heatran: {
randomBattleMoves: ["substitute","fireblast","lavaplume","willowisp","stealthrock","earthpower","hiddenpowerice","protect","toxic","roar"],
randomDoubleBattleMoves: ["heatwave","substitute","earthpower","protect","eruption","willowisp"],
eventPokemon: [
{"generation":4,"level":50,"nature":"Quiet","moves":["eruption","magmastorm","earthpower","ancientpower"]}
],
unreleasedHidden: true,
tier: "OU"
},
regigigas: {
randomBattleMoves: ["thunderwave","substitute","return","drainpunch","earthquake","confuseray"],
randomDoubleBattleMoves: ["thunderwave","substitute","return","icywind","rockslide","earthquake","knockoff","wideguard"],
eventPokemon: [
{"generation":4,"level":100,"moves":["ironhead","rockslide","icywind","crushgrip"],"pokeball":"cherishball"}
],
tier: "PU"
},
giratina: {
randomBattleMoves: ["rest","sleeptalk","dragontail","roar","willowisp","shadowball","dragonpulse"],
randomDoubleBattleMoves: ["tailwind","icywind","protect","dragontail","willowisp","calmmind","dragonpulse","shadowball"],
eventPokemon: [
{"generation":5,"level":100,"shiny":true,"isHidden":false,"moves":["dragonpulse","dragonclaw","aurasphere","shadowforce"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'dreamball',
tier: "Uber"
},
giratinaorigin: {
randomBattleMoves: ["dracometeor","shadowsneak","dragontail","willowisp","defog","toxic","shadowball","stoneedge","earthquake"],
randomDoubleBattleMoves: ["dracometeor","shadowsneak","tailwind","hiddenpowerfire","willowisp","calmmind","substitute","dragonpulse","shadowball","aurasphere","protect","earthquake"],
requiredItem: "Griseous Orb",
tier: "Uber"
},
cresselia: {
randomBattleMoves: ["moonlight","psychic","icebeam","thunderwave","toxic","lunardance","rest","sleeptalk","calmmind"],
randomDoubleBattleMoves: ["psyshock","icywind","thunderwave","trickroom","moonblast","moonlight","skillswap","reflect","lightscreen","icebeam","protect","helpinghand"],
eventPokemon: [
{"generation":5,"level":68,"gender":"F","nature":"Modest","moves":["icebeam","psyshock","energyball","hiddenpower"]}
],
tier: "RU"
},
phione: {
randomBattleMoves: ["raindance","scald","uturn","rest","icebeam"],
randomDoubleBattleMoves: ["raindance","scald","uturn","rest","icebeam","helpinghand","icywind","protect"],
eventPokemon: [
{"generation":4,"level":50,"abilities":["hydration"],"moves":["grassknot","raindance","rest","surf"],"pokeball":"cherishball"}
],
tier: "PU"
},
manaphy: {
randomBattleMoves: ["tailglow","surf","icebeam","energyball","psychic"],
randomDoubleBattleMoves: ["tailglow","surf","icebeam","energyball","protect","scald","icywind","helpinghand"],
eventPokemon: [
{"generation":4,"level":5,"moves":["tailglow","bubble","watersport"]},
{"generation":4,"level":1,"moves":["tailglow","bubble","watersport"]},
{"generation":4,"level":50,"moves":["acidarmor","whirlpool","waterpulse","heartswap"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["heartswap","waterpulse","whirlpool","acidarmor"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["heartswap","whirlpool","waterpulse","acidarmor"],"pokeball":"cherishball"},
{"generation":4,"level":50,"nature":"Impish","moves":["aquaring","waterpulse","watersport","heartswap"],"pokeball":"cherishball"}
],
tier: "OU"
},
darkrai: {
randomBattleMoves: ["darkvoid","darkpulse","focusblast","nastyplot","substitute","trick","sludgebomb"],
randomDoubleBattleMoves: ["darkpulse","focusblast","nastyplot","substitute","snarl","protect"],
eventPokemon: [
{"generation":4,"level":50,"moves":["roaroftime","spacialrend","nightmare","hypnosis"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["darkvoid","darkpulse","shadowball","doubleteam"]},
{"generation":4,"level":50,"moves":["nightmare","hypnosis","roaroftime","spacialrend"],"pokeball":"cherishball"},
{"generation":4,"level":50,"moves":["doubleteam","nightmare","feintattack","hypnosis"]},
{"generation":5,"level":50,"moves":["darkvoid","ominouswind","feintattack","nightmare"],"pokeball":"cherishball"},
{"generation":6,"level":50,"moves":["darkvoid","darkpulse","phantomforce","dreameater"],"pokeball":"cherishball"}
],
tier: "Uber"
},
shaymin: {
randomBattleMoves: ["seedflare","earthpower","airslash","hiddenpowerfire","rest","substitute","leechseed"],
randomDoubleBattleMoves: ["seedflare","earthpower","airslash","hiddenpowerfire","rest","substitute","leechseed","tailwind","protect"],
eventPokemon: [
{"generation":4,"level":50,"moves":["seedflare","aromatherapy","substitute","energyball"],"pokeball":"cherishball"},
{"generation":4,"level":30,"moves":["synthesis","leechseed","magicalleaf","growth"]},
{"generation":4,"level":30,"moves":["growth","magicalleaf","leechseed","synthesis"]},
{"generation":5,"level":50,"moves":["seedflare","leechseed","synthesis","sweetscent"],"pokeball":"cherishball"},
{"generation":6,"level":15,"moves":["growth","magicalleaf","seedflare","airslash"],"pokeball":"cherishball"}
],
tier: "UU"
},
shayminsky: {
randomBattleMoves: ["seedflare","earthpower","airslash","hiddenpowerice","hiddenpowerfire","substitute","leechseed"],
randomDoubleBattleMoves: ["seedflare","earthpower","airslash","hiddenpowerfire","rest","substitute","leechseed","tailwind","protect","hiddenpowerice"],
tier: "Uber"
},
arceus: {
randomBattleMoves: ["swordsdance","extremespeed","shadowclaw","earthquake","recover"],
randomDoubleBattleMoves: ["swordsdance","extremespeed","shadowclaw","earthquake","recover","protect"],
eventPokemon: [
{"generation":4,"level":100,"moves":["judgment","roaroftime","spacialrend","shadowforce"],"pokeball":"cherishball"},
{"generation":5,"level":100,"moves":["recover","hyperbeam","perishsong","judgment"]}
],
unobtainableShiny: true,
tier: "Uber"
},
arceusbug: {
randomBattleMoves: ["swordsdance","xscissor","stoneedge","recover","earthquake","ironhead"],
randomDoubleBattleMoves: ["swordsdance","xscissor","stoneedge","recover","earthquake","ironhead","protect"],
requiredItem: "Insect Plate"
},
arceusdark: {
randomBattleMoves: ["calmmind","judgment","recover","fireblast","thunderbolt"],
randomDoubleBattleMoves: ["calmmind","judgment","recover","focusblast","safeguard","snarl","willowisp","protect"],
requiredItem: "Dread Plate"
},
arceusdragon: {
randomBattleMoves: ["swordsdance","outrage","extremespeed","earthquake","recover","calmmind","judgment","fireblast"],
randomDoubleBattleMoves: ["swordsdance","dragonclaw","extremespeed","earthquake","recover","protect"],
requiredItem: "Draco Plate"
},
arceuselectric: {
randomBattleMoves: ["calmmind","judgment","recover","icebeam","grassknot","fireblast","willowisp"],
randomDoubleBattleMoves: ["calmmind","judgment","recover","icebeam","protect"],
requiredItem: "Zap Plate"
},
arceusfairy: {
randomBattleMoves: ["calmmind","judgment","recover","willowisp","defog","thunderbolt","toxic","fireblast"],
randomDoubleBattleMoves: ["calmmind","judgment","recover","willowisp","protect","earthpower","thunderbolt"],
requiredItem: "Pixie Plate",
gen: 6
},
arceusfighting: {
randomBattleMoves: ["calmmind","judgment","stoneedge","shadowball","recover","toxic","defog"],
randomDoubleBattleMoves: ["calmmind","judgment","icebeam","shadowball","recover","willowisp","protect"],
requiredItem: "Fist Plate"
},
arceusfire: {
randomBattleMoves: ["calmmind","judgment","grassknot","thunderbolt","icebeam","recover"],
randomDoubleBattleMoves: ["calmmind","judgment","thunderbolt","recover","heatwave","protect","willowisp"],
requiredItem: "Flame Plate"
},
arceusflying: {
randomBattleMoves: ["calmmind","judgment","earthpower","fireblast","substitute","recover"],
randomDoubleBattleMoves: ["calmmind","judgment","safeguard","recover","substitute","tailwind","protect"],
requiredItem: "Sky Plate"
},
arceusghost: {
randomBattleMoves: ["calmmind","judgment","focusblast","recover","swordsdance","shadowforce","brickbreak","willowisp","roar","defog"],
randomDoubleBattleMoves: ["calmmind","judgment","focusblast","recover","swordsdance","shadowforce","brickbreak","willowisp","protect"],
requiredItem: "Spooky Plate"
},
arceusgrass: {
randomBattleMoves: ["judgment","recover","calmmind","icebeam","fireblast"],
randomDoubleBattleMoves: ["calmmind","icebeam","judgment","earthpower","recover","safeguard","thunderwave","protect"],
requiredItem: "Meadow Plate"
},
arceusground: {
randomBattleMoves: ["swordsdance","earthquake","stoneedge","recover","extremespeed","icebeam"],
randomDoubleBattleMoves: ["swordsdance","earthquake","stoneedge","recover","calmmind","judgment","icebeam","rockslide","protect"],
requiredItem: "Earth Plate"
},
arceusice: {
randomBattleMoves: ["calmmind","judgment","thunderbolt","fireblast","recover"],
randomDoubleBattleMoves: ["calmmind","judgment","thunderbolt","focusblast","recover","protect","icywind"],
requiredItem: "Icicle Plate"
},
arceuspoison: {
randomBattleMoves: ["calmmind","sludgebomb","fireblast","recover","willowisp","defog","thunderwave"],
randomDoubleBattleMoves: ["calmmind","judgment","sludgebomb","heatwave","recover","willowisp","protect","earthpower"],
requiredItem: "Toxic Plate"
},
arceuspsychic: {
randomBattleMoves: ["judgment","calmmind","focusblast","recover","defog","thunderbolt","willowisp"],
randomDoubleBattleMoves: ["calmmind","psyshock","focusblast","recover","willowisp","judgment","protect"],
requiredItem: "Mind Plate"
},
arceusrock: {
randomBattleMoves: ["recover","swordsdance","earthquake","stoneedge","extremespeed"],
randomDoubleBattleMoves: ["swordsdance","stoneedge","recover","rockslide","earthquake","protect"],
requiredItem: "Stone Plate"
},
arceussteel: {
randomBattleMoves: ["calmmind","judgment","recover","willowisp","thunderbolt","swordsdance","ironhead","earthquake","stoneedge"],
randomDoubleBattleMoves: ["calmmind","judgment","recover","protect","willowisp"],
requiredItem: "Iron Plate"
},
arceuswater: {
randomBattleMoves: ["recover","calmmind","judgment","substitute","willowisp","thunderbolt"],
randomDoubleBattleMoves: ["recover","calmmind","judgment","icebeam","fireblast","icywind","surf","protect"],
requiredItem: "Splash Plate"
},
victini: {
randomBattleMoves: ["vcreate","boltstrike","uturn","psychic","focusblast","blueflare"],
randomDoubleBattleMoves: ["vcreate","boltstrike","uturn","psychic","focusblast","blueflare","protect"],
eventPokemon: [
{"generation":5,"level":15,"moves":["incinerate","quickattack","endure","confusion"]},
{"generation":5,"level":50,"moves":["vcreate","fusionflare","fusionbolt","searingshot"],"pokeball":"cherishball"},
{"generation":5,"level":100,"moves":["vcreate","blueflare","boltstrike","glaciate"],"pokeball":"cherishball"},
{"generation":6,"level":15,"moves":["confusion","quickattack","vcreate","searingshot"],"pokeball":"cherishball"}
],
unobtainableShiny: true,
tier: "BL"
},
snivy: {
randomBattleMoves: ["leafstorm","hiddenpowerfire","substitute","leechseed","hiddenpowerice","gigadrain"],
eventPokemon: [
{"generation":5,"level":5,"gender":"M","nature":"Hardy","isHidden":false,"moves":["growth","synthesis","energyball","aromatherapy"],"pokeball":"cherishball"}
],
tier: "LC"
},
servine: {
randomBattleMoves: ["leafstorm","hiddenpowerfire","substitute","leechseed","hiddenpowerice","gigadrain"],
tier: "NFE"
},
serperior: {
randomBattleMoves: ["leafstorm","hiddenpowerfire","substitute","leechseed","dragonpulse","gigadrain"],
randomDoubleBattleMoves: ["leafstorm","hiddenpowerfire","substitute","taunt","dragonpulse","gigadrain","protect"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["leafstorm","substitute","gigadrain","leechseed"],"pokeball":"cherishball"},
{"generation":6,"level":50,"isHidden":true,"moves":["leafstorm","holdback","wringout","gigadrain"],"pokeball":"cherishball"}
],
tier: "UU"
},
tepig: {
randomBattleMoves: ["flamecharge","flareblitz","wildcharge","superpower","headsmash"],
tier: "LC"
},
pignite: {
randomBattleMoves: ["flamecharge","flareblitz","wildcharge","superpower","headsmash"],
tier: "NFE"
},
emboar: {
randomBattleMoves: ["flareblitz","superpower","flamecharge","wildcharge","headsmash","suckerpunch","fireblast"],
randomDoubleBattleMoves: ["flareblitz","superpower","flamecharge","wildcharge","headsmash","protect","heatwave","rockslide"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["flareblitz","hammerarm","wildcharge","headsmash"],"pokeball":"cherishball"},
{"generation":6,"level":50,"isHidden":true,"moves":["flareblitz","holdback","headsmash","takedown"],"pokeball":"cherishball"}
],
tier: "RU"
},
oshawott: {
randomBattleMoves: ["swordsdance","waterfall","aquajet","xscissor"],
tier: "LC"
},
dewott: {
randomBattleMoves: ["swordsdance","waterfall","aquajet","xscissor"],
tier: "NFE"
},
samurott: {
randomBattleMoves: ["swordsdance","aquajet","waterfall","megahorn","superpower"],
randomDoubleBattleMoves: ["hydropump","aquajet","icebeam","scald","hiddenpowergrass","taunt","helpinghand","protect"],
eventPokemon: [
{"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["hydropump","icebeam","megahorn","superpower"],"pokeball":"cherishball"},
{"generation":6,"level":50,"isHidden":true,"moves":["razorshell","holdback","confide","hydropump"],"pokeball":"cherishball"}
],
tier: "NU"
},
patrat: {
randomBattleMoves: ["swordsdance","batonpass","substitute","hypnosis","return","superfang"],
tier: "LC"
},
watchog: {
randomBattleMoves: ["swordsdance","batonpass","substitute","hypnosis","return","superfang"],
randomDoubleBattleMoves: ["swordsdance","knockoff","substitute","hypnosis","return","superfang","protect"],
tier: "PU"
},
lillipup: {
randomBattleMoves: ["return","wildcharge","firefang","crunch","icefang"],
tier: "LC"
},
herdier: {
randomBattleMoves: ["return","wildcharge","firefang","crunch","icefang"],
tier: "NFE"
},
stoutland: {
randomBattleMoves: ["return","wildcharge","superpower","crunch","icefang"],
randomDoubleBattleMoves: ["return","wildcharge","superpower","crunch","icefang","protect"],
tier: "PU"
},
purrloin: {
randomBattleMoves: ["encore","suckerpunch","playrough","uturn","knockoff"],
tier: "LC"
},
liepard: {
randomBattleMoves: ["encore","thunderwave","substitute","knockoff","playrough","uturn","suckerpunch"],
randomDoubleBattleMoves: ["encore","thunderwave","substitute","knockoff","playrough","uturn","suckerpunch","fakeout","protect"],
eventPokemon: [
{"generation":5,"level":20,"gender":"F","nature":"Jolly","isHidden":true,"moves":["fakeout","foulplay","encore","swagger"]}
],
tier: "NU"
},
pansage: {
randomBattleMoves: ["leafstorm","hiddenpowerfire","hiddenpowerice","gigadrain","nastyplot","substitute","leechseed"],
eventPokemon: [
{"generation":5,"level":1,"gender":"M","nature":"Brave","isHidden":false,"moves":["bulletseed","bite","solarbeam","dig"],"pokeball":"cherishball"},
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["leer","lick","vinewhip","leafstorm"]},
{"generation":5,"level":30,"gender":"M","nature":"Serious","isHidden":false,"moves":["seedbomb","solarbeam","rocktomb","dig"],"pokeball":"cherishball"}
],
tier: "LC"
},
simisage: {
randomBattleMoves: ["nastyplot","leafstorm","hiddenpowerfire","hiddenpowerice","gigadrain","focusblast","substitute","leechseed","synthesis"],
randomDoubleBattleMoves: ["nastyplot","leafstorm","hiddenpowerfire","hiddenpowerice","gigadrain","focusblast","substitute","taunt","synthesis","helpinghand","protect"],
tier: "PU"
},
pansear: {
randomBattleMoves: ["nastyplot","fireblast","hiddenpowerelectric","hiddenpowerground","sunnyday","solarbeam","overheat"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["leer","lick","incinerate","heatwave"]}
],
tier: "LC"
},
simisear: {
randomBattleMoves: ["nastyplot","fireblast","focusblast","grassknot","hiddenpowerground","substitute","flamethrower","overheat"],
randomDoubleBattleMoves: ["nastyplot","fireblast","focusblast","grassknot","hiddenpowerground","substitute","heatwave","taunt","protect"],
tier: "PU"
},
panpour: {
randomBattleMoves: ["nastyplot","hydropump","hiddenpowergrass","substitute","surf","icebeam"],
eventPokemon: [
{"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["leer","lick","watergun","hydropump"]}
],
tier: "LC"
},
simipour: {
randomBattleMoves: ["nastyplot","hydropump","icebeam","substitute","grassknot","surf"],
randomDoubleBattleMoves: ["nastyplot","hydropump","icebeam","substitute","grassknot","surf","taunt","helpinghand","protect"],
tier: "PU"
},
munna: {
randomBattleMoves: ["psychic","hiddenpowerfighting","hypnosis","calmmind","moonlight","thunderwave","batonpass","psyshock","healbell","signalbeam"],
tier: "LC"
},
musharna: {
randomBattleMoves: ["calmmind","thunderwave","moonlight","psychic","hiddenpowerfighting","batonpass","psyshock","healbell","signalbeam"],
randomDoubleBattleMoves: ["trickroom","thunderwave","moonlight","psychic","hiddenpowerfighting","helpinghand","psyshock","healbell","signalbeam","protect"],
eventPokemon: [
{"generation":5,"level":50,"isHidden":true,"moves":["defensecurl","luckychant","psybeam","hypnosis"]}
],
tier: "NU"
},
pidove: {
randomBattleMoves: ["pluck","uturn","return","detect","roost","wish"],
eventPokemon: [
{"generation":5,"level":1,"gender":"F","nature":"Hardy","isHidden":false,"abilities":["superluck"],"moves":["gust","quickattack","aircutter"]}
],
tier: "LC"
},
tranquill: {
randomBattleMoves: ["pluck","uturn","return","detect","roost","wish"],
tier: "NFE"
},
unfezant: {
randomBattleMoves: ["pluck","uturn","return","detect","roost","wish"],
randomDoubleBattleMoves: ["pluck","uturn","return","protect","tailwind","taunt","wish"],
tier: "PU"
},
blitzle: {
randomBattleMoves: ["voltswitch","hiddenpowergrass","wildcharge","mefirst"],
tier: "LC"
},
zebstrika: {
randomBattleMoves: ["voltswitch","hiddenpowergrass","overheat","wildcharge","thunderbolt"],
randomDoubleBattleMoves: ["voltswitch","hiddenpowergrass","overheat","wildcharge","protect"],
tier: "PU"
},
roggenrola: {
randomBattleMoves: ["autotomize","stoneedge","stealthrock","rockblast","earthquake","explosion"],
tier: "LC"
},
boldore: {
randomBattleMoves: ["autotomize","stoneedge","stealthrock","rockblast","earthquake","explosion"],
tier: "NFE"
},
gigalith: {
randomBattleMoves: ["stealthrock","rockblast","earthquake","explosion","stoneedge","autotomize","superpower"],
randomDoubleBattleMoves: ["stealthrock","rockslide","earthquake","explosion","stoneedge","autotomize","superpower","wideguard","protect"],
tier: "PU"
},
woobat: {
randomBattleMoves: ["calmmind","psychic","airslash","gigadrain","roost","heatwave","storedpower"],
tier: "LC"
},
swoobat: {
randomBattleMoves: ["calmmind","psychic","airslash","gigadrain","roost","heatwave","storedpower"],
randomDoubleBattleMoves: ["calmmind","psychic","airslash","gigadrain","protect","heatwave","tailwind"],
tier: "PU"
},
drilbur: {
randomBattleMoves: ["swordsdance","rapidspin","earthquake","rockslide","shadowclaw","return","xscissor"],
tier: "LC"
},
excadrill: {
randomBattleMoves: ["swordsdance","rapidspin","earthquake","rockslide","ironhead"],
randomDoubleBattleMoves: ["swordsdance","drillrun","earthquake","rockslide","ironhead","substitute","protect"],
tier: "OU"
},
audino: {
randomBattleMoves: ["wish","protect","healbell","toxic","thunderwave","reflect","lightscreen","return"],
randomDoubleBattleMoves: ["healpulse","protect","healbell","trickroom","thunderwave","reflect","lightscreen","return","helpinghand"],
eventPokemon: [
{"generation":5,"level":30,"gender":"F","nature":"Calm","isHidden":false,"abilities":["healer"],"moves":["healpulse","helpinghand","refresh","doubleslap"],"pokeball":"cherishball"},
{"generation":5,"level":30,"gender":"F","nature":"Serious","isHidden":false,"abilities":["healer"],"moves":["healpulse","helpinghand","refresh","present"],"pokeball":"cherishball"}
],
tier: "NU"
},
audinomega: {
randomBattleMoves: ["wish","protect","healbell","toxic","thunderwave","reflect","lightscreen","return"],
randomDoubleBattleMoves: ["healpulse","protect","healbell","trickroom","thunderwave","reflect","lightscreen","hypervoice","helpinghand","dazzlinggleam"],
requiredItem: "Audinite"
},
timburr: {
randomBattleMoves: ["machpunch","bulkup","drainpunch","icepunch","knockoff"],
tier: "LC"
},
gurdurr: {
randomBattleMoves: ["bulkup","machpunch","drainpunch","icepunch","knockoff"],
tier: "NU"
},
conkeldurr: {
randomBattleMoves: ["bulkup","machpunch","drainpunch","icepunch","knockoff"],
randomDoubleBattleMoves: ["wideguard","machpunch","drainpunch","icepunch","knockoff","protect"],
tier: "OU"
},
tympole: {
randomBattleMoves: ["hydropump","surf","sludgewave","earthpower","hiddenpowerelectric"],
tier: "LC"
},
palpitoad: {
randomBattleMoves: ["hydropump","surf","sludgewave","earthpower","hiddenpowerelectric","stealthrock"],
tier: "NFE"
},
seismitoad: {
randomBattleMoves: ["hydropump","surf","sludgewave","earthpower","hiddenpowerelectric","stealthrock"],
randomDoubleBattleMoves: ["hydropump","muddywater","sludgebomb","earthpower","hiddenpowerelectric","icywind","protect"],
tier: "NU"
},
throh: {
randomBattleMoves: ["bulkup","circlethrow","icepunch","stormthrow","rest","sleeptalk","knockoff"],
randomDoubleBattleMoves: ["helpinghand","circlethrow","icepunch","stormthrow","wideguard","knockoff","protect"],
tier: "PU"
},
sawk: {
randomBattleMoves: ["closecombat","earthquake","icepunch","stoneedge","bulkup","knockoff"],
randomDoubleBattleMoves: ["closecombat","knockoff","icepunch","rockslide","protect"],
tier: "NU"
},
sewaddle: {
randomBattleMoves: ["calmmind","gigadrain","bugbuzz","hiddenpowerfire","hiddenpowerice","airslash"],
tier: "LC"
},
swadloon: {
randomBattleMoves: ["calmmind","gigadrain","bugbuzz","hiddenpowerfire","hiddenpowerice","airslash","stickyweb"],
tier: "NFE"
},
leavanny: {
randomBattleMoves: ["swordsdance","leafblade","xscissor","batonpass","stickyweb","poisonjab"],
randomDoubleBattleMoves: ["swordsdance","leafblade","xscissor","protect","stickyweb","poisonjab"],
tier: "PU"
},
venipede: {
randomBattleMoves: ["toxicspikes","steamroller","spikes","poisonjab"],
tier: "LC"
},
whirlipede: {
randomBattleMoves: ["toxicspikes","steamroller","spikes","poisonjab"],
tier: "NFE"
},
scolipede: {
randomBattleMoves: ["spikes","toxicspikes","megahorn","rockslide","earthquake","swordsdance","batonpass","aquatail","superpower"],
randomDoubleBattleMoves: ["substitute","protect","megahorn","rockslide","poisonjab","swordsdance","batonpass","aquatail","superpower"],
tier: "BL"
},
cottonee: {
randomBattleMoves: ["encore","taunt","substitute","leechseed","toxic","stunspore"],
tier: "LC"
},
whimsicott: {
randomBattleMoves: ["encore","taunt","substitute","leechseed","uturn","toxic","stunspore","memento","tailwind","moonblast"],
randomDoubleBattleMoves: ["encore","taunt","substitute","leechseed","uturn","helpinghand","stunspore","moonblast","tailwind","dazzlinggleam","gigadrain","protect"],
eventPokemon: [
{"generation":5,"level":50,"gender":"F","nature":"Timid","isHidden":false,"abilities":["prankster"],"moves":["swagger","gigadrain","beatup","helpinghand"],"pokeball":"cherishball"}
],
tier: "RU"
},
petilil: {
randomBattleMoves: ["sunnyday","sleeppowder","solarbeam","hiddenpowerfire","hiddenpowerice","healingwish"],
tier: "LC"
},
lilligant: {
randomBattleMoves: ["quiverdance","gigadrain","sleeppowder","hiddenpowerice","hiddenpowerfire","hiddenpowerrock","petaldance"],
randomDoubleBattleMoves: ["quiverdance","gigadrain","sleeppowder","hiddenpowerice","hiddenpowerfire","hiddenpowerrock","petaldance","helpinghand","protect"],
tier: "NU"
},
basculin: {
randomBattleMoves: ["waterfall","aquajet","superpower","crunch","doubleedge"],
randomDoubleBattleMoves: ["waterfall","aquajet","superpower","crunch","doubleedge","protect"],
tier: "PU"
},
basculinbluestriped: {
randomBattleMoves: ["waterfall","aquajet","superpower","crunch","doubleedge"],
randomDoubleBattleMoves: ["waterfall","aquajet","superpower","crunch","doubleedge","protect"],
tier: "PU"
},
sandile: {
randomBattleMoves: ["earthquake","stoneedge","pursuit","crunch"],
tier: "LC"
},
krokorok: {
randomBattleMoves: ["earthquake","stoneedge","pursuit","crunch"],
tier: "NFE"
},
krookodile: {
randomBattleMoves: ["earthquake","stoneedge","pursuit","knockoff","bulkup","superpower"],
randomDoubleBattleMoves: ["earthquake","stoneedge","protect","knockoff","bulkup","superpower"],
tier: "UU"
},
darumaka: {
randomBattleMoves: ["uturn","flareblitz","firepunch","rockslide","superpower"],
tier: "LC"
},
darmanitan: {
randomBattleMoves: ["uturn","flareblitz","firepunch","rockslide","earthquake","superpower"],
randomDoubleBattleMoves: ["uturn","flareblitz","firepunch","rockslide","earthquake","superpower","protect"],
eventPokemon: [
{"generation":5,"level":35,"isHidden":true,"moves":["thrash","bellydrum","flareblitz","hammerarm"]}
],
tier: "UU"
},
maractus: {
randomBattleMoves: ["spikes","gigadrain","leechseed","hiddenpowerfire","toxic","suckerpunch","spikyshield"],
randomDoubleBattleMoves: ["grassyterrain","gigadrain","leechseed","hiddenpowerfire","helpinghand","suckerpunch","spikyshield"],
tier: "PU"
},
dwebble: {
randomBattleMoves: ["stealthrock","spikes","shellsmash","earthquake","rockblast","xscissor","stoneedge"],
tier: "LC"
},
crustle: {
randomBattleMoves: ["stealthrock","spikes","shellsmash","earthquake","rockblast","xscissor","stoneedge"],
randomDoubleBattleMoves: ["protect","shellsmash","earthquake","rockslide","xscissor","stoneedge"],
tier: "NU"
},
scraggy: {
randomBattleMoves: ["dragondance","icepunch","highjumpkick","drainpunch","rest","bulkup","crunch","knockoff"],
eventPokemon: [
{"generation":5,"level":1,"gender":"M","nature":"Adamant","isHidden":false,"abilities":["moxie"],"moves":["headbutt","leer","highjumpkick","lowkick"],"pokeball":"cherishball"}
],
tier: "LC"
},
scrafty: {
randomBattleMoves: ["dragondance","icepunch","highjumpkick","drainpunch","rest","bulkup","knockoff"],
randomDoubleBattleMoves: ["fakeout","drainpunch","knockoff","icepunch","stoneedge", "protect"],
eventPokemon: [
{"generation":5,"level":50,"gender":"M","nature":"Brave","isHidden":false,"abilities":["moxie"],"moves":["firepunch","payback","drainpunch","substitute"],"pokeball":"cherishball"}
],
tier: "UU"
},
sigilyph: {
randomBattleMoves: ["cosmicpower","roost","storedpower","psychoshift"],
randomDoubleBattleMoves: ["psyshock","heatwave","icebeam","airslash","energyball","shadowball","tailwind","protect"],
tier: "BL3"
},
yamask: {
randomBattleMoves: ["nastyplot","trickroom","shadowball","hiddenpowerfighting","willowisp","haze","rest","sleeptalk","painsplit"],
tier: "LC"
},
cofagrigus: {
randomBattleMoves: ["nastyplot","trickroom","shadowball","hiddenpowerfighting","willowisp","haze","rest","sleeptalk","painsplit"],
randomDoubleBattleMoves: ["nastyplot","trickroom","shadowball","hiddenpowerfighting","willowisp","protect","painsplit"],
tier: "RU"
},
tirtouga: {
randomBattleMoves: ["shellsmash","aquajet","waterfall","stoneedge","earthquake","stealthrock"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","isHidden":false,"abilities":["sturdy"],"moves":["bite","protect","aquajet","bodyslam"],"pokeball":"cherishball"}
],
tier: "LC"
},
carracosta: {
randomBattleMoves: ["shellsmash","aquajet","waterfall","stoneedge","earthquake","stealthrock"],
randomDoubleBattleMoves: ["shellsmash","aquajet","waterfall","stoneedge","earthquake","protect","wideguard","rockslide"],
tier: "PU"
},
archen: {
randomBattleMoves: ["stoneedge","rockslide","earthquake","uturn","pluck","headsmash"],
eventPokemon: [
{"generation":5,"level":15,"gender":"M","moves":["headsmash","wingattack","doubleteam","scaryface"],"pokeball":"cherishball"}
],
tier: "LC"
},
archeops: {
randomBattleMoves: ["stoneedge","rockslide","earthquake","uturn","pluck","headsmash"],
randomDoubleBattleMoves: ["stoneedge","rockslide","earthquake","uturn","pluck","tailwind","taunt","protect"],
tier: "NU"
},
trubbish: {
randomBattleMoves: ["clearsmog","toxicspikes","spikes","gunkshot","painsplit","toxic"],
tier: "LC"
},
garbodor: {
randomBattleMoves: ["spikes","toxicspikes","gunkshot","haze","painsplit","toxic","rockblast"],
randomDoubleBattleMoves: ["protect","painsplit","gunkshot","seedbomb","drainpunch","explosion","rockblast"],
tier: "NU"
},
zorua: {
randomBattleMoves: ["suckerpunch","extrasensory","darkpulse","hiddenpowerfighting","uturn","knockoff"],
tier: "LC"
},
zoroark: {
randomBattleMoves: ["suckerpunch","darkpulse","focusblast","flamethrower","uturn","nastyplot","knockoff"],
randomDoubleBattleMoves: ["suckerpunch","darkpulse","focusblast","flamethrower","uturn","nastyplot","knockoff","protect"],
eventPokemon: [
{"generation":5,"level":50,"gender":"M","nature":"Quirky","moves":["agility","embargo","punishment","snarl"],"pokeball":"cherishball"}
],
tier: "BL2"
},
minccino: {
randomBattleMoves: ["return","tailslap","wakeupslap","uturn","aquatail"],
tier: "LC"
},
cinccino: {
randomBattleMoves: ["return","tailslap","wakeupslap","uturn","aquatail","bulletseed","rockblast"],
randomDoubleBattleMoves: ["return","tailslap","wakeupslap","uturn","aquatail","bulletseed","rockblast","protect"],
tier: "RU"
},
gothita: {
randomBattleMoves: ["psychic","thunderbolt","hiddenpowerfighting","shadowball","substitute","calmmind","reflect","lightscreen","trick","grassknot","signalbeam"],
tier: "LC"
},
gothorita: {
randomBattleMoves: ["psychic","thunderbolt","hiddenpowerfighting","shadowball","substitute","calmmind","reflect","lightscreen","trick","grassknot","signalbeam"],
eventPokemon: [
{"generation":5,"level":32,"gender":"M","isHidden":true,"moves":["psyshock","flatter","futuresight","mirrorcoat"]},
{"generation":5,"level":32,"gender":"M","isHidden":true,"moves":["psyshock","flatter","futuresight","imprison"]}
],
tier: "NFE"
},
gothitelle: {
randomBattleMoves: ["psychic","thunderbolt","hiddenpowerfighting","shadowball","substitute","calmmind","reflect","lightscreen","trick","psyshock","grassknot","signalbeam"],
randomDoubleBattleMoves: ["psychic","thunderbolt","hiddenpowerfighting","shadowball","calmmind","reflect","lightscreen","trick","psyshock","grassknot","signalbeam","trickroom","taunt","helpinghand","healpulse","protect"],
tier: "OU"
},
solosis: {
randomBattleMoves: ["calmmind","recover","psychic","hiddenpowerfighting","shadowball","trickroom","psyshock"],
tier: "LC"
},
duosion: {
randomBattleMoves: ["calmmind","recover","psychic","hiddenpowerfighting","shadowball","trickroom","psyshock"],
tier: "NFE"
},
reuniclus: {
randomBattleMoves: ["calmmind","recover","psychic","focusblast","shadowball","trickroom","psyshock","hiddenpowerfire"],
randomDoubleBattleMoves: ["calmmind","recover","psychic","focusblast","shadowball","trickroom","psyshock","hiddenpowerfire","protect"],
tier: "RU"
},
ducklett: {
randomBattleMoves: ["scald","airslash","roost","hurricane","icebeam","hiddenpowergrass","bravebird","defog"],
tier: "LC"
},
swanna: {
randomBattleMoves: ["airslash","roost","hurricane","surf","icebeam","raindance","defog","scald"],
randomDoubleBattleMoves: ["airslash","roost","hurricane","surf","icebeam","raindance","tailwind","scald","protect"],
tier: "PU"
},
vanillite: {
randomBattleMoves: ["icebeam","explosion","hiddenpowerelectric","hiddenpowerfighting","autotomize"],
tier: "LC"
},
vanillish: {
randomBattleMoves: ["icebeam","explosion","hiddenpowerelectric","hiddenpowerfighting","autotomize"],
tier: "NFE"
},
vanilluxe: {
randomBattleMoves: ["icebeam","explosion","hiddenpowerelectric","hiddenpowerfighting","autotomize"],
randomDoubleBattleMoves: ["icebeam","taunt","hiddenpowerelectric","hiddenpowerfighting","autotomize","protect","freezedry"],
tier: "PU"
},
deerling: {
randomBattleMoves: ["agility","batonpass","seedbomb","jumpkick","synthesis","return","thunderwave"],
eventPokemon: [
{"generation":5,"level":30,"gender":"F","isHidden":true,"moves":["feintattack","takedown","jumpkick","aromatherapy"]}
],
tier: "LC"
},
sawsbuck: {
randomBattleMoves: ["swordsdance","hornleech","jumpkick","return","substitute","synthesis","batonpass"],
randomDoubleBattleMoves: ["swordsdance","hornleech","jumpkick","return","substitute","synthesis","protect"],
tier: "PU"
},
emolga: {
randomBattleMoves: ["agility","chargebeam","batonpass","substitute","thunderbolt","airslash","roost"],
randomDoubleBattleMoves: ["helpinghand","tailwind","encore","substitute","thunderbolt","airslash","roost","protect"],
tier: "PU"
},
karrablast: {
randomBattleMoves: ["swordsdance","megahorn","return","substitute"],
eventPokemon: [
{"generation":5,"level":30,"isHidden":false,"moves":["furyattack","headbutt","falseswipe","bugbuzz"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["megahorn","takedown","xscissor","flail"],"pokeball":"cherishball"}
],
tier: "LC"
},
escavalier: {
randomBattleMoves: ["megahorn","pursuit","ironhead","knockoff","swordsdance","drillrun"],
randomDoubleBattleMoves: ["megahorn","protect","ironhead","knockoff","swordsdance","drillrun"],
tier: "RU"
},
foongus: {
randomBattleMoves: ["spore","stunspore","gigadrain","clearsmog","hiddenpowerfire","synthesis","sludgebomb"],
tier: "LC"
},
amoonguss: {
randomBattleMoves: ["spore","stunspore","gigadrain","clearsmog","hiddenpowerfire","synthesis","sludgebomb"],
randomDoubleBattleMoves: ["spore","stunspore","gigadrain","ragepowder","hiddenpowerfire","synthesis","sludgebomb","protect"],
tier: "RU"
},
frillish: {
randomBattleMoves: ["scald","willowisp","recover","toxic","shadowball","taunt"],
tier: "LC"
},
jellicent: {
randomBattleMoves: ["scald","willowisp","recover","toxic","shadowball","icebeam","gigadrain","taunt"],
randomDoubleBattleMoves: ["scald","willowisp","recover","trickroom","shadowball","icebeam","gigadrain","waterspout","icywind","protect"],
eventPokemon: [
{"generation":5,"level":40,"isHidden":true,"moves":["waterpulse","ominouswind","brine","raindance"]}
],
tier: "RU"
},
alomomola: {
randomBattleMoves: ["wish","protect","waterfall","toxic","scald"],
randomDoubleBattleMoves: ["wish","protect","waterfall","icywind","scald","helpinghand","wideguard"],
tier: "RU"
},
joltik: {
randomBattleMoves: ["thunderbolt","bugbuzz","hiddenpowerice","gigadrain","voltswitch","stickyweb"],
tier: "LC"
},
galvantula: {
randomBattleMoves: ["thunder","hiddenpowerice","gigadrain","bugbuzz","voltswitch","stickyweb"],
randomDoubleBattleMoves: ["thunder","hiddenpowerice","gigadrain","bugbuzz","voltswitch","stickyweb",'protect'],
tier: "UU"
},
ferroseed: {
randomBattleMoves: ["spikes","stealthrock","leechseed","seedbomb","protect","thunderwave","gyroball"],
tier: "NU"
},
ferrothorn: {
randomBattleMoves: ["spikes","stealthrock","leechseed","powerwhip","thunderwave","protect","knockoff","gyroball"],
randomDoubleBattleMoves: ["gyroball","stealthrock","leechseed","powerwhip","thunderwave","protect"],
tier: "OU"
},
klink: {
randomBattleMoves: ["shiftgear","return","geargrind","wildcharge","substitute"],
tier: "LC"
},
klang: {
randomBattleMoves: ["shiftgear","return","geargrind","wildcharge","substitute"],
tier: "NFE"
},
klinklang: {
randomBattleMoves: ["shiftgear","return","geargrind","wildcharge","substitute"],
randomDoubleBattleMoves: ["shiftgear","return","geargrind","wildcharge","protect"],
tier: "NU"
},
tynamo: {
randomBattleMoves: ["spark","chargebeam","thunderwave","tackle"],
tier: "LC"
},
eelektrik: {
randomBattleMoves: ["uturn","voltswitch","acidspray","wildcharge","thunderbolt","gigadrain","aquatail","coil"],
tier: "NFE"
},
eelektross: {
randomBattleMoves: ["thunderbolt","flamethrower","uturn","voltswitch","acidspray","wildcharge","drainpunch","superpower","gigadrain","aquatail","coil"],
randomDoubleBattleMoves: ["thunderbolt","flamethrower","uturn","voltswitch","thunderwave","wildcharge","drainpunch","superpower","gigadrain","aquatail","protect"],
tier: "RU"
},
elgyem: {
randomBattleMoves: ["nastyplot","psychic","thunderbolt","hiddenpowerfighting","substitute","calmmind","recover","trick", "trickroom", "signalbeam"],
tier: "LC"
},
beheeyem: {
randomBattleMoves: ["nastyplot","psychic","psyshock","thunderbolt","hiddenpowerfighting","substitute","calmmind","recover","trick","trickroom", "signalbeam"],
randomDoubleBattleMoves: ["nastyplot","psychic","thunderbolt","hiddenpowerfighting","recover","trick","trickroom", "signalbeam","protect"],
tier: "PU"
},
litwick: {
randomBattleMoves: ["calmmind","shadowball","energyball","fireblast","overheat","hiddenpowerfighting","hiddenpowerground","hiddenpowerrock","trick","substitute", "painsplit"],
tier: "LC"
},
lampent: {
randomBattleMoves: ["calmmind","shadowball","energyball","fireblast","overheat","hiddenpowerfighting","hiddenpowerground","hiddenpowerrock","trick","substitute", "painsplit"],
tier: "NFE"
},
chandelure: {
randomBattleMoves: ["shadowball","energyball","fireblast","overheat","hiddenpowerfighting","hiddenpowerground","trick","substitute","painsplit"],
randomDoubleBattleMoves: ["shadowball","energyball","fireblast","heatwave","hiddenpowerfighting","hiddenpowerground","trick","substitute","protect"],
eventPokemon: [
{"generation":5,"level":50,"gender":"F","nature":"Modest","isHidden":false,"abilities":["flashfire"],"moves":["heatwave","shadowball","energyball","psychic"],"pokeball":"cherishball"}
],
tier: "UU"
},
axew: {
randomBattleMoves: ["dragondance","outrage","dragonclaw","swordsdance","aquatail","superpower","poisonjab","taunt", "substitute"],
eventPokemon: [
{"generation":5,"level":1,"gender":"M","nature":"Naive","isHidden":false,"abilities":["moldbreaker"],"moves":["scratch","dragonrage"]},
{"generation":5,"level":10,"gender":"F","isHidden":false,"abilities":["moldbreaker"],"moves":["dragonrage","return","endure","dragonclaw"],"pokeball":"cherishball"},
{"generation":5,"level":30,"gender":"M","nature":"Naive","isHidden":false,"abilities":["rivalry"],"moves":["dragonrage","scratch","outrage","gigaimpact"],"pokeball":"cherishball"}
],
tier: "LC"
},
fraxure: {
randomBattleMoves: ["dragondance","swordsdance","outrage","dragonclaw","aquatail","superpower","poisonjab","taunt", "substitute"],
tier: "NFE"
},
haxorus: {
randomBattleMoves: ["dragondance","swordsdance","outrage","dragonclaw","earthquake","lowkick","poisonjab","taunt", "substitute"],
randomDoubleBattleMoves: ["dragondance","swordsdance","protect","dragonclaw","earthquake","lowkick","poisonjab","taunt", "substitute"],
eventPokemon: [
{"generation":5,"level":59,"gender":"F","nature":"Naive","isHidden":false,"abilities":["moldbreaker"],"moves":["earthquake","dualchop","xscissor","dragondance"],"pokeball":"cherishball"}
],
tier: "UU"
},
cubchoo: {
randomBattleMoves: ["icebeam","surf","hiddenpowergrass","superpower"],
eventPokemon: [
{"generation":5,"level":15,"isHidden":false,"moves":["powdersnow","growl","bide","icywind"],"pokeball":"cherishball"}
],
tier: "LC"
},
beartic: {
randomBattleMoves: ["iciclecrash","superpower","nightslash","stoneedge","swordsdance","aquajet"],
randomDoubleBattleMoves: ["iciclecrash","superpower","nightslash","stoneedge","swordsdance","aquajet","protect"],
tier: "PU"
},
cryogonal: {
randomBattleMoves: ["icebeam","recover","toxic","rapidspin","reflect","freezedry","hiddenpowerfire"],
randomDoubleBattleMoves: ["icebeam","recover","icywind","protect","reflect","freezedry","hiddenpowerfire"],
tier: "NU"
},
shelmet: {
randomBattleMoves: ["spikes","yawn","substitute","acidarmor","batonpass","recover","toxic","bugbuzz","infestation"],
eventPokemon: [
{"generation":5,"level":30,"isHidden":false,"moves":["strugglebug","megadrain","yawn","protect"],"pokeball":"cherishball"},
{"generation":5,"level":50,"isHidden":false,"moves":["encore","gigadrain","bodyslam","bugbuzz"],"pokeball":"cherishball"}
],
tier: "LC"
},
accelgor: {
randomBattleMoves: ["spikes","yawn","bugbuzz","focusblast","gigadrain","hiddenpowerrock","encore","sludgebomb"],
randomDoubleBattleMoves: ["protect","yawn","bugbuzz","focusblast","gigadrain","hiddenpowerrock","encore","sludgebomb"],
tier: "RU"
},
stunfisk: {
randomBattleMoves: ["discharge","thunderbolt","earthpower","scald","toxic","rest","sleeptalk","stealthrock"],
randomDoubleBattleMoves: ["discharge","thunderbolt","earthpower","scald","electroweb","protect","stealthrock"],
tier: "PU"
},
mienfoo: {
randomBattleMoves: ["uturn","drainpunch","stoneedge","swordsdance","batonpass","highjumpkick","fakeout","knockoff"],
tier: "LC"
},
mienshao: {
randomBattleMoves: ["uturn","fakeout","highjumpkick","stoneedge","drainpunch","swordsdance","batonpass","knockoff"],
randomDoubleBattleMoves: ["uturn","fakeout","highjumpkick","stoneedge","drainpunch","swordsdance","wideguard","knockoff","feint","protect"],
tier: "UU"
},
druddigon: {
randomBattleMoves: ["outrage","superpower","earthquake","suckerpunch","dragonclaw","dragontail","substitute","glare","stealthrock","firepunch","thunderpunch"],
randomDoubleBattleMoves: ["superpower","earthquake","suckerpunch","dragonclaw","glare","protect","firepunch","thunderpunch"],
eventPokemon: [
{"generation":5,"level":1,"shiny":true,"isHidden":false,"moves":["leer","scratch"]}
],
tier: "RU"
},
golett: {
randomBattleMoves: ["earthquake","shadowpunch","dynamicpunch","icepunch","stealthrock","rockpolish"],
tier: "LC"
},
golurk: {
randomBattleMoves: ["earthquake","shadowpunch","dynamicpunch","icepunch","stoneedge","stealthrock","rockpolish"],
randomDoubleBattleMoves: ["earthquake","shadowpunch","dynamicpunch","icepunch","stoneedge","protect","rockpolish"],
eventPokemon: [
{"generation":5,"level":70,"shiny":true,"isHidden":false,"abilities":["ironfist"],"moves":["shadowpunch","hyperbeam","gyroball","hammerarm"],"pokeball":"cherishball"}
],
tier: "NU"
},
pawniard: {
randomBattleMoves: ["swordsdance","substitute","suckerpunch","ironhead","brickbreak","knockoff"],
tier: "PU"
},
bisharp: {
randomBattleMoves: ["swordsdance","substitute","suckerpunch","ironhead","brickbreak","knockoff"],
randomDoubleBattleMoves: ["swordsdance","substitute","suckerpunch","ironhead","brickbreak","knockoff","protect"],
tier: "OU"
},
bouffalant: {
randomBattleMoves: ["headcharge","earthquake","stoneedge","megahorn","swordsdance","superpower"],
randomDoubleBattleMoves: ["headcharge","earthquake","stoneedge","megahorn","swordsdance","superpower","protect"],
tier: "NU"
},
rufflet: {
randomBattleMoves: ["bravebird","rockslide","return","uturn","substitute","bulkup","roost"],
tier: "LC"
},
braviary: {
randomBattleMoves: ["bravebird","superpower","return","uturn","substitute","rockslide","bulkup","roost"],
randomDoubleBattleMoves: ["bravebird","superpower","return","uturn","tailwind","rockslide","bulkup","roost","skydrop","protect"],
eventPokemon: [
{"generation":5,"level":25,"gender":"M","isHidden":true,"moves":["wingattack","honeclaws","scaryface","aerialace"]}
],
tier: "RU"
},
vullaby: {
randomBattleMoves: ["knockoff","roost","taunt","whirlwind","toxic","defog","uturn","bravebird"],
tier: "LC"
},
mandibuzz: {
randomBattleMoves: ["knockoff","roost","taunt","whirlwind","toxic","uturn","bravebird","defog"],
randomDoubleBattleMoves: ["knockoff","roost","taunt","tailwind","snarl","uturn","bravebird","protect"],
eventPokemon: [
{"generation":5,"level":25,"gender":"F","isHidden":true,"moves":["pluck","nastyplot","flatter","feintattack"]}
],
tier: "OU"
},
heatmor: {
randomBattleMoves: ["fireblast","suckerpunch","focusblast","gigadrain"],
randomDoubleBattleMoves: ["fireblast","suckerpunch","focusblast","gigadrain","heatwave","protect"],
tier: "PU"
},
durant: {
randomBattleMoves: ["honeclaws","ironhead","xscissor","stoneedge","batonpass","superpower"],
randomDoubleBattleMoves: ["honeclaws","ironhead","xscissor","rockslide","protect","superpower"],
tier: "RU"
},
deino: {
randomBattleMoves: ["outrage","crunch","firefang","dragontail","thunderwave","superpower"],
eventPokemon: [
{"generation":5,"level":1,"shiny":true,"moves":["tackle","dragonrage"]}
],
tier: "LC"
},
zweilous: {
randomBattleMoves: ["outrage","crunch","firefang","dragontail","thunderwave","superpower"],
tier: "NFE"
},
hydreigon: {
randomBattleMoves: ["uturn","dracometeor","dragonpulse","earthpower","fireblast","darkpulse","roost","flashcannon","superpower"],
randomDoubleBattleMoves: ["uturn","dracometeor","dragonpulse","earthpower","fireblast","darkpulse","roost","flashcannon","superpower","tailwind","protect"],
eventPokemon: [
{"generation":5,"level":70,"shiny":true,"gender":"M","moves":["hypervoice","dragonbreath","flamethrower","focusblast"],"pokeball":"cherishball"}
],
tier: "UU"
},
larvesta: {
randomBattleMoves: ["flareblitz","uturn","wildcharge","zenheadbutt","morningsun","willowisp"],
tier: "LC"
},
volcarona: {
randomBattleMoves: ["quiverdance","fierydance","fireblast","bugbuzz","roost","gigadrain","hiddenpowerice"],
randomDoubleBattleMoves: ["quiverdance","fierydance","fireblast","bugbuzz","roost","gigadrain","hiddenpowerice","heatwave","willowisp","ragepowder","tailwind","protect"],
eventPokemon: [
{"generation":5,"level":35,"isHidden":false,"moves":["stringshot","leechlife","gust","firespin"]},
{"generation":5,"level":77,"gender":"M","nature":"Calm","isHidden":false,"moves":["bugbuzz","overheat","hyperbeam","quiverdance"],"pokeball":"cherishball"}
],
tier: "BL"
},
cobalion: {
randomBattleMoves: ["closecombat","ironhead","swordsdance","substitute","stoneedge","voltswitch","hiddenpowerice","thunderwave","stealthrock"],
randomDoubleBattleMoves: ["closecombat","ironhead","swordsdance","substitute","stoneedge","voltswitch","hiddenpowerice","thunderwave","protect","helpinghand"],
tier: "RU"
},
terrakion: {
randomBattleMoves: ["stoneedge","closecombat","swordsdance","rockpolish","substitute","stealthrock","earthquake"],
randomDoubleBattleMoves: ["stoneedge","closecombat","substitute","rockslide","earthquake","protect"],
tier: "UU"
},
virizion: {
randomBattleMoves: ["swordsdance","calmmind","closecombat","focusblast","hiddenpowerice","stoneedge","leafblade","gigadrain","substitute","synthesis"],
randomDoubleBattleMoves: ["taunt","closecombat","focusblast","hiddenpowerice","stoneedge","leafblade","gigadrain","substitute","synthesis","protect","helpinghand"],
tier: "NU"
},
tornadus: {
randomBattleMoves: ["hurricane","airslash","uturn","superpower","focusblast","taunt","substitute","heatwave","tailwind"],
randomDoubleBattleMoves: ["hurricane","airslash","uturn","superpower","focusblast","taunt","substitute","heatwave","tailwind","protect","skydrop"],
eventPokemon: [
{"generation":5,"level":70,"gender":"M","isHidden":false,"moves":["hurricane","hammerarm","airslash","hiddenpower"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'dreamball',
tier: "BL2"
},
tornadustherian: {
randomBattleMoves: ["hurricane","airslash","focusblast","uturn","heatwave","knockoff"],
randomDoubleBattleMoves: ["hurricane","airslash","focusblast","uturn","heatwave","skydrop","tailwind","taunt","protect"],
eventPokemon: [
{"generation":5,"level":70,"gender":"M","isHidden":false,"moves":["hurricane","hammerarm","airslash","hiddenpower"],"pokeball":"cherishball"}
],
tier: "BL"
},
thundurus: {
randomBattleMoves: ["thunderwave","nastyplot","thunderbolt","hiddenpowerice","focusblast","grassknot","substitute"],
randomDoubleBattleMoves: ["thunderwave","nastyplot","thunderbolt","hiddenpowerice","focusblast","grassknot","substitute","taunt","protect"],
eventPokemon: [
{"generation":5,"level":70,"gender":"M","isHidden":false,"moves":["thunder","hammerarm","focusblast","wildcharge"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'dreamball',
tier: "OU"
},
thundurustherian: {
randomBattleMoves: ["nastyplot","agility","thunderbolt","hiddenpowerice","focusblast","grassknot","superpower"],
randomDoubleBattleMoves: ["nastyplot","agility","thunderbolt","hiddenpowerice","focusblast","grassknot","superpower","protect"],
eventPokemon: [
{"generation":5,"level":70,"gender":"M","isHidden":false,"moves":["thunder","hammerarm","focusblast","wildcharge"],"pokeball":"cherishball"}
],
tier: "BL"
},
reshiram: {
randomBattleMoves: ["blueflare","dracometeor","dragonpulse","flamethrower","flamecharge","roost"],
randomDoubleBattleMoves: ["blueflare","dracometeor","dragonpulse","heatwave","flamecharge","roost","protect","tailwind"],
eventPokemon: [
{"generation":5,"level":100,"moves":["blueflare","fusionflare","mist","dracometeor"],"pokeball":"cherishball"}
],
tier: "Uber"
},
zekrom: {
randomBattleMoves: ["voltswitch","outrage","dragonclaw","boltstrike","honeclaws","substitute","dracometeor","fusionbolt","roost"],
randomDoubleBattleMoves: ["voltswitch","protect","dragonclaw","boltstrike","honeclaws","substitute","dracometeor","fusionbolt","roost","tailwind"],
eventPokemon: [
{"generation":5,"level":100,"moves":["boltstrike","fusionbolt","haze","outrage"],"pokeball":"cherishball"}
],
tier: "Uber"
},
landorus: {
randomBattleMoves: ["earthpower","focusblast","rockpolish","hiddenpowerice","psychic","sludgewave"],
randomDoubleBattleMoves: ["earthpower","focusblast","rockpolish","hiddenpowerice","psychic","sludgebomb","protect"],
dreamWorldPokeball: 'dreamball',
tier: "OU"
},
landorustherian: {
randomBattleMoves: ["rockpolish","earthquake","stoneedge","uturn","superpower","stealthrock","swordsdance"],
randomDoubleBattleMoves: ["rockslide","earthquake","stoneedge","uturn","superpower","knockoff","protect"],
tier: "OU"
},
kyurem: {
randomBattleMoves: ["substitute","icebeam","dracometeor","dragonpulse","focusblast","outrage","earthpower","roost"],
randomDoubleBattleMoves: ["substitute","icebeam","dracometeor","dragonpulse","focusblast","glaciate","earthpower","roost","protect"],
tier: "BL2"
},
kyuremblack: {
randomBattleMoves: ["outrage","fusionbolt","icebeam","roost","substitute","honeclaws","earthpower","dragonclaw"],
randomDoubleBattleMoves: ["protect","fusionbolt","icebeam","roost","substitute","honeclaws","earthpower","dragonclaw"],
tier: "OU"
},
kyuremwhite: {
randomBattleMoves: ["dracometeor","dragonpulse","icebeam","fusionflare","earthpower","focusblast","roost"],
randomDoubleBattleMoves: ["dracometeor","dragonpulse","icebeam","fusionflare","earthpower","focusblast","roost","protect"],
tier: "Uber"
},
keldeo: {
randomBattleMoves: ["hydropump","secretsword","calmmind","hiddenpowerghost","hiddenpowerelectric","substitute","scald","icywind"],
randomDoubleBattleMoves: ["hydropump","secretsword","protect","hiddenpowerghost","hiddenpowerelectric","substitute","surf","icywind","taunt"],
eventPokemon: [
{"generation":5,"level":15,"moves":["aquajet","leer","doublekick","bubblebeam"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["sacredsword","hydropump","aquajet","swordsdance"],"pokeball":"cherishball"},
{"generation":6,"level":15,"moves":["aquajet","leer","doublekick","hydropump"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'cherishball',
unobtainableShiny: true,
tier: "OU"
},
keldeoresolute: {},
meloetta: {
randomBattleMoves: ["relicsong","closecombat","calmmind","psychic","thunderbolt","hypervoice","uturn"],
randomDoubleBattleMoves: ["relicsong","closecombat","calmmind","psychic","thunderbolt","hypervoice","uturn","protect"],
eventPokemon: [
{"generation":5,"level":15,"moves":["quickattack","confusion","round"],"pokeball":"cherishball"},
{"generation":5,"level":50,"moves":["round","teeterdance","psychic","closecombat"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'cherishball',
unobtainableShiny: true,
tier: "RU"
},
genesect: {
randomBattleMoves: ["uturn","bugbuzz","icebeam","flamethrower","thunderbolt","ironhead","shiftgear","extremespeed","blazekick"],
randomDoubleBattleMoves: ["uturn","bugbuzz","icebeam","flamethrower","thunderbolt","ironhead","shiftgear","extremespeed","blazekick","protect"],
eventPokemon: [
{"generation":5,"level":50,"moves":["technoblast","magnetbomb","solarbeam","signalbeam"],"pokeball":"cherishball"},
{"generation":5,"level":15,"moves":["technoblast","magnetbomb","solarbeam","signalbeam"],"pokeball":"cherishball"},
{"generation":5,"level":100,"shiny":true,"nature":"Hasty","moves":["extremespeed","technoblast","blazekick","shiftgear"],"pokeball":"cherishball"}
],
dreamWorldPokeball: 'cherishball',
tier: "Uber"
},
genesectburn: {
randomBattleMoves: ["uturn","bugbuzz","icebeam","technoblast","thunderbolt","ironhead","shiftgear","extremespeed"],
randomDoubleBattleMoves: ["uturn","bugbuzz","icebeam","technoblast","thunderbolt","ironhead","shiftgear","extremespeed","blazekick","protect"],
dreamWorldPokeball: 'cherishball',
requiredItem: "Burn Drive"
},
genesectchill: {
randomBattleMoves: ["uturn","bugbuzz","technoblast","flamethrower","thunderbolt","ironhead","shiftgear","extremespeed","blazekick"],
randomDoubleBattleMoves: ["uturn","bugbuzz","icebeam","technoblast","thunderbolt","ironhead","shiftgear","extremespeed","blazekick","protect"],
dreamWorldPokeball: 'cherishball',
requiredItem: "Chill Drive"
},
genesectdouse: {
randomBattleMoves: ["uturn","bugbuzz","icebeam","flamethrower","thunderbolt","technoblast","ironhead","shiftgear","extremespeed","blazekick"],
randomDoubleBattleMoves: ["uturn","bugbuzz","icebeam","technoblast","thunderbolt","ironhead","shiftgear","extremespeed","blazekick","protect"],
dreamWorldPokeball: 'cherishball',
requiredItem: "Douse Drive"
},
genesectshock: {
randomBattleMoves: ["uturn","bugbuzz","icebeam","flamethrower","technoblast","ironhead","shiftgear","extremespeed","blazekick"],
randomDoubleBattleMoves: ["uturn","bugbuzz","icebeam","technoblast","thunderbolt","ironhead","shiftgear","extremespeed","blazekick","protect"],
dreamWorldPokeball: 'cherishball',
requiredItem: "Shock Drive"
},
chespin: {
randomBattleMoves: ["curse","gyroball","seedbomb","stoneedge","spikes","synthesis"],
tier: "LC"
},
quilladin: {
randomBattleMoves: ["curse","gyroball","seedbomb","stoneedge","spikes","synthesis"],
tier: "NFE"
},
chesnaught: {
randomBattleMoves: ["leechseed","synthesis","spikes","drainpunch","spikyshield","woodhammer"],
randomDoubleBattleMoves: ["leechseed","synthesis","hammerarm","spikyshield","stoneedge","woodhammer","rockslide"],
tier: "UU"
},
fennekin: {
randomBattleMoves: ["fireblast","psychic","psyshock","grassknot","willowisp","hypnosis","hiddenpowerrock","flamecharge","dazzlinggleam"],
tier: "LC"
},
braixen: {
randomBattleMoves: ["fireblast","flamethrower","psychic","psyshock","grassknot","willowisp","hiddenpowerrock","dazzlinggleam"],
tier: "NFE"
},
delphox: {
randomBattleMoves: ["calmmind","fireblast","flamethrower","psyshock","grassknot","switcheroo","shadowball","dazzlinggleam"],
randomDoubleBattleMoves: ["calmmind","fireblast","flamethrower","psyshock","grassknot","switcheroo","shadowball","heatwave","dazzlinggleam","protect"],
tier: "RU"
},
froakie: {
randomBattleMoves: ["quickattack","hydropump","icebeam","waterfall","toxicspikes","poweruppunch","uturn"],
eventPokemon: [
{"generation":6,"level":7,"isHidden":false,"moves":["pound","growl","bubble","return"],"pokeball":"cherishball"}
],
tier: "LC"
},
frogadier: {
randomBattleMoves: ["hydropump","surf","icebeam","uturn","taunt","toxicspikes"],
tier: "NFE"
},
greninja: {
randomBattleMoves: ["hydropump","uturn","surf","icebeam","spikes","taunt","darkpulse","toxicspikes","hiddenpowerfire","gunkshot"],
randomDoubleBattleMoves: ["hydropump","uturn","surf","icebeam","matblock","taunt","darkpulse","protect","hiddenpowerfire"],
eventPokemon: [
{"generation":6,"level":36,"isHidden":true,"moves":["watershuriken","shadowsneak","hydropump","substitute"],"pokeball":"cherishball"}
],
tier: "Uber"
},
bunnelby: {
randomBattleMoves: ["agility","earthquake","return","quickattack","uturn","stoneedge","spikes","bounce"],
tier: "LC"
},
diggersby: {
randomBattleMoves: ["earthquake","uturn","return","wildcharge","swordsdance","quickattack","agility","knockoff"],
randomDoubleBattleMoves: ["earthquake","uturn","return","wildcharge","protect","quickattack"],
tier: "BL"
},
fletchling: {
randomBattleMoves: ["roost","swordsdance","uturn","return","overheat","flamecharge","tailwind"],
tier: "LC"
},
fletchinder: {
randomBattleMoves: ["roost","swordsdance","uturn","return","overheat","flamecharge","tailwind","acrobatics"],
tier: "RU"
},
talonflame: {
randomBattleMoves: ["bravebird","flareblitz","roost","swordsdance","uturn","willowisp","tailwind"],
randomDoubleBattleMoves: ["bravebird","flareblitz","roost","swordsdance","uturn","willowisp","tailwind","taunt","protect"],
tier: "OU"
},
scatterbug: {
randomBattleMoves: ["tackle","stringshot","stunspore","bugbite","poisonpowder"],
tier: "LC"
},
spewpa: {
randomBattleMoves: ["tackle","stringshot","stunspore","bugbite","poisonpowder"],
tier: "NFE"
},
vivillon: {
randomBattleMoves: ["sleeppowder","quiverdance","hurricane","bugbuzz","roost"],
randomDoubleBattleMoves: ["sleeppowder","quiverdance","hurricane","bugbuzz","roost","protect"],
eventPokemon: [
// Poké Ball pattern
{"generation":6,"level":12,"gender":"M","isHidden":false,"moves":["stunspore","gust","lightscreen","strugglebug"],"pokeball":"cherishball"},
// Fancy pattern
{"generation":6,"level":12,"isHidden":false,"moves":["gust","lightscreen","strugglebug","holdhands"],"pokeball":"cherishball"}
],
tier: "NU"
},
litleo: {
randomBattleMoves: ["hypervoice","fireblast","willowisp","bulldoze","yawn"],
tier: "LC"
},
pyroar: {
randomBattleMoves: ["hypervoice","fireblast","willowisp","bulldoze","sunnyday","solarbeam"],
randomDoubleBattleMoves: ["hypervoice","fireblast","willowisp","protect","sunnyday","solarbeam"],
tier: "NU"
},
flabebe: {
randomBattleMoves: ["moonblast","toxic","wish","psychic","aromatherapy","protect","calmmind"],
tier: "LC"
},
floette: {
randomBattleMoves: ["moonblast","toxic","wish","psychic","aromatherapy","protect","calmmind"],
tier: "NFE"
},
floetteeternalflower: {
randomBattleMoves: ["lightofruin","psychic","hiddenpowerfire","hiddenpowerground","moonblast"],
randomDoubleBattleMoves: ["lightofruin","dazzlinggleam","wish","psychic","aromatherapy","protect","calmmind"],
isUnreleased: true,
tier: "Unreleased"
},
florges: {
randomBattleMoves: ["moonblast","toxic","wish","psychic","aromatherapy","protect","calmmind"],
randomDoubleBattleMoves: ["moonblast","dazzlinggleam","wish","psychic","aromatherapy","protect","calmmind"],
tier: "UU"
},
skiddo: {
randomBattleMoves: ["hornleech","earthquake","brickbreak","bulkup","leechseed","milkdrink","rockslide"],
tier: "LC"
},
gogoat: {
randomBattleMoves: ["hornleech","earthquake","brickbreak","bulkup","leechseed","milkdrink","rockslide"],
randomDoubleBattleMoves: ["hornleech","earthquake","brickbreak","bulkup","leechseed","milkdrink","rockslide","protect"],
tier: "PU"
},
pancham: {
randomBattleMoves: ["partingshot","skyuppercut","crunch","stoneedge","bulldoze","shadowclaw","bulkup"],
tier: "LC"
},
pangoro: {
randomBattleMoves: ["partingshot","superpower","knockoff","drainpunch","icepunch","earthquake","gunkshot"],
randomDoubleBattleMoves: ["partingshot","hammerarm","crunch","circlethrow","icepunch","earthquake","poisonjab","protect"],
tier: "RU"
},
furfrou: {
randomBattleMoves: ["return","cottonguard","uturn","thunderwave","suckerpunch","roar","wildcharge","rest","sleeptalk"],
randomDoubleBattleMoves: ["return","cottonguard","uturn","thunderwave","suckerpunch","snarl","wildcharge","protect"],
tier: "PU"
},
espurr: {
randomBattleMoves: ["fakeout","yawn","thunderwave","psyshock","trick","darkpulse"],
tier: "LC"
},
meowstic: {
randomBattleMoves: ["toxic","yawn","thunderwave","psyshock","trick","psychic","reflect","lightscreen","healbell"],
randomDoubleBattleMoves: ["fakeout","thunderwave","psyshock","psychic","reflect","lightscreen","safeguard","protect"],
tier: "PU"
},
meowsticf: {
randomBattleMoves: ["psyshock","darkpulse","calmmind","energyball","signalbeam","thunderbolt"],
randomDoubleBattleMoves: ["psyshock","darkpulse","fakeout","energyball","signalbeam","thunderbolt","protect","helpinghand"],
tier: "PU"
},
honedge: {
randomBattleMoves: ["swordsdance","shadowclaw","shadowsneak","ironhead","rockslide","aerialace","destinybond"],
tier: "LC"
},
doublade: {
randomBattleMoves: ["swordsdance","shadowclaw","shadowsneak","ironhead","sacredsword"],
randomDoubleBattleMoves: ["swordsdance","shadowclaw","shadowsneak","ironhead","sacredsword","rockslide","protect"],
tier: "RU"
},
aegislash: {
randomBattleMoves: ["kingsshield","swordsdance","shadowclaw","sacredsword","ironhead","shadowsneak","hiddenpowerice","shadowball","flashcannon"],
randomDoubleBattleMoves: ["kingsshield","swordsdance","shadowclaw","sacredsword","ironhead","shadowsneak","wideguard","hiddenpowerice","shadowball","flashcannon"],
eventPokemon: [
{"generation":6,"level":50,"gender":"F","nature":"Quiet","moves":["wideguard","kingsshield","shadowball","flashcannon"],"pokeball":"cherishball"}
],
tier: "Uber"
},
spritzee: {
randomBattleMoves: ["calmmind","drainingkiss","moonblast","psychic","aromatherapy","wish","trickroom","thunderbolt"],
tier: "LC"
},
aromatisse: {
randomBattleMoves: ["calmmind","moonblast","psychic","aromatherapy","wish","trickroom","thunderbolt"],
randomDoubleBattleMoves: ["moonblast","aromatherapy","wish","trickroom","thunderbolt","protect","healpulse"],
tier: "RU"
},
swirlix: {
randomBattleMoves: ["calmmind","drainingkiss","dazzlinggleam","surf","psychic","flamethrower","bellydrum","thunderbolt","return","thief","cottonguard"],
tier: "LC Uber"
},
slurpuff: {
randomBattleMoves: ["calmmind","dazzlinggleam","surf","psychic","flamethrower","thunderbolt"],
randomDoubleBattleMoves: ["calmmind","dazzlinggleam","surf","psychic","flamethrower","thunderbolt","protect"],
tier: "RU"
},
inkay: {
randomBattleMoves: ["topsyturvy","switcheroo","superpower","psychocut","flamethrower","rockslide","trickroom"],
eventPokemon: [
{"generation":6,"level":10,"isHidden":false,"moves":["happyhour","foulplay","hypnosis","topsyturvy"],"pokeball":"cherishball"}
],
tier: "LC"
},
malamar: {
randomBattleMoves: ["switcheroo","superpower","psychocut","rockslide","trickroom","knockoff"],
randomDoubleBattleMoves: ["switcheroo","superpower","psychocut","rockslide","trickroom","knockoff","protect"],
tier: "NU"
},
binacle: {
randomBattleMoves: ["shellsmash","razorshell","stoneedge","earthquake","crosschop","poisonjab","xscissor","rockslide"],
tier: "LC"
},
barbaracle: {
randomBattleMoves: ["shellsmash","razorshell","stoneedge","earthquake","crosschop","poisonjab","xscissor","rockslide"],
randomDoubleBattleMoves: ["shellsmash","razorshell","stoneedge","earthquake","crosschop","poisonjab","xscissor","rockslide","protect"],
tier: "PU"
},
skrelp: {
randomBattleMoves: ["scald","sludgebomb","thunderbolt","shadowball","toxicspikes","hydropump"],
tier: "LC"
},
dragalge: {
randomBattleMoves: ["scald","sludgebomb","thunderbolt","toxicspikes","hydropump","focusblast","dracometeor","dragontail","substitute"],
randomDoubleBattleMoves: ["scald","sludgebomb","thunderbolt","protect","hydropump","focusblast","dracometeor","dragonpulse","substitute"],
tier: "BL2"
},
clauncher: {
randomBattleMoves: ["waterpulse","flashcannon","uturn","darkpulse","crabhammer","aquajet","sludgebomb"],
tier: "LC"
},
clawitzer: {
randomBattleMoves: ["waterpulse","icebeam","uturn","darkpulse","dragonpulse","aurasphere"],
randomDoubleBattleMoves: ["waterpulse","icebeam","uturn","darkpulse","dragonpulse","aurasphere","muddywater","helpinghand","protect"],
tier: "RU"
},
helioptile: {
randomBattleMoves: ["surf","voltswitch","hiddenpowerice","raindance","thunder","darkpulse","thunderbolt"],
tier: "LC"
},
heliolisk: {
randomBattleMoves: ["surf","voltswitch","hiddenpowerice","raindance","thunder","darkpulse","thunderbolt"],
randomDoubleBattleMoves: ["surf","voltswitch","hiddenpowerice","raindance","thunder","darkpulse","thunderbolt","electricterrain","protect"],
tier: "NU"
},
tyrunt: {
randomBattleMoves: ["stealthrock","dragondance","stoneedge","dragonclaw","earthquake","icefang","firefang"],
unreleasedHidden: true,
tier: "LC"
},
tyrantrum: {
randomBattleMoves: ["stealthrock","dragondance","stoneedge","dragonclaw","earthquake","firefang","outrage"],
randomDoubleBattleMoves: ["rockslide","dragondance","stoneedge","dragonclaw","earthquake","icefang","firefang","protect"],
unreleasedHidden: true,
tier: "RU"
},
amaura: {
randomBattleMoves: ["naturepower","hypervoice","ancientpower","thunderbolt","darkpulse","thunderwave","dragontail","flashcannon"],
unreleasedHidden: true,
tier: "LC"
},
aurorus: {
randomBattleMoves: ["naturepower","ancientpower","thunderbolt","encore","thunderwave","earthpower","freezedry","hypervoice","stealthrock"],
randomDoubleBattleMoves: ["hypervoice","ancientpower","thunderbolt","encore","thunderwave","flashcannon","freezedry","icywind","protect"],
unreleasedHidden: true,
tier: "PU"
},
sylveon: {
randomBattleMoves: ["hypervoice","calmmind","wish","protect","psyshock","batonpass","shadowball"],
randomDoubleBattleMoves: ["hypervoice","calmmind","wish","protect","psyshock","helpinghand","shadowball","hiddenpowerground"],
eventPokemon: [
{"generation":6,"level":10,"isHidden":false,"moves":["celebrate","helpinghand","sandattack","fairywind"],"pokeball":"cherishball"},
{"generation":6,"level":10,"gender":"F","isHidden":false,"moves":["disarmingvoice","babydolleyes","quickattack","drainingkiss"],"pokeball":"cherishball"}
],
tier: "OU"
},
hawlucha: {
randomBattleMoves: ["swordsdance","highjumpkick","acrobatics","roost","thunderpunch","substitute"],
randomDoubleBattleMoves: ["swordsdance","highjumpkick","uturn","stoneedge","skydrop","encore","protect"],
tier: "BL"
},
dedenne: {
randomBattleMoves: ["voltswitch","thunderbolt","nuzzle","grassknot","hiddenpowerice","uturn","toxic"],
randomDoubleBattleMoves: ["voltswitch","thunderbolt","nuzzle","grassknot","hiddenpowerice","uturn","helpinghand","protect"],
tier: "PU"
},
carbink: {
randomBattleMoves: ["stealthrock","lightscreen","reflect","explosion","powergem","moonblast"],
randomDoubleBattleMoves: ["trickroom","lightscreen","reflect","explosion","powergem","moonblast","protect"],
tier: "PU"
},
goomy: {
randomBattleMoves: ["sludgebomb","thunderbolt","toxic","protect","infestation"],
tier: "LC"
},
sliggoo: {
randomBattleMoves: ["sludgebomb","thunderbolt","toxic","protect","infestation","icebeam"],
tier: "NFE"
},
goodra: {
randomBattleMoves: ["thunderbolt","toxic","icebeam","dragonpulse","fireblast","dragontail","dracometeor","focusblast"],
randomDoubleBattleMoves: ["thunderbolt","feint","icebeam","dragonpulse","fireblast","muddywater","dracometeor","focusblast","protect"],
tier: "UU"
},
klefki: {
randomBattleMoves: ["reflect","lightscreen","spikes","torment","substitute","thunderwave","drainingkiss","flashcannon","dazzlinggleam"],
randomDoubleBattleMoves: ["reflect","lightscreen","safeguard","playrough","substitute","thunderwave","protect","flashcannon","dazzlinggleam"],
tier: "BL"
},
phantump: {
randomBattleMoves: ["hornleech","leechseed","phantomforce","substitute","willowisp","curse","bulldoze","rockslide","poisonjab"],
tier: "LC"
},
trevenant: {
randomBattleMoves: ["hornleech","leechseed","shadowclaw","substitute","willowisp","rest","phantomforce"],
randomDoubleBattleMoves: ["hornleech","woodhammer","leechseed","shadowclaw","willowisp","trickroom","earthquake","rockslide","protect"],
tier: "UU"
},
pumpkaboo: {
randomBattleMoves: ["willowisp","shadowsneak","fireblast","synthesis","seedbomb"],
tier: "LC"
},
pumpkaboosmall: {
randomBattleMoves: ["willowisp","shadowsneak","fireblast","synthesis","seedbomb"],
unreleasedHidden: true,
tier: "LC"
},
pumpkaboolarge: {
randomBattleMoves: ["willowisp","shadowsneak","fireblast","synthesis","seedbomb"],
unreleasedHidden: true,
tier: "LC"
},
pumpkaboosuper: {
randomBattleMoves: ["willowisp","shadowsneak","fireblast","synthesis","seedbomb"],
eventPokemon: [
{"generation":6,"level":50,"moves":["trickortreat","astonish","scaryface","shadowsneak"],"pokeball":"cherishball"}
],
tier: "LC"
},
gourgeist: {
randomBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion"],
randomDoubleBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion","protect"],
tier: "PU"
},
gourgeistsmall: {
randomBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion"],
randomDoubleBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion","protect"],
unreleasedHidden: true,
tier: "PU"
},
gourgeistlarge: {
randomBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion"],
randomDoubleBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion","protect","trickroom"],
unreleasedHidden: true,
tier: "PU"
},
gourgeistsuper: {
randomBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion"],
randomDoubleBattleMoves: ["willowisp","shadowsneak","painsplit","seedbomb","leechseed","phantomforce","explosion","protect","trickroom"],
tier: "PU"
},
bergmite: {
randomBattleMoves: ["avalanche","recover","stoneedge","curse","gyroball","rapidspin"],
tier: "LC"
},
avalugg: {
randomBattleMoves: ["avalanche","recover","stoneedge","curse","gyroball","rapidspin","roar","earthquake"],
randomDoubleBattleMoves: ["avalanche","recover","stoneedge","protect","gyroball","earthquake","curse"],
tier: "PU"
},
noibat: {
randomBattleMoves: ["airslash","hurricane","dracometeor","uturn","roost","switcheroo"],
tier: "LC"
},
noivern: {
randomBattleMoves: ["airslash","hurricane","dragonpulse","dracometeor","focusblast","flamethrower","uturn","roost","boomburst","switcheroo"],
randomDoubleBattleMoves: ["airslash","hurricane","dragonpulse","dracometeor","focusblast","flamethrower","uturn","roost","boomburst","switcheroo","tailwind","taunt","protect"],
tier: "UU"
},
xerneas: {
randomBattleMoves: ["geomancy","moonblast","thunder","focusblast"],
randomDoubleBattleMoves: ["geomancy","dazzlinggleam","thunder","focusblast","protect"],
unobtainableShiny: true,
tier: "Uber"
},
yveltal: {
randomBattleMoves: ["darkpulse","oblivionwing","taunt","focusblast","hurricane","roost","suckerpunch"],
randomDoubleBattleMoves: ["darkpulse","oblivionwing","taunt","focusblast","hurricane","roost","suckerpunch","snarl","skydrop","protect"],
unobtainableShiny: true,
tier: "Uber"
},
zygarde: {
randomBattleMoves: ["dragondance","earthquake","extremespeed","outrage","coil","stoneedge"],
randomDoubleBattleMoves: ["dragondance","landswrath","extremespeed","rockslide","coil","stoneedge","glare","protect"],
unobtainableShiny: true,
tier: "BL"
},
diancie: {
randomBattleMoves: ["diamondstorm","moonblast","reflect","lightscreen","substitute","calmmind","psychic","stealthrock"],
randomDoubleBattleMoves: ["diamondstorm","moonblast","reflect","lightscreen","safeguard","substitute","calmmind","psychic","dazzlinggleam","protect"],
eventPokemon: [
{"generation":6,"level":50,"moves":["diamondstorm","reflect","return","moonblast"],"pokeball":"cherishball"}
],
unobtainableShiny: true,
tier: "OU"
},
dianciemega: {
randomBattleMoves: ["diamondstorm","moonblast","calmmind","psyshock","earthpower","hiddenpowerfire"],
randomDoubleBattleMoves: ["diamondstorm","moonblast","calmmind","psyshock","earthpower","hiddenpowerfire","dazzlinggleam","protect"],
requiredItem: "Diancite"
},
hoopa: {
isUnreleased: true,
randomBattleMoves: ["nastyplot","psyshock","shadowball","focusblast","trick"],
randomDoubleBattleMoves: ["hyperspacehole","shadowball","focusblast","protect","psychic"],
tier: "Unreleased"
},
hoopaunbound: {
isUnreleased: true,
randomBattleMoves: ["nastyplot","psyshock","darkpulse","focusblast","hyperspacefury","zenheadbutt","icepunch","drainpunch","knockoff","trick"],
randomDoubleBattleMoves: ["psychic","darkpulse","focusblast","protect","hyperspacefury","zenheadbutt","icepunch","drainpunch"],
tier: "Unreleased"
},
volcanion: {
isUnreleased: true,
randomBattleMoves: ["substitute","steameruption","fireblast","sludgewave","hiddenpowerice","earthpower","superpower"],
randomDoubleBattleMoves: ["substitute","steameruption","heatwave","sludgewave","rockslide","earthquake","protect"],
tier: "Unreleased"
},
missingno: {
randomBattleMoves: ["watergun","skyattack","doubleedge","metronome"],
isNonstandard: true,
tier: ""
},
tomohawk: {
randomBattleMoves: ["aurasphere","roost","stealthrock","rapidspin","hurricane","airslash","taunt","substitute","toxic","naturepower","earthpower"],
isNonstandard: true,
tier: "CAP"
},
necturna: {
randomBattleMoves: ["powerwhip","hornleech","willowisp","shadowsneak","stoneedge","sacredfire","boltstrike","vcreate","extremespeed","closecombat","shellsmash","spore","milkdrink","batonpass","stickyweb"],
isNonstandard: true,
tier: "CAP"
},
mollux: {
randomBattleMoves: ["fireblast","thunderbolt","sludgebomb","thunderwave","willowisp","recover","rapidspin","trick","stealthrock","toxicspikes","lavaplume"],
isNonstandard: true,
tier: "CAP"
},
aurumoth: {
randomBattleMoves: ["dragondance","quiverdance","closecombat","bugbuzz","hydropump","megahorn","psychic","blizzard","thunder","focusblast","zenheadbutt"],
isNonstandard: true,
tier: "CAP"
},
malaconda: {
randomBattleMoves: ["powerwhip","glare","toxic","suckerpunch","rest","substitute","uturn","synthesis","rapidspin","knockoff"],
isNonstandard: true,
tier: "CAP"
},
cawmodore: {
randomBattleMoves: ["bellydrum","bulletpunch","drainpunch","acrobatics","drillpeck","substitute","ironhead","quickattack"],
isNonstandard: true,
tier: "CAP"
},
volkraken: {
randomBattleMoves: ["scald","powergem","hydropump","memento","hiddenpowerice","fireblast","willowisp","uturn","substitute","flashcannon","surf"],
isNonstandard: true,
tier: "CAP"
},
plasmanta: {
randomBattleMoves: ["sludgebomb","thunderbolt","substitute","hiddenpowerice","psyshock","dazzlinggleam","flashcannon"],
isNonstandard: true,
tier: "CAP"
},
syclant: {
randomBattleMoves: ["bugbuzz","icebeam","blizzard","earthpower","spikes","superpower","tailglow","uturn","focusblast"],
isNonstandard: true,
tier: "CAP"
},
revenankh: {
randomBattleMoves: ["bulkup","shadowsneak","drainpunch","rest","moonlight","icepunch","glare"],
isNonstandard: true,
tier: "CAP"
},
pyroak: {
randomBattleMoves: ["leechseed","lavaplume","substitute","protect","gigadrain"],
isNonstandard: true,
tier: "CAP"
},
fidgit: {
randomBattleMoves: ["spikes","stealthrock","toxicspikes","wish","rapidspin","encore","uturn","sludgebomb","earthpower"],
isNonstandard: true,
tier: "CAP"
},
stratagem: {
randomBattleMoves: ["paleowave","earthpower","fireblast","gigadrain","calmmind","substitute"],
isNonstandard: true,
tier: "CAP"
},
arghonaut: {
randomBattleMoves: ["recover","bulkup","waterfall","drainpunch","crosschop","stoneedge","thunderpunch","aquajet","machpunch"],
isNonstandard: true,
tier: "CAP"
},
kitsunoh: {
randomBattleMoves: ["shadowstrike","earthquake","superpower","meteormash","uturn","icepunch","trick","willowisp"],
isNonstandard: true,
tier: "CAP"
},
cyclohm: {
randomBattleMoves: ["slackoff","dracometeor","dragonpulse","fireblast","thunderbolt","hydropump","discharge","healbell"],
isNonstandard: true,
tier: "CAP"
},
colossoil: {
randomBattleMoves: ["earthquake","crunch","suckerpunch","uturn","rapidspin","encore","pursuit","knockoff"],
isNonstandard: true,
tier: "CAP"
},
krilowatt: {
randomBattleMoves: ["surf","thunderbolt","icebeam","earthpower"],
isNonstandard: true,
tier: "CAP"
},
voodoom: {
randomBattleMoves: ["aurasphere","darkpulse","taunt","painsplit","substitute","hiddenpowerice","vacuumwave"],
isNonstandard: true,
tier: "CAP"
}
};
| Update Random Battle moves
Reverted some from 03150fd7c039482e79eedfe06c85dfa83acb2344 and added a
few changes.
| data/formats-data.js | Update Random Battle moves | <ide><path>ata/formats-data.js
<ide> tier: "RU"
<ide> },
<ide> kangaskhan: {
<del> randomBattleMoves: ["return","suckerpunch","earthquake","poweruppunch","drainpunch","crunch","fakeout"],
<add> randomBattleMoves: ["return","suckerpunch","earthquake","drainpunch","crunch","fakeout"],
<ide> randomDoubleBattleMoves: ["fakeout","return","suckerpunch","earthquake","doubleedge","poweruppunch","drainpunch","crunch","protect"],
<ide> eventPokemon: [
<ide> {"generation":3,"level":5,"gender":"F","abilities":["earlybird"],"moves":["yawn","wish"]},
<ide> tier: "NU"
<ide> },
<ide> kangaskhanmega: {
<del> randomBattleMoves: ["fakeout","return","suckerpunch","earthquake","poweruppunch","drainpunch","crunch"],
<add> randomBattleMoves: ["fakeout","return","suckerpunch","earthquake","poweruppunch","crunch"],
<ide> randomDoubleBattleMoves: ["fakeout","return","suckerpunch","earthquake","doubleedge","poweruppunch","drainpunch","crunch","protect"],
<ide> requiredItem: "Kangaskhanite",
<ide> tier: "Uber"
<ide> tier: "LC"
<ide> },
<ide> mrmime: {
<del> randomBattleMoves: ["psychic","psyshock","focusblast","healingwish","nastyplot","thunderbolt","encore","dazzlinggleam"],
<add> randomBattleMoves: ["batonpass","psychic","psyshock","focusblast","healingwish","nastyplot","thunderbolt","encore","dazzlinggleam"],
<ide> randomDoubleBattleMoves: ["fakeout","psychic","thunderwave","hiddenpowerfighting","healingwish","nastyplot","thunderbolt","encore","icywind","protect","wideguard","dazzlinggleam"],
<ide> eventPokemon: [
<ide> {"generation":3,"level":42,"abilities":["soundproof"],"moves":["followme","psychic","encore","thunderpunch"]}
<ide> tier: "UU"
<ide> },
<ide> leafeon: {
<del> randomBattleMoves: ["swordsdance","leafblade","substitute","xscissor","synthesis","roar","healbell","batonpass","knockoff"],
<add> randomBattleMoves: ["swordsdance","leafblade","substitute","xscissor","synthesis","healbell","batonpass","knockoff"],
<ide> randomDoubleBattleMoves: ["swordsdance","leafblade","substitute","xscissor","protect","helpinghand","knockoff"],
<ide> eventPokemon: [
<ide> {"generation":5,"level":10,"gender":"M","isHidden":true,"moves":["tailwhip","tackle","helpinghand","sandattack"]},
<ide> tier: "UU"
<ide> },
<ide> ampharosmega: {
<del> randomBattleMoves: ["voltswitch","focusblast","agility","thunderbolt","healbell","dragonpulse","hiddenpowerice"],
<add> randomBattleMoves: ["voltswitch","focusblast","agility","thunderbolt","healbell","dragonpulse"],
<ide> randomDoubleBattleMoves: ["focusblast","hiddenpowerice","hiddenpowergrass","thunderbolt","discharge","dragonpulse","protect"],
<ide> requiredItem: "Ampharosite"
<ide> },
<ide> tier: "LC"
<ide> },
<ide> magcargo: {
<del> randomBattleMoves: ["recover","lavaplume","willowisp","toxic","hiddenpowergrass","hiddenpowerrock","stealthrock","fireblast","earthpower","shellsmash","ancientpower"],
<add> randomBattleMoves: ["recover","lavaplume","toxic","hiddenpowergrass","stealthrock","fireblast","earthpower","shellsmash","ancientpower"],
<ide> randomDoubleBattleMoves: ["protect","heatwave","willowisp","shellsmash","hiddenpowergrass","hiddenpowerrock","stealthrock","fireblast","earthpower"],
<ide> eventPokemon: [
<ide> {"generation":3,"level":38,"moves":["refresh","heatwave","earthquake","flamethrower"]}
<ide> tier: "PU"
<ide> },
<ide> delibird: {
<del> randomBattleMoves: ["fakeout","rapidspin","iceshard","icepunch","freezedry","aerialace","spikes","destinybond"],
<add> randomBattleMoves: ["rapidspin","iceshard","icepunch","freezedry","aerialace","spikes","destinybond"],
<ide> randomDoubleBattleMoves: ["fakeout","iceshard","icepunch","freezedry","aerialace","brickbreak","protect"],
<ide> eventPokemon: [
<ide> {"generation":3,"level":10,"gender":"M","moves":["present"]}
<ide> requiredItem: "Sablenite"
<ide> },
<ide> mawile: {
<del> randomBattleMoves: ["swordsdance","ironhead","substitute","playrough","suckerpunch","painsplit"],
<add> randomBattleMoves: ["swordsdance","ironhead","substitute","playrough","suckerpunch","batonpass"],
<ide> randomDoubleBattleMoves: ["swordsdance","ironhead","firefang","substitute","playrough","suckerpunch","knockoff","protect"],
<ide> eventPokemon: [
<ide> {"generation":3,"level":10,"gender":"M","moves":["astonish","faketears"]},
<ide> tier: "OU"
<ide> },
<ide> deoxys: {
<del> randomBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","spikes","stealthrock","knockoff","psyshock"],
<add> randomBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","spikes","stealthrock","knockoff"],
<ide> randomDoubleBattleMoves: ["psychoboost","superpower","extremespeed","icebeam","thunderbolt","firepunch","protect","knockoff","psyshock"],
<ide> eventPokemon: [
<ide> {"generation":3,"level":30,"moves":["snatch","psychic","spikes","knockoff"]},
<ide> },
<ide> empoleon: {
<ide> randomBattleMoves: ["stealthrock","hydropump","scald","icebeam","roar","grassknot","flashcannon","defog","agility"],
<del> randomDoubleBattleMoves: ["icywind","hydropump","scald","surf","icebeam","hiddenpowerelectric","protect","grassknot","flashcannon"],
<add> randomDoubleBattleMoves: ["icywind","hydropump","scald","icebeam","hiddenpowerelectric","protect","grassknot","flashcannon"],
<ide> eventPokemon: [
<ide> {"generation":5,"level":100,"gender":"M","isHidden":false,"moves":["hydropump","icebeam","aquajet","grassknot"],"pokeball":"cherishball"}
<ide> ], |
|
Java | mit | b0001cab8ba69ef65d255f6ad563a2a07a002a8d | 0 | wrapp/WebImage-Android,wrapp/WebImage-Android | /*
* Copyright (c) 2011 Bohemian Wrappsody AB
*
* 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.wrapp.android.webimage;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import java.io.*;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ImageCache {
private static final long ONE_DAY_IN_SEC = 24 * 60 * 60;
private static final long CACHE_RECHECK_AGE_IN_SEC = ONE_DAY_IN_SEC;
public static final long CACHE_RECHECK_AGE_IN_MS = CACHE_RECHECK_AGE_IN_SEC * 1000;
public static final long CACHE_EXPIRATION_AGE_IN_SEC = ONE_DAY_IN_SEC * 30;
private static final String DEFAULT_CACHE_SUBDIRECTORY_NAME = "images";
private static File cacheDirectory;
private static Map<String, WeakReference<Bitmap>> memoryCache = new HashMap<String, WeakReference<Bitmap>>();
public static boolean isImageCached(Context context, String imageKey) {
final File cacheFile = new File(getCacheDirectory(context), imageKey);
return cacheFile.exists();
}
public static Bitmap loadImage(ImageRequest request) {
final String imageKey = getKeyForUrl(request.imageUrl);
LogWrapper.logMessage("Loading image: " + request.imageUrl);
// Always check the memory cache first, even if the caller doesn't request this image to be cached
// there. This lookup is pretty fast, so it's a good performance gain.
Bitmap bitmap = loadImageFromMemoryCache(imageKey);
if(bitmap != null) {
LogWrapper.logMessage("Found image " + request.imageUrl + " in memory cache");
return bitmap;
}
final String externalStorageState = Environment.getExternalStorageState();
if(externalStorageState.equals(Environment.MEDIA_MOUNTED) || externalStorageState.endsWith(Environment.MEDIA_MOUNTED_READ_ONLY)) {
bitmap = loadImageFromFileCache(request.context, imageKey, request.imageUrl, request.loadOptions);
if(bitmap != null) {
LogWrapper.logMessage("Found image " + request.imageUrl + " in file cache");
return bitmap;
}
}
if(externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
if(ImageDownloader.loadImage(request.context, imageKey, request.imageUrl)) {
bitmap = loadImageFromFileCache(request.context, imageKey, request.imageUrl, request.loadOptions);
if(bitmap != null) {
if(request.cacheInMemory) {
saveImageInMemoryCache(imageKey, bitmap);
}
return bitmap;
}
}
}
else {
// TODO: Download directly
LogWrapper.logMessage("No SD Card present!");
return null;
}
LogWrapper.logMessage("Could not load image, returning null");
return bitmap;
}
public static Bitmap loadImageFromMemoryCache(final String imageKey) {
synchronized(memoryCache) {
if(memoryCache.containsKey(imageKey)) {
// Apparently Android's SoftReference can sometimes free objects too early, see:
// http://groups.google.com/group/android-developers/browse_thread/thread/ebabb0dadf38acc1
// If that happens then it's no big deal, as this class will simply re-load the image
// from file, but if that is the case then we should be polite and remove the imageKey
// from the cache to reflect the actual caching state of this image.
final Bitmap bitmap = memoryCache.get(imageKey).get();
if(bitmap == null) {
memoryCache.remove(imageKey);
}
return bitmap;
}
else {
return null;
}
}
}
private static Bitmap loadImageFromFileCache(final Context context, final String imageKey, final URL imageUrl, BitmapFactory.Options options) {
Bitmap bitmap = null;
File cacheFile = new File(getCacheDirectory(context), imageKey);
if(cacheFile.exists()) {
try {
Date now = new Date();
long fileAgeInMs = now.getTime() - cacheFile.lastModified();
if(fileAgeInMs > CACHE_RECHECK_AGE_IN_MS) {
Date expirationDate = ImageDownloader.getServerTimestamp(imageUrl);
if(expirationDate.after(now)) {
// TODO: decodeFileDescriptor might be faster, see http://stackoverflow.com/a/7116158/14302
bitmap = BitmapFactory.decodeStream(new FileInputStream(cacheFile), null, options);
LogWrapper.logMessage("Cached version of " + imageUrl.toString() + " is still current, updating timestamp");
if(!cacheFile.setLastModified(now.getTime())) {
LogWrapper.logMessage("Can't update timestamp!");
// Ugh, it seems that in some cases this call will always return false and refuse to update the timestamp
// For more info, see: http://code.google.com/p/android/issues/detail?id=18624
// In these cases, we manually re-write the file to disk. Yes, that sucks, but it's better than loosing
// the ability to do any intelligent file caching at all.
// TODO: saveImageInFileCache(imageKey, bitmap);
}
}
else {
LogWrapper.logMessage("Cached version of " + imageUrl.toString() + " found, but has expired.");
}
}
else {
// TODO: decodeFileDescriptor might be faster, see http://stackoverflow.com/a/7116158/14302
bitmap = BitmapFactory.decodeStream(new FileInputStream(cacheFile), null, options);
if(bitmap == null) {
throw new Exception("Could not create bitmap from image: " + imageUrl.toString());
}
}
}
catch(Exception e) {
LogWrapper.logException(e);
}
}
return bitmap;
}
private static void saveImageInMemoryCache(String imageKey, final Bitmap bitmap) {
synchronized(memoryCache) {
memoryCache.put(imageKey, new WeakReference<Bitmap>(bitmap));
}
}
public static File getCacheDirectory(final Context context) {
if(cacheDirectory == null) {
setCacheDirectory(context, DEFAULT_CACHE_SUBDIRECTORY_NAME);
}
return cacheDirectory;
}
public static void setCacheDirectory(Context context, String subdirectoryName) {
// Final destination is Android/data/com.packagename/cache/subdirectory
final File androidDirectory = new File(android.os.Environment.getExternalStorageDirectory(), "Android");
if(!androidDirectory.exists()) {
androidDirectory.mkdir();
}
final File dataDirectory = new File(androidDirectory, "data");
if(!dataDirectory.exists()) {
dataDirectory.mkdir();
}
final File packageDirectory = new File(dataDirectory, context.getPackageName());
if(!packageDirectory.exists()) {
packageDirectory.mkdir();
}
final File packageCacheDirectory = new File(packageDirectory, "cache");
if(!packageCacheDirectory.exists()) {
packageCacheDirectory.mkdir();
}
cacheDirectory = new File(packageCacheDirectory, subdirectoryName);
if(!cacheDirectory.exists()) {
cacheDirectory.mkdir();
}
LogWrapper.logMessage("Cache directory is '" + cacheDirectory.toString() + "'");
// WebImage versions prior to 1.2.2 stored images in /mnt/sdcard/data/packageName. If images are found
// there, we should migrate them to the correct location. Unfortunately, WebImage 1.1.2 and below also
// used the location /mnt/sdcard/data/images if no packageName was supplied. Since this isn't very
// specific, we don't bother to remove those images, as they may belong to other applications.
final File oldDataDirectory = new File(android.os.Environment.getExternalStorageDirectory(), "data");
final File oldPackageDirectory = new File(oldDataDirectory, context.getPackageName());
final File oldCacheDirectory = new File(oldPackageDirectory, subdirectoryName);
if(oldCacheDirectory.exists()) {
if(cacheDirectory.delete()) {
if(!oldCacheDirectory.renameTo(cacheDirectory)) {
LogWrapper.logMessage("Could not migrate old cache directory from " + oldCacheDirectory.toString());
cacheDirectory.mkdir();
}
else {
LogWrapper.logMessage("Finished migrating <1.2.2 cache directory");
}
}
}
else {
// WebImage versions prior to 1.6.0 stored the subdirectory directly under the package name, avoiding
// the intermediate cache directory. Migrate these images if this is the case.
if(!subdirectoryName.equals("cache")) {
final File oldSubdirectory = new File(packageDirectory, subdirectoryName);
if(oldSubdirectory.exists()) {
if(cacheDirectory.delete()) {
if(!oldSubdirectory.renameTo(cacheDirectory)) {
LogWrapper.logMessage("Could not migrate old cache directory from " + oldSubdirectory.toString());
cacheDirectory.mkdir();
}
else {
LogWrapper.logMessage("Finished migrating <1.6.0 cache directory");
}
}
}
}
}
}
public static void clearImageFromCaches(final Context context, final URL imageUrl) {
String imageKey = getCacheKeyForUrl(imageUrl);
synchronized(memoryCache) {
if(memoryCache.containsKey(imageKey)) {
memoryCache.remove(imageKey);
}
}
final File cacheFile = new File(getCacheDirectory(context), imageKey);
if(cacheFile.exists()) {
if(!cacheFile.delete()) {
LogWrapper.logMessage("Could not remove cached version of image '" + imageUrl + "'");
}
}
}
/**
* Clear expired images in the file cache to save disk space. This method will remove all
* images older than {@link #CACHE_EXPIRATION_AGE_IN_SEC} seconds.
* @param context Context used for getting app's package name
*/
public static void clearOldCacheFiles(final Context context) {
clearOldCacheFiles(context, CACHE_EXPIRATION_AGE_IN_SEC);
}
/**
* Clear all images older than a given amount of seconds.
* @param context Context used for getting app's package name
* @param cacheAgeInSec Image expiration limit, in seconds
*/
public static void clearOldCacheFiles(final Context context, long cacheAgeInSec) {
final long cacheAgeInMs = cacheAgeInSec * 1000;
Date now = new Date();
String[] cacheFiles = getCacheDirectory(context).list();
if(cacheFiles != null) {
for(String child : cacheFiles) {
File childFile = new File(getCacheDirectory(context), child);
if(childFile.isFile()) {
long fileAgeInMs = now.getTime() - childFile.lastModified();
if(fileAgeInMs > cacheAgeInMs) {
LogWrapper.logMessage("Deleting image '" + child + "' from cache");
childFile.delete();
}
}
}
}
}
/**
* Remove all images from the fast in-memory cache. This should be called to free up memory
* when receiving onLowMemory warnings or when the activity knows it has no use for the items
* in the memory cache anymore.
*/
public static void clearMemoryCaches() {
if(memoryCache != null) {
synchronized(memoryCache) {
LogWrapper.logMessage("Emptying in-memory cache");
for(String key : memoryCache.keySet()) {
WeakReference reference = memoryCache.get(key);
if(reference != null) {
reference.clear();
}
}
memoryCache.clear();
}
}
}
private static final char[] HEX_CHARACTERS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
/**
* Calculate a hash key for the given URL, which is used to create safe filenames and
* key strings. Internally, this method uses MD5, as that is available on Android 2.1
* devices (unlike base64, for example).
* @param url Image URL
* @return Hash for image URL
*/
public static String getCacheKeyForUrl(URL url) {
String result = "";
try {
String urlString = url.toString();
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(urlString.getBytes(), 0, urlString.length());
byte[] resultBytes = digest.digest();
StringBuilder hexStringBuilder = new StringBuilder(2 * resultBytes.length);
for(final byte b : resultBytes) {
hexStringBuilder.append(HEX_CHARACTERS[(b & 0xf0) >> 4]).append(HEX_CHARACTERS[b & 0x0f]);
}
result = hexStringBuilder.toString();
}
catch(NoSuchAlgorithmException e) {
LogWrapper.logException(e);
}
return result;
}
}
| src/com/wrapp/android/webimage/ImageCache.java | /*
* Copyright (c) 2011 Bohemian Wrappsody AB
*
* 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.wrapp.android.webimage;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import java.io.*;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ImageCache {
private static final long ONE_DAY_IN_SEC = 24 * 60 * 60;
private static final long CACHE_RECHECK_AGE_IN_SEC = ONE_DAY_IN_SEC;
private static final long CACHE_RECHECK_AGE_IN_MS = CACHE_RECHECK_AGE_IN_SEC * 1000;
private static final long CACHE_EXPIRATION_AGE_IN_SEC = ONE_DAY_IN_SEC * 30;
private static final String DEFAULT_CACHE_SUBDIRECTORY_NAME = "images";
private static File cacheDirectory;
private static Map<String, WeakReference<Bitmap>> memoryCache = new HashMap<String, WeakReference<Bitmap>>();
public static boolean isImageCached(Context context, URL imageUrl) {
final String imageKey = getKeyForUrl(imageUrl);
final File cacheFile = new File(getCacheDirectory(context), imageKey);
return cacheFile.exists();
}
public static Bitmap loadImage(ImageRequest request) {
final String imageKey = getKeyForUrl(request.imageUrl);
LogWrapper.logMessage("Loading image: " + request.imageUrl);
// Always check the memory cache first, even if the caller doesn't request this image to be cached
// there. This lookup is pretty fast, so it's a good performance gain.
Bitmap bitmap = loadImageFromMemoryCache(imageKey);
if(bitmap != null) {
LogWrapper.logMessage("Found image " + request.imageUrl + " in memory cache");
return bitmap;
}
final String externalStorageState = Environment.getExternalStorageState();
if(externalStorageState.equals(Environment.MEDIA_MOUNTED) || externalStorageState.endsWith(Environment.MEDIA_MOUNTED_READ_ONLY)) {
bitmap = loadImageFromFileCache(request.context, imageKey, request.imageUrl, request.loadOptions);
if(bitmap != null) {
LogWrapper.logMessage("Found image " + request.imageUrl + " in file cache");
return bitmap;
}
}
if(externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
if(ImageDownloader.loadImage(request.context, imageKey, request.imageUrl)) {
bitmap = loadImageFromFileCache(request.context, imageKey, request.imageUrl, request.loadOptions);
if(bitmap != null) {
if(request.cacheInMemory) {
saveImageInMemoryCache(imageKey, bitmap);
}
return bitmap;
}
}
}
else {
// TODO: Download directly
LogWrapper.logMessage("No SD Card present!");
return null;
}
LogWrapper.logMessage("Could not load image, returning null");
return bitmap;
}
private static Bitmap loadImageFromMemoryCache(final String imageKey) {
synchronized(memoryCache) {
if(memoryCache.containsKey(imageKey)) {
// Apparently Android's SoftReference can sometimes free objects too early, see:
// http://groups.google.com/group/android-developers/browse_thread/thread/ebabb0dadf38acc1
// If that happens then it's no big deal, as this class will simply re-load the image
// from file, but if that is the case then we should be polite and remove the imageKey
// from the cache to reflect the actual caching state of this image.
final Bitmap bitmap = memoryCache.get(imageKey).get();
if(bitmap == null) {
memoryCache.remove(imageKey);
}
return bitmap;
}
else {
return null;
}
}
}
private static Bitmap loadImageFromFileCache(final Context context, final String imageKey, final URL imageUrl, BitmapFactory.Options options) {
Bitmap bitmap = null;
File cacheFile = new File(getCacheDirectory(context), imageKey);
if(cacheFile.exists()) {
try {
Date now = new Date();
long fileAgeInMs = now.getTime() - cacheFile.lastModified();
if(fileAgeInMs > CACHE_RECHECK_AGE_IN_MS) {
Date expirationDate = ImageDownloader.getServerTimestamp(imageUrl);
if(expirationDate.after(now)) {
// TODO: decodeFileDescriptor might be faster, see http://stackoverflow.com/a/7116158/14302
bitmap = BitmapFactory.decodeStream(new FileInputStream(cacheFile), null, options);
LogWrapper.logMessage("Cached version of " + imageUrl.toString() + " is still current, updating timestamp");
if(!cacheFile.setLastModified(now.getTime())) {
LogWrapper.logMessage("Can't update timestamp!");
// Ugh, it seems that in some cases this call will always return false and refuse to update the timestamp
// For more info, see: http://code.google.com/p/android/issues/detail?id=18624
// In these cases, we manually re-write the file to disk. Yes, that sucks, but it's better than loosing
// the ability to do any intelligent file caching at all.
// TODO: saveImageInFileCache(imageKey, bitmap);
}
}
else {
LogWrapper.logMessage("Cached version of " + imageUrl.toString() + " found, but has expired.");
}
}
else {
// TODO: decodeFileDescriptor might be faster, see http://stackoverflow.com/a/7116158/14302
bitmap = BitmapFactory.decodeStream(new FileInputStream(cacheFile), null, options);
if(bitmap == null) {
throw new Exception("Could not create bitmap from image: " + imageUrl.toString());
}
}
}
catch(Exception e) {
LogWrapper.logException(e);
}
}
return bitmap;
}
private static void saveImageInMemoryCache(String imageKey, final Bitmap bitmap) {
synchronized(memoryCache) {
memoryCache.put(imageKey, new WeakReference<Bitmap>(bitmap));
}
}
public static File getCacheDirectory(final Context context) {
if(cacheDirectory == null) {
setCacheDirectory(context, DEFAULT_CACHE_SUBDIRECTORY_NAME);
}
return cacheDirectory;
}
public static void setCacheDirectory(Context context, String subdirectoryName) {
// Final destination is Android/data/com.packagename/cache/subdirectory
final File androidDirectory = new File(android.os.Environment.getExternalStorageDirectory(), "Android");
if(!androidDirectory.exists()) {
androidDirectory.mkdir();
}
final File dataDirectory = new File(androidDirectory, "data");
if(!dataDirectory.exists()) {
dataDirectory.mkdir();
}
final File packageDirectory = new File(dataDirectory, context.getPackageName());
if(!packageDirectory.exists()) {
packageDirectory.mkdir();
}
final File packageCacheDirectory = new File(packageDirectory, "cache");
if(!packageCacheDirectory.exists()) {
packageCacheDirectory.mkdir();
}
cacheDirectory = new File(packageCacheDirectory, subdirectoryName);
if(!cacheDirectory.exists()) {
cacheDirectory.mkdir();
}
LogWrapper.logMessage("Cache directory is '" + cacheDirectory.toString() + "'");
// WebImage versions prior to 1.2.2 stored images in /mnt/sdcard/data/packageName. If images are found
// there, we should migrate them to the correct location. Unfortunately, WebImage 1.1.2 and below also
// used the location /mnt/sdcard/data/images if no packageName was supplied. Since this isn't very
// specific, we don't bother to remove those images, as they may belong to other applications.
final File oldDataDirectory = new File(android.os.Environment.getExternalStorageDirectory(), "data");
final File oldPackageDirectory = new File(oldDataDirectory, context.getPackageName());
final File oldCacheDirectory = new File(oldPackageDirectory, subdirectoryName);
if(oldCacheDirectory.exists()) {
if(cacheDirectory.delete()) {
if(!oldCacheDirectory.renameTo(cacheDirectory)) {
LogWrapper.logMessage("Could not migrate old cache directory from " + oldCacheDirectory.toString());
cacheDirectory.mkdir();
}
else {
LogWrapper.logMessage("Finished migrating <1.2.2 cache directory");
}
}
}
else {
// WebImage versions prior to 1.6.0 stored the subdirectory directly under the package name, avoiding
// the intermediate cache directory. Migrate these images if this is the case.
if(!subdirectoryName.equals("cache")) {
final File oldSubdirectory = new File(packageDirectory, subdirectoryName);
if(oldSubdirectory.exists()) {
if(cacheDirectory.delete()) {
if(!oldSubdirectory.renameTo(cacheDirectory)) {
LogWrapper.logMessage("Could not migrate old cache directory from " + oldSubdirectory.toString());
cacheDirectory.mkdir();
}
else {
LogWrapper.logMessage("Finished migrating <1.6.0 cache directory");
}
}
}
}
}
}
public static void clearImageFromCaches(final Context context, final URL imageUrl) {
String imageKey = getKeyForUrl(imageUrl);
synchronized(memoryCache) {
if(memoryCache.containsKey(imageKey)) {
memoryCache.remove(imageKey);
}
}
final File cacheFile = new File(getCacheDirectory(context), imageKey);
if(cacheFile.exists()) {
if(!cacheFile.delete()) {
LogWrapper.logMessage("Could not remove cached version of image '" + imageUrl + "'");
}
}
}
/**
* Clear expired images in the file cache to save disk space. This method will remove all
* images older than {@link #CACHE_EXPIRATION_AGE_IN_SEC} seconds.
* @param context Context used for getting app's package name
*/
public static void clearOldCacheFiles(final Context context) {
clearOldCacheFiles(context, CACHE_EXPIRATION_AGE_IN_SEC);
}
/**
* Clear all images older than a given amount of seconds.
* @param context Context used for getting app's package name
* @param cacheAgeInSec Image expiration limit, in seconds
*/
public static void clearOldCacheFiles(final Context context, long cacheAgeInSec) {
final long cacheAgeInMs = cacheAgeInSec * 1000;
Date now = new Date();
String[] cacheFiles = getCacheDirectory(context).list();
if(cacheFiles != null) {
for(String child : cacheFiles) {
File childFile = new File(getCacheDirectory(context), child);
if(childFile.isFile()) {
long fileAgeInMs = now.getTime() - childFile.lastModified();
if(fileAgeInMs > cacheAgeInMs) {
LogWrapper.logMessage("Deleting image '" + child + "' from cache");
childFile.delete();
}
}
}
}
}
/**
* Remove all images from the fast in-memory cache. This should be called to free up memory
* when receiving onLowMemory warnings or when the activity knows it has no use for the items
* in the memory cache anymore.
*/
public static void clearMemoryCaches() {
if(memoryCache != null) {
synchronized(memoryCache) {
LogWrapper.logMessage("Emptying in-memory cache");
for(String key : memoryCache.keySet()) {
WeakReference reference = memoryCache.get(key);
if(reference != null) {
reference.clear();
}
}
memoryCache.clear();
}
}
}
private static final char[] HEX_CHARACTERS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
/**
* Calculate a hash key for the given URL, which is used to create safe filenames and
* key strings. Internally, this method uses MD5, as that is available on Android 2.1
* devices (unlike base64, for example).
* @param url Image URL
* @return Hash for image URL
*/
public static String getKeyForUrl(URL url) {
String result = "";
try {
String urlString = url.toString();
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(urlString.getBytes(), 0, urlString.length());
byte[] resultBytes = digest.digest();
StringBuilder hexStringBuilder = new StringBuilder(2 * resultBytes.length);
for(final byte b : resultBytes) {
hexStringBuilder.append(HEX_CHARACTERS[(b & 0xf0) >> 4]).append(HEX_CHARACTERS[b & 0x0f]);
}
result = hexStringBuilder.toString();
}
catch(NoSuchAlgorithmException e) {
LogWrapper.logException(e);
}
return result;
}
}
| Making methods public for static access
| src/com/wrapp/android/webimage/ImageCache.java | Making methods public for static access | <ide><path>rc/com/wrapp/android/webimage/ImageCache.java
<ide> public class ImageCache {
<ide> private static final long ONE_DAY_IN_SEC = 24 * 60 * 60;
<ide> private static final long CACHE_RECHECK_AGE_IN_SEC = ONE_DAY_IN_SEC;
<del> private static final long CACHE_RECHECK_AGE_IN_MS = CACHE_RECHECK_AGE_IN_SEC * 1000;
<del> private static final long CACHE_EXPIRATION_AGE_IN_SEC = ONE_DAY_IN_SEC * 30;
<add> public static final long CACHE_RECHECK_AGE_IN_MS = CACHE_RECHECK_AGE_IN_SEC * 1000;
<add> public static final long CACHE_EXPIRATION_AGE_IN_SEC = ONE_DAY_IN_SEC * 30;
<ide> private static final String DEFAULT_CACHE_SUBDIRECTORY_NAME = "images";
<ide>
<ide> private static File cacheDirectory;
<ide> private static Map<String, WeakReference<Bitmap>> memoryCache = new HashMap<String, WeakReference<Bitmap>>();
<ide>
<del> public static boolean isImageCached(Context context, URL imageUrl) {
<del> final String imageKey = getKeyForUrl(imageUrl);
<add> public static boolean isImageCached(Context context, String imageKey) {
<ide> final File cacheFile = new File(getCacheDirectory(context), imageKey);
<ide> return cacheFile.exists();
<ide> }
<ide> return bitmap;
<ide> }
<ide>
<del> private static Bitmap loadImageFromMemoryCache(final String imageKey) {
<add> public static Bitmap loadImageFromMemoryCache(final String imageKey) {
<ide> synchronized(memoryCache) {
<ide> if(memoryCache.containsKey(imageKey)) {
<ide> // Apparently Android's SoftReference can sometimes free objects too early, see:
<ide> }
<ide>
<ide> public static void clearImageFromCaches(final Context context, final URL imageUrl) {
<del> String imageKey = getKeyForUrl(imageUrl);
<add> String imageKey = getCacheKeyForUrl(imageUrl);
<ide> synchronized(memoryCache) {
<ide> if(memoryCache.containsKey(imageKey)) {
<ide> memoryCache.remove(imageKey);
<ide> * @param url Image URL
<ide> * @return Hash for image URL
<ide> */
<del> public static String getKeyForUrl(URL url) {
<add> public static String getCacheKeyForUrl(URL url) {
<ide> String result = "";
<ide>
<ide> try { |
|
Java | mit | e9fc05a0c1f24b0a4076c144627fbbaba30d8ffb | 0 | GlobalTechnology/gma-android | package com.expidev.gcmapp.service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.expidev.gcmapp.Constants;
import com.expidev.gcmapp.db.MeasurementDao;
import com.expidev.gcmapp.http.GmaApiClient;
import com.expidev.gcmapp.json.MeasurementsJsonParser;
import com.expidev.gcmapp.model.measurement.Measurement;
import com.expidev.gcmapp.model.measurement.MeasurementDetails;
import org.ccci.gto.android.common.api.ApiException;
import org.ccci.gto.android.common.app.ThreadedIntentService;
import org.ccci.gto.android.common.db.AbstractDao;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static com.expidev.gcmapp.service.Type.RETRIEVE_AND_SAVE_MEASUREMENTS;
import static com.expidev.gcmapp.service.Type.SAVE_MEASUREMENTS;
import static com.expidev.gcmapp.service.Type.SAVE_MEASUREMENT_DETAILS;
import static com.expidev.gcmapp.service.Type.SYNC_MEASUREMENTS;
import static com.expidev.gcmapp.utils.BroadcastUtils.runningBroadcast;
import static com.expidev.gcmapp.utils.BroadcastUtils.startBroadcast;
import static com.expidev.gcmapp.utils.BroadcastUtils.stopBroadcast;
import static com.expidev.gcmapp.utils.BroadcastUtils.updateMeasurementDetailsBroadcast;
import static com.expidev.gcmapp.utils.BroadcastUtils.updateMeasurementsBroadcast;
/**
* Created by William.Randall on 2/4/2015.
*/
public class MeasurementsService extends ThreadedIntentService
{
private static final String TAG = MeasurementsService.class.getSimpleName();
private static final String PREFS_SYNC = "gma_sync";
private static final String PREF_SYNC_TIME_MEASUREMENTS = "last_synced.measurements";
private static final String PREF_SYNC_TIME_MEASUREMENT_DETAILS = "last_synced.measurement_details";
private static final String EXTRA_FORCE = MeasurementsService.class.getName() + ".EXTRA_FORCE";
private static final String EXTRA_TYPE = "type";
private static final long HOUR_IN_MS = 60 * 60 * 1000;
private static final long DAY_IN_MS = 24 * HOUR_IN_MS;
private static final long STALE_DURATION_MEASUREMENTS = DAY_IN_MS;
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM", Locale.getDefault());
@NonNull
private MeasurementDao measurementDao;
private LocalBroadcastManager broadcastManager;
public MeasurementsService()
{
super("MeasurementsService", 5);
}
/////////////////////////////////////////////////////
// Lifecycle Handlers //
////////////////////////////////////////////////////
@Override
public void onCreate()
{
super.onCreate();
broadcastManager = LocalBroadcastManager.getInstance(this);
broadcastManager.sendBroadcast(startBroadcast());
Log.i(TAG, "Action Started");
measurementDao = MeasurementDao.getInstance(this);
}
@Override
public void onHandleIntent(Intent intent)
{
broadcastManager.sendBroadcast(runningBroadcast());
Log.i(TAG, "Action Running");
final Type type = (Type) intent.getSerializableExtra(EXTRA_TYPE);
try {
switch (type) {
case SAVE_MEASUREMENTS:
saveMeasurementsToDatabase(intent);
break;
case SYNC_MEASUREMENTS:
syncMeasurements(intent);
break;
case RETRIEVE_AND_SAVE_MEASUREMENTS:
retrieveAndSaveInitialMeasurementsAndDetails(intent);
break;
case SAVE_MEASUREMENT_DETAILS:
saveMeasurementDetailsToDatabase(intent);
break;
default:
Log.i(TAG, "Unhandled Type: " + type);
break;
}
} catch (final ApiException e) {
// XXX: ignore for now, maybe eventually broadcast something on specific ApiExceptions
}
}
/////////////////////////////////////////////////////
// Service API //
////////////////////////////////////////////////////
private static Intent baseIntent(final Context context, Bundle extras)
{
final Intent intent = new Intent(context, MeasurementsService.class);
if(extras != null)
{
intent.putExtras(extras);
}
return intent;
}
public static void saveMeasurementsToDatabase(final Context context, List<Measurement> measurements)
{
Bundle extras = new Bundle(2);
extras.putSerializable(EXTRA_TYPE, SAVE_MEASUREMENTS);
extras.putSerializable("measurements", (ArrayList<Measurement>) measurements);
context.startService(baseIntent(context, extras));
}
public static void syncMeasurements(final Context context, String ministryId, String mcc, String period)
{
syncMeasurements(context, ministryId, mcc, period, false);
}
public static void syncMeasurements(
final Context context,
String ministryId,
String mcc,
String period,
final boolean force)
{
Bundle extras = new Bundle(5);
extras.putSerializable(EXTRA_TYPE, SYNC_MEASUREMENTS);
extras.putString(Constants.ARG_MINISTRY_ID, ministryId);
extras.putString(Constants.ARG_MCC, mcc);
extras.putString(Constants.ARG_PERIOD, setPeriodToCurrentIfNecessary(period));
extras.putBoolean(EXTRA_FORCE, force);
context.startService(baseIntent(context, extras));
}
public static void retrieveAndSaveInitialMeasurements(
final Context context,
String ministryId,
String mcc,
String period)
{
Bundle extras = new Bundle(4);
extras.putSerializable(EXTRA_TYPE, RETRIEVE_AND_SAVE_MEASUREMENTS);
extras.putString(Constants.ARG_MINISTRY_ID, ministryId);
extras.putString(Constants.ARG_MCC, mcc);
extras.putString(Constants.ARG_PERIOD, setPeriodToCurrentIfNecessary(period));
context.startService(baseIntent(context, extras));
}
public static void saveMeasurementDetailsToDatabase(final Context context, MeasurementDetails measurementDetails)
{
Bundle extras = new Bundle(2);
extras.putSerializable(EXTRA_TYPE, SAVE_MEASUREMENT_DETAILS);
extras.putSerializable("measurementDetails", measurementDetails);
context.startService(baseIntent(context, extras));
}
private static String setPeriodToCurrentIfNecessary(String period)
{
if(period == null)
{
Calendar calendar = Calendar.getInstance();
period = dateFormat.format(calendar.getTime());
}
return period;
}
/////////////////////////////////////////////////////
// Actions //
////////////////////////////////////////////////////
private List<Measurement> searchMeasurements(String ministryId, String mcc, String period) throws ApiException
{
final GmaApiClient apiClient = GmaApiClient.getInstance(this);
period = setPeriodToCurrentIfNecessary(period);
JSONArray results = apiClient.searchMeasurements(ministryId, mcc, period);
if(results == null)
{
Log.e(TAG, "No measurement results!");
return null;
}
else
{
return MeasurementsJsonParser.parseMeasurements(results, ministryId, mcc, period);
}
}
private MeasurementDetails retrieveDetailsForMeasurement(
String measurementId,
String ministryId,
String mcc,
String period) throws ApiException
{
GmaApiClient apiClient = GmaApiClient.getInstance(this);
JSONObject json = apiClient.getDetailsForMeasurement(measurementId, ministryId, mcc, period);
if(json == null)
{
Log.e(TAG, "No measurement details!");
return null;
}
else
{
Log.i(TAG, "Measurement details retrieved: " + json);
MeasurementDetails measurementDetails = MeasurementsJsonParser.parseMeasurementDetails(json);
measurementDetails.setMeasurementId(measurementId);
measurementDetails.setMinistryId(ministryId);
measurementDetails.setMcc(mcc);
measurementDetails.setPeriod(period);
return measurementDetails;
}
}
private void saveMeasurementsToDatabase(Intent intent)
{
@SuppressWarnings(value = "unchecked")
List<Measurement> measurements = (ArrayList<Measurement>) intent.getSerializableExtra("measurements");
if(measurements != null)
{
updateMeasurements(measurements);
}
Log.i(TAG, "Measurements saved to the database");
}
private void syncMeasurements(Intent intent) throws ApiException
{
final SharedPreferences prefs = this.getSharedPreferences(PREFS_SYNC, MODE_PRIVATE);
final boolean force = intent.getBooleanExtra(EXTRA_FORCE, false);
final boolean stale =
System.currentTimeMillis() - prefs.getLong(PREF_SYNC_TIME_MEASUREMENTS, 0) > STALE_DURATION_MEASUREMENTS;
// only sync if being forced or the data is stale
if(force || stale)
{
String ministryId = intent.getStringExtra(Constants.ARG_MINISTRY_ID);
String mcc = intent.getStringExtra(Constants.ARG_MCC);
String period = intent.getStringExtra(Constants.ARG_PERIOD);
List<Measurement> measurements = searchMeasurements(ministryId, mcc, period);
// only update the saved measurements if we received any back
if(measurements != null)
{
updateMeasurements(measurements);
}
}
}
private void updateMeasurements(List<Measurement> measurements)
{
// save measurements for the given period, ministry, and mcc to the database
final AbstractDao.Transaction transaction = measurementDao.newTransaction();
try
{
transaction.begin();
// update measurements in local database
for(final Measurement measurement : measurements)
{
measurement.setLastSynced(new Date());
measurementDao.saveMeasurement(measurement);
}
transaction.setSuccessful();
// update the sync time
this.getSharedPreferences(PREFS_SYNC, MODE_PRIVATE).edit()
.putLong(PREF_SYNC_TIME_MEASUREMENTS, System.currentTimeMillis()).apply();
// send broadcasts for updated data
broadcastManager.sendBroadcast(stopBroadcast(SAVE_MEASUREMENTS));
broadcastManager.sendBroadcast(updateMeasurementsBroadcast());
}
catch(final SQLException e)
{
Log.e(TAG, "Error updating measurements", e);
}
finally
{
transaction.end();
}
}
private void retrieveAndSaveInitialMeasurementsAndDetails(Intent intent) throws ApiException
{
String ministryId = intent.getStringExtra(Constants.ARG_MINISTRY_ID);
String mcc = intent.getStringExtra(Constants.ARG_MCC);
String period = intent.getStringExtra(Constants.ARG_PERIOD);
Calendar previousMonth = Calendar.getInstance();
previousMonth.add(Calendar.MONTH, -1);
String previousPeriod = dateFormat.format(previousMonth.getTime());
// retrieve and save the measurements for the current and previous period
List<Measurement> measurements = searchMeasurements(ministryId, mcc, period);
List<Measurement> previousPeriodMeasurements = searchMeasurements(ministryId, mcc, previousPeriod);
if(previousPeriodMeasurements != null)
{
measurements.addAll(previousPeriodMeasurements);
}
if(!measurements.isEmpty())
{
updateMeasurements(measurements);
}
List<MeasurementDetails> measurementDetailsList = new ArrayList<>();
// retrieve and save all measurement details for the measurements retrieved
for(Measurement measurement : measurements)
{
MeasurementDetails measurementDetails = retrieveDetailsForMeasurement(
measurement.getMeasurementId(),
measurement.getMinistryId(),
measurement.getMcc(),
measurement.getPeriod());
if(measurementDetails != null)
{
measurementDetailsList.add(measurementDetails);
}
}
if(!measurementDetailsList.isEmpty())
{
Log.d(TAG, "Updating measurement details...");
updateMeasurementDetails(measurementDetailsList);
}
}
private void updateMeasurementDetails(List<MeasurementDetails> measurementDetailsList) throws ApiException
{
final AbstractDao.Transaction transaction = measurementDao.newTransaction();
try
{
transaction.begin();
for(MeasurementDetails measurementDetails : measurementDetailsList)
{
measurementDetails.setLastSynced(new Date());
measurementDao.saveMeasurementDetails(measurementDetails);
}
transaction.setSuccessful();
// update the sync time
this.getSharedPreferences(PREFS_SYNC, MODE_PRIVATE).edit()
.putLong(PREF_SYNC_TIME_MEASUREMENT_DETAILS, System.currentTimeMillis()).apply();
// send broadcasts for updated data
broadcastManager.sendBroadcast(stopBroadcast(SAVE_MEASUREMENT_DETAILS));
broadcastManager.sendBroadcast(updateMeasurementDetailsBroadcast());
}
catch(final SQLException e)
{
Log.e(TAG, "Error updating measurement details", e);
}
finally
{
transaction.end();
}
}
private void saveMeasurementDetailsToDatabase(Intent intent) throws ApiException
{
MeasurementDetails measurementDetails = (MeasurementDetails) intent.getSerializableExtra("measurementDetails");
if(measurementDetails != null)
{
List<MeasurementDetails> rowsToSave = new ArrayList<>();
rowsToSave.add(measurementDetails);
updateMeasurementDetails(rowsToSave);
}
Log.i(TAG, "Measurement details saved to local storage");
}
}
| app/src/main/java/com/expidev/gcmapp/service/MeasurementsService.java | package com.expidev.gcmapp.service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.expidev.gcmapp.Constants;
import com.expidev.gcmapp.db.MeasurementDao;
import com.expidev.gcmapp.http.GmaApiClient;
import com.expidev.gcmapp.json.MeasurementsJsonParser;
import com.expidev.gcmapp.model.measurement.Measurement;
import com.expidev.gcmapp.model.measurement.MeasurementDetails;
import org.ccci.gto.android.common.api.ApiException;
import org.ccci.gto.android.common.app.ThreadedIntentService;
import org.ccci.gto.android.common.db.AbstractDao;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import static com.expidev.gcmapp.service.Type.RETRIEVE_AND_SAVE_MEASUREMENTS;
import static com.expidev.gcmapp.service.Type.SAVE_MEASUREMENTS;
import static com.expidev.gcmapp.service.Type.SAVE_MEASUREMENT_DETAILS;
import static com.expidev.gcmapp.service.Type.SYNC_MEASUREMENTS;
import static com.expidev.gcmapp.utils.BroadcastUtils.runningBroadcast;
import static com.expidev.gcmapp.utils.BroadcastUtils.startBroadcast;
import static com.expidev.gcmapp.utils.BroadcastUtils.stopBroadcast;
import static com.expidev.gcmapp.utils.BroadcastUtils.updateMeasurementDetailsBroadcast;
import static com.expidev.gcmapp.utils.BroadcastUtils.updateMeasurementsBroadcast;
/**
* Created by William.Randall on 2/4/2015.
*/
public class MeasurementsService extends ThreadedIntentService
{
private static final String TAG = MeasurementsService.class.getSimpleName();
private static final String PREFS_SYNC = "gma_sync";
private static final String PREF_SYNC_TIME_MEASUREMENTS = "last_synced.measurements";
private static final String PREF_SYNC_TIME_MEASUREMENT_DETAILS = "last_synced.measurement_details";
private static final String EXTRA_FORCE = MeasurementsService.class.getName() + ".EXTRA_FORCE";
private static final String EXTRA_TYPE = "type";
private static final long HOUR_IN_MS = 60 * 60 * 1000;
private static final long DAY_IN_MS = 24 * HOUR_IN_MS;
private static final long STALE_DURATION_MEASUREMENTS = DAY_IN_MS;
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM", Locale.getDefault());
@NonNull
private MeasurementDao measurementDao;
private LocalBroadcastManager broadcastManager;
public MeasurementsService()
{
super("MeasurementsService", 5);
}
/////////////////////////////////////////////////////
// Lifecycle Handlers //
////////////////////////////////////////////////////
@Override
public void onCreate()
{
super.onCreate();
broadcastManager = LocalBroadcastManager.getInstance(this);
broadcastManager.sendBroadcast(startBroadcast());
Log.i(TAG, "Action Started");
measurementDao = MeasurementDao.getInstance(this);
}
@Override
public void onHandleIntent(Intent intent)
{
broadcastManager.sendBroadcast(runningBroadcast());
Log.i(TAG, "Action Running");
final Type type = (Type) intent.getSerializableExtra(EXTRA_TYPE);
try {
switch (type) {
case SAVE_MEASUREMENTS:
saveMeasurementsToDatabase(intent);
break;
case SYNC_MEASUREMENTS:
syncMeasurements(intent);
break;
case RETRIEVE_AND_SAVE_MEASUREMENTS:
retrieveAndSaveInitialMeasurementsAndDetails(intent);
break;
case SAVE_MEASUREMENT_DETAILS:
saveMeasurementDetailsToDatabase(intent);
break;
default:
Log.i(TAG, "Unhandled Type: " + type);
break;
}
} catch (final ApiException e) {
// XXX: ignore for now, maybe eventually broadcast something on specific ApiExceptions
}
}
/////////////////////////////////////////////////////
// Service API //
////////////////////////////////////////////////////
private static Intent baseIntent(final Context context, Bundle extras)
{
final Intent intent = new Intent(context, MeasurementsService.class);
if(extras != null)
{
intent.putExtras(extras);
}
return intent;
}
public static void saveMeasurementsToDatabase(final Context context, List<Measurement> measurements)
{
Bundle extras = new Bundle(2);
extras.putSerializable(EXTRA_TYPE, SAVE_MEASUREMENTS);
extras.putSerializable("measurements", (ArrayList<Measurement>) measurements);
context.startService(baseIntent(context, extras));
}
public static void syncMeasurements(final Context context, String ministryId, String mcc, String period)
{
syncMeasurements(context, ministryId, mcc, period, false);
}
public static void syncMeasurements(
final Context context,
String ministryId,
String mcc,
String period,
final boolean force)
{
Bundle extras = new Bundle(5);
extras.putSerializable(EXTRA_TYPE, SYNC_MEASUREMENTS);
extras.putString(Constants.ARG_MINISTRY_ID, ministryId);
extras.putString(Constants.ARG_MCC, mcc);
extras.putString(Constants.ARG_PERIOD, setPeriodToCurrentIfNecessary(period));
extras.putBoolean(EXTRA_FORCE, force);
context.startService(baseIntent(context, extras));
}
public static void retrieveAndSaveInitialMeasurements(
final Context context,
String ministryId,
String mcc,
String period)
{
Bundle extras = new Bundle(4);
extras.putSerializable(EXTRA_TYPE, RETRIEVE_AND_SAVE_MEASUREMENTS);
extras.putString(Constants.ARG_MINISTRY_ID, ministryId);
extras.putString(Constants.ARG_MCC, mcc);
extras.putString(Constants.ARG_PERIOD, setPeriodToCurrentIfNecessary(period));
context.startService(baseIntent(context, extras));
}
public static void saveMeasurementDetailsToDatabase(final Context context, MeasurementDetails measurementDetails)
{
Bundle extras = new Bundle(2);
extras.putSerializable(EXTRA_TYPE, SAVE_MEASUREMENT_DETAILS);
extras.putSerializable("measurementDetails", measurementDetails);
context.startService(baseIntent(context, extras));
}
private static String setPeriodToCurrentIfNecessary(String period)
{
if(period == null)
{
Calendar calendar = Calendar.getInstance();
period = dateFormat.format(calendar.getTime());
}
return period;
}
/////////////////////////////////////////////////////
// Actions //
////////////////////////////////////////////////////
private List<Measurement> searchMeasurements(String ministryId, String mcc, String period) throws ApiException
{
final GmaApiClient apiClient = GmaApiClient.getInstance(this);
period = setPeriodToCurrentIfNecessary(period);
JSONArray results = apiClient.searchMeasurements(ministryId, mcc, period);
if(results == null)
{
Log.e(TAG, "No measurement results!");
return null;
}
else
{
return MeasurementsJsonParser.parseMeasurements(results, ministryId, mcc, period);
}
}
private MeasurementDetails retrieveDetailsForMeasurement(
String measurementId,
String ministryId,
String mcc,
String period) throws ApiException
{
GmaApiClient apiClient = GmaApiClient.getInstance(this);
JSONObject json = apiClient.getDetailsForMeasurement(measurementId, ministryId, mcc, period);
if(json == null)
{
Log.e(TAG, "No measurement details!");
return null;
}
else
{
Log.i(TAG, "Measurement details retrieved: " + json);
MeasurementDetails measurementDetails = MeasurementsJsonParser.parseMeasurementDetails(json);
measurementDetails.setMeasurementId(measurementId);
measurementDetails.setMinistryId(ministryId);
measurementDetails.setMcc(mcc);
measurementDetails.setPeriod(period);
return measurementDetails;
}
}
private void saveMeasurementsToDatabase(Intent intent)
{
@SuppressWarnings(value = "unchecked")
List<Measurement> measurements = (ArrayList<Measurement>) intent.getSerializableExtra("measurements");
if(measurements != null)
{
updateMeasurements(measurements);
}
Log.i(TAG, "Measurements saved to the database");
}
private void syncMeasurements(Intent intent) throws ApiException
{
final SharedPreferences prefs = this.getSharedPreferences(PREFS_SYNC, MODE_PRIVATE);
final boolean force = intent.getBooleanExtra(EXTRA_FORCE, false);
final boolean stale =
System.currentTimeMillis() - prefs.getLong(PREF_SYNC_TIME_MEASUREMENTS, 0) > STALE_DURATION_MEASUREMENTS;
// only sync if being forced or the data is stale
if(force || stale)
{
String ministryId = intent.getStringExtra(Constants.ARG_MINISTRY_ID);
String mcc = intent.getStringExtra(Constants.ARG_MCC);
String period = intent.getStringExtra(Constants.ARG_PERIOD);
List<Measurement> measurements = searchMeasurements(ministryId, mcc, period);
// only update the saved measurements if we received any back
if(measurements != null)
{
updateMeasurements(measurements);
}
}
}
private void updateMeasurements(List<Measurement> measurements)
{
// save measurements for the given period, ministry, and mcc to the database
final AbstractDao.Transaction transaction = measurementDao.newTransaction();
try
{
transaction.begin();
// update measurements in local database
for(final Measurement measurement : measurements)
{
measurementDao.saveMeasurement(measurement);
}
transaction.setSuccessful();
// update the sync time
this.getSharedPreferences(PREFS_SYNC, MODE_PRIVATE).edit()
.putLong(PREF_SYNC_TIME_MEASUREMENTS, System.currentTimeMillis()).apply();
// send broadcasts for updated data
broadcastManager.sendBroadcast(stopBroadcast(SAVE_MEASUREMENTS));
broadcastManager.sendBroadcast(updateMeasurementsBroadcast());
}
catch(final SQLException e)
{
Log.e(TAG, "Error updating measurements", e);
}
finally
{
transaction.end();
}
}
private void retrieveAndSaveInitialMeasurementsAndDetails(Intent intent) throws ApiException
{
String ministryId = intent.getStringExtra(Constants.ARG_MINISTRY_ID);
String mcc = intent.getStringExtra(Constants.ARG_MCC);
String period = intent.getStringExtra(Constants.ARG_PERIOD);
Calendar previousMonth = Calendar.getInstance();
previousMonth.add(Calendar.MONTH, -1);
String previousPeriod = dateFormat.format(previousMonth.getTime());
// retrieve and save the measurements for the current and previous period
List<Measurement> measurements = searchMeasurements(ministryId, mcc, period);
List<Measurement> previousPeriodMeasurements = searchMeasurements(ministryId, mcc, previousPeriod);
if(previousPeriodMeasurements != null)
{
measurements.addAll(previousPeriodMeasurements);
}
if(!measurements.isEmpty())
{
updateMeasurements(measurements);
}
List<MeasurementDetails> measurementDetailsList = new ArrayList<>();
// retrieve and save all measurement details for the measurements retrieved
for(Measurement measurement : measurements)
{
MeasurementDetails measurementDetails = retrieveDetailsForMeasurement(
measurement.getMeasurementId(),
measurement.getMinistryId(),
measurement.getMcc(),
measurement.getPeriod());
if(measurementDetails != null)
{
measurementDetailsList.add(measurementDetails);
}
}
if(!measurementDetailsList.isEmpty())
{
Log.d(TAG, "Updating measurement details...");
updateMeasurementDetails(measurementDetailsList);
}
}
private void updateMeasurementDetails(List<MeasurementDetails> measurementDetailsList) throws ApiException
{
final AbstractDao.Transaction transaction = measurementDao.newTransaction();
try
{
transaction.begin();
for(MeasurementDetails measurementDetails : measurementDetailsList)
{
measurementDao.saveMeasurementDetails(measurementDetails);
}
transaction.setSuccessful();
// update the sync time
this.getSharedPreferences(PREFS_SYNC, MODE_PRIVATE).edit()
.putLong(PREF_SYNC_TIME_MEASUREMENT_DETAILS, System.currentTimeMillis()).apply();
// send broadcasts for updated data
broadcastManager.sendBroadcast(stopBroadcast(SAVE_MEASUREMENT_DETAILS));
broadcastManager.sendBroadcast(updateMeasurementDetailsBroadcast());
}
catch(final SQLException e)
{
Log.e(TAG, "Error updating measurement details", e);
}
finally
{
transaction.end();
}
}
private void saveMeasurementDetailsToDatabase(Intent intent) throws ApiException
{
MeasurementDetails measurementDetails = (MeasurementDetails) intent.getSerializableExtra("measurementDetails");
if(measurementDetails != null)
{
List<MeasurementDetails> rowsToSave = new ArrayList<>();
rowsToSave.add(measurementDetails);
updateMeasurementDetails(rowsToSave);
}
Log.i(TAG, "Measurement details saved to local storage");
}
}
| Save the current time in the database for measurements and details
| app/src/main/java/com/expidev/gcmapp/service/MeasurementsService.java | Save the current time in the database for measurements and details | <ide><path>pp/src/main/java/com/expidev/gcmapp/service/MeasurementsService.java
<ide> import java.text.SimpleDateFormat;
<ide> import java.util.ArrayList;
<ide> import java.util.Calendar;
<add>import java.util.Date;
<ide> import java.util.List;
<ide> import java.util.Locale;
<ide>
<ide> // update measurements in local database
<ide> for(final Measurement measurement : measurements)
<ide> {
<add> measurement.setLastSynced(new Date());
<ide> measurementDao.saveMeasurement(measurement);
<ide> }
<ide>
<ide>
<ide> for(MeasurementDetails measurementDetails : measurementDetailsList)
<ide> {
<add> measurementDetails.setLastSynced(new Date());
<ide> measurementDao.saveMeasurementDetails(measurementDetails);
<ide> }
<ide> |
|
Java | apache-2.0 | 980fac46eb580e5f8b11a20dab25e8e99f697d21 | 0 | lmdbjava/lmdbjava,phraktle/lmdbjava | /*
* Copyright 2016 The LmdbJava Project, http://lmdbjava.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.lmdbjava;
import java.io.File;
import static java.lang.Integer.MAX_VALUE;
import java.nio.ByteBuffer;
import static java.nio.ByteBuffer.allocateDirect;
import static java.util.Collections.nCopies;
import java.util.Random;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.lmdbjava.Dbi.DbFullException;
import org.lmdbjava.Dbi.KeyExistsException;
import static org.lmdbjava.DbiFlags.MDB_CREATE;
import static org.lmdbjava.DbiFlags.MDB_DUPSORT;
import org.lmdbjava.Env.MapFullException;
import org.lmdbjava.Env.NotOpenException;
import static org.lmdbjava.Env.create;
import static org.lmdbjava.EnvFlags.MDB_NOSUBDIR;
import static org.lmdbjava.GetOp.MDB_SET_KEY;
import static org.lmdbjava.PutFlags.MDB_NOOVERWRITE;
import static org.lmdbjava.TestUtils.DB_1;
import static org.lmdbjava.TestUtils.POSIX_MODE;
import static org.lmdbjava.TestUtils.createBb;
import org.lmdbjava.Txn.CommittedException;
import org.lmdbjava.Txn.ReadWriteRequiredException;
public class DbiTest {
@Rule
public final TemporaryFolder tmp = new TemporaryFolder();
private Env<ByteBuffer> env;
@Before
public void before() throws Exception {
env = create();
final File path = tmp.newFile();
env.setMapSize(1_024 * 1_024 * 1_024);
env.setMaxDbs(2);
env.setMaxReaders(1);
env.open(path, POSIX_MODE, MDB_NOSUBDIR);
}
@Test(expected = DbFullException.class)
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public void dbOpenMaxDatabases() {
env.openDbi("db1 is OK", MDB_CREATE);
env.openDbi("db2 is OK", MDB_CREATE);
env.openDbi("db3 fails", MDB_CREATE);
}
@Test
public void getName() throws Exception {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
assertThat(db.getName(), is(DB_1));
}
@Test(expected = KeyExistsException.class)
public void keyExistsException() throws Exception {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
db.put(txn, createBb(5), createBb(5), MDB_NOOVERWRITE);
db.put(txn, createBb(5), createBb(5), MDB_NOOVERWRITE);
}
}
@Test
public void putAbortGet() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
db.put(txn, createBb(5), createBb(5));
txn.abort();
}
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
assertNull(db.get(txn, createBb(5)));
}
}
@Test
public void putAndGetAndDeleteWithInternalTx() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
db.put(createBb(5), createBb(5));
try (final Txn<ByteBuffer> txn = env.txnRead()) {
final ByteBuffer found = db.get(txn, createBb(5));
assertNotNull(found);
assertThat(txn.val().getInt(), is(5));
}
db.delete(createBb(5));
try (final Txn<ByteBuffer> txn = env.txnRead()) {
assertNull(db.get(txn, createBb(5)));
}
}
@Test
public void putCommitGet() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
db.put(txn, createBb(5), createBb(5));
txn.commit();
}
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
final ByteBuffer found = db.get(txn, createBb(5));
assertNotNull(found);
assertThat(txn.val().getInt(), is(5));
}
}
@Test
public void putDelete() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
db.put(txn, createBb(5), createBb(5));
db.delete(txn, createBb(5));
assertNull(db.get(txn, createBb(5)));
txn.abort();
}
}
@Test
public void putDuplicateDelete() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE, MDB_DUPSORT);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
db.put(txn, createBb(5), createBb(5));
db.put(txn, createBb(5), createBb(6));
db.put(txn, createBb(5), createBb(7));
db.delete(txn, createBb(5), createBb(6));
try (final Cursor<ByteBuffer> cursor = db.openCursor(txn)) {
final ByteBuffer key = createBb(5);
cursor.get(key, MDB_SET_KEY);
assertThat(cursor.count(), is(2L));
}
txn.abort();
}
}
@Test
public void putReserve() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
final ByteBuffer key = createBb(5);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
final ByteBuffer val = createBb(MAX_VALUE);
assertNull(db.get(txn, key));
db.reserve(txn, key, val);
assertNotNull(db.get(txn, key));
val.putInt(16).flip();
txn.commit();
}
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
final ByteBuffer val = db.get(txn, key);
assertThat(val.getInt(), is(16));
}
}
@Test(expected = MapFullException.class)
public void testMapFullException() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
final ByteBuffer v = allocateDirect(1_024 * 1_024 * 1_024);
db.put(txn, createBb(1), v);
}
}
@Test
public void testParallelWritesStress() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
// Travis CI has 1.5 cores for legacy builds
nCopies(2, null).parallelStream()
.forEach(ignored -> {
Random random = new Random();
for (int i = 0; i < 15_000; i++) {
try {
db.put(createBb(random.nextInt()), createBb(random.nextInt()));
} catch (CommittedException | LmdbNativeException | NotOpenException |
ReadWriteRequiredException e) {
throw new RuntimeException(e);
}
}
});
}
}
| src/test/java/org/lmdbjava/DbiTest.java | /*
* Copyright 2016 The LmdbJava Project, http://lmdbjava.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.lmdbjava;
import java.io.File;
import java.nio.ByteBuffer;
import static java.nio.ByteBuffer.allocateDirect;
import static java.util.Collections.nCopies;
import java.util.Random;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.lmdbjava.Dbi.DbFullException;
import org.lmdbjava.Dbi.KeyExistsException;
import static org.lmdbjava.DbiFlags.MDB_CREATE;
import static org.lmdbjava.DbiFlags.MDB_DUPSORT;
import org.lmdbjava.Env.MapFullException;
import org.lmdbjava.Env.NotOpenException;
import static org.lmdbjava.Env.create;
import static org.lmdbjava.EnvFlags.MDB_NOSUBDIR;
import static org.lmdbjava.GetOp.MDB_SET_KEY;
import static org.lmdbjava.PutFlags.MDB_NOOVERWRITE;
import static org.lmdbjava.TestUtils.DB_1;
import static org.lmdbjava.TestUtils.POSIX_MODE;
import static org.lmdbjava.TestUtils.createBb;
import org.lmdbjava.Txn.CommittedException;
import org.lmdbjava.Txn.ReadWriteRequiredException;
public class DbiTest {
@Rule
public final TemporaryFolder tmp = new TemporaryFolder();
private Env<ByteBuffer> env;
@Before
public void before() throws Exception {
env = create();
final File path = tmp.newFile();
env.setMapSize(1_024 * 1_024 * 1_024);
env.setMaxDbs(2);
env.setMaxReaders(1);
env.open(path, POSIX_MODE, MDB_NOSUBDIR);
}
@Test(expected = DbFullException.class)
@SuppressWarnings("ResultOfObjectAllocationIgnored")
public void dbOpenMaxDatabases() {
env.openDbi("db1 is OK", MDB_CREATE);
env.openDbi("db2 is OK", MDB_CREATE);
env.openDbi("db3 fails", MDB_CREATE);
}
@Test
public void getName() throws Exception {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
assertThat(db.getName(), is(DB_1));
}
@Test(expected = KeyExistsException.class)
public void keyExistsException() throws Exception {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
db.put(txn, createBb(5), createBb(5), MDB_NOOVERWRITE);
db.put(txn, createBb(5), createBb(5), MDB_NOOVERWRITE);
}
}
@Test
public void putAbortGet() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
db.put(txn, createBb(5), createBb(5));
txn.abort();
}
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
assertNull(db.get(txn, createBb(5)));
}
}
@Test
public void putAndGetAndDeleteWithInternalTx() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
db.put(createBb(5), createBb(5));
try (final Txn<ByteBuffer> txn = env.txnRead()) {
final ByteBuffer found = db.get(txn, createBb(5));
assertNotNull(found);
assertThat(txn.val().getInt(), is(5));
}
db.delete(createBb(5));
try (final Txn<ByteBuffer> txn = env.txnRead()) {
assertNull(db.get(txn, createBb(5)));
}
}
@Test
public void putCommitGet() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
db.put(txn, createBb(5), createBb(5));
txn.commit();
}
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
final ByteBuffer found = db.get(txn, createBb(5));
assertNotNull(found);
assertThat(txn.val().getInt(), is(5));
}
}
@Test
public void putDelete() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
db.put(txn, createBb(5), createBb(5));
db.delete(txn, createBb(5));
assertNull(db.get(txn, createBb(5)));
txn.abort();
}
}
@Test
public void putDuplicateDelete() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE, MDB_DUPSORT);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
db.put(txn, createBb(5), createBb(5));
db.put(txn, createBb(5), createBb(6));
db.put(txn, createBb(5), createBb(7));
db.delete(txn, createBb(5), createBb(6));
try (final Cursor<ByteBuffer> cursor = db.openCursor(txn)) {
final ByteBuffer key = createBb(5);
cursor.get(key, MDB_SET_KEY);
assertThat(cursor.count(), is(2L));
}
txn.abort();
}
}
@Test
public void putReserve() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
ByteBuffer in = createBb(16);
db.reserve(txn, createBb(5), in);
in.putInt(16).flip();
assertNotNull(db.get(txn, createBb(5)));
txn.commit();
}
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
ByteBuffer byteBuffer = db.get(txn, createBb(5));
assertThat(byteBuffer.getInt(), is(16));
}
}
@Test(expected = MapFullException.class)
public void testMapFullException() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
try (final Txn<ByteBuffer> txn = env.txnWrite()) {
final ByteBuffer v = allocateDirect(1_024 * 1_024 * 1_024);
db.put(txn, createBb(1), v);
}
}
@Test
public void testParallelWritesStress() {
final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
// Travis CI has 1.5 cores for legacy builds
nCopies(2, null).parallelStream()
.forEach(ignored -> {
Random random = new Random();
for (int i = 0; i < 15_000; i++) {
try {
db.put(createBb(random.nextInt()), createBb(random.nextInt()));
} catch (CommittedException | LmdbNativeException | NotOpenException |
ReadWriteRequiredException e) {
throw new RuntimeException(e);
}
}
});
}
}
| Make DbiTest of reserve a little clearer
| src/test/java/org/lmdbjava/DbiTest.java | Make DbiTest of reserve a little clearer | <ide><path>rc/test/java/org/lmdbjava/DbiTest.java
<ide> package org.lmdbjava;
<ide>
<ide> import java.io.File;
<add>import static java.lang.Integer.MAX_VALUE;
<ide> import java.nio.ByteBuffer;
<ide> import static java.nio.ByteBuffer.allocateDirect;
<ide> import static java.util.Collections.nCopies;
<ide> public void putReserve() {
<ide> final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE);
<ide>
<del> try (final Txn<ByteBuffer> txn = env.txnWrite()) {
<del> ByteBuffer in = createBb(16);
<del> db.reserve(txn, createBb(5), in);
<del> in.putInt(16).flip();
<del> assertNotNull(db.get(txn, createBb(5)));
<add> final ByteBuffer key = createBb(5);
<add> try (final Txn<ByteBuffer> txn = env.txnWrite()) {
<add> final ByteBuffer val = createBb(MAX_VALUE);
<add> assertNull(db.get(txn, key));
<add> db.reserve(txn, key, val);
<add> assertNotNull(db.get(txn, key));
<add> val.putInt(16).flip();
<ide> txn.commit();
<ide> }
<ide> try (final Txn<ByteBuffer> txn = env.txnWrite()) {
<del> ByteBuffer byteBuffer = db.get(txn, createBb(5));
<del> assertThat(byteBuffer.getInt(), is(16));
<add> final ByteBuffer val = db.get(txn, key);
<add> assertThat(val.getInt(), is(16));
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 32ec15da348f163110041ac85842ca1ce9112547 | 0 | GiovanniPaoloGibilisco/spark-log-processor,GiovanniPaoloGibilisco/spark-log-processor,GiovanniPaoloGibilisco/spark-log-processor | package it.polimi.spark;
import it.polimi.spark.dag.RDDnode;
import it.polimi.spark.dag.Stagenode;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SQLContext;
import org.apache.spark.sql.hive.HiveContext;
import org.apache.spark.sql.types.ArrayType;
import org.apache.spark.sql.types.DataType;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import org.jgraph.graph.AttributeMap;
import org.jgraph.graph.DefaultEdge;
import org.jgrapht.experimental.dag.DirectedAcyclicGraph;
import org.jgrapht.ext.ComponentAttributeProvider;
import org.jgrapht.ext.DOTExporter;
import org.jgrapht.ext.EdgeNameProvider;
import org.jgrapht.ext.VertexNameProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.collection.JavaConversions;
import scala.collection.Seq;
import scala.collection.Traversable;
import scala.collection.mutable.ArrayBuffer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class LoggerParser {
static Config config;
static FileSystem hdfs;
static final Logger logger = LoggerFactory.getLogger(LoggerParser.class);
static SQLContext sqlContext;
static final String STAGE_LABEL = "Stage_";
static final String JOB_LABEL = "Job_";
static final String RDD_LABEL = "RDD_";
static final String APPLICATION_DAG_LABEL = "application-graph";
static final String APPLICATION_RDD_LABEL = "application-rdd";
static final String DOT_EXTENSION = ".dot";
static Map<Integer, List<Integer>> job2StagesMap = new HashMap<Integer, List<Integer>>();
static Map<Integer, Integer> stage2jobMap = new HashMap<Integer, Integer>();
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException,
URISyntaxException, ClassNotFoundException {
// the hadoop configuration
Configuration hadoopConf = new Configuration();
hdfs = FileSystem.get(hadoopConf);
// the spark configuration
SparkConf conf = new SparkConf().setAppName("logger-parser");
// the configuration of the application (as launched by the user)
Config.init(args);
config = Config.getInstance();
if (config.usage) {
config.usage();
return;
}
if (config.runLocal) {
conf.setMaster("local[1]");
}
// either -i or -app has to be specified
if (config.inputFile == null && config.applicationID == null) {
logger.info("No input file (-i option) or application id (-a option) has been specified. At least one of these options has to be provided");
config.usage();
return;
}
// exactly one otherwise we will not know where the user wants to get
// the logs from
if (config.inputFile != null && config.applicationID != null) {
logger.info("Either the input file (-i option) or the application id (-app option) has to be specified.");
return;
}
// if the -a option has been specified, then get the default
// logging directory from sparkconf (property spark.eventLog.dir) and
// use it as base folder to look for the application log
if (config.applicationID != null) {
String eventLogDir = conf.get("spark.eventLog.dir", null).replace(
"file://", "");
if (eventLogDir == null) {
logger.info("Could not retireve the logging directory from the spark configuration, the property spark.eventLog.dir has to be set in the cluster configuration");
return;
}
config.inputFile = eventLogDir + "/" + config.applicationID;
}
logger.info("Reding logs from: " + config.inputFile);
// if the file does not exist
if (config.inputFile != null
&& !hdfs.exists(new Path(config.inputFile))) {
logger.info("Input file " + config.inputFile + " does not exist");
return;
}
@SuppressWarnings("resource")
JavaSparkContext sc = new JavaSparkContext(conf);
sqlContext = new HiveContext(sc.sc());
if (hdfs.exists(new Path(config.outputFolder)))
hdfs.delete(new Path(config.outputFolder), true);
// load the logs
DataFrame logsframe = sqlContext.jsonFile(config.inputFile);
logsframe = sqlContext.applySchema(logsframe.toJavaRDD(),
(StructType) cleanSchema(logsframe.schema()));
logsframe.cache();
// register the main table with all the logs as "events"
logsframe.registerTempTable("events");
// stageDetails.show((int) stageDetails.count());
// save CSV with performance information
if (config.task) {
logger.info("Retrieving Task information");
DataFrame taskDetails = retrieveTaskInformation();
saveListToCSV(taskDetails, "TaskDetails.csv");
}
DataFrame stageDetailsFrame = null;
List<Row> stageDetails = null;
List<String> stageDetailsColumns = null;
DataFrame jobDetailsFrame = null;
List<Row> jobDetails = null;
List<String> jobDetailsColumns = null;
List<Stagenode> stageNodes = null;
List<Stage> stages = null;
List<Job> jobs = null;
int numberOfJobs = 0;
int numberOfStages = 0;
Benchmark application = null;
DBHandler dbHandler = null;
if (config.toDB) {
if (config.dbUser == null)
logger.warn("No user name has been specified for the connection with the DB, results will not be uploaded");
if (config.dbPassword == null)
logger.warn("No password has been specified for the connection with the DB, results will not be uploaded");
if (config.dbUser != null && config.dbPassword != null) {
dbHandler = new DBHandler(config.dbUrl, config.dbUser,
config.dbPassword);
logger.info("Retrieving Application Information");
application = retrieveApplicationConfiguration();
}
}
// I could also remove the if, almost every functionality require to
// parse stage details
if (config.ApplicationDAG || config.jobDAGS
|| config.buildStageRDDGraph || config.buildJobRDDGraph
|| config.toDB) {
DataFrame applicationEvents = retrieveApplicationEvents();
saveListToCSV(applicationEvents, "application.csv");
// add the duration to the application
if (application != null && config.toDB)
application.setDuration(getDuration(applicationEvents));
// collect stages from log files
logger.info("Retrieving Stage Information");
stageDetailsFrame = retrieveStageInformation();
saveListToCSV(stageDetailsFrame, "StageDetails.csv");
stageDetails = stageDetailsFrame.collectAsList();
stageDetailsColumns = new ArrayList<String>(
Arrays.asList(stageDetailsFrame.columns()));
// collect jobs from log files
logger.info("Retrieving Job Information");
jobDetailsFrame = retrieveJobInformation();
saveListToCSV(jobDetailsFrame, "JobDetails.csv");
jobDetails = jobDetailsFrame.collectAsList();
jobDetailsColumns = new ArrayList<String>(
Arrays.asList(jobDetailsFrame.columns()));
initMaps(stageDetails, stageDetailsColumns, jobDetails,
jobDetailsColumns);
stageNodes = extractStageNodes(stageDetails, stageDetailsColumns);
if (config.toDB && application != null) {
stages = extractStages(stageDetails, stageDetailsColumns,
application.getClusterName(), application.getAppID());
jobs = extractJobs(jobDetails, jobDetailsColumns,
application.getClusterName(), application.getAppID());
Map<Integer, Stage> stageById = new HashMap<Integer, Stage>(
stages.size());
for (Stage stage : stages)
stageById.put(stage.getStageID(), stage);
for (Job job : jobs) {
// link job to application
application.addJob(job);
// link stages to jobs
for (int stageId : job2StagesMap.get(job.getJobID()))
// skip non executed
if (stageById.containsKey(stageId))
job.addStage(stageById.get(stageId));
}
}
numberOfJobs = jobDetails.size();
numberOfStages = stageDetails.size();
}
if (config.ApplicationDAG) {
logger.info("Building Stage DAG");
DirectedAcyclicGraph<Stagenode, DefaultEdge> stageDag = buildStageDag(stageNodes);
printStageGraph(stageDag);
}
if (config.jobDAGS) {
for (int i = 0; i <= numberOfJobs; i++) {
logger.info("Building Job DAG");
DirectedAcyclicGraph<Stagenode, DefaultEdge> stageDag = buildStageDag(
stageNodes, i);
printStageGraph(stageDag, i);
if (config.export)
serializeDag(stageDag, JOB_LABEL + i);
}
}
// This part takes care of functionalities related to rdds
List<RDDnode> rdds = null;
if (config.buildJobRDDGraph || config.buildStageRDDGraph) {
logger.info("Building Retrieving RDD information");
DataFrame rddDetails = retrieveRDDInformation();
saveListToCSV(rddDetails, "rdd.csv");
rdds = extractRDDs(rddDetails);
}
if (config.buildJobRDDGraph) {
for (int i = 0; i <= numberOfJobs; i++) {
logger.info("Building RDD Job DAG");
DirectedAcyclicGraph<RDDnode, DefaultEdge> rddDag = buildRDDDag(
rdds, i, -1);
printRDDGraph(rddDag, i, -1);
if (config.export)
serializeDag(rddDag, RDD_LABEL + JOB_LABEL
+ stage2jobMap.get(i).intValue());
}
}
if (config.buildStageRDDGraph) {
// register the current dataframe as jobs table
logger.info("Building RDD Stage DAG");
for (int i = 0; i <= numberOfStages; i++) {
DirectedAcyclicGraph<RDDnode, DefaultEdge> rddDag = buildRDDDag(
rdds, -1, i);
printRDDGraph(rddDag, stage2jobMap.get(i).intValue(), i);
if (config.export)
serializeDag(rddDag, RDD_LABEL + JOB_LABEL
+ stage2jobMap.get(i).intValue() + STAGE_LABEL + i);
}
}
if (config.toDB && application != null && dbHandler != null) {
logger.info("Adding application to the database");
logger.info("Cluster name: " + application.getClusterName());
logger.info("Application Id: " + application.getAppID());
logger.info("Application Name: " + application.getAppName());
try {
dbHandler.insertBenchmark(application);
} catch (SQLException e) {
logger.warn(
"The application could not be added to the database ",
e);
}finally{
saveApplicationInfo(application.getClusterName(), application.getAppID(), application.getAppName(), config.dbUser);
}
}
if (dbHandler != null)
dbHandler.close();
}
/**
* Extract all the jobs in objects containing performance information, no
* topological info is saved
*
* @param jobDetails
* @param jobColumns
* @param clusterName
* @param applicationID
* @return
*/
private static List<Job> extractJobs(List<Row> jobDetails,
List<String> jobColumns, String clusterName, String appID) {
List<Job> jobs = new ArrayList<Job>();
for (Row row : jobDetails) {
int jobId = (int) row.getLong(jobColumns.indexOf("Job ID"));
Job job = new Job(clusterName, appID, jobId);
job.setDuration((int) row.getLong(jobColumns.indexOf("Duration")));
jobs.add(job);
}
return jobs;
}
/**
* Initializes the hashmaps used to retrieve job id from stage and viceversa
* (a list of stage id from a job id)
*
* @param stageDetails
* @param stageColumns
* @param jobDetails
* @param jobColumns
*/
@SuppressWarnings("unchecked")
private static void initMaps(List<Row> stageDetails,
List<String> stageColumns, List<Row> jobDetails,
List<String> jobColumns) {
// setup hashmap from job to list of stages ids and viceversa
for (Row row : jobDetails) {
int jobID = (int) row.getLong(jobColumns.indexOf("Job ID"));
List<Long> tmpStageList = null;
List<Integer> stageList = null;
if (row.get(jobColumns.indexOf("Stage IDs")) instanceof scala.collection.immutable.List<?>)
tmpStageList = JavaConversions.asJavaList((Seq<Long>) row
.get(jobColumns.indexOf("Stage IDs")));
else if (row.get(jobColumns.indexOf("Stage IDs")) instanceof ArrayBuffer<?>)
tmpStageList = JavaConversions
.asJavaList((ArrayBuffer<Long>) row.get(jobColumns
.indexOf("Stage IDs")));
else {
logger.warn("Could not parse Stage IDs Serialization:"
+ row.get(jobColumns.indexOf("Stage IDs")).toString()
+ " class: "
+ row.get(jobColumns.indexOf("Stage IDs")).getClass()
+ " Object: "
+ row.get(jobColumns.indexOf("Stage IDs")));
}
// convert it to integers
stageList = new ArrayList<Integer>();
for (Long stage : tmpStageList) {
stageList.add(stage.intValue());
// Initialize the hashmap StageID -> JobID
stage2jobMap.put(stage.intValue(), jobID);
}
// and the one JobID -> List of stage IDs
job2StagesMap.put(jobID, stageList);
}
}
/**
* Extract all the stages in objects containing performance information, no
* topological info is saved
*
* @param stageDetails
* @param stageColumns
* @param clusterName
* @param applicationID
* @return
*/
private static List<Stage> extractStages(List<Row> stageDetails,
List<String> stageColumns, String clusterName, String applicationID) {
List<Stage> stages = new ArrayList<Stage>();
for (Row row : stageDetails) {
// filter outnon executed stages
if (Boolean.parseBoolean(row.getString(stageColumns
.indexOf("Executed")))) {
int stageId = (int) row.getLong(stageColumns
.indexOf("Stage ID"));
Stage stage = new Stage(clusterName, applicationID,
stage2jobMap.get(stageId), stageId);
stage.setDuration(Integer.parseInt(row.getString(stageColumns
.indexOf("Duration"))));
// TODO: add parsing of input/output and shuffle sizes
stages.add(stage);
}
}
return stages;
}
private static int getDuration(DataFrame applicationEvents) {
Row[] events = applicationEvents.collect();
long startTime = 0;
long endTime = 0;
for (Row event : events) {
if (event.getString(0).equals("SparkListenerApplicationStart"))
startTime = event.getLong(2);
else
endTime = event.getLong(2);
}
return (int) (endTime - startTime);
}
private static Benchmark retrieveApplicationConfiguration() {
DataFrame sparkPropertiesDf = sqlContext
.sql("SELECT `Spark Properties` FROM events WHERE Event LIKE '%EnvironmentUpdate'");
StructType schema = (StructType) ((StructType) sparkPropertiesDf
.schema()).fields()[0].dataType();
List<String> columns = new ArrayList<String>();
for (String column : schema.fieldNames())
columns.add(column);
String selectedColumns = "";
for (String column : columns) {
selectedColumns += "`Spark Properties." + column + "`" + ", ";
}
sparkPropertiesDf = sqlContext.sql("SELECT " + selectedColumns
+ "`System Properties.sun-java-command`"
+ " FROM events WHERE Event LIKE '%EnvironmentUpdate'");
// there should only be one of such events
Row row = sparkPropertiesDf.toJavaRDD().first();
Benchmark application = new Benchmark(row.getString(columns
.indexOf("spark-master")), row.getString(columns
.indexOf("spark-app-id")));
if (columns.contains("spark-app-name"))
application.setAppName(row.getString(columns
.indexOf("spark-app-name")));
if (columns.contains("spark-driver-memory")) {
String memory = row.getString(columns
.indexOf("spark-driver-memory"));
// removing g or m
memory = memory.substring(0, memory.length() - 1);
application.setDriverMemory(Double.parseDouble(memory));
}
if (columns.contains("spark-executor-memory")) {
String memory = row.getString(columns
.indexOf("spark-executor-memory"));
// removing g or m
memory = memory.substring(0, memory.length() - 1);
application.setExecutorMemory(Double.parseDouble(memory));
}
if (columns.contains("spark-kryoserializer-buffer-max")) {
String memory = row.getString(columns
.indexOf("spark-kryoserializer-buffer-max"));
// removing g or m
memory = memory.substring(0, memory.length() - 1);
application.setKryoMaxBuffer(Integer.parseInt(memory));
}
if (columns.contains("spark-rdd-compress"))
application.setRddCompress(Boolean.parseBoolean(row
.getString(columns.indexOf("spark-rdd-compress"))));
if (columns.contains("spark-storage-memoryFraction"))
application
.setStorageMemoryFraction(Double.parseDouble(row
.getString(columns
.indexOf("spark-storage-memoryFraction"))));
if (columns.contains("spark-shuffle-memoryFraction"))
application
.setShuffleMemoryFraction(Double.parseDouble(row
.getString(columns
.indexOf("spark-shuffle-memoryFraction"))));
String storageLevel = row.getString(columns.size()).split(" ")[row
.getString(columns.size()).split(" ").length - 1];
if (storageLevel.equals("MEMORY_ONLY")
|| storageLevel.equals("MEMORY_AND_DISK")
|| storageLevel.equals("DISK_ONLY")
|| storageLevel.equals("MEMORY_AND_DISK_SER")
|| storageLevel.equals("MEMORY_ONLY_2")
|| storageLevel.equals("MEMORY_AND_DISK_2")
|| storageLevel.equals("OFF_HEAP")
|| storageLevel.equals("MEMORY_ONLY_SER"))
application.setStorageLevel(storageLevel);
// sqlContext.sql("SELECT * FROM SystemProperties").show();
return application;
}
/**
* fixes the schema derived from json by subsituting dots in names with -
*
* @param dataType
* @return
*/
private static DataType cleanSchema(DataType dataType) {
if (dataType instanceof StructType) {
StructField[] fields = new StructField[((StructType) dataType)
.fields().length];
int i = 0;
for (StructField field : ((StructType) dataType).fields()) {
fields[i] = field.copy(field.name().replace('.', '-'),
cleanSchema(field.dataType()), field.nullable(),
field.metadata());
i++;
}
return new StructType(fields);
} else if (dataType instanceof ArrayType) {
return new ArrayType(
cleanSchema(((ArrayType) dataType).elementType()),
((ArrayType) dataType).containsNull());
} else
return dataType;
}
private static DataFrame retrieveApplicationEvents() {
return sqlContext
.sql("SELECT Event, `App ID`, Timestamp FROM events WHERE Event LIKE '%ApplicationStart' OR Event LIKE '%ApplicationEnd'");
}
/**
* serializes the DAG for later use
*
* @param dag
* @param string
* - the name of the file in which serialize the DAG
* @throws IOException
*/
private static void serializeDag(DirectedAcyclicGraph<?, DefaultEdge> dag,
String filename) throws IOException {
OutputStream os = hdfs.create(new Path(new Path(config.outputFolder,
"dags"), filename));
ObjectOutputStream objectStream = new ObjectOutputStream(os);
objectStream.writeObject(dag);
objectStream.close();
os.close();
}
/**
* collects the information the RDDs (id, name, parents, scope, number of
* partitions) by looking into the "jobs" table
*
* @return
*/
private static DataFrame retrieveRDDInformation() {
return sqlContext
.sql("SELECT `Stage Info.Stage ID`, "
+ "`RDDInfo.RDD ID`,"
+ "RDDInfo.Name,"
+ "RDDInfo.Scope,"
+ "`RDDInfo.Parent IDs`,"
+ "`RDDInfo.Storage Level.Use Disk`,"
+ "`RDDInfo.Storage Level.Use Memory`,"
+ "`RDDInfo.Storage Level.Use ExternalBlockStore`,"
+ "`RDDInfo.Storage Level.Deserialized`,"
+ "`RDDInfo.Storage Level.Replication`,"
+ "`RDDInfo.Number of Partitions`,"
+ "`RDDInfo.Number of Cached Partitions`,"
+ "`RDDInfo.Memory Size`,"
+ "`RDDInfo.ExternalBlockStore Size`,"
+ "`RDDInfo.Disk Size`"
+ " FROM events LATERAL VIEW explode(`Stage Info.RDD Info`) rddInfoTable AS RDDInfo"
+ " WHERE Event LIKE '%StageCompleted'");
}
/**
* gets a list of stages from the dataframe
*
* @param stageDetails
* - The collected dataframe containing stages details
* @param stageDetailsColumns
* - The columns of stageDetails
* @param jobDetails
* - The collected dataframe containing jobs details
* @param jobDetailsColumns
* - The columns of job Details
* @return
*/
@SuppressWarnings("unchecked")
private static List<Stagenode> extractStageNodes(List<Row> stageDetails,
List<String> stageColumns) {
List<Stagenode> stages = new ArrayList<Stagenode>();
for (Row row : stageDetails) {
List<Long> tmpParentList = null;
List<Integer> parentList = null;
if (row.get(stageColumns.indexOf("Parent IDs")) instanceof scala.collection.immutable.List<?>)
tmpParentList = JavaConversions.asJavaList((Seq<Long>) row
.get(stageColumns.indexOf("Parent IDs")));
else if (row.get(stageColumns.indexOf("Parent IDs")) instanceof ArrayBuffer<?>)
tmpParentList = JavaConversions
.asJavaList((ArrayBuffer<Long>) row.get(stageColumns
.indexOf("Parent IDs")));
else {
logger.warn("Could not parse Stage Parent IDs Serialization:"
+ row.get(stageColumns.indexOf("Parent IDs"))
.toString()
+ " class: "
+ row.get(stageColumns.indexOf("Parent IDs"))
.getClass() + " Object: "
+ row.get(stageColumns.indexOf("Parent IDs")));
}
parentList = new ArrayList<Integer>();
for (Long parent : tmpParentList)
parentList.add(parent.intValue());
Stagenode stage = null;
int stageId = (int) row.getLong(stageColumns.indexOf("Stage ID"));
stage = new Stagenode(stage2jobMap.get(stageId), stageId,
parentList, row.getString(stageColumns
.indexOf("Stage Name")), Boolean.parseBoolean(row
.getString(stageColumns.indexOf("Executed"))));
stages.add(stage);
}
logger.info(stages.size() + "Stages found");
return stages;
}
/**
* Extracts a list of RDDs from the table
*
* @param stageDetails
* @return list of RDDs
*/
@SuppressWarnings("unchecked")
private static List<RDDnode> extractRDDs(DataFrame rddDetails) {
List<RDDnode> rdds = new ArrayList<RDDnode>();
DataFrame table = rddDetails.select("RDD ID", "Parent IDs", "Name",
"Scope", "Number of Partitions", "Stage ID", "Use Disk",
"Use Memory", "Use ExternalBlockStore", "Deserialized",
"Replication").distinct();
for (Row row : table.collectAsList()) {
List<Long> tmpParentList = null;
List<Integer> parentList = null;
if (row.get(1) instanceof scala.collection.immutable.List<?>)
tmpParentList = JavaConversions.asJavaList((Seq<Long>) row
.get(1));
else if (row.get(1) instanceof ArrayBuffer<?>)
tmpParentList = JavaConversions
.asJavaList((ArrayBuffer<Long>) row.get(1));
else {
logger.warn("Could not parse RDD PArent IDs Serialization:"
+ row.get(1).toString() + " class: "
+ row.get(1).getClass() + " Object: " + row.get(1));
}
parentList = new ArrayList<Integer>();
for (Long parent : tmpParentList)
parentList.add(parent.intValue());
int scopeID = 0;
String scopeName = null;
if (row.get(3) != null && !row.getString(3).isEmpty()
&& row.getString(3).startsWith("{")) {
JsonObject scopeObject = new JsonParser().parse(
row.getString(3)).getAsJsonObject();
scopeID = scopeObject.get("id").getAsInt();
scopeName = scopeObject.get("name").getAsString();
}
rdds.add(new RDDnode((int) row.getLong(0), row.getString(2),
parentList, scopeID, (int) row.getLong(4), scopeName,
(int) row.getLong(5), row.getBoolean(6), row.getBoolean(7),
row.getBoolean(8), row.getBoolean(9), (int) row.getLong(10)));
}
return rdds;
}
/**
* saves the dag it into a .dot file that can be used for visualization
*
* @param dag
* @throws IOException
*/
private static void printRDDGraph(
DirectedAcyclicGraph<RDDnode, DefaultEdge> dag, int jobNumber,
int stageNumber) throws IOException {
DOTExporter<RDDnode, DefaultEdge> exporter = new DOTExporter<RDDnode, DefaultEdge>(
new VertexNameProvider<RDDnode>() {
public String getVertexName(RDDnode rdd) {
return STAGE_LABEL + rdd.getStageID() + RDD_LABEL
+ rdd.getId();
}
}, new VertexNameProvider<RDDnode>() {
public String getVertexName(RDDnode rdd) {
return rdd.getName() + " (" + rdd.getStageID() + ","
+ rdd.getId() + ") ";
}
}, new EdgeNameProvider<DefaultEdge>() {
@Override
public String getEdgeName(DefaultEdge edge) {
AttributeMap attributes = edge.getAttributes();
if (attributes != null)
if ((int) attributes.get("cardinality") > 1)
return attributes.get("cardinality").toString();
return null;
}
}, new ComponentAttributeProvider<RDDnode>() {
@Override
public Map<String, String> getComponentAttributes(
RDDnode rdd) {
Map<String, String> map = new LinkedHashMap<String, String>();
if (rdd.isUseMemory()) {
map.put("style", "filled");
map.put("fillcolor", "red");
}
return map;
}
}, null);
String filename = null;
// if we are building a dag for the entire application
if (stageNumber < 0 && jobNumber < 0)
filename = APPLICATION_RDD_LABEL + DOT_EXTENSION;
else {
// otherwise build the filename using jobnumber and stage number
filename = RDD_LABEL;
if (jobNumber >= 0)
filename += JOB_LABEL + jobNumber;
if (stageNumber >= 0)
filename += STAGE_LABEL + stageNumber;
filename += DOT_EXTENSION;
}
OutputStream os = hdfs.create(new Path(new Path(config.outputFolder,
"rdd"), filename));
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os,
"UTF-8"));
exporter.export(br, dag);
br.close();
}
/**
* Build the DAG with RDD as nodes and Parent relationship as edges. job and
* stage number canbe used to specify the context of the DAG
*
* @param rdds
* @param jobNumber
* - uses only RDDs of the specified job (specify negative values
* to use RDDs from all the jobs)
* @param stageNumber
* - uses only RDDs of the specified stage (specify negative
* values to use RDDs from all the stages)
* @return
*/
private static DirectedAcyclicGraph<RDDnode, DefaultEdge> buildRDDDag(
List<RDDnode> rdds, int jobNumber, int stageNumber) {
DirectedAcyclicGraph<RDDnode, DefaultEdge> dag = new DirectedAcyclicGraph<RDDnode, DefaultEdge>(
DefaultEdge.class);
// build an hashmap to look for rdds quickly
// add vertexes to the graph
HashMap<Integer, RDDnode> rddMap = new HashMap<Integer, RDDnode>(
rdds.size());
for (RDDnode rdd : rdds) {
if ((stageNumber < 0 || rdd.getStageID() == stageNumber)
&& (jobNumber < 0 || stage2jobMap.get(rdd.getStageID()) == jobNumber)) {
if (!rddMap.containsKey(rdd.getId())) {
rddMap.put(rdd.getId(), rdd);
if (!dag.containsVertex(rdd))
dag.addVertex(rdd);
logger.debug("Added RDD" + rdd.getId()
+ " to the graph of stage " + stageNumber);
}
}
}
// add all edges then
// note that we are ignoring edges going outside of the context (stage
// or job)
for (RDDnode rdd : dag.vertexSet()) {
if (rdd.getParentIDs() != null)
for (Integer source : rdd.getParentIDs()) {
if (dag.vertexSet().contains(rddMap.get(source))) {
logger.debug("Adding link from RDD " + source
+ "to RDD" + rdd.getId());
RDDnode sourceRdd = rddMap.get(source);
if (!dag.containsEdge(sourceRdd, rdd)) {
dag.addEdge(sourceRdd, rdd);
Map<String, Integer> map = new LinkedHashMap<>();
map.put("cardinality", 1);
dag.getEdge(sourceRdd, rdd).setAttributes(
new AttributeMap(map));
} else {
int cardinality = (int) dag.getEdge(sourceRdd, rdd)
.getAttributes().get("cardinality");
dag.getEdge(sourceRdd, rdd).getAttributes()
.put("cardinality", cardinality + 1);
}
}
}
}
return dag;
}
/**
* convenience method to print the entire application dag
*
* @param dag
* @throws IOException
*/
private static void printStageGraph(
DirectedAcyclicGraph<Stagenode, DefaultEdge> dag)
throws IOException {
printStageGraph(dag, -1);
}
/**
* Export the Dag in dotty the job number is used to name the dot file, if
* it is -1 the file is names application-graph
*
* @param dag
* @param jobNumber
* @throws IOException
*/
private static void printStageGraph(
DirectedAcyclicGraph<Stagenode, DefaultEdge> dag, int jobNumber)
throws IOException {
DOTExporter<Stagenode, DefaultEdge> exporter = new DOTExporter<Stagenode, DefaultEdge>(
new VertexNameProvider<Stagenode>() {
public String getVertexName(Stagenode stage) {
return JOB_LABEL + stage.getJobId() + STAGE_LABEL
+ stage.getId();
}
}, new VertexNameProvider<Stagenode>() {
public String getVertexName(Stagenode stage) {
return JOB_LABEL + stage.getJobId() + " " + STAGE_LABEL
+ stage.getId();
}
}, null, new ComponentAttributeProvider<Stagenode>() {
@Override
public Map<String, String> getComponentAttributes(
Stagenode stage) {
Map<String, String> map = new LinkedHashMap<String, String>();
if (stage.isExecuted()) {
map.put("style", "filled");
map.put("fillcolor", "red");
}
return map;
}
}, new ComponentAttributeProvider<DefaultEdge>() {
@Override
public Map<String, String> getComponentAttributes(
DefaultEdge edge) {
Map<String, String> map = new LinkedHashMap<String, String>();
if (edge.getSource() instanceof Stagenode
&& ((Stagenode) edge.getSource()).isExecuted())
map.put("color", "red");
if (edge.getTarget() instanceof Stagenode
&& ((Stagenode) edge.getTarget()).isExecuted())
map.put("color", "red");
return map;
}
});
String filename = null;
if (jobNumber < 0)
filename = APPLICATION_DAG_LABEL + DOT_EXTENSION;
else
filename = JOB_LABEL + jobNumber + DOT_EXTENSION;
OutputStream os = hdfs.create(new Path(new Path(config.outputFolder,
"stage"), filename));
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os,
"UTF-8"));
exporter.export(br, dag);
br.close();
}
/**
* Retireves a Dataframe with the following columns: Stage ID, Stage Name,
* Parent IDs, Submission Time, Completion Time, Duration, Number of Tasks,
* Executed
* */
private static DataFrame retrieveStageInformation()
throws UnsupportedEncodingException, IOException {
sqlContext
.sql("SELECT `Stage Info.Stage ID`,"
+ "`Stage Info.Stage Name`,"
+ "`Stage Info.Parent IDs`,"
+ "`Stage Info.Number of Tasks`,"
+ "`Stage Info.Submission Time`,"
+ "`Stage Info.Completion Time`,"
+ "`Stage Info.Completion Time` - `Stage Info.Submission Time` as Duration,"
+ "'True' as Executed"
+ " FROM events WHERE Event LIKE '%StageCompleted'")
.registerTempTable("ExecutedStages");
sqlContext
.sql("SELECT `StageInfo.Stage ID`,"
+ "`StageInfo.Stage Name`,"
+ "`StageInfo.Parent IDs`,"
+ "`StageInfo.Number of Tasks`,"
+ "'0' as `Submission Time`,"
+ "'0' as `Completion Time`,"
+ "'0' as Duration,"
+ "'False' as Executed"
+ " FROM events LATERAL VIEW explode(`Stage Infos`) stageInfosTable AS `StageInfo`"
+ " WHERE Event LIKE '%JobStart'").registerTempTable(
"AllStages");
sqlContext
.sql("SELECT AllStages.* "
+ " FROM AllStages"
+ " LEFT JOIN ExecutedStages ON `AllStages.Stage ID`=`ExecutedStages.Stage ID`"
+ " WHERE `ExecutedStages.Stage ID` IS NULL")
.registerTempTable("NonExecutedStages");
return sqlContext.sql("SELECT * " + " FROM ExecutedStages"
+ " UNION ALL" + " SELECT *" + " FROM NonExecutedStages");
}
private static DataFrame retrieveJobInformation()
throws UnsupportedEncodingException, IOException {
return sqlContext
.sql("SELECT `s.Job ID`,"
+ "`s.Submission Time`,"
+ "`e.Completion Time`,"
+ "`e.Completion Time` - `s.Submission Time` as Duration,"
+ "`s.Stage IDs`,"
+ "max(prova) as maxStageID,"
+ "min(prova) as minStageID"
+ " FROM events s LATERAL VIEW explode(`s.Stage IDs`) idsTable as prova"
+ " INNER JOIN events e ON s.`Job ID`=e.`Job ID`"
+ " WHERE s.Event LIKE '%JobStart' AND e.Event LIKE '%JobEnd'"
+ "GROUP BY `s.Job ID`,`s.Submission Time`,`e.Completion Time`,`s.Stage IDs`");
}
/**
* Retrieves the information on the Tasks
*
* @return
*
* @throws IOException
* @throws UnsupportedEncodingException
*/
private static DataFrame retrieveTaskInformation() throws IOException,
UnsupportedEncodingException {
// register two tables, one for the task start event and the other for
// the task end event
sqlContext.sql("SELECT * FROM events WHERE Event LIKE '%TaskStart'")
.registerTempTable("taskStartInfos");
sqlContext.sql("SELECT * FROM events WHERE Event LIKE '%TaskEnd'")
.registerTempTable("taskEndInfos");
// query the two tables for the task details
DataFrame taskDetails = sqlContext
.sql("SELECT `start.Task Info.Task ID` AS id,"
+ " `start.Stage ID` AS stageID,"
+ " `start.Task Info.Executor ID` AS executorID,"
+ " `start.Task Info.Host` AS host,"
+ " `finish.Task Type` AS type,"
+ " `finish.Task Info.Finish Time` - `start.Task Info.Launch Time` AS executionTime,"
+ " `finish.Task Info.Finish Time` AS finishTime,"
+ " `finish.Task Info.Getting Result Time` AS gettingResultTime,"
+ " `start.Task Info.Launch Time` AS startTime,"
+ " `finish.Task Metrics.Executor Run Time` AS executorRunTime,"
+ " `finish.Task Metrics.Executor Deserialize Time` AS executorDeserializerTime,"
+ " `finish.Task Metrics.Result Serialization Time` AS resultSerializationTime,"
+ " `finish.Task Metrics.Shuffle Write Metrics.Shuffle Write Time` AS shuffleWriteTime,"
+ " `finish.Task Metrics.JVM GC Time` AS GCTime,"
+ " `finish.Task Metrics.Result Size` AS resultSize,"
+ " `finish.Task Metrics.Memory Bytes Spilled` AS memoryBytesSpilled,"
+ " `finish.Task Metrics.Disk Bytes Spilled` AS diskBytesSpilled,"
+ " `finish.Task Metrics.Shuffle Write Metrics.Shuffle Bytes Written` AS shuffleBytesWritten,"
+ " `finish.Task Metrics.Shuffle Write Metrics.Shuffle Records Written` AS shuffleRecordsWritten,"
+ " `finish.Task Metrics.Input Metrics.Data Read Method` AS dataReadMethod,"
+ " `finish.Task Metrics.Input Metrics.Bytes Read` AS bytesRead,"
+ " `finish.Task Metrics.Input Metrics.Records Read` AS recordsRead,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Remote Blocks Fetched` AS shuffleRemoteBlocksFetched,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Local Blocks Fetched` AS shuffleLocalBlocksFetched,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Fetch Wait Time` AS shuffleFetchWaitTime,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Remote Bytes Read` AS shuffleRemoteBytesRead,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Local Bytes Read` AS shuffleLocalBytesRead,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Total Records Read` AS shuffleTotalRecordsRead"
+ " FROM taskStartInfos AS start"
+ " JOIN taskEndInfos AS finish"
+ " ON `start.Task Info.Task ID`=`finish.Task Info.Task ID`");
return taskDetails;
}
/**
* Saves the table in the specified dataFrame in a CSV file. In order to
* save the whole table into a single the DataFrame is transformed into and
* RDD and then elements are collected. This might cause performance issue
* if the table is too long If a field contains an array (ArrayBuffer) its
* content is serialized with spaces as delimiters
*
* @param data
* @param fileName
* @throws IOException
* @throws UnsupportedEncodingException
*/
private static void saveListToCSV(DataFrame data, String fileName)
throws IOException, UnsupportedEncodingException {
List<Row> table = data.toJavaRDD().collect();
OutputStream os = hdfs.create(new Path(config.outputFolder, fileName));
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os,
"UTF-8"));
// the schema first
for (String column : data.columns())
br.write(column + ",");
br.write("\n");
// the values after
for (Row row : table) {
for (int i = 0; i < row.size(); i++) {
if (row.get(i) instanceof String
&& row.getString(i).startsWith("{")) {
// if the string starts with a parenthesis it is probably a
// Json object not deserialized (the scope)
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(row.getString(i))
.getAsJsonObject();
for (Entry<String, JsonElement> element : jsonObject
.entrySet())
br.write(element.getValue().getAsString() + " ");
br.write(",");
}
// if it is an array print all the elements separated by a space
// (instead of a comma)
else if (row.get(i) instanceof Traversable<?>)
br.write(((Traversable<?>) row.get(i)).mkString(" ") + ',');
// if the element itself contains a comma then switch it to a
// semicolon
else if (row.get(i) instanceof String
&& ((String) row.get(i)).contains(","))
br.write(((String) row.get(i)).replace(',', ';') + ",");
else {
br.write(row.get(i) + ",");
}
}
br.write("\n");
}
br.close();
}
private static void saveApplicationInfo(String clusterName, String appId,
String appName, String dbUser) throws IOException {
OutputStream os = hdfs.create(new Path(config.outputFolder,
"application.info"));
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os,
"UTF-8"));
br.write("Cluster name:" + clusterName);
br.write("Application Id:" + appId);
br.write("Application Name:" + appName);
br.write("Database User:" + dbUser);
br.close();
}
/**
* Builds a DAG using all the stages in the provided list.
*
* @param stages
* @return
*/
private static DirectedAcyclicGraph<Stagenode, DefaultEdge> buildStageDag(
List<Stagenode> stages) {
DirectedAcyclicGraph<Stagenode, DefaultEdge> dag = new DirectedAcyclicGraph<Stagenode, DefaultEdge>(
DefaultEdge.class);
// build an hashmap to look for stages quickly
// and add vertexes to the graph
HashMap<Integer, Stagenode> stageMap = new HashMap<Integer, Stagenode>(
stages.size());
for (Stagenode stage : stages) {
stageMap.put(stage.getId(), stage);
logger.debug("Adding Stage " + stage.getId() + " to the graph");
dag.addVertex(stage);
}
// add all edges then
for (Stagenode stage : stages) {
if (stage.getParentIDs() != null)
for (Integer source : stage.getParentIDs()) {
logger.debug("Adding link from Stage " + source
+ "to Stage" + stage.getId());
dag.addEdge(stageMap.get(source), stage);
}
}
return dag;
}
/**
* builds a DAG using only the stages in the specified job, selected by
* those provided in the list
*
* @param stages
* @param stageNumber
* @return
*/
private static DirectedAcyclicGraph<Stagenode, DefaultEdge> buildStageDag(
List<Stagenode> stages, int jobNumber) {
List<Stagenode> jobStages = new ArrayList<Stagenode>();
for (Stagenode s : stages)
if ((int) s.getJobId() == jobNumber)
jobStages.add(s);
return buildStageDag(jobStages);
}
}
| sparkloggerparser/src/main/java/it/polimi/spark/LoggerParser.java | package it.polimi.spark;
import it.polimi.spark.dag.RDDnode;
import it.polimi.spark.dag.Stagenode;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SQLContext;
import org.apache.spark.sql.hive.HiveContext;
import org.apache.spark.sql.types.ArrayType;
import org.apache.spark.sql.types.DataType;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import org.jgraph.graph.AttributeMap;
import org.jgraph.graph.DefaultEdge;
import org.jgrapht.experimental.dag.DirectedAcyclicGraph;
import org.jgrapht.ext.ComponentAttributeProvider;
import org.jgrapht.ext.DOTExporter;
import org.jgrapht.ext.EdgeNameProvider;
import org.jgrapht.ext.VertexNameProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.collection.JavaConversions;
import scala.collection.Seq;
import scala.collection.Traversable;
import scala.collection.mutable.ArrayBuffer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class LoggerParser {
static Config config;
static FileSystem hdfs;
static final Logger logger = LoggerFactory.getLogger(LoggerParser.class);
static SQLContext sqlContext;
static final String STAGE_LABEL = "Stage_";
static final String JOB_LABEL = "Job_";
static final String RDD_LABEL = "RDD_";
static final String APPLICATION_DAG_LABEL = "application-graph";
static final String APPLICATION_RDD_LABEL = "application-rdd";
static final String DOT_EXTENSION = ".dot";
static Map<Integer, List<Integer>> job2StagesMap = new HashMap<Integer, List<Integer>>();
static Map<Integer, Integer> stage2jobMap = new HashMap<Integer, Integer>();
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException,
URISyntaxException, ClassNotFoundException {
// the hadoop configuration
Configuration hadoopConf = new Configuration();
hdfs = FileSystem.get(hadoopConf);
// the spark configuration
SparkConf conf = new SparkConf().setAppName("logger-parser");
// the configuration of the application (as launched by the user)
Config.init(args);
config = Config.getInstance();
if (config.usage) {
config.usage();
return;
}
if (config.runLocal) {
conf.setMaster("local[1]");
}
// either -i or -app has to be specified
if (config.inputFile == null && config.applicationID == null) {
logger.info("No input file (-i option) or application id (-a option) has been specified. At least one of these options has to be provided");
config.usage();
return;
}
// exactly one otherwise we will not know where the user wants to get
// the logs from
if (config.inputFile != null && config.applicationID != null) {
logger.info("Either the input file (-i option) or the application id (-app option) has to be specified.");
return;
}
// if the -a option has been specified, then get the default
// logging directory from sparkconf (property spark.eventLog.dir) and
// use it as base folder to look for the application log
if (config.applicationID != null) {
String eventLogDir = conf.get("spark.eventLog.dir", null).replace(
"file://", "");
if (eventLogDir == null) {
logger.info("Could not retireve the logging directory from the spark configuration, the property spark.eventLog.dir has to be set in the cluster configuration");
return;
}
config.inputFile = eventLogDir + "/" + config.applicationID;
}
logger.info("Reding logs from: " + config.inputFile);
// if the file does not exist
if (config.inputFile != null
&& !hdfs.exists(new Path(config.inputFile))) {
logger.info("Input file " + config.inputFile + " does not exist");
return;
}
@SuppressWarnings("resource")
JavaSparkContext sc = new JavaSparkContext(conf);
sqlContext = new HiveContext(sc.sc());
if (hdfs.exists(new Path(config.outputFolder)))
hdfs.delete(new Path(config.outputFolder), true);
// load the logs
DataFrame logsframe = sqlContext.jsonFile(config.inputFile);
logsframe = sqlContext.applySchema(logsframe.toJavaRDD(),
(StructType) cleanSchema(logsframe.schema()));
logsframe.cache();
// register the main table with all the logs as "events"
logsframe.registerTempTable("events");
// stageDetails.show((int) stageDetails.count());
// save CSV with performance information
if (config.task) {
logger.info("Retrieving Task information");
DataFrame taskDetails = retrieveTaskInformation();
saveListToCSV(taskDetails, "TaskDetails.csv");
}
DataFrame stageDetailsFrame = null;
List<Row> stageDetails = null;
List<String> stageDetailsColumns = null;
DataFrame jobDetailsFrame = null;
List<Row> jobDetails = null;
List<String> jobDetailsColumns = null;
List<Stagenode> stageNodes = null;
List<Stage> stages = null;
List<Job> jobs = null;
int numberOfJobs = 0;
int numberOfStages = 0;
Benchmark application = null;
DBHandler dbHandler = null;
if (config.toDB) {
if (config.dbUser == null)
logger.warn("No user name has been specified for the connection with the DB, results will not be uploaded");
if (config.dbPassword == null)
logger.warn("No password has been specified for the connection with the DB, results will not be uploaded");
if (config.dbUser != null && config.dbPassword != null) {
dbHandler = new DBHandler(config.dbUrl, config.dbUser,
config.dbPassword);
logger.info("Retrieving Application Information");
application = retrieveApplicationConfiguration();
}
}
// I could also remove the if, almost every functionality require to
// parse stage details
if (config.ApplicationDAG || config.jobDAGS
|| config.buildStageRDDGraph || config.buildJobRDDGraph
|| config.toDB) {
DataFrame applicationEvents = retrieveApplicationEvents();
saveListToCSV(applicationEvents, "application.csv");
// add the duration to the application
if (application != null && config.toDB)
application.setDuration(getDuration(applicationEvents));
// collect stages from log files
logger.info("Retrieving Stage Information");
stageDetailsFrame = retrieveStageInformation();
saveListToCSV(stageDetailsFrame, "StageDetails.csv");
stageDetails = stageDetailsFrame.collectAsList();
stageDetailsColumns = new ArrayList<String>(
Arrays.asList(stageDetailsFrame.columns()));
// collect jobs from log files
logger.info("Retrieving Job Information");
jobDetailsFrame = retrieveJobInformation();
saveListToCSV(jobDetailsFrame, "JobDetails.csv");
jobDetails = jobDetailsFrame.collectAsList();
jobDetailsColumns = new ArrayList<String>(
Arrays.asList(jobDetailsFrame.columns()));
initMaps(stageDetails, stageDetailsColumns, jobDetails,
jobDetailsColumns);
stageNodes = extractStageNodes(stageDetails, stageDetailsColumns);
if (config.toDB && application != null) {
stages = extractStages(stageDetails, stageDetailsColumns,
application.getClusterName(), application.getAppID());
jobs = extractJobs(jobDetails, jobDetailsColumns,
application.getClusterName(), application.getAppID());
Map<Integer, Stage> stageById = new HashMap<Integer, Stage>(
stages.size());
for (Stage stage : stages)
stageById.put(stage.getStageID(), stage);
for (Job job : jobs) {
// link job to application
application.addJob(job);
// link stages to jobs
for (int stageId : job2StagesMap.get(job.getJobID()))
// skip non executed
if (stageById.containsKey(stageId))
job.addStage(stageById.get(stageId));
}
}
numberOfJobs = jobDetails.size();
numberOfStages = stageDetails.size();
}
if (config.ApplicationDAG) {
logger.info("Building Stage DAG");
DirectedAcyclicGraph<Stagenode, DefaultEdge> stageDag = buildStageDag(stageNodes);
printStageGraph(stageDag);
}
if (config.jobDAGS) {
for (int i = 0; i <= numberOfJobs; i++) {
logger.info("Building Job DAG");
DirectedAcyclicGraph<Stagenode, DefaultEdge> stageDag = buildStageDag(
stageNodes, i);
printStageGraph(stageDag, i);
if (config.export)
serializeDag(stageDag, JOB_LABEL + i);
}
}
// This part takes care of functionalities related to rdds
List<RDDnode> rdds = null;
if (config.buildJobRDDGraph || config.buildStageRDDGraph) {
logger.info("Building Retrieving RDD information");
DataFrame rddDetails = retrieveRDDInformation();
saveListToCSV(rddDetails, "rdd.csv");
rdds = extractRDDs(rddDetails);
}
if (config.buildJobRDDGraph) {
for (int i = 0; i <= numberOfJobs; i++) {
logger.info("Building RDD Job DAG");
DirectedAcyclicGraph<RDDnode, DefaultEdge> rddDag = buildRDDDag(
rdds, i, -1);
printRDDGraph(rddDag, i, -1);
if (config.export)
serializeDag(rddDag, RDD_LABEL + JOB_LABEL
+ stage2jobMap.get(i).intValue());
}
}
if (config.buildStageRDDGraph) {
// register the current dataframe as jobs table
logger.info("Building RDD Stage DAG");
for (int i = 0; i <= numberOfStages; i++) {
DirectedAcyclicGraph<RDDnode, DefaultEdge> rddDag = buildRDDDag(
rdds, -1, i);
printRDDGraph(rddDag, stage2jobMap.get(i).intValue(), i);
if (config.export)
serializeDag(rddDag, RDD_LABEL + JOB_LABEL
+ stage2jobMap.get(i).intValue() + STAGE_LABEL + i);
}
}
if (config.toDB && application != null && dbHandler != null) {
logger.info("Adding application to the database");
logger.info("Cluster name: " + application.getClusterName());
logger.info("Application Id: " + application.getAppID());
logger.info("Application Name: " + application.getAppName());
try {
dbHandler.insertBenchmark(application);
} catch (SQLException e) {
logger.warn(
"The application could not be added to the database ",
e);
}
}
if (dbHandler != null)
dbHandler.close();
}
/**
* Extract all the jobs in objects containing performance information, no
* topological info is saved
*
* @param jobDetails
* @param jobColumns
* @param clusterName
* @param applicationID
* @return
*/
private static List<Job> extractJobs(List<Row> jobDetails,
List<String> jobColumns, String clusterName, String appID) {
List<Job> jobs = new ArrayList<Job>();
for (Row row : jobDetails) {
int jobId = (int) row.getLong(jobColumns.indexOf("Job ID"));
Job job = new Job(clusterName, appID, jobId);
job.setDuration((int) row.getLong(jobColumns.indexOf("Duration")));
jobs.add(job);
}
return jobs;
}
/**
* Initializes the hashmaps used to retrieve job id from stage and viceversa
* (a list of stage id from a job id)
*
* @param stageDetails
* @param stageColumns
* @param jobDetails
* @param jobColumns
*/
@SuppressWarnings("unchecked")
private static void initMaps(List<Row> stageDetails,
List<String> stageColumns, List<Row> jobDetails,
List<String> jobColumns) {
// setup hashmap from job to list of stages ids and viceversa
for (Row row : jobDetails) {
int jobID = (int) row.getLong(jobColumns.indexOf("Job ID"));
List<Long> tmpStageList = null;
List<Integer> stageList = null;
if (row.get(jobColumns.indexOf("Stage IDs")) instanceof scala.collection.immutable.List<?>)
tmpStageList = JavaConversions.asJavaList((Seq<Long>) row
.get(jobColumns.indexOf("Stage IDs")));
else if (row.get(jobColumns.indexOf("Stage IDs")) instanceof ArrayBuffer<?>)
tmpStageList = JavaConversions
.asJavaList((ArrayBuffer<Long>) row.get(jobColumns
.indexOf("Stage IDs")));
else {
logger.warn("Could not parse Stage IDs Serialization:"
+ row.get(jobColumns.indexOf("Stage IDs")).toString()
+ " class: "
+ row.get(jobColumns.indexOf("Stage IDs")).getClass()
+ " Object: "
+ row.get(jobColumns.indexOf("Stage IDs")));
}
// convert it to integers
stageList = new ArrayList<Integer>();
for (Long stage : tmpStageList) {
stageList.add(stage.intValue());
// Initialize the hashmap StageID -> JobID
stage2jobMap.put(stage.intValue(), jobID);
}
// and the one JobID -> List of stage IDs
job2StagesMap.put(jobID, stageList);
}
}
/**
* Extract all the stages in objects containing performance information, no
* topological info is saved
*
* @param stageDetails
* @param stageColumns
* @param clusterName
* @param applicationID
* @return
*/
private static List<Stage> extractStages(List<Row> stageDetails,
List<String> stageColumns, String clusterName, String applicationID) {
List<Stage> stages = new ArrayList<Stage>();
for (Row row : stageDetails) {
// filter outnon executed stages
if (Boolean.parseBoolean(row.getString(stageColumns
.indexOf("Executed")))) {
int stageId = (int) row.getLong(stageColumns
.indexOf("Stage ID"));
Stage stage = new Stage(clusterName, applicationID,
stage2jobMap.get(stageId), stageId);
stage.setDuration(Integer.parseInt(row.getString(stageColumns
.indexOf("Duration"))));
// TODO: add parsing of input/output and shuffle sizes
stages.add(stage);
}
}
return stages;
}
private static int getDuration(DataFrame applicationEvents) {
Row[] events = applicationEvents.collect();
long startTime = 0;
long endTime = 0;
for (Row event : events) {
if (event.getString(0).equals("SparkListenerApplicationStart"))
startTime = event.getLong(2);
else
endTime = event.getLong(2);
}
return (int) (endTime - startTime);
}
private static Benchmark retrieveApplicationConfiguration() {
DataFrame sparkPropertiesDf = sqlContext
.sql("SELECT `Spark Properties` FROM events WHERE Event LIKE '%EnvironmentUpdate'");
StructType schema = (StructType) ((StructType) sparkPropertiesDf
.schema()).fields()[0].dataType();
List<String> columns = new ArrayList<String>();
for (String column : schema.fieldNames())
columns.add(column);
String selectedColumns = "";
for (String column : columns) {
selectedColumns += "`Spark Properties." + column + "`" + ", ";
}
sparkPropertiesDf = sqlContext.sql("SELECT " + selectedColumns
+ "`System Properties.sun-java-command`"
+ " FROM events WHERE Event LIKE '%EnvironmentUpdate'");
// there should only be one of such events
Row row = sparkPropertiesDf.toJavaRDD().first();
Benchmark application = new Benchmark(row.getString(columns
.indexOf("spark-master")), row.getString(columns
.indexOf("spark-app-id")));
if (columns.contains("spark-app-name"))
application.setAppName(row.getString(columns
.indexOf("spark-app-name")));
if (columns.contains("spark-driver-memory")) {
String memory = row.getString(columns
.indexOf("spark-driver-memory"));
// removing g or m
memory = memory.substring(0, memory.length() - 1);
application.setDriverMemory(Double.parseDouble(memory));
}
if (columns.contains("spark-executor-memory")) {
String memory = row.getString(columns
.indexOf("spark-executor-memory"));
// removing g or m
memory = memory.substring(0, memory.length() - 1);
application.setExecutorMemory(Double.parseDouble(memory));
}
if (columns.contains("spark-kryoserializer-buffer-max")) {
String memory = row.getString(columns
.indexOf("spark-kryoserializer-buffer-max"));
// removing g or m
memory = memory.substring(0, memory.length() - 1);
application.setKryoMaxBuffer(Integer.parseInt(memory));
}
if (columns.contains("spark-rdd-compress"))
application.setRddCompress(Boolean.parseBoolean(row
.getString(columns.indexOf("spark-rdd-compress"))));
if (columns.contains("spark-storage-memoryFraction"))
application
.setStorageMemoryFraction(Double.parseDouble(row
.getString(columns
.indexOf("spark-storage-memoryFraction"))));
if (columns.contains("spark-shuffle-memoryFraction"))
application
.setShuffleMemoryFraction(Double.parseDouble(row
.getString(columns
.indexOf("spark-shuffle-memoryFraction"))));
String storageLevel = row.getString(columns.size()).split(" ")[row
.getString(columns.size()).split(" ").length - 1];
if (storageLevel.equals("MEMORY_ONLY")
|| storageLevel.equals("MEMORY_AND_DISK")
|| storageLevel.equals("DISK_ONLY")
|| storageLevel.equals("MEMORY_AND_DISK_SER")
|| storageLevel.equals("MEMORY_ONLY_2")
|| storageLevel.equals("MEMORY_AND_DISK_2")
|| storageLevel.equals("OFF_HEAP")
|| storageLevel.equals("MEMORY_ONLY_SER"))
application.setStorageLevel(storageLevel);
// sqlContext.sql("SELECT * FROM SystemProperties").show();
return application;
}
/**
* fixes the schema derived from json by subsituting dots in names with -
*
* @param dataType
* @return
*/
private static DataType cleanSchema(DataType dataType) {
if (dataType instanceof StructType) {
StructField[] fields = new StructField[((StructType) dataType)
.fields().length];
int i = 0;
for (StructField field : ((StructType) dataType).fields()) {
fields[i] = field.copy(field.name().replace('.', '-'),
cleanSchema(field.dataType()), field.nullable(),
field.metadata());
i++;
}
return new StructType(fields);
} else if (dataType instanceof ArrayType) {
return new ArrayType(
cleanSchema(((ArrayType) dataType).elementType()),
((ArrayType) dataType).containsNull());
} else
return dataType;
}
private static DataFrame retrieveApplicationEvents() {
return sqlContext
.sql("SELECT Event, `App ID`, Timestamp FROM events WHERE Event LIKE '%ApplicationStart' OR Event LIKE '%ApplicationEnd'");
}
/**
* serializes the DAG for later use
*
* @param dag
* @param string
* - the name of the file in which serialize the DAG
* @throws IOException
*/
private static void serializeDag(DirectedAcyclicGraph<?, DefaultEdge> dag,
String filename) throws IOException {
OutputStream os = hdfs.create(new Path(new Path(config.outputFolder,
"dags"), filename));
ObjectOutputStream objectStream = new ObjectOutputStream(os);
objectStream.writeObject(dag);
objectStream.close();
os.close();
}
/**
* collects the information the RDDs (id, name, parents, scope, number of
* partitions) by looking into the "jobs" table
*
* @return
*/
private static DataFrame retrieveRDDInformation() {
return sqlContext
.sql("SELECT `Stage Info.Stage ID`, "
+ "`RDDInfo.RDD ID`,"
+ "RDDInfo.Name,"
+ "RDDInfo.Scope,"
+ "`RDDInfo.Parent IDs`,"
+ "`RDDInfo.Storage Level.Use Disk`,"
+ "`RDDInfo.Storage Level.Use Memory`,"
+ "`RDDInfo.Storage Level.Use ExternalBlockStore`,"
+ "`RDDInfo.Storage Level.Deserialized`,"
+ "`RDDInfo.Storage Level.Replication`,"
+ "`RDDInfo.Number of Partitions`,"
+ "`RDDInfo.Number of Cached Partitions`,"
+ "`RDDInfo.Memory Size`,"
+ "`RDDInfo.ExternalBlockStore Size`,"
+ "`RDDInfo.Disk Size`"
+ " FROM events LATERAL VIEW explode(`Stage Info.RDD Info`) rddInfoTable AS RDDInfo"
+ " WHERE Event LIKE '%StageCompleted'");
}
/**
* gets a list of stages from the dataframe
*
* @param stageDetails
* - The collected dataframe containing stages details
* @param stageDetailsColumns
* - The columns of stageDetails
* @param jobDetails
* - The collected dataframe containing jobs details
* @param jobDetailsColumns
* - The columns of job Details
* @return
*/
@SuppressWarnings("unchecked")
private static List<Stagenode> extractStageNodes(List<Row> stageDetails,
List<String> stageColumns) {
List<Stagenode> stages = new ArrayList<Stagenode>();
for (Row row : stageDetails) {
List<Long> tmpParentList = null;
List<Integer> parentList = null;
if (row.get(stageColumns.indexOf("Parent IDs")) instanceof scala.collection.immutable.List<?>)
tmpParentList = JavaConversions.asJavaList((Seq<Long>) row
.get(stageColumns.indexOf("Parent IDs")));
else if (row.get(stageColumns.indexOf("Parent IDs")) instanceof ArrayBuffer<?>)
tmpParentList = JavaConversions
.asJavaList((ArrayBuffer<Long>) row.get(stageColumns
.indexOf("Parent IDs")));
else {
logger.warn("Could not parse Stage Parent IDs Serialization:"
+ row.get(stageColumns.indexOf("Parent IDs"))
.toString()
+ " class: "
+ row.get(stageColumns.indexOf("Parent IDs"))
.getClass() + " Object: "
+ row.get(stageColumns.indexOf("Parent IDs")));
}
parentList = new ArrayList<Integer>();
for (Long parent : tmpParentList)
parentList.add(parent.intValue());
Stagenode stage = null;
int stageId = (int) row.getLong(stageColumns.indexOf("Stage ID"));
stage = new Stagenode(stage2jobMap.get(stageId), stageId,
parentList, row.getString(stageColumns
.indexOf("Stage Name")), Boolean.parseBoolean(row
.getString(stageColumns.indexOf("Executed"))));
stages.add(stage);
}
logger.info(stages.size() + "Stages found");
return stages;
}
/**
* Extracts a list of RDDs from the table
*
* @param stageDetails
* @return list of RDDs
*/
@SuppressWarnings("unchecked")
private static List<RDDnode> extractRDDs(DataFrame rddDetails) {
List<RDDnode> rdds = new ArrayList<RDDnode>();
DataFrame table = rddDetails.select("RDD ID", "Parent IDs", "Name",
"Scope", "Number of Partitions", "Stage ID", "Use Disk",
"Use Memory", "Use ExternalBlockStore", "Deserialized",
"Replication").distinct();
for (Row row : table.collectAsList()) {
List<Long> tmpParentList = null;
List<Integer> parentList = null;
if (row.get(1) instanceof scala.collection.immutable.List<?>)
tmpParentList = JavaConversions.asJavaList((Seq<Long>) row
.get(1));
else if (row.get(1) instanceof ArrayBuffer<?>)
tmpParentList = JavaConversions
.asJavaList((ArrayBuffer<Long>) row.get(1));
else {
logger.warn("Could not parse RDD PArent IDs Serialization:"
+ row.get(1).toString() + " class: "
+ row.get(1).getClass() + " Object: " + row.get(1));
}
parentList = new ArrayList<Integer>();
for (Long parent : tmpParentList)
parentList.add(parent.intValue());
int scopeID = 0;
String scopeName = null;
if (row.get(3) != null && !row.getString(3).isEmpty()
&& row.getString(3).startsWith("{")) {
JsonObject scopeObject = new JsonParser().parse(
row.getString(3)).getAsJsonObject();
scopeID = scopeObject.get("id").getAsInt();
scopeName = scopeObject.get("name").getAsString();
}
rdds.add(new RDDnode((int) row.getLong(0), row.getString(2),
parentList, scopeID, (int) row.getLong(4), scopeName,
(int) row.getLong(5), row.getBoolean(6), row.getBoolean(7),
row.getBoolean(8), row.getBoolean(9), (int) row.getLong(10)));
}
return rdds;
}
/**
* saves the dag it into a .dot file that can be used for visualization
*
* @param dag
* @throws IOException
*/
private static void printRDDGraph(
DirectedAcyclicGraph<RDDnode, DefaultEdge> dag, int jobNumber,
int stageNumber) throws IOException {
DOTExporter<RDDnode, DefaultEdge> exporter = new DOTExporter<RDDnode, DefaultEdge>(
new VertexNameProvider<RDDnode>() {
public String getVertexName(RDDnode rdd) {
return STAGE_LABEL + rdd.getStageID() + RDD_LABEL
+ rdd.getId();
}
}, new VertexNameProvider<RDDnode>() {
public String getVertexName(RDDnode rdd) {
return rdd.getName() + " (" + rdd.getStageID() + ","
+ rdd.getId() + ") ";
}
}, new EdgeNameProvider<DefaultEdge>() {
@Override
public String getEdgeName(DefaultEdge edge) {
AttributeMap attributes = edge.getAttributes();
if (attributes != null)
if ((int) attributes.get("cardinality") > 1)
return attributes.get("cardinality").toString();
return null;
}
}, new ComponentAttributeProvider<RDDnode>() {
@Override
public Map<String, String> getComponentAttributes(
RDDnode rdd) {
Map<String, String> map = new LinkedHashMap<String, String>();
if (rdd.isUseMemory()) {
map.put("style", "filled");
map.put("fillcolor", "red");
}
return map;
}
}, null);
String filename = null;
// if we are building a dag for the entire application
if (stageNumber < 0 && jobNumber < 0)
filename = APPLICATION_RDD_LABEL + DOT_EXTENSION;
else {
// otherwise build the filename using jobnumber and stage number
filename = RDD_LABEL;
if (jobNumber >= 0)
filename += JOB_LABEL + jobNumber;
if (stageNumber >= 0)
filename += STAGE_LABEL + stageNumber;
filename += DOT_EXTENSION;
}
OutputStream os = hdfs.create(new Path(new Path(config.outputFolder,
"rdd"), filename));
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os,
"UTF-8"));
exporter.export(br, dag);
br.close();
}
/**
* Build the DAG with RDD as nodes and Parent relationship as edges. job and
* stage number canbe used to specify the context of the DAG
*
* @param rdds
* @param jobNumber
* - uses only RDDs of the specified job (specify negative values
* to use RDDs from all the jobs)
* @param stageNumber
* - uses only RDDs of the specified stage (specify negative
* values to use RDDs from all the stages)
* @return
*/
private static DirectedAcyclicGraph<RDDnode, DefaultEdge> buildRDDDag(
List<RDDnode> rdds, int jobNumber, int stageNumber) {
DirectedAcyclicGraph<RDDnode, DefaultEdge> dag = new DirectedAcyclicGraph<RDDnode, DefaultEdge>(
DefaultEdge.class);
// build an hashmap to look for rdds quickly
// add vertexes to the graph
HashMap<Integer, RDDnode> rddMap = new HashMap<Integer, RDDnode>(
rdds.size());
for (RDDnode rdd : rdds) {
if ((stageNumber < 0 || rdd.getStageID() == stageNumber)
&& (jobNumber < 0 || stage2jobMap.get(rdd.getStageID()) == jobNumber)) {
if (!rddMap.containsKey(rdd.getId())) {
rddMap.put(rdd.getId(), rdd);
if (!dag.containsVertex(rdd))
dag.addVertex(rdd);
logger.debug("Added RDD" + rdd.getId()
+ " to the graph of stage " + stageNumber);
}
}
}
// add all edges then
// note that we are ignoring edges going outside of the context (stage
// or job)
for (RDDnode rdd : dag.vertexSet()) {
if (rdd.getParentIDs() != null)
for (Integer source : rdd.getParentIDs()) {
if (dag.vertexSet().contains(rddMap.get(source))) {
logger.debug("Adding link from RDD " + source
+ "to RDD" + rdd.getId());
RDDnode sourceRdd = rddMap.get(source);
if (!dag.containsEdge(sourceRdd, rdd)) {
dag.addEdge(sourceRdd, rdd);
Map<String, Integer> map = new LinkedHashMap<>();
map.put("cardinality", 1);
dag.getEdge(sourceRdd, rdd).setAttributes(
new AttributeMap(map));
} else {
int cardinality = (int) dag.getEdge(sourceRdd, rdd)
.getAttributes().get("cardinality");
dag.getEdge(sourceRdd, rdd).getAttributes()
.put("cardinality", cardinality + 1);
}
}
}
}
return dag;
}
/**
* convenience method to print the entire application dag
*
* @param dag
* @throws IOException
*/
private static void printStageGraph(
DirectedAcyclicGraph<Stagenode, DefaultEdge> dag)
throws IOException {
printStageGraph(dag, -1);
}
/**
* Export the Dag in dotty the job number is used to name the dot file, if
* it is -1 the file is names application-graph
*
* @param dag
* @param jobNumber
* @throws IOException
*/
private static void printStageGraph(
DirectedAcyclicGraph<Stagenode, DefaultEdge> dag, int jobNumber)
throws IOException {
DOTExporter<Stagenode, DefaultEdge> exporter = new DOTExporter<Stagenode, DefaultEdge>(
new VertexNameProvider<Stagenode>() {
public String getVertexName(Stagenode stage) {
return JOB_LABEL + stage.getJobId() + STAGE_LABEL
+ stage.getId();
}
}, new VertexNameProvider<Stagenode>() {
public String getVertexName(Stagenode stage) {
return JOB_LABEL + stage.getJobId() + " " + STAGE_LABEL
+ stage.getId();
}
}, null, new ComponentAttributeProvider<Stagenode>() {
@Override
public Map<String, String> getComponentAttributes(
Stagenode stage) {
Map<String, String> map = new LinkedHashMap<String, String>();
if (stage.isExecuted()) {
map.put("style", "filled");
map.put("fillcolor", "red");
}
return map;
}
}, new ComponentAttributeProvider<DefaultEdge>() {
@Override
public Map<String, String> getComponentAttributes(
DefaultEdge edge) {
Map<String, String> map = new LinkedHashMap<String, String>();
if (edge.getSource() instanceof Stagenode
&& ((Stagenode) edge.getSource()).isExecuted())
map.put("color", "red");
if (edge.getTarget() instanceof Stagenode
&& ((Stagenode) edge.getTarget()).isExecuted())
map.put("color", "red");
return map;
}
});
String filename = null;
if (jobNumber < 0)
filename = APPLICATION_DAG_LABEL + DOT_EXTENSION;
else
filename = JOB_LABEL + jobNumber + DOT_EXTENSION;
OutputStream os = hdfs.create(new Path(new Path(config.outputFolder,
"stage"), filename));
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os,
"UTF-8"));
exporter.export(br, dag);
br.close();
}
/**
* Retireves a Dataframe with the following columns: Stage ID, Stage Name,
* Parent IDs, Submission Time, Completion Time, Duration, Number of Tasks,
* Executed
* */
private static DataFrame retrieveStageInformation()
throws UnsupportedEncodingException, IOException {
sqlContext
.sql("SELECT `Stage Info.Stage ID`,"
+ "`Stage Info.Stage Name`,"
+ "`Stage Info.Parent IDs`,"
+ "`Stage Info.Number of Tasks`,"
+ "`Stage Info.Submission Time`,"
+ "`Stage Info.Completion Time`,"
+ "`Stage Info.Completion Time` - `Stage Info.Submission Time` as Duration,"
+ "'True' as Executed"
+ " FROM events WHERE Event LIKE '%StageCompleted'")
.registerTempTable("ExecutedStages");
sqlContext
.sql("SELECT `StageInfo.Stage ID`,"
+ "`StageInfo.Stage Name`,"
+ "`StageInfo.Parent IDs`,"
+ "`StageInfo.Number of Tasks`,"
+ "'0' as `Submission Time`,"
+ "'0' as `Completion Time`,"
+ "'0' as Duration,"
+ "'False' as Executed"
+ " FROM events LATERAL VIEW explode(`Stage Infos`) stageInfosTable AS `StageInfo`"
+ " WHERE Event LIKE '%JobStart'").registerTempTable(
"AllStages");
sqlContext
.sql("SELECT AllStages.* "
+ " FROM AllStages"
+ " LEFT JOIN ExecutedStages ON `AllStages.Stage ID`=`ExecutedStages.Stage ID`"
+ " WHERE `ExecutedStages.Stage ID` IS NULL")
.registerTempTable("NonExecutedStages");
return sqlContext.sql("SELECT * " + " FROM ExecutedStages"
+ " UNION ALL" + " SELECT *" + " FROM NonExecutedStages");
}
private static DataFrame retrieveJobInformation()
throws UnsupportedEncodingException, IOException {
return sqlContext
.sql("SELECT `s.Job ID`,"
+ "`s.Submission Time`,"
+ "`e.Completion Time`,"
+ "`e.Completion Time` - `s.Submission Time` as Duration,"
+ "`s.Stage IDs`,"
+ "max(prova) as maxStageID,"
+ "min(prova) as minStageID"
+ " FROM events s LATERAL VIEW explode(`s.Stage IDs`) idsTable as prova"
+ " INNER JOIN events e ON s.`Job ID`=e.`Job ID`"
+ " WHERE s.Event LIKE '%JobStart' AND e.Event LIKE '%JobEnd'"
+ "GROUP BY `s.Job ID`,`s.Submission Time`,`e.Completion Time`,`s.Stage IDs`");
}
/**
* Retrieves the information on the Tasks
*
* @return
*
* @throws IOException
* @throws UnsupportedEncodingException
*/
private static DataFrame retrieveTaskInformation() throws IOException,
UnsupportedEncodingException {
// register two tables, one for the task start event and the other for
// the task end event
sqlContext.sql("SELECT * FROM events WHERE Event LIKE '%TaskStart'")
.registerTempTable("taskStartInfos");
sqlContext.sql("SELECT * FROM events WHERE Event LIKE '%TaskEnd'")
.registerTempTable("taskEndInfos");
// query the two tables for the task details
DataFrame taskDetails = sqlContext
.sql("SELECT `start.Task Info.Task ID` AS id,"
+ " `start.Stage ID` AS stageID,"
+ " `start.Task Info.Executor ID` AS executorID,"
+ " `start.Task Info.Host` AS host,"
+ " `finish.Task Type` AS type,"
+ " `finish.Task Info.Finish Time` - `start.Task Info.Launch Time` AS executionTime,"
+ " `finish.Task Info.Finish Time` AS finishTime,"
+ " `finish.Task Info.Getting Result Time` AS gettingResultTime,"
+ " `start.Task Info.Launch Time` AS startTime,"
+ " `finish.Task Metrics.Executor Run Time` AS executorRunTime,"
+ " `finish.Task Metrics.Executor Deserialize Time` AS executorDeserializerTime,"
+ " `finish.Task Metrics.Result Serialization Time` AS resultSerializationTime,"
+ " `finish.Task Metrics.Shuffle Write Metrics.Shuffle Write Time` AS shuffleWriteTime,"
+ " `finish.Task Metrics.JVM GC Time` AS GCTime,"
+ " `finish.Task Metrics.Result Size` AS resultSize,"
+ " `finish.Task Metrics.Memory Bytes Spilled` AS memoryBytesSpilled,"
+ " `finish.Task Metrics.Disk Bytes Spilled` AS diskBytesSpilled,"
+ " `finish.Task Metrics.Shuffle Write Metrics.Shuffle Bytes Written` AS shuffleBytesWritten,"
+ " `finish.Task Metrics.Shuffle Write Metrics.Shuffle Records Written` AS shuffleRecordsWritten,"
+ " `finish.Task Metrics.Input Metrics.Data Read Method` AS dataReadMethod,"
+ " `finish.Task Metrics.Input Metrics.Bytes Read` AS bytesRead,"
+ " `finish.Task Metrics.Input Metrics.Records Read` AS recordsRead,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Remote Blocks Fetched` AS shuffleRemoteBlocksFetched,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Local Blocks Fetched` AS shuffleLocalBlocksFetched,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Fetch Wait Time` AS shuffleFetchWaitTime,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Remote Bytes Read` AS shuffleRemoteBytesRead,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Local Bytes Read` AS shuffleLocalBytesRead,"
+ " `finish.Task Metrics.Shuffle Read Metrics.Total Records Read` AS shuffleTotalRecordsRead"
+ " FROM taskStartInfos AS start"
+ " JOIN taskEndInfos AS finish"
+ " ON `start.Task Info.Task ID`=`finish.Task Info.Task ID`");
return taskDetails;
}
/**
* Saves the table in the specified dataFrame in a CSV file. In order to
* save the whole table into a single the DataFrame is transformed into and
* RDD and then elements are collected. This might cause performance issue
* if the table is too long If a field contains an array (ArrayBuffer) its
* content is serialized with spaces as delimiters
*
* @param data
* @param fileName
* @throws IOException
* @throws UnsupportedEncodingException
*/
private static void saveListToCSV(DataFrame data, String fileName)
throws IOException, UnsupportedEncodingException {
List<Row> table = data.toJavaRDD().collect();
OutputStream os = hdfs.create(new Path(config.outputFolder, fileName));
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os,
"UTF-8"));
// the schema first
for (String column : data.columns())
br.write(column + ",");
br.write("\n");
// the values after
for (Row row : table) {
for (int i = 0; i < row.size(); i++) {
if (row.get(i) instanceof String
&& row.getString(i).startsWith("{")) {
// if the string starts with a parenthesis it is probably a
// Json object not deserialized (the scope)
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(row.getString(i))
.getAsJsonObject();
for (Entry<String, JsonElement> element : jsonObject
.entrySet())
br.write(element.getValue().getAsString() + " ");
br.write(",");
}
// if it is an array print all the elements separated by a space
// (instead of a comma)
else if (row.get(i) instanceof Traversable<?>)
br.write(((Traversable<?>) row.get(i)).mkString(" ") + ',');
// if the element itself contains a comma then switch it to a
// semicolon
else if (row.get(i) instanceof String
&& ((String) row.get(i)).contains(","))
br.write(((String) row.get(i)).replace(',', ';') + ",");
else {
br.write(row.get(i) + ",");
}
}
br.write("\n");
}
br.close();
}
/**
* Builds a DAG using all the stages in the provided list.
*
* @param stages
* @return
*/
private static DirectedAcyclicGraph<Stagenode, DefaultEdge> buildStageDag(
List<Stagenode> stages) {
DirectedAcyclicGraph<Stagenode, DefaultEdge> dag = new DirectedAcyclicGraph<Stagenode, DefaultEdge>(
DefaultEdge.class);
// build an hashmap to look for stages quickly
// and add vertexes to the graph
HashMap<Integer, Stagenode> stageMap = new HashMap<Integer, Stagenode>(
stages.size());
for (Stagenode stage : stages) {
stageMap.put(stage.getId(), stage);
logger.debug("Adding Stage " + stage.getId() + " to the graph");
dag.addVertex(stage);
}
// add all edges then
for (Stagenode stage : stages) {
if (stage.getParentIDs() != null)
for (Integer source : stage.getParentIDs()) {
logger.debug("Adding link from Stage " + source
+ "to Stage" + stage.getId());
dag.addEdge(stageMap.get(source), stage);
}
}
return dag;
}
/**
* builds a DAG using only the stages in the specified job, selected by
* those provided in the list
*
* @param stages
* @param stageNumber
* @return
*/
private static DirectedAcyclicGraph<Stagenode, DefaultEdge> buildStageDag(
List<Stagenode> stages, int jobNumber) {
List<Stagenode> jobStages = new ArrayList<Stagenode>();
for (Stagenode s : stages)
if ((int) s.getJobId() == jobNumber)
jobStages.add(s);
return buildStageDag(jobStages);
}
}
| [Parser]
added export of general app info (useful for scripting) | sparkloggerparser/src/main/java/it/polimi/spark/LoggerParser.java | [Parser] added export of general app info (useful for scripting) | <ide><path>parkloggerparser/src/main/java/it/polimi/spark/LoggerParser.java
<ide> logger.warn(
<ide> "The application could not be added to the database ",
<ide> e);
<add> }finally{
<add> saveApplicationInfo(application.getClusterName(), application.getAppID(), application.getAppName(), config.dbUser);
<ide> }
<ide> }
<ide> if (dbHandler != null)
<ide> br.close();
<ide> }
<ide>
<add> private static void saveApplicationInfo(String clusterName, String appId,
<add> String appName, String dbUser) throws IOException {
<add> OutputStream os = hdfs.create(new Path(config.outputFolder,
<add> "application.info"));
<add> BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os,
<add> "UTF-8"));
<add> br.write("Cluster name:" + clusterName);
<add> br.write("Application Id:" + appId);
<add> br.write("Application Name:" + appName);
<add> br.write("Database User:" + dbUser);
<add> br.close();
<add> }
<add>
<ide> /**
<ide> * Builds a DAG using all the stages in the provided list.
<ide> * |
|
Java | apache-2.0 | f9c8a8dba785a6c9dc8163c541f2b0c46111e122 | 0 | aygalinc/Context-SOCM,aygalinc/Context-SOCM | package fr.liglab.adele.cream.annotations.entity;
import fr.liglab.adele.cream.annotations.behavior.Behavior;
import fr.liglab.adele.cream.annotations.internal.BehaviorReference;
import fr.liglab.adele.cream.utils.CustomInvocationHandler;
import fr.liglab.adele.cream.utils.SuccessorStrategy;
import org.apache.felix.ipojo.InstanceManager;
import org.apache.felix.ipojo.handlers.providedservice.CreationStrategy;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* Created by aygalinc on 10/06/16.
*/
public class ContextProvideStrategy extends CreationStrategy {
private static final Logger LOG = LoggerFactory.getLogger(ContextProvideStrategy.class);
/**
* The instance manager passed to the iPOJO ServiceFactory to manage
* instances.
*/
private InstanceManager myManager;
/**
* The lists of interfaces provided by this service.
*/
private String[] mySpecs;
@Override
public void onPublication(InstanceManager instance, String[] interfaces, Properties props) {
this.mySpecs = interfaces;
this.myManager = instance;
}
@Override
public void onUnpublication() {
}
@Override
public Object getService(Bundle bundle, ServiceRegistration serviceRegistration) {
Object pojo = myManager.getPojoObject();
Class clazz = myManager.getClazz();
Behavior[] behaviors = (Behavior[]) clazz.getAnnotationsByType(Behavior.class);
Class<?> clazzInterface[] = clazz.getInterfaces();
Class<?> interfaces[] = new Class[behaviors.length+clazzInterface.length];
int i = 0;
for (Behavior behavior:behaviors){
Class service = behavior.spec();
interfaces[i] = service;
i++;
}
for (Class interfaz:clazzInterface){
interfaces[i] = interfaz;
i++;
}
List<InvocationHandler> successor = new ArrayList<InvocationHandler>();
InvocationHandler behaviorHandler = getBehaviorHandler();
if (behaviorHandler != null){
successor.add(behaviorHandler);
}
InvocationHandler invocationHandler = new CustomInvocationHandler(pojo,myManager,
new ParentSuccessorStrategy(),successor
);
try{
pojo = Proxy.newProxyInstance(clazz.getClassLoader(),interfaces,invocationHandler);
}catch (java.lang.NoClassDefFoundError e){
LOG.warn("Import-package declaration in bundle that contains instance " + myManager.getInstanceName() + " isn't enought explicit to load class defined in error. Context Provide strategy cannot be used, singleton strategy used instead ! " + e.toString());
}
return pojo;
}
@Override
public void ungetService(Bundle bundle, ServiceRegistration serviceRegistration, Object o) {
}
private InvocationHandler getBehaviorHandler(){
Object handler = myManager.getHandler(BehaviorReference.BEHAVIOR_NAMESPACE+":"+BehaviorReference.DEFAULT_BEHAVIOR_TYPE);
if (handler == null) return null;
return (InvocationHandler) handler;
}
private class ParentSuccessorStrategy implements SuccessorStrategy {
private final static String EQUALS_METHOD_CALL = "equals";
private final static String HASHCODE_METHOD_CALL = "hashcode";
private final static String TOSTRING_METHOD_CALL = "toString";
private final static String NONE_OBJECT_METHOD_CALL = "None";
@Override
public Object successorStrategy(Object pojo, List<InvocationHandler> successors, Object proxy, Method method, Object[] args) throws Throwable {
String nativeMethodCode = belongToObjectMethod( proxy, method, args);
if (!NONE_OBJECT_METHOD_CALL.equals(nativeMethodCode)){
if (EQUALS_METHOD_CALL.equals(nativeMethodCode)){
return pojo.equals(args[0]);
}
else if (HASHCODE_METHOD_CALL.equals(nativeMethodCode)){
return pojo.hashCode();
}
else if (TOSTRING_METHOD_CALL.equals(nativeMethodCode)){
return pojo.toString();
}
}
for (InvocationHandler successor : successors){
Object returnObj = successor.invoke(proxy,method,args);
if (SuccessorStrategy.NO_FOUND_CODE.equals(returnObj)){
continue;
}
return returnObj;
}
throw new RuntimeException();
}
private String belongToObjectMethod(Object proxy, Method method, Object[] args){
if (TOSTRING_METHOD_CALL.equals(method.getName()) && args == null ){
return TOSTRING_METHOD_CALL;
}
if (HASHCODE_METHOD_CALL.equals(method.getName()) && args == null ){
return HASHCODE_METHOD_CALL;
}
if (EQUALS_METHOD_CALL.equals(method.getName()) && args.length == 1 ){
return EQUALS_METHOD_CALL;
}
return NONE_OBJECT_METHOD_CALL;
}
}
}
| cream-core/src/main/java/fr/liglab/adele/cream/annotations/entity/ContextProvideStrategy.java | package fr.liglab.adele.cream.annotations.entity;
import fr.liglab.adele.cream.annotations.behavior.Behavior;
import fr.liglab.adele.cream.annotations.internal.BehaviorReference;
import fr.liglab.adele.cream.utils.CustomInvocationHandler;
import fr.liglab.adele.cream.utils.SuccessorStrategy;
import org.apache.felix.ipojo.InstanceManager;
import org.apache.felix.ipojo.handlers.providedservice.CreationStrategy;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceRegistration;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* Created by aygalinc on 10/06/16.
*/
public class ContextProvideStrategy extends CreationStrategy {
/**
* The instance manager passed to the iPOJO ServiceFactory to manage
* instances.
*/
private InstanceManager myManager;
/**
* The lists of interfaces provided by this service.
*/
private String[] mySpecs;
@Override
public void onPublication(InstanceManager instance, String[] interfaces, Properties props) {
this.mySpecs = interfaces;
this.myManager = instance;
}
@Override
public void onUnpublication() {
}
@Override
public Object getService(Bundle bundle, ServiceRegistration serviceRegistration) {
Object pojo = myManager.getPojoObject();
Class clazz = myManager.getClazz();
Behavior[] behaviors = (Behavior[]) clazz.getAnnotationsByType(Behavior.class);
Class<?> clazzInterface[] = clazz.getInterfaces();
Class<?> interfaces[] = new Class[behaviors.length+clazzInterface.length];
int i = 0;
for (Behavior behavior:behaviors){
Class service = behavior.spec();
interfaces[i] = service;
i++;
}
for (Class interfaz:clazzInterface){
interfaces[i] = interfaz;
i++;
}
List<InvocationHandler> successor = new ArrayList<InvocationHandler>();
InvocationHandler behaviorHandler = getBehaviorHandler();
if (behaviorHandler != null){
successor.add(behaviorHandler);
}
InvocationHandler invocationHandler = new CustomInvocationHandler(pojo,myManager,
new ParentSuccessorStrategy(),successor
);
return Proxy.newProxyInstance(clazz.getClassLoader(),interfaces,invocationHandler);
}
@Override
public void ungetService(Bundle bundle, ServiceRegistration serviceRegistration, Object o) {
}
private InvocationHandler getBehaviorHandler(){
Object handler = myManager.getHandler(BehaviorReference.BEHAVIOR_NAMESPACE+":"+BehaviorReference.DEFAULT_BEHAVIOR_TYPE);
if (handler == null) return null;
return (InvocationHandler) handler;
}
private class ParentSuccessorStrategy implements SuccessorStrategy {
private final static String EQUALS_METHOD_CALL = "equals";
private final static String HASHCODE_METHOD_CALL = "hashcode";
private final static String TOSTRING_METHOD_CALL = "toString";
private final static String NONE_OBJECT_METHOD_CALL = "None";
@Override
public Object successorStrategy(Object pojo, List<InvocationHandler> successors, Object proxy, Method method, Object[] args) throws Throwable {
String nativeMethodCode = belongToObjectMethod( proxy, method, args);
if (!NONE_OBJECT_METHOD_CALL.equals(nativeMethodCode)){
if (EQUALS_METHOD_CALL.equals(nativeMethodCode)){
return pojo.equals(args[0]);
}
else if (HASHCODE_METHOD_CALL.equals(nativeMethodCode)){
return pojo.hashCode();
}
else if (TOSTRING_METHOD_CALL.equals(nativeMethodCode)){
return pojo.toString();
}
}
for (InvocationHandler successor : successors){
Object returnObj = successor.invoke(proxy,method,args);
if (SuccessorStrategy.NO_FOUND_CODE.equals(returnObj)){
continue;
}
return returnObj;
}
throw new RuntimeException();
}
private String belongToObjectMethod(Object proxy, Method method, Object[] args){
if (TOSTRING_METHOD_CALL.equals(method.getName()) && args == null ){
return TOSTRING_METHOD_CALL;
}
if (HASHCODE_METHOD_CALL.equals(method.getName()) && args == null ){
return HASHCODE_METHOD_CALL;
}
if (EQUALS_METHOD_CALL.equals(method.getName()) && args.length == 1 ){
return EQUALS_METHOD_CALL;
}
return NONE_OBJECT_METHOD_CALL;
}
}
}
| Add try catch if import package of context entity does not allowed to create a proxy , it swtiches on a singleton strategy
| cream-core/src/main/java/fr/liglab/adele/cream/annotations/entity/ContextProvideStrategy.java | Add try catch if import package of context entity does not allowed to create a proxy , it swtiches on a singleton strategy | <ide><path>ream-core/src/main/java/fr/liglab/adele/cream/annotations/entity/ContextProvideStrategy.java
<ide> import org.apache.felix.ipojo.handlers.providedservice.CreationStrategy;
<ide> import org.osgi.framework.Bundle;
<ide> import org.osgi.framework.ServiceRegistration;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<ide>
<ide> import java.lang.reflect.InvocationHandler;
<ide> import java.lang.reflect.Method;
<ide> * Created by aygalinc on 10/06/16.
<ide> */
<ide> public class ContextProvideStrategy extends CreationStrategy {
<add>
<add> private static final Logger LOG = LoggerFactory.getLogger(ContextProvideStrategy.class);
<ide>
<ide> /**
<ide> * The instance manager passed to the iPOJO ServiceFactory to manage
<ide> InvocationHandler invocationHandler = new CustomInvocationHandler(pojo,myManager,
<ide> new ParentSuccessorStrategy(),successor
<ide> );
<del>
<del> return Proxy.newProxyInstance(clazz.getClassLoader(),interfaces,invocationHandler);
<add> try{
<add> pojo = Proxy.newProxyInstance(clazz.getClassLoader(),interfaces,invocationHandler);
<add> }catch (java.lang.NoClassDefFoundError e){
<add> LOG.warn("Import-package declaration in bundle that contains instance " + myManager.getInstanceName() + " isn't enought explicit to load class defined in error. Context Provide strategy cannot be used, singleton strategy used instead ! " + e.toString());
<add> }
<add> return pojo;
<ide> }
<ide>
<ide> @Override |
|
Java | unlicense | 7b86245783c9da1f6a8ec91aa794c72ba740bcb1 | 0 | danielricci/Chess | /**
* Daniel Ricci <[email protected]>
*
* 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 game.components;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import controllers.PlayerController;
import engine.core.factories.AbstractFactory;
import engine.core.factories.ControllerFactory;
import engine.utils.io.logging.Tracelog;
import game.components.MovementComponent.EntityMovements;
import game.components.MovementComponent.PlayerDirection;
import game.entities.concrete.AbstractChessEntity;
import models.PlayerModel;
import models.PlayerModel.PlayerTeam;
import models.TileModel;
/**
* This class represents the instructions for how the board game should operate
*
* @author Daniel Ricci {@literal <[email protected]>}
*
*/
public class BoardComponent {
/**
* The dimensions of the board game
*/
private final Dimension _dimensions;
/**
* The list of neighbors logically associated to a specified controller
*
* Key1: The tile model center
* Key2: The TOP, BOTTOM, LEFT, RIGHT neighboring tiles of the specified key1
*/
private final Map<TileModel, Map<EntityMovements, TileModel>> _neighbors = new LinkedHashMap();
/**
* Constructs a new instance of this class type
*
* @param dimensions The board game dimensions
*/
public BoardComponent(Dimension dimensions) {
_dimensions = dimensions;
}
/**
* Adds the specified tile model into the neighbors list
*
* @param tileModel The tile model
*/
public void addTileEntity(TileModel tileModel) {
// If what are trying to insert has already been inserted then something went wrong
if(_neighbors.putIfAbsent(tileModel, null) != null) {
Tracelog.log(Level.SEVERE, true, "Error: Tile model already exists in the list... cannot add this one in");
}
// If we have enough neighboring elements, then its time to link them together
if(_dimensions.width * _dimensions.height == _neighbors.size()) {
generateLogicalTileLinks();
}
}
/**
* Indicates if the specified tile contains an entity that has the ability to move forward
*
* @param tileModel The tile model in question
*
* @return TRUE if the specified tile contains an entity that has the ability to move forward
*/
public boolean canMoveForward(TileModel tileModel) {
AbstractChessEntity entity = tileModel.getEntity();
if(entity != null) {
return _neighbors.get(tileModel).get(PlayerDirection.getNormalizedMovement(entity.getTeam().DIRECTION, EntityMovements.UP)) != null;
}
return false;
}
/**
* Logically attaches the list of tiles together by sub-dividing the list of tiles.
* Note: Order matters in cases such as this, which is why insertion order was important
* when I chose the data structure for the neighbors map
*/
private void generateLogicalTileLinks() {
// Get the array representation of our tile models.
// Note: This is done because it is easier to get a subset of an array
// and because the neighbor data structure tracks the insertion
// order at runtime which is what is important here.
TileModel[] tiles = _neighbors.keySet().toArray(new TileModel[0]);
// For every row that exists within our setup model
for(int i = 0, rows = _dimensions.height, columns = _dimensions.width; i < rows; ++i) {
// Link the tile rows together
linkTiles(
// Previous row
i - 1 >= 0 ? Arrays.copyOfRange(tiles, (i - 1) * columns, ((i - 1) * columns) + columns) : null,
// Current Row
Arrays.copyOfRange(tiles, i * columns, (i * columns) + columns),
// Next Row
i + 1 >= 0 ? Arrays.copyOfRange(tiles, (i + 1) * columns, ((i + 1) * columns) + columns) : null
);
}
}
/**
* Gets all the neighbors associated to the particular model
*
* @param tileModel The tile model to use as a search for neighbors around it
*
* @return The list of tile models that neighbor the passed in tile model
*/
public List<TileModel> getAllNeighbors(TileModel tileModel) {
// Get the list of neighbors associated to our tile model
Map<EntityMovements, TileModel> tileModelNeighbors = _neighbors.get(tileModel);
// This collection holds the list of all the neighbors
List<TileModel> allNeighbors = new ArrayList();
// Go through every entry set in our structure
for(Map.Entry<EntityMovements, TileModel> entry : tileModelNeighbors.entrySet()) {
// Get the tile model
TileModel tile = entry.getValue();
if(tile == null) {
continue;
}
// Add our tile to the list
allNeighbors.add(tile);
// To get the diagonals, make sure that if we are on the top or bottom tile
// that we fetch their respective tiles, and provided that they are valid
// add them to our list.
switch(entry.getKey()) {
case UP:
case DOWN:
TileModel left = _neighbors.get(tile).get(EntityMovements.LEFT);
if(left != null) {
allNeighbors.add(left);
}
TileModel right = _neighbors.get(tile).get(EntityMovements.RIGHT);
if(right != null) {
allNeighbors.add(right);
}
break;
}
}
// return the list of neighbors
return allNeighbors;
}
/**
* Gets all the board positions that the specified entity on the specified tile can move to
*
* @param tileModel The tile model
*
* @return All the board positions
*/
public Map<TileModel, EntityMovements[]> getBoardPositions(TileModel tileModel) {
// Get a reference to the player controller
PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true);
// Get the list of positions that can be moved to
Map<TileModel, EntityMovements[]> availablePositions = getBoardPositionsImpl(tileModel);
// Go through the list of moves and scrub the ones that would result in my being in check
for(Iterator<Map.Entry<TileModel, EntityMovements[]>> it = availablePositions.entrySet().iterator(); it.hasNext();) {
Map.Entry<TileModel, EntityMovements[]> entry = it.next();
if(isMoveChecked(playerController.getPlayer(tileModel.getEntity().getTeam()), tileModel, entry.getKey())) {
it.remove();
}
}
// If the current tile has an entity and it can be used to castle
if(tileModel.getEntity() != null && !tileModel.getEntity().getIsChecked() && tileModel.getEntity().getIsCastlableFromCandidate()) {
// Get the left-most rook castle candidate
TileModel leftCandidate = getCastlableToEntity(tileModel, EntityMovements.LEFT);
if(leftCandidate != null) {
availablePositions.put(
_neighbors.get(_neighbors.get(tileModel).get(EntityMovements.LEFT)).get(EntityMovements.LEFT),
new EntityMovements[] {EntityMovements.LEFT, EntityMovements.LEFT}
);
}
// Get the right-most rook castle candidate
TileModel rightCandidate = getCastlableToEntity(tileModel, EntityMovements.RIGHT);
if(rightCandidate != null) {
availablePositions.put(
_neighbors.get(_neighbors.get(tileModel).get(EntityMovements.RIGHT)).get(EntityMovements.RIGHT),
new EntityMovements[] {EntityMovements.RIGHT, EntityMovements.RIGHT}
);
}
}
// Return back the list of available positions
return availablePositions;
}
/**
* Gets the castlable to entity in the specified movement direction
*
* @param from The from tile
* @param movement The direction to move in
*
* @return The tile that can be castled with if any
*/
public TileModel getCastlableToEntity(TileModel from, EntityMovements movement) {
// Get the list of castle candidates that can be castled to
PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true);
List<AbstractChessEntity> candidates = playerController.getPlayer(from.getEntity().getTeam()).getCastlableToCandidates();
// This represents the number of movements that the king needs
// to ensure that there is no check
int kingPositions = 0;
TileModel temp = from;
while((temp = _neighbors.get(temp).get(movement)) != null) {
// If the first two moves would put you in check then
// a valid castling cannot be performed
if(++kingPositions <= 2 && isMoveChecked(from.getEntity().getPlayer(), from, temp)) {
return null;
}
// If the entity exists make sure it is one of our candidates
else if(temp.getEntity() != null) {
if(candidates.contains(temp.getEntity()) && temp.getEntity().getIsCastlableToCandidate() && _neighbors.get(temp).get(movement) == null) {
break;
}
else {
return null;
}
}
}
return temp;
}
/**
* Sets the new position of the castlable entity
*
* @param fromPosition The position of where the from would be AFTER it has been updated
* @param castleableTo The position of the entity that the king will castle with
* @param fromMovement The movement that resulted in the from position from arriving at its updated location
*/
public void setCastlableMovement(TileModel fromPosition, TileModel castleableTo, EntityMovements fromMovement) {
if(fromMovement == EntityMovements.LEFT || fromMovement == EntityMovements.RIGHT) {
AbstractChessEntity castleEntity = castleableTo.getEntity();
castleableTo.setEntity(null);
TileModel newCastleLocation = _neighbors.get(fromPosition).get(MovementComponent.invert(fromMovement));
newCastleLocation.setEntity(castleEntity);
}
}
/**
* Gets the list of board positions that the specified tile can move on
*
* @param tileModel The tile model being played
*
* @return The list of tiles to move towards
*/
public Map<TileModel, EntityMovements[]> getBoardPositionsImpl(TileModel tileModel) {
Map<TileModel, EntityMovements[]> allMoves = new HashMap();
// Attempt to get the en-passent moves of the specified tile
for(Map.Entry<TileModel, EntityMovements[]> kvp : getEnPassentBoardPositions(tileModel).entrySet()) {
allMoves.putIfAbsent(kvp.getKey(), kvp.getValue());
}
// If tile model does not has a chess entity then
// there are no moves to get
AbstractChessEntity entity = tileModel.getEntity();
if(entity == null) {
return allMoves;
}
// The flag indicating if the entity can capture enemy pieces with the same
// movement as their allowed list of movements or if they have a separate list for that
final boolean isMovementCapturable = entity.isMovementCapturable();
// Holds the list of regular movements and capturable movements which
// are movements outside the general scope of a normal movement
List<EntityMovements[]> movements = entity.getMovements();
List<EntityMovements[]> capturableMovements = new ArrayList();
// If this entity is an entity where its movements are different
// from it's actual capture movements then add those into a separate
// list so we can differentiate between both of them
if(!isMovementCapturable) {
capturableMovements.addAll(entity.getCapturableBoardMovements());
movements.addAll(capturableMovements);
}
// Go through the list of path movements for the entity
for(EntityMovements[] movementPath : movements) {
TileModel traverser = tileModel;
do {
// Temporary list to hold our entire path, and from there I
// pick the last element
List<TileModel> tiles = new ArrayList();
for(EntityMovements movement : movementPath) {
// Normalize the movement w.r.t the player of the entity
movement = PlayerDirection.getNormalizedMovement(entity.getTeam().DIRECTION, movement);
// Get the movements of the tile from our position
traverser = _neighbors.get(traverser).get(movement);
// If the position is outside the board dimensions then clear the movement to get
// to that location and exit the loop
if(traverser == null) {
tiles.clear();
break;
}
// If the entity contains movements that differ from their capture movements
// and we are trying to use a regular movement then this is not legal.
// As an example, without this code a pawn could do a capture on it's two move
// movement, or it could hop over another enemy pawn
if(!isMovementCapturable && traverser.getEntity() != null && !capturableMovements.contains(movementPath)) {
tiles.clear();
break;
}
// Add the traversed tile to our constructed path
tiles.add(traverser);
}
if(tiles.isEmpty()) {
break;
}
// Get the last tile within our path (the endpoint)
TileModel destinationTile = tiles.get(tiles.size() - 1);
// If the entity contains movements that differ from their capture movements
// then ensure that if we are trying to capture an enemy player that it only
// ever is allowed if the movement is within the capture movement list
// that the entity holds
// Note: This line of code looks a little similar to the one above in the second for-each, however
// they both do completely different things however they are both related to differences of
// how a piece moves and captures
if(!isMovementCapturable && (destinationTile.getEntity() == null || destinationTile.getEntity().getTeam().equals(entity.getTeam())) && capturableMovements.contains(movementPath)) {
break;
}
// if the end tile is ourselves then do not consider it and stop
if(destinationTile.getEntity() != null && destinationTile.getEntity().getTeam().equals(entity.getTeam())) {
break;
}
// Add the last tile into our list of valid tiles
allMoves.put(destinationTile, movementPath);
// If the tile has an enemy player on it then stop here
// If the tile is not continuous then we do not need to
// continue with the same move
if((destinationTile.getEntity() != null && !destinationTile.getEntity().getTeam().equals(entity.getTeam())) || !entity.isMovementContinuous()) {
break;
}
} while(true);
}
return allMoves;
}
/**
* Gets the list of checked positions of the specified player
*
* @param player The player to check for checked positions
*
* @return The list of checked positions
*/
public List<TileModel> getCheckedPositions(PlayerModel player) {
PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true);
PlayerModel enemy = playerController.getPlayer(player.getTeam() == PlayerTeam.BLACK ? PlayerTeam.WHITE : PlayerTeam.BLACK);
// The list of enemy owned tiles that are checked by the specified player
List<TileModel> checkedEntities = new ArrayList();
// Get the list of checkable entities owned by the enemy player
List<AbstractChessEntity> checkableEntities = player.getCheckableEntities();
// Go through the list of enemy entities and see if any of them
// can move to a position of that which is in the checkable entities list above
for(AbstractChessEntity enemyEntity : enemy.getEntities()) {
Map<TileModel, EntityMovements[]> positions = getBoardPositionsImpl(enemyEntity.getTile());
for(Map.Entry<TileModel, EntityMovements[]> movement : positions.entrySet()) {
if(checkableEntities.contains(movement.getKey().getEntity())) {
checkedEntities.add(movement.getKey());
}
}
}
return checkedEntities;
}
/**
* Gets the En-Passent movements of the specified tile
*
* @param source The tile to get the moves from
*
* @return The mappings of available moves for the specified tile
*/
public Map<TileModel, EntityMovements[]> getEnPassentBoardPositions(TileModel source) {
Map<TileModel, EntityMovements[]> movements = new HashMap();
// Verify if the passed in source is a valid tile for performing an en-passent move
if(source == null || source.getEntity() == null || !source.getEntity().isEnPassent()) {
return movements;
}
AbstractChessEntity entity = source.getEntity();
PlayerDirection direction = entity.getTeam().DIRECTION;
// Left En-Passent
EntityMovements enPassentLeft = PlayerDirection.getNormalizedMovement(direction, EntityMovements.LEFT);
TileModel capturableEnPassentLeft = _neighbors.get(source).get(enPassentLeft);
if(capturableEnPassentLeft != null && capturableEnPassentLeft.getEntity() != null && !capturableEnPassentLeft.getEntity().getTeam().equals(source.getEntity().getTeam()) && capturableEnPassentLeft.getEntity().isEnPassentCapturable()) {
EntityMovements enPassentBackwards = PlayerDirection.getNormalizedMovement(capturableEnPassentLeft.getEntity().getTeam().DIRECTION, EntityMovements.DOWN);
TileModel capturableEnPassentPosition = _neighbors.get(capturableEnPassentLeft).get(enPassentBackwards);
movements.put(
capturableEnPassentPosition,
PlayerDirection.getNormalizedMovement(direction, new EntityMovements[] { EntityMovements.UP, EntityMovements.LEFT })
);
}
// Right En-Passent
EntityMovements enPassentRight = PlayerDirection.getNormalizedMovement(direction, EntityMovements.RIGHT);
TileModel capturableEnPassentRight = _neighbors.get(source).get(enPassentRight);
if(capturableEnPassentRight != null && capturableEnPassentRight.getEntity() != null && !capturableEnPassentRight.getEntity().getTeam().equals(source.getEntity().getTeam()) && capturableEnPassentRight.getEntity().isEnPassentCapturable()) {
EntityMovements enPassentBackwards = PlayerDirection.getNormalizedMovement(capturableEnPassentRight.getEntity().getTeam().DIRECTION, EntityMovements.DOWN);
TileModel capturableEnPassentPosition = _neighbors.get(capturableEnPassentRight).get(enPassentBackwards);
movements.put(
capturableEnPassentPosition,
PlayerDirection.getNormalizedMovement(direction, new EntityMovements[] { EntityMovements.UP, EntityMovements.RIGHT })
);
}
return movements;
}
/**
* Gets the enemy tile associated to the specified tile
*
* @param tile The tile of the entity doing the en-passent
*
* @return The enemy tile
*/
public TileModel getEnPassentEnemy(TileModel tile) {
for(Map.Entry<TileModel, EntityMovements[]> kvp : getEnPassentBoardPositions(tile).entrySet()) {
TileModel enemy = _neighbors.get(kvp.getKey()).get(PlayerDirection.getNormalizedMovement(tile.getEntity().getTeam().DIRECTION, EntityMovements.DOWN));
if(enemy.getEntity() != null && enemy.getEntity().isEnPassentCapturable()) {
return enemy;
}
}
return null;
}
/**
* Verifies if a movement from the specified tile to the specified tile
* will result in a check of the specified player
*
* @param player The player to verify for being in check
* @param from The starting tile position
* @param to The end tile position
*
* @return TRUE If the move would result in a check of the specified player, FALSE otherwise
*/
public boolean isMoveChecked(PlayerModel player, TileModel from, TileModel to) {
// Hold temporary references to both entities of the tiles
AbstractChessEntity tempEntityFrom = from.getEntity();
AbstractChessEntity tempEntityTo = to.getEntity();
// Suppress the update events for both tiles
from.setSuppressUpdates(true);
to.setSuppressUpdates(true);
// Perform the logical steps of a movement
from.setEntity(null);
to.setEntity(null);
to.setEntity(tempEntityFrom);
PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true);
// If there is a player piece there, then remove it from the player
// temporarily
if(tempEntityTo != null) {
PlayerModel myPlayer = playerController.getPlayer(tempEntityTo.getTeam());
myPlayer.removeEntity(tempEntityTo);
}
// Check if the player is now in check
List<TileModel> checkedPositions = getCheckedPositions(player);
// Set back the piece belonging to the player of the 'to entity'
if(tempEntityTo != null) {
PlayerModel myPlayer = playerController.getPlayer(tempEntityTo.getTeam());
myPlayer.addEntity(tempEntityTo);
}
// Put back the entities into their tiles
to.setEntity(null);
from.setEntity(tempEntityFrom);
to.setEntity(tempEntityTo);
// Remove the suppressed flags from both tiles
from.setSuppressUpdates(false);
to.setSuppressUpdates(false);
// Indicate if there were any checked positions found
return !checkedPositions.isEmpty();
}
/**
* Links together the passed in rows
*
* @param topRow The top row
* @param neutralRow the neutral row
* @param bottomRow The bottom row
*/
private void linkTiles(TileModel[] topRow, TileModel[] neutralRow, TileModel[] bottomRow) {
for(int i = 0, columns = _dimensions.width; i < columns; ++i) {
// Represents the structural view of a particular tile
Map<EntityMovements, TileModel> neighbors = new HashMap<EntityMovements, TileModel>();
// Populate the neighbors structure with the movement elements
// Note: Diagonals can be fetched using these primitives
neighbors.put(EntityMovements.UP, topRow == null ? null : topRow[i]);
neighbors.put(EntityMovements.LEFT, i - 1 < 0 ? null : neutralRow[i - 1]);
neighbors.put(EntityMovements.RIGHT, i + 1 >= columns ? null : neutralRow[i + 1]);
neighbors.put(EntityMovements.DOWN, bottomRow == null ? null : bottomRow[i]);
// Assign the mappings where we reference the neutral-neutral tile as the key
_neighbors.put(neutralRow[i], neighbors);
}
}
} | Chess/src/game/components/BoardComponent.java | /**
* Daniel Ricci <[email protected]>
*
* 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 game.components;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import controllers.PlayerController;
import engine.core.factories.AbstractFactory;
import engine.core.factories.ControllerFactory;
import engine.utils.io.logging.Tracelog;
import game.components.MovementComponent.EntityMovements;
import game.components.MovementComponent.PlayerDirection;
import game.entities.concrete.AbstractChessEntity;
import models.PlayerModel;
import models.PlayerModel.PlayerTeam;
import models.TileModel;
/**
* This class represents the instructions for how the board game should operate
*
* @author Daniel Ricci {@literal <[email protected]>}
*
*/
public class BoardComponent {
/**
* The dimensions of the board game
*/
private final Dimension _dimensions;
/**
* The list of neighbors logically associated to a specified controller
*
* Key1: The tile model center
* Key2: The TOP, BOTTOM, LEFT, RIGHT neighboring tiles of the specified key1
*/
private final Map<TileModel, Map<EntityMovements, TileModel>> _neighbors = new LinkedHashMap();
/**
* Constructs a new instance of this class type
*
* @param dimensions The board game dimensions
*/
public BoardComponent(Dimension dimensions) {
_dimensions = dimensions;
}
/**
* Adds the specified tile model into the neighbors list
*
* @param tileModel The tile model
*/
public void addTileEntity(TileModel tileModel) {
// If what are trying to insert has already been inserted then something went wrong
if(_neighbors.putIfAbsent(tileModel, null) != null) {
Tracelog.log(Level.SEVERE, true, "Error: Tile model already exists in the list... cannot add this one in");
}
// If we have enough neighboring elements, then its time to link them together
if(_dimensions.width * _dimensions.height == _neighbors.size()) {
generateLogicalTileLinks();
}
}
/**
* Indicates if the specified tile contains an entity that has the ability to move forward
*
* @param tileModel The tile model in question
*
* @return TRUE if the specified tile contains an entity that has the ability to move forward
*/
public boolean canMoveForward(TileModel tileModel) {
AbstractChessEntity entity = tileModel.getEntity();
if(entity != null) {
return _neighbors.get(tileModel).get(PlayerDirection.getNormalizedMovement(entity.getTeam().DIRECTION, EntityMovements.UP)) != null;
}
return false;
}
/**
* Logically attaches the list of tiles together by sub-dividing the list of tiles.
* Note: Order matters in cases such as this, which is why insertion order was important
* when I chose the data structure for the neighbors map
*/
private void generateLogicalTileLinks() {
// Get the array representation of our tile models.
// Note: This is done because it is easier to get a subset of an array
// and because the neighbor data structure tracks the insertion
// order at runtime which is what is important here.
TileModel[] tiles = _neighbors.keySet().toArray(new TileModel[0]);
// For every row that exists within our setup model
for(int i = 0, rows = _dimensions.height, columns = _dimensions.width; i < rows; ++i) {
// Link the tile rows together
linkTiles(
// Previous row
i - 1 >= 0 ? Arrays.copyOfRange(tiles, (i - 1) * columns, ((i - 1) * columns) + columns) : null,
// Current Row
Arrays.copyOfRange(tiles, i * columns, (i * columns) + columns),
// Next Row
i + 1 >= 0 ? Arrays.copyOfRange(tiles, (i + 1) * columns, ((i + 1) * columns) + columns) : null
);
}
}
/**
* Gets all the neighbors associated to the particular model
*
* @param tileModel The tile model to use as a search for neighbors around it
*
* @return The list of tile models that neighbor the passed in tile model
*/
public List<TileModel> getAllNeighbors(TileModel tileModel) {
// Get the list of neighbors associated to our tile model
Map<EntityMovements, TileModel> tileModelNeighbors = _neighbors.get(tileModel);
// This collection holds the list of all the neighbors
List<TileModel> allNeighbors = new ArrayList();
// Go through every entry set in our structure
for(Map.Entry<EntityMovements, TileModel> entry : tileModelNeighbors.entrySet()) {
// Get the tile model
TileModel tile = entry.getValue();
if(tile == null) {
continue;
}
// Add our tile to the list
allNeighbors.add(tile);
// To get the diagonals, make sure that if we are on the top or bottom tile
// that we fetch their respective tiles, and provided that they are valid
// add them to our list.
switch(entry.getKey()) {
case UP:
case DOWN:
TileModel left = _neighbors.get(tile).get(EntityMovements.LEFT);
if(left != null) {
allNeighbors.add(left);
}
TileModel right = _neighbors.get(tile).get(EntityMovements.RIGHT);
if(right != null) {
allNeighbors.add(right);
}
break;
}
}
// return the list of neighbors
return allNeighbors;
}
/**
* Gets all the board positions that the specified entity on the specified tile can move to
*
* @param tileModel The tile model
*
* @return All the board positions
*/
public Map<TileModel, EntityMovements[]> getBoardPositions(TileModel tileModel) {
// Get a reference to the player controller
PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true);
// Get the list of positions that can be moved to
Map<TileModel, EntityMovements[]> availablePositions = getBoardPositionsImpl(tileModel);
// Go through the list of moves and scrub the ones that would result in my being in check
for(Iterator<Map.Entry<TileModel, EntityMovements[]>> it = availablePositions.entrySet().iterator(); it.hasNext();) {
Map.Entry<TileModel, EntityMovements[]> entry = it.next();
if(isMoveChecked(playerController.getPlayer(tileModel.getEntity().getTeam()), tileModel, entry.getKey())) {
it.remove();
}
}
// If the current tile has an entity and it can be used to castle
if(tileModel.getEntity() != null && tileModel.getEntity().getIsCastlableFromCandidate()) {
// Get the left-most rook castle candidate
TileModel leftCandidate = getCastlableToEntity(tileModel, EntityMovements.LEFT);
if(leftCandidate != null) {
availablePositions.put(
_neighbors.get(_neighbors.get(tileModel).get(EntityMovements.LEFT)).get(EntityMovements.LEFT),
new EntityMovements[] {EntityMovements.LEFT, EntityMovements.LEFT}
);
}
// Get the right-most rook castle candidate
TileModel rightCandidate = getCastlableToEntity(tileModel, EntityMovements.RIGHT);
if(rightCandidate != null) {
availablePositions.put(
_neighbors.get(_neighbors.get(tileModel).get(EntityMovements.RIGHT)).get(EntityMovements.RIGHT),
new EntityMovements[] {EntityMovements.RIGHT, EntityMovements.RIGHT}
);
}
}
// Return back the list of available positions
return availablePositions;
}
/**
* Gets the castlable to entity in the specified movement direction
*
* @param from The from tile
* @param movement The direction to move in
*
* @return The tile that can be castled with if any
*/
public TileModel getCastlableToEntity(TileModel from, EntityMovements movement) {
// Get the list of castle candidates that can be castled to
PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true);
List<AbstractChessEntity> candidates = playerController.getPlayer(from.getEntity().getTeam()).getCastlableToCandidates();
// This represents the number of movements that the king needs
// to ensure that there is no check
int kingPositions = 0;
TileModel temp = from;
while((temp = _neighbors.get(temp).get(movement)) != null) {
// If the first two moves would put you in check then
// a valid castling cannot be performed
if(++kingPositions <= 2 && isMoveChecked(from.getEntity().getPlayer(), from, temp)) {
return null;
}
// If the entity exists make sure it is one of our candidates
else if(temp.getEntity() != null) {
if(candidates.contains(temp.getEntity()) && temp.getEntity().getIsCastlableToCandidate() && _neighbors.get(temp).get(movement) == null) {
break;
}
else {
return null;
}
}
}
return temp;
}
/**
* Sets the new position of the castlable entity
*
* @param fromPosition The position of where the from would be AFTER it has been updated
* @param castleableTo The position of the entity that the king will castle with
* @param fromMovement The movement that resulted in the from position from arriving at its updated location
*/
public void setCastlableMovement(TileModel fromPosition, TileModel castleableTo, EntityMovements fromMovement) {
if(fromMovement == EntityMovements.LEFT || fromMovement == EntityMovements.RIGHT) {
AbstractChessEntity castleEntity = castleableTo.getEntity();
castleableTo.setEntity(null);
TileModel newCastleLocation = _neighbors.get(fromPosition).get(MovementComponent.invert(fromMovement));
newCastleLocation.setEntity(castleEntity);
}
}
/**
* Gets the list of board positions that the specified tile can move on
*
* @param tileModel The tile model being played
*
* @return The list of tiles to move towards
*/
public Map<TileModel, EntityMovements[]> getBoardPositionsImpl(TileModel tileModel) {
Map<TileModel, EntityMovements[]> allMoves = new HashMap();
// Attempt to get the en-passent moves of the specified tile
for(Map.Entry<TileModel, EntityMovements[]> kvp : getEnPassentBoardPositions(tileModel).entrySet()) {
allMoves.putIfAbsent(kvp.getKey(), kvp.getValue());
}
// If tile model does not has a chess entity then
// there are no moves to get
AbstractChessEntity entity = tileModel.getEntity();
if(entity == null) {
return allMoves;
}
// The flag indicating if the entity can capture enemy pieces with the same
// movement as their allowed list of movements or if they have a separate list for that
final boolean isMovementCapturable = entity.isMovementCapturable();
// Holds the list of regular movements and capturable movements which
// are movements outside the general scope of a normal movement
List<EntityMovements[]> movements = entity.getMovements();
List<EntityMovements[]> capturableMovements = new ArrayList();
// If this entity is an entity where its movements are different
// from it's actual capture movements then add those into a separate
// list so we can differentiate between both of them
if(!isMovementCapturable) {
capturableMovements.addAll(entity.getCapturableBoardMovements());
movements.addAll(capturableMovements);
}
// Go through the list of path movements for the entity
for(EntityMovements[] movementPath : movements) {
TileModel traverser = tileModel;
do {
// Temporary list to hold our entire path, and from there I
// pick the last element
List<TileModel> tiles = new ArrayList();
for(EntityMovements movement : movementPath) {
// Normalize the movement w.r.t the player of the entity
movement = PlayerDirection.getNormalizedMovement(entity.getTeam().DIRECTION, movement);
// Get the movements of the tile from our position
traverser = _neighbors.get(traverser).get(movement);
// If the position is outside the board dimensions then clear the movement to get
// to that location and exit the loop
if(traverser == null) {
tiles.clear();
break;
}
// If the entity contains movements that differ from their capture movements
// and we are trying to use a regular movement then this is not legal.
// As an example, without this code a pawn could do a capture on it's two move
// movement, or it could hop over another enemy pawn
if(!isMovementCapturable && traverser.getEntity() != null && !capturableMovements.contains(movementPath)) {
tiles.clear();
break;
}
// Add the traversed tile to our constructed path
tiles.add(traverser);
}
if(tiles.isEmpty()) {
break;
}
// Get the last tile within our path (the endpoint)
TileModel destinationTile = tiles.get(tiles.size() - 1);
// If the entity contains movements that differ from their capture movements
// then ensure that if we are trying to capture an enemy player that it only
// ever is allowed if the movement is within the capture movement list
// that the entity holds
// Note: This line of code looks a little similar to the one above in the second for-each, however
// they both do completely different things however they are both related to differences of
// how a piece moves and captures
if(!isMovementCapturable && (destinationTile.getEntity() == null || destinationTile.getEntity().getTeam().equals(entity.getTeam())) && capturableMovements.contains(movementPath)) {
break;
}
// if the end tile is ourselves then do not consider it and stop
if(destinationTile.getEntity() != null && destinationTile.getEntity().getTeam().equals(entity.getTeam())) {
break;
}
// Add the last tile into our list of valid tiles
allMoves.put(destinationTile, movementPath);
// If the tile has an enemy player on it then stop here
// If the tile is not continuous then we do not need to
// continue with the same move
if((destinationTile.getEntity() != null && !destinationTile.getEntity().getTeam().equals(entity.getTeam())) || !entity.isMovementContinuous()) {
break;
}
} while(true);
}
return allMoves;
}
/**
* Gets the list of checked positions of the specified player
*
* @param player The player to check for checked positions
*
* @return The list of checked positions
*/
public List<TileModel> getCheckedPositions(PlayerModel player) {
PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true);
PlayerModel enemy = playerController.getPlayer(player.getTeam() == PlayerTeam.BLACK ? PlayerTeam.WHITE : PlayerTeam.BLACK);
// The list of enemy owned tiles that are checked by the specified player
List<TileModel> checkedEntities = new ArrayList();
// Get the list of checkable entities owned by the enemy player
List<AbstractChessEntity> checkableEntities = player.getCheckableEntities();
// Go through the list of enemy entities and see if any of them
// can move to a position of that which is in the checkable entities list above
for(AbstractChessEntity enemyEntity : enemy.getEntities()) {
Map<TileModel, EntityMovements[]> positions = getBoardPositionsImpl(enemyEntity.getTile());
for(Map.Entry<TileModel, EntityMovements[]> movement : positions.entrySet()) {
if(checkableEntities.contains(movement.getKey().getEntity())) {
checkedEntities.add(movement.getKey());
}
}
}
return checkedEntities;
}
/**
* Gets the En-Passent movements of the specified tile
*
* @param source The tile to get the moves from
*
* @return The mappings of available moves for the specified tile
*/
public Map<TileModel, EntityMovements[]> getEnPassentBoardPositions(TileModel source) {
Map<TileModel, EntityMovements[]> movements = new HashMap();
// Verify if the passed in source is a valid tile for performing an en-passent move
if(source == null || source.getEntity() == null || !source.getEntity().isEnPassent()) {
return movements;
}
AbstractChessEntity entity = source.getEntity();
PlayerDirection direction = entity.getTeam().DIRECTION;
// Left En-Passent
EntityMovements enPassentLeft = PlayerDirection.getNormalizedMovement(direction, EntityMovements.LEFT);
TileModel capturableEnPassentLeft = _neighbors.get(source).get(enPassentLeft);
if(capturableEnPassentLeft != null && capturableEnPassentLeft.getEntity() != null && !capturableEnPassentLeft.getEntity().getTeam().equals(source.getEntity().getTeam()) && capturableEnPassentLeft.getEntity().isEnPassentCapturable()) {
EntityMovements enPassentBackwards = PlayerDirection.getNormalizedMovement(capturableEnPassentLeft.getEntity().getTeam().DIRECTION, EntityMovements.DOWN);
TileModel capturableEnPassentPosition = _neighbors.get(capturableEnPassentLeft).get(enPassentBackwards);
movements.put(
capturableEnPassentPosition,
PlayerDirection.getNormalizedMovement(direction, new EntityMovements[] { EntityMovements.UP, EntityMovements.LEFT })
);
}
// Right En-Passent
EntityMovements enPassentRight = PlayerDirection.getNormalizedMovement(direction, EntityMovements.RIGHT);
TileModel capturableEnPassentRight = _neighbors.get(source).get(enPassentRight);
if(capturableEnPassentRight != null && capturableEnPassentRight.getEntity() != null && !capturableEnPassentRight.getEntity().getTeam().equals(source.getEntity().getTeam()) && capturableEnPassentRight.getEntity().isEnPassentCapturable()) {
EntityMovements enPassentBackwards = PlayerDirection.getNormalizedMovement(capturableEnPassentRight.getEntity().getTeam().DIRECTION, EntityMovements.DOWN);
TileModel capturableEnPassentPosition = _neighbors.get(capturableEnPassentRight).get(enPassentBackwards);
movements.put(
capturableEnPassentPosition,
PlayerDirection.getNormalizedMovement(direction, new EntityMovements[] { EntityMovements.UP, EntityMovements.RIGHT })
);
}
return movements;
}
/**
* Gets the enemy tile associated to the specified tile
*
* @param tile The tile of the entity doing the en-passent
*
* @return The enemy tile
*/
public TileModel getEnPassentEnemy(TileModel tile) {
for(Map.Entry<TileModel, EntityMovements[]> kvp : getEnPassentBoardPositions(tile).entrySet()) {
TileModel enemy = _neighbors.get(kvp.getKey()).get(PlayerDirection.getNormalizedMovement(tile.getEntity().getTeam().DIRECTION, EntityMovements.DOWN));
if(enemy.getEntity() != null && enemy.getEntity().isEnPassentCapturable()) {
return enemy;
}
}
return null;
}
/**
* Verifies if a movement from the specified tile to the specified tile
* will result in a check of the specified player
*
* @param player The player to verify for being in check
* @param from The starting tile position
* @param to The end tile position
*
* @return TRUE If the move would result in a check of the specified player, FALSE otherwise
*/
public boolean isMoveChecked(PlayerModel player, TileModel from, TileModel to) {
// Hold temporary references to both entities of the tiles
AbstractChessEntity tempEntityFrom = from.getEntity();
AbstractChessEntity tempEntityTo = to.getEntity();
// Suppress the update events for both tiles
from.setSuppressUpdates(true);
to.setSuppressUpdates(true);
// Perform the logical steps of a movement
from.setEntity(null);
to.setEntity(null);
to.setEntity(tempEntityFrom);
PlayerController playerController = AbstractFactory.getFactory(ControllerFactory.class).get(PlayerController.class, true);
// If there is a player piece there, then remove it from the player
// temporarily
if(tempEntityTo != null) {
PlayerModel myPlayer = playerController.getPlayer(tempEntityTo.getTeam());
myPlayer.removeEntity(tempEntityTo);
}
// Check if the player is now in check
List<TileModel> checkedPositions = getCheckedPositions(player);
// Set back the piece belonging to the player of the 'to entity'
if(tempEntityTo != null) {
PlayerModel myPlayer = playerController.getPlayer(tempEntityTo.getTeam());
myPlayer.addEntity(tempEntityTo);
}
// Put back the entities into their tiles
to.setEntity(null);
from.setEntity(tempEntityFrom);
to.setEntity(tempEntityTo);
// Remove the suppressed flags from both tiles
from.setSuppressUpdates(false);
to.setSuppressUpdates(false);
// Indicate if there were any checked positions found
return !checkedPositions.isEmpty();
}
/**
* Links together the passed in rows
*
* @param topRow The top row
* @param neutralRow the neutral row
* @param bottomRow The bottom row
*/
private void linkTiles(TileModel[] topRow, TileModel[] neutralRow, TileModel[] bottomRow) {
for(int i = 0, columns = _dimensions.width; i < columns; ++i) {
// Represents the structural view of a particular tile
Map<EntityMovements, TileModel> neighbors = new HashMap<EntityMovements, TileModel>();
// Populate the neighbors structure with the movement elements
// Note: Diagonals can be fetched using these primitives
neighbors.put(EntityMovements.UP, topRow == null ? null : topRow[i]);
neighbors.put(EntityMovements.LEFT, i - 1 < 0 ? null : neutralRow[i - 1]);
neighbors.put(EntityMovements.RIGHT, i + 1 >= columns ? null : neutralRow[i + 1]);
neighbors.put(EntityMovements.DOWN, bottomRow == null ? null : bottomRow[i]);
// Assign the mappings where we reference the neutral-neutral tile as the key
_neighbors.put(neutralRow[i], neighbors);
}
}
} | #fixes 117
- Fixed a bug where the king could move out of check by performing a
castle. The king can no longer castle when in check | Chess/src/game/components/BoardComponent.java | #fixes 117 | <ide><path>hess/src/game/components/BoardComponent.java
<ide> }
<ide>
<ide> // If the current tile has an entity and it can be used to castle
<del> if(tileModel.getEntity() != null && tileModel.getEntity().getIsCastlableFromCandidate()) {
<add> if(tileModel.getEntity() != null && !tileModel.getEntity().getIsChecked() && tileModel.getEntity().getIsCastlableFromCandidate()) {
<ide>
<ide> // Get the left-most rook castle candidate
<ide> TileModel leftCandidate = getCastlableToEntity(tileModel, EntityMovements.LEFT); |
|
Java | apache-2.0 | 08f890e2c327cdf7bae4331fa83ab3d0f578c940 | 0 | lolocripto/wikokit,componavt/wikokit,componavt/wikokit,lolocripto/wikokit,componavt/wikokit,componavt/wikokit,lolocripto/wikokit,componavt/wikokit,lolocripto/wikokit,lolocripto/wikokit,componavt/wikokit | /* ShortestPathRelation.java - Distance calculations.
*
* Copyright (c) 2009 Andrew Krizhanovsky <andrew.krizhanovsky at gmail.com>
* Distributed under GNU Public License.
*/
package wigraph.experiment;
import wigraph.PathSearcher;
import wigraph.DistanceData;
import wigraph.LoadRelations;
import wikipedia.sql.Connect;
import wikipedia.util.*;
import wikipedia.language.LanguageType;
import wikt.sql.TTranslation;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
import java.text.DateFormat;
import java.util.Locale;
import java.util.Date;
/** Calculation of distances between 353 pairs of English words,
* based on path length in thesaurus of Russian words,
* extracted from Russian Wiktionary.
*/
public class ShortestPathEnViaRu353 {
private static final boolean DEBUG = true;
public static void main(String[] s) {
FileWriter dump;
DijkstraShortestPath<String,Integer> alg;
Graph g_all_relations;
Connect ruwikt_parsed_conn = new Connect();
ruwikt_parsed_conn.Open(Connect.RUWIKT_HOST,Connect.RUWIKT_PARSED_DB,Connect.RUWIKT_USER,Connect.RUWIKT_PASS);
g_all_relations = LoadRelations.loadGraph(ruwikt_parsed_conn, "relation_pairs.txt", "unique_words.txt");
assert(null != g_all_relations);
System.out.println("Calculation Dijkstra shortest path...");
alg = new DijkstraShortestPath(g_all_relations);
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG,
new Locale("en","US"));
String today = formatter.format(new Date());
String directory;
//directory = "data/synonyms_ru/"; //String filename = "ruwiki_synonyms.txt";
directory = System.getProperty("user.home") + "/.wikokit/ruwikt_20090122_353/";
dump = new FileWriter();
dump.SetDir(directory);
dump.SetFilename( "wordsim353.txt");
dump.Open(true, "UTF-8"); // Cp1251
dump.Print("\n\ntime start:" + today + " \n");
if(DEBUG) {
dump.Print("\n" +
"isct_wo - Number of intersection words, they are synonyms of word1 and word2" + "\n" +
"t sec - time sec" + "\n" +
"rel.min - relatedness = 1 / distance {minimum, average, maximum} (synynyms word set 1, set 2)" + "\n" +
"syn1.len - number of synonyms in first list" + "\n" +
"syn2.len - number of synonyms in first list" + "\n" +
"human - human_wordsim" + "\n");
dump.Print("\n" +
"word1\t" + "word2\t" + "human\t" +
// intersect.length + "\t" + dist_f + "\t" + dist_i + "\t" +
"rel.min\t" + "average\t" + "max\t" +
"syn1.list\t" +
"syn1.len\t" +
"syn2.list\t" +
"syn2.len\t" +
"t sec" +
"\n"
//"vert-s\t" +
//"edges\t" +
);
}
dump.Flush();
long t_start, t_end;
float t_work;
t_start = System.currentTimeMillis();
int i = 0;
System.out.println ("\nThe words are processing:\n");
WordSim353 wordsim353= new WordSim353();
Valuer.absent_counter = 0;
//for(WordSim w:wordsim353.data) {
// i++;
for(i=320; i<wordsim353.data.size(); i ++) { WordSim w = wordsim353.data.get(i);
String word1 = w.word1;
String word2 = w.word2;
word1 = "deliverable"; // computer plane smart Jerusalem alcohol noon
word2 = "publication"; // keyboard car student Israel chemistry string
//System.out.println ("The word Latin1ToUTF8 '"+Encodings.Latin1ToUTF8(all_words[i])+"' is processing...");
System.out.println (i + ": " + word1 + ", " + word2);
LanguageType source_lang = LanguageType.ru;
LanguageType target_lang = LanguageType.en;
DistanceData dist = Valuer.compareSynonyms (
g_all_relations, alg,
word1, word2, w.sim,
ruwikt_parsed_conn,
source_lang, target_lang,
dump);
// if( i > 9)
break;
}
t_end = System.currentTimeMillis();
t_work = (t_end - t_start)/1000f; // in sec
dump.Print("\n" + "Total time: " + t_work + "sec.\n");
dump.Print("\n" + "Number of absent data items: " + Valuer.absent_counter + ".\n");
dump.Flush();
ruwikt_parsed_conn.Close();
}
}
| wigraph/src/wigraph/experiment/ShortestPathEnViaRu353.java | /* ShortestPathRelation.java - Distance calculations.
*
* Copyright (c) 2009 Andrew Krizhanovsky <andrew.krizhanovsky at gmail.com>
* Distributed under GNU Public License.
*/
package wigraph.experiment;
import wigraph.PathSearcher;
import wigraph.DistanceData;
import wigraph.LoadRelations;
import wikipedia.sql.Connect;
import wikipedia.util.*;
import wikipedia.language.LanguageType;
import wikt.sql.TTranslation;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath;
import java.text.DateFormat;
import java.util.Locale;
import java.util.Date;
/** Calculation of distances between 353 pairs of English words,
* based on path length in thesaurus of Russian words,
* extracted from Russian Wiktionary.
*/
public class ShortestPathEnViaRu353 {
private static final boolean DEBUG = true;
public static void main(String[] s) {
FileWriter dump;
DijkstraShortestPath<String,Integer> alg;
Graph g_all_relations;
Connect ruwikt_parsed_conn = new Connect();
ruwikt_parsed_conn.Open(Connect.RUWIKT_HOST,Connect.RUWIKT_PARSED_DB,Connect.RUWIKT_USER,Connect.RUWIKT_PASS);
g_all_relations = LoadRelations.loadGraph(ruwikt_parsed_conn, "relation_pairs.txt", "unique_words.txt");
assert(null != g_all_relations);
System.out.println("Calculation Dijkstra shortest path...");
alg = new DijkstraShortestPath(g_all_relations);
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG,
new Locale("en","US"));
String today = formatter.format(new Date());
String directory;
//directory = "data/synonyms_ru/"; //String filename = "ruwiki_synonyms.txt";
directory = System.getProperty("user.home") + "/.wikokit/ruwikt_20090122_353/";
dump = new FileWriter();
dump.SetDir(directory);
dump.SetFilename( "wordsim353.txt");
dump.Open(true, "UTF-8"); // Cp1251
dump.Print("\n\ntime start:" + today + " \n");
if(DEBUG) {
dump.Print("\n" +
"isct_wo - Number of intersection words, they are synonyms of word1 and word2" + "\n" +
"t sec - time sec" + "\n" +
"rel.min - relatedness = 1 / distance {minimum, average, maximum} (synynyms word set 1, set 2)" + "\n" +
"syn1.len - number of synonyms in first list" + "\n" +
"syn2.len - number of synonyms in first list" + "\n" +
"human - human_wordsim" + "\n");
dump.Print("\n" +
"word1\t" + "word2\t" + "human\t" +
// intersect.length + "\t" + dist_f + "\t" + dist_i + "\t" +
"rel.min\t" + "average\t" + "max\t" +
"syn1.list\t" +
"syn1.len\t" +
"syn2.list\t" +
"syn2.len\t" +
"t sec" +
"\n"
//"vert-s\t" +
//"edges\t" +
);
}
dump.Flush();
long t_start, t_end;
float t_work;
t_start = System.currentTimeMillis();
int i = 0;
System.out.println ("\nThe words are processing:\n");
WordSim353 wordsim353= new WordSim353();
Valuer.absent_counter = 0;
//for(WordSim w:wordsim353.data) {
// i++;
for(i=320; i<wordsim353.data.size(); i ++) { WordSim w = wordsim353.data.get(i);
String word1 = w.word1;
String word2 = w.word2;
//word1 = "noon"; // computer plane smart Jerusalem alcohol noon
//word2 = "string"; // keyboard car student Israel chemistry string
//System.out.println ("The word Latin1ToUTF8 '"+Encodings.Latin1ToUTF8(all_words[i])+"' is processing...");
System.out.println (i + ": " + word1 + ", " + word2);
LanguageType source_lang = LanguageType.ru;
LanguageType target_lang = LanguageType.en;
DistanceData dist = Valuer.compareSynonyms (
g_all_relations, alg,
word1, word2, w.sim,
ruwikt_parsed_conn,
source_lang, target_lang,
dump);
// if( i > 9)
// break;
}
t_end = System.currentTimeMillis();
t_work = (t_end - t_start)/1000f; // in sec
dump.Print("\n" + "Total time: " + t_work + "sec.\n");
dump.Print("\n" + "Number of absent data items: " + Valuer.absent_counter + ".\n");
dump.Flush();
ruwikt_parsed_conn.Close();
}
}
| + small changes | wigraph/src/wigraph/experiment/ShortestPathEnViaRu353.java | + small changes | <ide><path>igraph/src/wigraph/experiment/ShortestPathEnViaRu353.java
<ide> for(i=320; i<wordsim353.data.size(); i ++) { WordSim w = wordsim353.data.get(i);
<ide> String word1 = w.word1;
<ide> String word2 = w.word2;
<del> //word1 = "noon"; // computer plane smart Jerusalem alcohol noon
<del> //word2 = "string"; // keyboard car student Israel chemistry string
<add> word1 = "deliverable"; // computer plane smart Jerusalem alcohol noon
<add> word2 = "publication"; // keyboard car student Israel chemistry string
<ide>
<ide> //System.out.println ("The word Latin1ToUTF8 '"+Encodings.Latin1ToUTF8(all_words[i])+"' is processing...");
<ide> System.out.println (i + ": " + word1 + ", " + word2);
<ide> source_lang, target_lang,
<ide> dump);
<ide> // if( i > 9)
<del>// break;
<add> break;
<ide> }
<ide>
<ide> t_end = System.currentTimeMillis(); |
|
Java | mit | a8fc16a72c9d32afffbe301ef7cbfccf66e01676 | 0 | CodeKingdomsTeam/SpongeVanilla,kenzierocks/SpongeVanilla,DDoS/SpongeVanilla,DDoS/SpongeVanilla,CodeKingdomsTeam/SpongeVanilla,kenzierocks/SpongeVanilla | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.vanilla.mixin.world;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.world.Location;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.common.Sponge;
import org.spongepowered.common.block.SpongeBlockSnapshot;
import org.spongepowered.vanilla.interfaces.IMixinWorld;
import java.util.ArrayList;
@Mixin(value = World.class, priority = 1001)
public abstract class MixinWorld implements IMixinWorld {
@Shadow abstract IBlockState getBlockState(BlockPos blockPos);
@Shadow private net.minecraft.world.border.WorldBorder worldBorder;
@Shadow private boolean isRemote;
@Shadow abstract void markBlockForUpdate(BlockPos pos);
@Shadow abstract void notifyNeighborsRespectDebug(BlockPos pos, Block block);
@Shadow abstract void updateComparatorOutputLevel(BlockPos pos, Block block);
private boolean captureSnapshots, restoreSnapshots;
private final ArrayList<SpongeBlockSnapshot> capturedSnapshots = new ArrayList<SpongeBlockSnapshot>();
private SpongeBlockSnapshot injectCacheSnapshot;
@Inject(method = "spawnEntityInWorld", at = @At("HEAD"), cancellable = true)
public void cancelSpawnEntityIfRestoringSnapshots(Entity entityIn, CallbackInfoReturnable<Boolean> cir) {
// do not drop any items while restoring blocksnapshots. Prevents dupes
if (!this.isRemote && (entityIn == null || (entityIn instanceof net.minecraft.entity.item.EntityItem && this.restoreSnapshots))) {
cir.setReturnValue(true);
}
}
@Inject(method = "spawnEntityInWorld", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true,
at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getChunkFromChunkCoords(II)Lnet/minecraft/world/chunk/Chunk;"))
public void onSpawnEntityInWorld(Entity entity, CallbackInfoReturnable<Boolean> cir, int i, int j, @Coerce boolean flag) {
org.spongepowered.api.entity.Entity spongeEntity = (org.spongepowered.api.entity.Entity) entity;
if (Sponge.getGame().getEventManager().post(SpongeEventFactory.createSpawnEntityEvent(Sponge.getGame(), Cause.of(this), spongeEntity))
&& !flag) {
cir.setReturnValue(false);
}
}
@Surrogate
public void onSpawnEntityInWorld(Entity entity, CallbackInfoReturnable<Boolean> cir, int i, int j) {
boolean flag = entity.forceSpawn || entity instanceof EntityPlayer;
this.onSpawnEntityInWorld(entity, cir, i, j, flag);
}
@Inject(method = "setBlockState", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/Chunk;setBlockState(Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/state/IBlockState;)Lnet/minecraft/block/state/IBlockState;"))
public void createAndStoreBlockSnapshot(BlockPos pos, IBlockState newState, int flags, CallbackInfoReturnable<Boolean> ci) {
this.injectCacheSnapshot = null;
if (this.captureSnapshots && !((World) (Object) this).isRemote) {
final Location<org.spongepowered.api.world.World> location = new Location<org.spongepowered.api.world.World>(
(org.spongepowered.api.world.World) this, pos.getX(), pos.getY(), pos.getZ());
this.injectCacheSnapshot = new SpongeBlockSnapshot(location.getBlock(), location.getExtent(), location.getBlockPosition());
this.capturedSnapshots.add(this.injectCacheSnapshot);
}
}
@Inject(method = "setBlockState", at = @At(value = "RETURN", ordinal = 2))
public void removeBlockSnapshotIfNullType(BlockPos pos, IBlockState newState, int flags, CallbackInfoReturnable<Boolean> cir) {
if (this.injectCacheSnapshot != null){
this.capturedSnapshots.remove(this.injectCacheSnapshot);
this.injectCacheSnapshot = null;
}
}
@Inject(method = "setBlockState", at = @At(value = "INVOKE", target = "Lnet/minecraft/profiler/Profiler;endSection()V", shift = At.Shift.BY, by
= 2), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true)
public void callMarkAndNotifyBlock(BlockPos pos, IBlockState newState, int flags, CallbackInfoReturnable<Boolean> cir, Chunk chunk, Block block,
IBlockState iblockstate1, Block block1) {
cir.setReturnValue(true);
if (this.injectCacheSnapshot == null) {
this.markAndNotifyBlock(pos, chunk, iblockstate1, newState, flags); // Modularize client and physics updates
}
}
@Surrogate
public void callMarkAndNotifyBlock(BlockPos pos, IBlockState newState, int flags, CallbackInfoReturnable<Boolean> cir, Chunk chunk, Block block,
IBlockState iblockstate1) {
this.callMarkAndNotifyBlock(pos, newState, flags, cir, chunk, block, iblockstate1, null);
}
@Override
public boolean isCapturingBlockSnapshots() {
return this.captureSnapshots;
}
@Override
public boolean isRestoringBlockSnapshots() {
return this.restoreSnapshots;
}
@Override
public void captureBlockSnapshots(boolean captureSnapshots) {
this.captureSnapshots = captureSnapshots;
}
@Override
public void restoreBlockSnapshots(boolean restoreSnapshots) {
this.restoreSnapshots = restoreSnapshots;
}
@Override
public ArrayList<SpongeBlockSnapshot> getCapturedSnapshots() {
return this.capturedSnapshots;
}
@Override
public void markAndNotifyBlock(BlockPos pos, Chunk chunk, IBlockState snapshotState, IBlockState newState, int flags) {
if ((flags & 2) != 0 && (!this.isRemote || (flags & 4) == 0) && (chunk == null || chunk.isPopulated()))
{
this.markBlockForUpdate(pos);
}
if (!this.isRemote && (flags & 1) != 0)
{
this.notifyNeighborsRespectDebug(pos, snapshotState.getBlock());
if (newState.getBlock().hasComparatorInputOverride())
{
this.updateComparatorOutputLevel(pos, newState.getBlock());
}
}
}
}
| src/main/java/org/spongepowered/vanilla/mixin/world/MixinWorld.java | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.vanilla.mixin.world;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.world.Location;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Coerce;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.common.Sponge;
import org.spongepowered.common.block.SpongeBlockSnapshot;
import org.spongepowered.vanilla.interfaces.IMixinWorld;
import java.util.ArrayList;
@Mixin(value = World.class, priority = 1001)
public abstract class MixinWorld implements IMixinWorld {
@Shadow abstract IBlockState getBlockState(BlockPos blockPos);
@Shadow private net.minecraft.world.border.WorldBorder worldBorder;
@Shadow private boolean isRemote;
@Shadow abstract void markBlockForUpdate(BlockPos pos);
@Shadow abstract void notifyNeighborsRespectDebug(BlockPos pos, Block block);
@Shadow abstract void updateComparatorOutputLevel(BlockPos pos, Block block);
private boolean captureSnapshots, restoreSnapshots;
private final ArrayList<SpongeBlockSnapshot> capturedSnapshots = new ArrayList<SpongeBlockSnapshot>();
private SpongeBlockSnapshot injectCacheSnapshot;
@Inject(method = "spawnEntityInWorld", at = @At("HEAD"), cancellable = true)
public void cancelSpawnEntityIfRestoringSnapshots(Entity entityIn, CallbackInfoReturnable<Boolean> cir) {
// do not drop any items while restoring blocksnapshots. Prevents dupes
if (!this.isRemote && (entityIn == null || (entityIn instanceof net.minecraft.entity.item.EntityItem && this.restoreSnapshots))) {
cir.setReturnValue(true);
}
}
@Inject(method = "spawnEntityInWorld", locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true,
at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getChunkFromChunkCoords(II)Lnet/minecraft/world/chunk/Chunk;"))
public void onSpawnEntityInWorld(Entity entity, CallbackInfoReturnable<Boolean> cir, int i, int j, @Coerce boolean flag) {
org.spongepowered.api.entity.Entity spongeEntity = (org.spongepowered.api.entity.Entity) entity;
if (Sponge.getGame().getEventManager().post(SpongeEventFactory.createSpawnEntityEvent(Sponge.getGame(), Cause.of(this), spongeEntity))
&& !flag) {
cir.setReturnValue(false);
}
}
@Surrogate
public void onSpawnEntityInWorld(Entity entity, CallbackInfoReturnable<Boolean> cir, int i, int j) {
boolean flag = entity.forceSpawn || entity instanceof EntityPlayer;
this.onSpawnEntityInWorld(entity, cir, i, j, flag);
}
@Inject(method = "setBlockState", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/chunk/Chunk;setBlockState(Lnet/minecraft/util/BlockPos;Lnet/minecraft/block/state/IBlockState;)Lnet/minecraft/block/state/IBlockState;"))
public void createAndStoreBlockSnapshot(BlockPos pos, IBlockState newState, int flags, CallbackInfoReturnable<Boolean> ci) {
this.injectCacheSnapshot = null;
if (this.captureSnapshots && !((World) (Object) this).isRemote) {
final Location<org.spongepowered.api.world.World> location = new Location<org.spongepowered.api.world.World>(
(org.spongepowered.api.world.World) this, pos.getX(), pos.getY(), pos.getZ());
this.injectCacheSnapshot = new SpongeBlockSnapshot(location.getBlock(), location.getExtent(), location.getBlockPosition());
this.capturedSnapshots.add(this.injectCacheSnapshot);
}
}
@Inject(method = "setBlockState", at = @At(value = "RETURN", ordinal = 2))
public void removeBlockSnapshotIfNullType(BlockPos pos, IBlockState newState, int flags, CallbackInfoReturnable<Boolean> cir) {
if (this.injectCacheSnapshot != null){
this.capturedSnapshots.remove(this.injectCacheSnapshot);
this.injectCacheSnapshot = null;
}
}
@Inject(method = "setBlockState", at = @At(value = "INVOKE", target = "Lnet/minecraft/profiler/Profiler;endSection()V", shift = At.Shift.BY, by
= 2), locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true)
public void callMarkAndNotifyBlock(BlockPos pos, IBlockState newState, int flags, CallbackInfoReturnable<Boolean> cir, Chunk chunk, Block block,
IBlockState iblockstate1, Block block1) {
cir.setReturnValue(true);
if (this.injectCacheSnapshot == null) {
this.markAndNotifyBlock(pos, chunk, iblockstate1, newState, flags); // Modularize client and physics updates
}
}
@Override
public boolean isCapturingBlockSnapshots() {
return this.captureSnapshots;
}
@Override
public boolean isRestoringBlockSnapshots() {
return this.restoreSnapshots;
}
@Override
public void captureBlockSnapshots(boolean captureSnapshots) {
this.captureSnapshots = captureSnapshots;
}
@Override
public void restoreBlockSnapshots(boolean restoreSnapshots) {
this.restoreSnapshots = restoreSnapshots;
}
@Override
public ArrayList<SpongeBlockSnapshot> getCapturedSnapshots() {
return this.capturedSnapshots;
}
@Override
public void markAndNotifyBlock(BlockPos pos, Chunk chunk, IBlockState snapshotState, IBlockState newState, int flags) {
if ((flags & 2) != 0 && (!this.isRemote || (flags & 4) == 0) && (chunk == null || chunk.isPopulated()))
{
this.markBlockForUpdate(pos);
}
if (!this.isRemote && (flags & 1) != 0)
{
this.notifyNeighborsRespectDebug(pos, snapshotState.getBlock());
if (newState.getBlock().hasComparatorInputOverride())
{
this.updateComparatorOutputLevel(pos, newState.getBlock());
}
}
}
}
| Surrogate setBlockState to fix LVT error in production.
Signed-off-by: Chris Sanders <[email protected]>
| src/main/java/org/spongepowered/vanilla/mixin/world/MixinWorld.java | Surrogate setBlockState to fix LVT error in production. | <ide><path>rc/main/java/org/spongepowered/vanilla/mixin/world/MixinWorld.java
<ide> }
<ide> }
<ide>
<add> @Surrogate
<add> public void callMarkAndNotifyBlock(BlockPos pos, IBlockState newState, int flags, CallbackInfoReturnable<Boolean> cir, Chunk chunk, Block block,
<add> IBlockState iblockstate1) {
<add> this.callMarkAndNotifyBlock(pos, newState, flags, cir, chunk, block, iblockstate1, null);
<add> }
<add>
<ide> @Override
<ide> public boolean isCapturingBlockSnapshots() {
<ide> return this.captureSnapshots; |
|
JavaScript | apache-2.0 | 4fb2a8e021d65f5a7b5dfc4b26ca007226ceb6d1 | 0 | radicalbit/ambari,arenadata/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,alexryndin/ambari,alexryndin/ambari,sekikn/ambari,sekikn/ambari,radicalbit/ambari,arenadata/ambari,radicalbit/ambari,alexryndin/ambari,alexryndin/ambari,radicalbit/ambari,sekikn/ambari,sekikn/ambari,alexryndin/ambari,alexryndin/ambari,arenadata/ambari,sekikn/ambari,radicalbit/ambari,alexryndin/ambari,arenadata/ambari,radicalbit/ambari,arenadata/ambari,arenadata/ambari,radicalbit/ambari,sekikn/ambari,alexryndin/ambari,radicalbit/ambari,alexryndin/ambari,arenadata/ambari,arenadata/ambari,arenadata/ambari,radicalbit/ambari,radicalbit/ambari,radicalbit/ambari,arenadata/ambari,alexryndin/ambari,alexryndin/ambari,arenadata/ambari | /**
* 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.
*/
'use strict';
angular.module('ambariAdminConsole')
.controller('ViewsEditCtrl', ['$scope', '$routeParams' , 'View', 'Alert', 'PermissionLoader', 'PermissionSaver', 'ConfirmationModal', '$location', 'UnsavedDialog', function($scope, $routeParams, View, Alert, PermissionLoader, PermissionSaver, ConfirmationModal, $location, UnsavedDialog) {
$scope.identity = angular.identity;
$scope.isConfigurationEmpty = true;
function reloadViewInfo(){
// Load instance data, after View permissions meta loaded
View.getInstance($routeParams.viewId, $routeParams.version, $routeParams.instanceId)
.then(function(instance) {
$scope.instance = instance;
$scope.settings = {
'visible': $scope.instance.ViewInstanceInfo.visible,
'label': $scope.instance.ViewInstanceInfo.label,
'description': $scope.instance.ViewInstanceInfo.description
};
initConfigurations();
$scope.isConfigurationEmpty = angular.equals({}, $scope.configuration);
})
.catch(function(data) {
Alert.error('Cannot load instance info', data.data.message);
});
}
function initConfigurations() {
$scope.configuration = angular.copy($scope.instance.ViewInstanceInfo.properties);
for (var confName in $scope.configuration) {
if ($scope.configuration.hasOwnProperty(confName)) {
$scope.configuration[confName] = $scope.configuration[confName] === 'null' ? '' : $scope.configuration[confName];
}
}
}
// Get META for properties
View.getMeta($routeParams.viewId, $routeParams.version).then(function(data) {
$scope.configurationMeta = data.data.ViewVersionInfo.parameters;
reloadViewInfo();
});
function reloadViewPrivileges(){
PermissionLoader.getViewPermissions({
viewName: $routeParams.viewId,
version: $routeParams.version,
instanceId: $routeParams.instanceId
})
.then(function(permissions) {
// Refresh data for rendering
$scope.permissionsEdit = permissions;
$scope.permissions = angular.copy(permissions);
$scope.isPermissionsEmpty = angular.equals({}, $scope.permissions);
})
.catch(function(data) {
Alert.error('Cannot load permissions', data.data.message);
});
}
$scope.permissions = [];
reloadViewPrivileges();
$scope.editSettingsDisabled = true;
$scope.toggleSettingsEdit = function() {
$scope.editSettingsDisabled = !$scope.editSettingsDisabled;
};
$scope.saveSettings = function(callback) {
if( $scope.settingsForm.$valid ){
return View.updateInstance($routeParams.viewId, $routeParams.version, $routeParams.instanceId, {
'ViewInstanceInfo':{
'visible': $scope.settings.visible,
'label': $scope.settings.label,
'description': $scope.settings.description
}
})
.success(function() {
if( callback ){
callback();
} else {
reloadViewInfo();
$scope.editSettingsDisabled = true;
$scope.settingsForm.$setPristine();
}
})
.catch(function(data) {
Alert.error('Cannot save settings', data.data.message);
});
}
};
$scope.cancelSettings = function() {
$scope.settings = {
'visible': $scope.instance.ViewInstanceInfo.visible,
'label': $scope.instance.ViewInstanceInfo.label,
'description': $scope.instance.ViewInstanceInfo.description
};
$scope.editSettingsDisabled = true;
$scope.settingsForm.$setPristine();
};
$scope.editConfigurationDisabled = true;
$scope.togglePropertiesEditing = function () {
$scope.editConfigurationDisabled = !$scope.editConfigurationDisabled;
if (!$scope.editConfigurationDisabled) {
$scope.configurationMeta.forEach(function (element) {
if (element.masked) {
$scope.configuration[element.name] = '';
}
});
}
};
$scope.saveConfiguration = function() {
if( $scope.propertiesForm.$valid ){
return View.updateInstance($routeParams.viewId, $routeParams.version, $routeParams.instanceId, {
'ViewInstanceInfo':{
'properties': $scope.configuration
}
})
.success(function() {
$scope.editConfigurationDisabled = true;
$scope.propertiesForm.$setPristine();
})
.catch(function(data) {
Alert.error('Cannot save properties', data.data.message);
});
}
};
$scope.cancelConfiguration = function() {
initConfigurations();
$scope.editConfigurationDisabled = true;
$scope.propertiesForm.$setPristine();
};
// Permissions edit
$scope.editPermissionDisabled = true;
$scope.cancelPermissions = function() {
$scope.permissionsEdit = angular.copy($scope.permissions); // Reset textedit areaes
$scope.editPermissionDisabled = true;
};
$scope.savePermissions = function() {
$scope.editPermissionDisabled = true;
return PermissionSaver.saveViewPermissions(
$scope.permissionsEdit,
{
view_name: $routeParams.viewId,
version: $routeParams.version,
instance_name: $routeParams.instanceId
}
)
.then(reloadViewPrivileges)
.catch(function(data) {
reloadViewPrivileges();
Alert.error('Cannot save permissions', data.data.message);
});
};
$scope.$watch(function() {
return $scope.permissionsEdit;
}, function(newValue) {
if(newValue){
$scope.savePermissions();
}
}, true);
$scope.deleteInstance = function(instance) {
ConfirmationModal.show('Delete View Instance', 'Are you sure you want to delete View Instance '+ instance.ViewInstanceInfo.label +'?').then(function() {
View.deleteInstance(instance.ViewInstanceInfo.view_name, instance.ViewInstanceInfo.version, instance.ViewInstanceInfo.instance_name)
.then(function() {
$location.path('/views');
})
.catch(function(data) {
Alert.error('Cannot delete instance', data.data.message);
});
});
};
$scope.$on('$locationChangeStart', function(event, targetUrl) {
if( $scope.settingsForm.$dirty || $scope.propertiesForm.$dirty){
UnsavedDialog().then(function(action) {
targetUrl = targetUrl.split('#').pop();
switch(action){
case 'save':
if($scope.settingsForm.$valid && $scope.propertiesForm.$valid ){
$scope.saveSettings(function() {
$scope.saveConfiguration().then(function() {
$scope.propertiesForm.$setPristine();
$scope.settingsForm.$setPristine();
$location.path(targetUrl);
});
});
}
break;
case 'discard':
$scope.propertiesForm.$setPristine();
$scope.settingsForm.$setPristine();
$location.path(targetUrl);
break;
case 'cancel':
targetUrl = '';
break;
}
});
event.preventDefault();
}
});
}]);
| ambari-admin/src/main/resources/ui/admin-web/app/scripts/controllers/ambariViews/ViewsEditCtrl.js | /**
* 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.
*/
'use strict';
angular.module('ambariAdminConsole')
.controller('ViewsEditCtrl', ['$scope', '$routeParams' , 'View', 'Alert', 'PermissionLoader', 'PermissionSaver', 'ConfirmationModal', '$location', 'UnsavedDialog', function($scope, $routeParams, View, Alert, PermissionLoader, PermissionSaver, ConfirmationModal, $location, UnsavedDialog) {
$scope.identity = angular.identity;
$scope.isConfigurationEmpty = true;
function reloadViewInfo(){
// Load instance data, after View permissions meta loaded
View.getInstance($routeParams.viewId, $routeParams.version, $routeParams.instanceId)
.then(function(instance) {
$scope.instance = instance;
$scope.settings = {
'visible': $scope.instance.ViewInstanceInfo.visible,
'label': $scope.instance.ViewInstanceInfo.label,
'description': $scope.instance.ViewInstanceInfo.description
};
$scope.configuration = angular.copy($scope.instance.ViewInstanceInfo.properties);
for(var confName in $scope.configuration){
if( $scope.configuration.hasOwnProperty(confName) ){
$scope.configuration[confName] = $scope.configuration[confName] === 'null' ? '' : $scope.configuration[confName];
}
}
$scope.isConfigurationEmpty = angular.equals({}, $scope.configuration);
})
.catch(function(data) {
Alert.error('Cannot load instance info', data.data.message);
});
}
// Get META for properties
View.getMeta($routeParams.viewId, $routeParams.version).then(function(data) {
$scope.configurationMeta = data.data.ViewVersionInfo.parameters;
reloadViewInfo();
});
function reloadViewPrivileges(){
PermissionLoader.getViewPermissions({
viewName: $routeParams.viewId,
version: $routeParams.version,
instanceId: $routeParams.instanceId
})
.then(function(permissions) {
// Refresh data for rendering
$scope.permissionsEdit = permissions;
$scope.permissions = angular.copy(permissions);
$scope.isPermissionsEmpty = angular.equals({}, $scope.permissions);
})
.catch(function(data) {
Alert.error('Cannot load permissions', data.data.message);
});
}
$scope.permissions = [];
reloadViewPrivileges();
$scope.editSettingsDisabled = true;
$scope.toggleSettingsEdit = function() {
$scope.editSettingsDisabled = !$scope.editSettingsDisabled;
};
$scope.saveSettings = function(callback) {
if( $scope.settingsForm.$valid ){
return View.updateInstance($routeParams.viewId, $routeParams.version, $routeParams.instanceId, {
'ViewInstanceInfo':{
'visible': $scope.settings.visible,
'label': $scope.settings.label,
'description': $scope.settings.description
}
})
.success(function() {
if( callback ){
callback();
} else {
reloadViewInfo();
$scope.editSettingsDisabled = true;
$scope.settingsForm.$setPristine();
}
})
.catch(function(data) {
Alert.error('Cannot save settings', data.data.message);
});
}
};
$scope.cancelSettings = function() {
$scope.settings = {
'visible': $scope.instance.ViewInstanceInfo.visible,
'label': $scope.instance.ViewInstanceInfo.label,
'description': $scope.instance.ViewInstanceInfo.description
};
$scope.editSettingsDisabled = true;
$scope.settingsForm.$setPristine();
};
$scope.editConfigurationDisabled = true;
$scope.togglePropertiesEditing = function() {
$scope.editConfigurationDisabled = !$scope.editConfigurationDisabled;
}
$scope.saveConfiguration = function() {
if( $scope.propertiesForm.$valid ){
return View.updateInstance($routeParams.viewId, $routeParams.version, $routeParams.instanceId, {
'ViewInstanceInfo':{
'properties': $scope.configuration
}
})
.success(function() {
$scope.editConfigurationDisabled = true;
$scope.propertiesForm.$setPristine();
})
.catch(function(data) {
Alert.error('Cannot save properties', data.data.message);
});
}
};
$scope.cancelConfiguration = function() {
$scope.configuration = angular.copy($scope.instance.ViewInstanceInfo.properties);
$scope.editConfigurationDisabled = true;
$scope.propertiesForm.$setPristine();
};
// Permissions edit
$scope.editPermissionDisabled = true;
$scope.cancelPermissions = function() {
$scope.permissionsEdit = angular.copy($scope.permissions); // Reset textedit areaes
$scope.editPermissionDisabled = true;
};
$scope.savePermissions = function() {
$scope.editPermissionDisabled = true;
return PermissionSaver.saveViewPermissions(
$scope.permissionsEdit,
{
view_name: $routeParams.viewId,
version: $routeParams.version,
instance_name: $routeParams.instanceId
}
)
.then(reloadViewPrivileges)
.catch(function(data) {
reloadViewPrivileges();
Alert.error('Cannot save permissions', data.data.message);
});
};
$scope.$watch(function() {
return $scope.permissionsEdit;
}, function(newValue) {
if(newValue){
$scope.savePermissions();
}
}, true);
$scope.deleteInstance = function(instance) {
ConfirmationModal.show('Delete View Instance', 'Are you sure you want to delete View Instance '+ instance.ViewInstanceInfo.label +'?').then(function() {
View.deleteInstance(instance.ViewInstanceInfo.view_name, instance.ViewInstanceInfo.version, instance.ViewInstanceInfo.instance_name)
.then(function() {
$location.path('/views');
})
.catch(function(data) {
Alert.error('Cannot delete instance', data.data.message);
});
});
};
$scope.$on('$locationChangeStart', function(event, targetUrl) {
if( $scope.settingsForm.$dirty || $scope.propertiesForm.$dirty){
UnsavedDialog().then(function(action) {
targetUrl = targetUrl.split('#').pop();
switch(action){
case 'save':
if($scope.settingsForm.$valid && $scope.propertiesForm.$valid ){
$scope.saveSettings(function() {
$scope.saveConfiguration().then(function() {
$scope.propertiesForm.$setPristine();
$scope.settingsForm.$setPristine();
$location.path(targetUrl);
});
});
}
break;
case 'discard':
$scope.propertiesForm.$setPristine();
$scope.settingsForm.$setPristine();
$location.path(targetUrl);
break;
case 'cancel':
targetUrl = '';
break;
}
});
event.preventDefault();
}
});
}]);
| AMBARI-7893 Slider View: Updating view params in UI breaks masked params. (atkach)
| ambari-admin/src/main/resources/ui/admin-web/app/scripts/controllers/ambariViews/ViewsEditCtrl.js | AMBARI-7893 Slider View: Updating view params in UI breaks masked params. (atkach) | <ide><path>mbari-admin/src/main/resources/ui/admin-web/app/scripts/controllers/ambariViews/ViewsEditCtrl.js
<ide> 'description': $scope.instance.ViewInstanceInfo.description
<ide> };
<ide>
<del> $scope.configuration = angular.copy($scope.instance.ViewInstanceInfo.properties);
<del> for(var confName in $scope.configuration){
<del> if( $scope.configuration.hasOwnProperty(confName) ){
<del> $scope.configuration[confName] = $scope.configuration[confName] === 'null' ? '' : $scope.configuration[confName];
<del> }
<del> }
<del> $scope.isConfigurationEmpty = angular.equals({}, $scope.configuration);
<add> initConfigurations();
<add> $scope.isConfigurationEmpty = angular.equals({}, $scope.configuration);
<ide> })
<ide> .catch(function(data) {
<ide> Alert.error('Cannot load instance info', data.data.message);
<ide> });
<ide> }
<ide>
<add> function initConfigurations() {
<add> $scope.configuration = angular.copy($scope.instance.ViewInstanceInfo.properties);
<add> for (var confName in $scope.configuration) {
<add> if ($scope.configuration.hasOwnProperty(confName)) {
<add> $scope.configuration[confName] = $scope.configuration[confName] === 'null' ? '' : $scope.configuration[confName];
<add> }
<add> }
<add> }
<ide>
<ide> // Get META for properties
<ide> View.getMeta($routeParams.viewId, $routeParams.version).then(function(data) {
<ide>
<ide>
<ide> $scope.editConfigurationDisabled = true;
<del> $scope.togglePropertiesEditing = function() {
<del> $scope.editConfigurationDisabled = !$scope.editConfigurationDisabled;
<del> }
<add> $scope.togglePropertiesEditing = function () {
<add> $scope.editConfigurationDisabled = !$scope.editConfigurationDisabled;
<add> if (!$scope.editConfigurationDisabled) {
<add> $scope.configurationMeta.forEach(function (element) {
<add> if (element.masked) {
<add> $scope.configuration[element.name] = '';
<add> }
<add> });
<add> }
<add> };
<ide> $scope.saveConfiguration = function() {
<ide> if( $scope.propertiesForm.$valid ){
<ide> return View.updateInstance($routeParams.viewId, $routeParams.version, $routeParams.instanceId, {
<ide> }
<ide> };
<ide> $scope.cancelConfiguration = function() {
<del> $scope.configuration = angular.copy($scope.instance.ViewInstanceInfo.properties);
<add> initConfigurations();
<ide> $scope.editConfigurationDisabled = true;
<ide> $scope.propertiesForm.$setPristine();
<ide> }; |
|
Java | bsd-2-clause | a98d833d56d8a4ef3bf88ed35ba5931b4d8f083c | 0 | laffer1/justjournal,laffer1/justjournal,laffer1/justjournal,laffer1/justjournal | package com.justjournal;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public final class CrawlFilter implements Filter {
private FilterConfig filterConfig = null;
/**
* Initializes the filter configuration
*/
@Override
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
/**
* Filters all requests and invokes headless browser if necessary
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException {
if (filterConfig == null) {
return;
}
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String queryString = req.getQueryString();
if ((queryString != null) && (queryString.contains("_escaped_fragment_"))) {
StringBuilder pageNameSb = new StringBuilder("http://");
pageNameSb.append(req.getServerName());
if (req.getServerPort() != 0) {
pageNameSb.append(":");
pageNameSb.append(req.getServerPort());
}
pageNameSb.append(req.getRequestURI());
queryString = rewriteQueryString(queryString);
pageNameSb.append(queryString);
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getOptions().setJavaScriptEnabled(true);
String pageName = pageNameSb.toString();
HtmlPage page = webClient.getPage(pageName);
webClient.waitForBackgroundJavaScriptStartingBefore(2000);
webClient.waitForBackgroundJavaScript(8000);
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
out.println("<hr>");
out.println("<center><h3>You are viewing a non-interactive page that is intended for the crawler. You probably want to see this page: <a href=\""
+ pageName + "\">" + pageName + "</a></h3></center>");
out.println("<hr>");
out.println(page.asXml());
webClient.closeAllWindows();
out.close();
} else {
try {
chain.doFilter(request, response);
} catch (ServletException e) {
e.printStackTrace();
}
}
}
public void doFilterOld(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (filterConfig == null) {
return;
}
ServletOutputStream out = response.getOutputStream();
String escapedFragment = request.getParameter("_escaped_fragment_");
if (escapedFragment != null) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
/*
* Rewrite the URL back to the original #! version.
*/
String urlWithHashFragment = httpRequest.getScheme() + "://"
+ httpRequest.getServerName() + ":"
+ httpRequest.getServerPort()
+ httpRequest.getContextPath()
+ httpRequest.getServletPath();
String pathInfo = httpRequest.getPathInfo();
if (pathInfo != null) {
urlWithHashFragment += pathInfo;
}
String queryString = httpRequest.getQueryString();
Pattern pattern = Pattern
.compile("(.*&)?_escaped_fragment_=[^&]*(&(.*))?");
Matcher matcher = pattern.matcher(queryString);
if (matcher.matches()) {
urlWithHashFragment += "?" + matcher.group(1)
+ matcher.group(3);
}
/*
* TODO Unescape %XX characters.
*/
urlWithHashFragment += "#!" + escapedFragment;
/*
* Use the headless browser (HtmlUnit) to obtain an HTML snapshot.
*/
final WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(urlWithHashFragment);
/*
* Give the headless browser enough time to execute JavaScript. The
* exact time to wait may depend on your application.
*/
webClient.waitForBackgroundJavaScript(2000);
/*
* Return the snapshot.
*/
out.println(page.asXml());
} else {
try {
/*
* Not an _escaped_fragment_ URL, so move up the chain of
* servlet filters.
*/
chain.doFilter(request, response);
} catch (ServletException e) {
System.err.println("Servlet exception caught: " + e);
e.printStackTrace();
}
}
}
/**
* Destroys the filter configuration
*/
@Override
public void destroy() {
this.filterConfig = null;
}
private static String rewriteQueryString(String queryString) throws UnsupportedEncodingException {
StringBuilder queryStringSb = new StringBuilder(queryString);
int i = queryStringSb.indexOf("&_escaped_fragment_");
if (i != -1) {
StringBuilder tmpSb = new StringBuilder(queryStringSb.substring(0, i));
tmpSb.append("#!");
tmpSb.append(URLDecoder.decode(queryStringSb.substring(i + 20, queryStringSb.length()), "UTF-8"));
queryStringSb = tmpSb;
}
i = queryStringSb.indexOf("_escaped_fragment_");
if (i != -1) {
StringBuilder tmpSb = new StringBuilder(queryStringSb.substring(0, i));
tmpSb.append("#!");
tmpSb.append(URLDecoder.decode(queryStringSb.substring(i + 19, queryStringSb.length()), "UTF-8"));
queryStringSb = tmpSb;
}
if (queryStringSb.indexOf("#!") != 0) {
queryStringSb.insert(0, '?');
}
queryString = queryStringSb.toString();
return queryString;
}
} | src/main/java/com/justjournal/CrawlFilter.java | package com.justjournal;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public final class CrawlFilter implements Filter {
private FilterConfig filterConfig = null;
/**
* Initializes the filter configuration
*/
@Override
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
/**
* Filters all requests and invokes headless browser if necessary
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException {
if (filterConfig == null) {
return;
}
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String queryString = req.getQueryString();
if ((queryString != null) && (queryString.contains("_escaped_fragment_"))) {
StringBuilder pageNameSb = new StringBuilder("http://");
pageNameSb.append(req.getServerName());
if (req.getServerPort() != 0) {
pageNameSb.append(":");
pageNameSb.append(req.getServerPort());
}
pageNameSb.append(req.getRequestURI());
queryString = rewriteQueryString(queryString);
pageNameSb.append(queryString);
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getOptions().setJavaScriptEnabled(true);
String pageName = pageNameSb.toString();
HtmlPage page = webClient.getPage(pageName);
webClient.waitForBackgroundJavaScriptStartingBefore(2000);
webClient.waitForBackgroundJavaScript(10000);
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
out.println("<hr>");
out.println("<center><h3>You are viewing a non-interactive page that is intended for the crawler. You probably want to see this page: <a href=\""
+ pageName + "\">" + pageName + "</a></h3></center>");
out.println("<hr>");
out.println(page.asXml());
webClient.closeAllWindows();
out.close();
} else {
try {
chain.doFilter(request, response);
} catch (ServletException e) {
e.printStackTrace();
}
}
}
public void doFilterOld(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (filterConfig == null) {
return;
}
ServletOutputStream out = response.getOutputStream();
String escapedFragment = request.getParameter("_escaped_fragment_");
if (escapedFragment != null) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
/*
* Rewrite the URL back to the original #! version.
*/
String urlWithHashFragment = httpRequest.getScheme() + "://"
+ httpRequest.getServerName() + ":"
+ httpRequest.getServerPort()
+ httpRequest.getContextPath()
+ httpRequest.getServletPath();
String pathInfo = httpRequest.getPathInfo();
if (pathInfo != null) {
urlWithHashFragment += pathInfo;
}
String queryString = httpRequest.getQueryString();
Pattern pattern = Pattern
.compile("(.*&)?_escaped_fragment_=[^&]*(&(.*))?");
Matcher matcher = pattern.matcher(queryString);
if (matcher.matches()) {
urlWithHashFragment += "?" + matcher.group(1)
+ matcher.group(3);
}
/*
* TODO Unescape %XX characters.
*/
urlWithHashFragment += "#!" + escapedFragment;
/*
* Use the headless browser (HtmlUnit) to obtain an HTML snapshot.
*/
final WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(urlWithHashFragment);
/*
* Give the headless browser enough time to execute JavaScript. The
* exact time to wait may depend on your application.
*/
webClient.waitForBackgroundJavaScript(2000);
/*
* Return the snapshot.
*/
out.println(page.asXml());
} else {
try {
/*
* Not an _escaped_fragment_ URL, so move up the chain of
* servlet filters.
*/
chain.doFilter(request, response);
} catch (ServletException e) {
System.err.println("Servlet exception caught: " + e);
e.printStackTrace();
}
}
}
/**
* Destroys the filter configuration
*/
@Override
public void destroy() {
this.filterConfig = null;
}
private static String rewriteQueryString(String queryString) throws UnsupportedEncodingException {
StringBuilder queryStringSb = new StringBuilder(queryString);
int i = queryStringSb.indexOf("&_escaped_fragment_");
if (i != -1) {
StringBuilder tmpSb = new StringBuilder(queryStringSb.substring(0, i));
tmpSb.append("#!");
tmpSb.append(URLDecoder.decode(queryStringSb.substring(i + 20, queryStringSb.length()), "UTF-8"));
queryStringSb = tmpSb;
}
i = queryStringSb.indexOf("_escaped_fragment_");
if (i != -1) {
StringBuilder tmpSb = new StringBuilder(queryStringSb.substring(0, i));
tmpSb.append("#!");
tmpSb.append(URLDecoder.decode(queryStringSb.substring(i + 19, queryStringSb.length()), "UTF-8"));
queryStringSb = tmpSb;
}
if (queryStringSb.indexOf("#!") != 0) {
queryStringSb.insert(0, '?');
}
queryString = queryStringSb.toString();
return queryString;
}
} | lower the timeout so the process is a little faster for crawlers.
| src/main/java/com/justjournal/CrawlFilter.java | lower the timeout so the process is a little faster for crawlers. | <ide><path>rc/main/java/com/justjournal/CrawlFilter.java
<ide> String pageName = pageNameSb.toString();
<ide> HtmlPage page = webClient.getPage(pageName);
<ide> webClient.waitForBackgroundJavaScriptStartingBefore(2000);
<del> webClient.waitForBackgroundJavaScript(10000);
<add> webClient.waitForBackgroundJavaScript(8000);
<ide>
<ide> res.setContentType("text/html;charset=UTF-8");
<ide> PrintWriter out = res.getWriter(); |
|
Java | apache-2.0 | 11274e0b741b6b014f1fa87f40553c1aa228a9a8 | 0 | chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.store.jdbc;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.BrokerServiceAware;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.openwire.OpenWireFormat;
import org.apache.activemq.store.MessageStore;
import org.apache.activemq.store.PersistenceAdapter;
import org.apache.activemq.store.TopicMessageStore;
import org.apache.activemq.store.TransactionStore;
import org.apache.activemq.store.jdbc.adapter.DefaultJDBCAdapter;
import org.apache.activemq.store.memory.MemoryTransactionStore;
import org.apache.activemq.usage.SystemUsage;
import org.apache.activemq.util.FactoryFinder;
import org.apache.activemq.util.IOExceptionSupport;
import org.apache.activemq.wireformat.WireFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A {@link PersistenceAdapter} implementation using JDBC for persistence
* storage.
*
* This persistence adapter will correctly remember prepared XA transactions,
* but it will not keep track of local transaction commits so that operations
* performed against the Message store are done as a single uow.
*
* @org.apache.xbean.XBean element="jdbcPersistenceAdapter"
*
* @version $Revision: 1.9 $
*/
public class JDBCPersistenceAdapter extends DataSourceSupport implements PersistenceAdapter,
BrokerServiceAware {
private static final Log LOG = LogFactory.getLog(JDBCPersistenceAdapter.class);
private static FactoryFinder adapterFactoryFinder = new FactoryFinder(
"META-INF/services/org/apache/activemq/store/jdbc/");
private static FactoryFinder lockFactoryFinder = new FactoryFinder(
"META-INF/services/org/apache/activemq/store/jdbc/lock/");
private WireFormat wireFormat = new OpenWireFormat();
private BrokerService brokerService;
private Statements statements;
private JDBCAdapter adapter;
private MemoryTransactionStore transactionStore;
private ScheduledThreadPoolExecutor clockDaemon;
private ScheduledFuture<?> cleanupTicket, keepAliveTicket;
private int cleanupPeriod = 1000 * 60 * 5;
private boolean useExternalMessageReferences;
private boolean useDatabaseLock = true;
private long lockKeepAlivePeriod = 1000*30;
private long lockAcquireSleepInterval = DefaultDatabaseLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL;
private DatabaseLocker databaseLocker;
private boolean createTablesOnStartup = true;
private DataSource lockDataSource;
private int transactionIsolation;
public JDBCPersistenceAdapter() {
}
public JDBCPersistenceAdapter(DataSource ds, WireFormat wireFormat) {
super(ds);
this.wireFormat = wireFormat;
}
public Set<ActiveMQDestination> getDestinations() {
// Get a connection and insert the message into the DB.
TransactionContext c = null;
try {
c = getTransactionContext();
return getAdapter().doGetDestinations(c);
} catch (IOException e) {
return emptyDestinationSet();
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
return emptyDestinationSet();
} finally {
if (c != null) {
try {
c.close();
} catch (Throwable e) {
}
}
}
}
@SuppressWarnings("unchecked")
private Set<ActiveMQDestination> emptyDestinationSet() {
return Collections.EMPTY_SET;
}
public MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException {
MessageStore rc = new JDBCMessageStore(this, getAdapter(), wireFormat, destination);
if (transactionStore != null) {
rc = transactionStore.proxy(rc);
}
return rc;
}
public TopicMessageStore createTopicMessageStore(ActiveMQTopic destination) throws IOException {
TopicMessageStore rc = new JDBCTopicMessageStore(this, getAdapter(), wireFormat, destination);
if (transactionStore != null) {
rc = transactionStore.proxy(rc);
}
return rc;
}
/**
* Cleanup method to remove any state associated with the given destination
* No state retained.... nothing to do
*
* @param destination Destination to forget
*/
public void removeQueueMessageStore(ActiveMQQueue destination) {
}
/**
* Cleanup method to remove any state associated with the given destination
* No state retained.... nothing to do
*
* @param destination Destination to forget
*/
public void removeTopicMessageStore(ActiveMQTopic destination) {
}
public TransactionStore createTransactionStore() throws IOException {
if (transactionStore == null) {
transactionStore = new MemoryTransactionStore(this);
}
return this.transactionStore;
}
public long getLastMessageBrokerSequenceId() throws IOException {
// Get a connection and insert the message into the DB.
TransactionContext c = getTransactionContext();
try {
return getAdapter().doGetLastMessageBrokerSequenceId(c);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to get last broker message id: " + e, e);
} finally {
c.close();
}
}
public void start() throws Exception {
getAdapter().setUseExternalMessageReferences(isUseExternalMessageReferences());
if (isCreateTablesOnStartup()) {
TransactionContext transactionContext = getTransactionContext();
transactionContext.begin();
try {
try {
getAdapter().doCreateTables(transactionContext);
} catch (SQLException e) {
LOG.warn("Cannot create tables due to: " + e);
JDBCPersistenceAdapter.log("Failure Details: ", e);
}
} finally {
transactionContext.commit();
}
}
if (isUseDatabaseLock()) {
DatabaseLocker service = getDatabaseLocker();
if (service == null) {
LOG.warn("No databaseLocker configured for the JDBC Persistence Adapter");
} else {
service.start();
if (lockKeepAlivePeriod > 0) {
keepAliveTicket = getScheduledThreadPoolExecutor().scheduleAtFixedRate(new Runnable() {
public void run() {
databaseLockKeepAlive();
}
}, lockKeepAlivePeriod, lockKeepAlivePeriod, TimeUnit.MILLISECONDS);
}
if (brokerService != null) {
brokerService.getBroker().nowMasterBroker();
}
}
}
cleanup();
// Cleanup the db periodically.
if (cleanupPeriod > 0) {
cleanupTicket = getScheduledThreadPoolExecutor().scheduleWithFixedDelay(new Runnable() {
public void run() {
cleanup();
}
}, cleanupPeriod, cleanupPeriod, TimeUnit.MILLISECONDS);
}
}
public synchronized void stop() throws Exception {
if (cleanupTicket != null) {
cleanupTicket.cancel(true);
cleanupTicket = null;
}
if (keepAliveTicket != null) {
keepAliveTicket.cancel(false);
keepAliveTicket = null;
}
// do not shutdown clockDaemon as it may kill the thread initiating shutdown
DatabaseLocker service = getDatabaseLocker();
if (service != null) {
service.stop();
}
}
public void cleanup() {
TransactionContext c = null;
try {
LOG.debug("Cleaning up old messages.");
c = getTransactionContext();
getAdapter().doDeleteOldMessages(c);
} catch (IOException e) {
LOG.warn("Old message cleanup failed due to: " + e, e);
} catch (SQLException e) {
LOG.warn("Old message cleanup failed due to: " + e);
JDBCPersistenceAdapter.log("Failure Details: ", e);
} finally {
if (c != null) {
try {
c.close();
} catch (Throwable e) {
}
}
LOG.debug("Cleanup done.");
}
}
public void setScheduledThreadPoolExecutor(ScheduledThreadPoolExecutor clockDaemon) {
this.clockDaemon = clockDaemon;
}
public ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor() {
if (clockDaemon == null) {
clockDaemon = new ScheduledThreadPoolExecutor(5, new ThreadFactory() {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "ActiveMQ Cleanup Timer");
thread.setDaemon(true);
return thread;
}
});
}
return clockDaemon;
}
public JDBCAdapter getAdapter() throws IOException {
if (adapter == null) {
setAdapter(createAdapter());
}
return adapter;
}
public DatabaseLocker getDatabaseLocker() throws IOException {
if (databaseLocker == null && isUseDatabaseLock()) {
setDatabaseLocker(loadDataBaseLocker());
}
return databaseLocker;
}
/**
* Sets the database locker strategy to use to lock the database on startup
* @throws IOException
*/
public void setDatabaseLocker(DatabaseLocker locker) throws IOException {
databaseLocker = locker;
databaseLocker.setPersistenceAdapter(this);
databaseLocker.setLockAcquireSleepInterval(getLockAcquireSleepInterval());
}
public DataSource getLockDataSource() throws IOException {
if (lockDataSource == null) {
lockDataSource = getDataSource();
if (lockDataSource == null) {
throw new IllegalArgumentException(
"No dataSource property has been configured");
}
} else {
LOG.info("Using a separate dataSource for locking: "
+ lockDataSource);
}
return lockDataSource;
}
public void setLockDataSource(DataSource dataSource) {
this.lockDataSource = dataSource;
}
public BrokerService getBrokerService() {
return brokerService;
}
public void setBrokerService(BrokerService brokerService) {
this.brokerService = brokerService;
}
/**
* @throws IOException
*/
protected JDBCAdapter createAdapter() throws IOException {
adapter = (JDBCAdapter) loadAdapter(adapterFactoryFinder, "adapter");
// Use the default JDBC adapter if the
// Database type is not recognized.
if (adapter == null) {
adapter = new DefaultJDBCAdapter();
LOG.debug("Using default JDBC Adapter: " + adapter);
}
return adapter;
}
private Object loadAdapter(FactoryFinder finder, String kind) throws IOException {
Object adapter = null;
TransactionContext c = getTransactionContext();
try {
try {
// Make the filename file system safe.
String dirverName = c.getConnection().getMetaData().getDriverName();
dirverName = dirverName.replaceAll("[^a-zA-Z0-9\\-]", "_").toLowerCase();
try {
adapter = finder.newInstance(dirverName);
LOG.info("Database " + kind + " driver override recognized for : [" + dirverName + "] - adapter: " + adapter.getClass());
} catch (Throwable e) {
LOG.info("Database " + kind + " driver override not found for : [" + dirverName
+ "]. Will use default implementation.");
}
} catch (SQLException e) {
LOG.warn("JDBC error occurred while trying to detect database type for overrides. Will use default implementations: "
+ e.getMessage());
JDBCPersistenceAdapter.log("Failure Details: ", e);
}
} finally {
c.close();
}
return adapter;
}
public void setAdapter(JDBCAdapter adapter) {
this.adapter = adapter;
this.adapter.setStatements(getStatements());
}
public WireFormat getWireFormat() {
return wireFormat;
}
public void setWireFormat(WireFormat wireFormat) {
this.wireFormat = wireFormat;
}
public TransactionContext getTransactionContext(ConnectionContext context) throws IOException {
if (context == null) {
return getTransactionContext();
} else {
TransactionContext answer = (TransactionContext)context.getLongTermStoreContext();
if (answer == null) {
answer = getTransactionContext();
context.setLongTermStoreContext(answer);
}
return answer;
}
}
public TransactionContext getTransactionContext() throws IOException {
TransactionContext answer = new TransactionContext(getDataSource());
if (transactionIsolation > 0) {
answer.setTransactionIsolation(transactionIsolation);
}
return answer;
}
public void beginTransaction(ConnectionContext context) throws IOException {
TransactionContext transactionContext = getTransactionContext(context);
transactionContext.begin();
}
public void commitTransaction(ConnectionContext context) throws IOException {
TransactionContext transactionContext = getTransactionContext(context);
transactionContext.commit();
}
public void rollbackTransaction(ConnectionContext context) throws IOException {
TransactionContext transactionContext = getTransactionContext(context);
transactionContext.rollback();
}
public int getCleanupPeriod() {
return cleanupPeriod;
}
/**
* Sets the number of milliseconds until the database is attempted to be
* cleaned up for durable topics
*/
public void setCleanupPeriod(int cleanupPeriod) {
this.cleanupPeriod = cleanupPeriod;
}
public void deleteAllMessages() throws IOException {
TransactionContext c = getTransactionContext();
try {
getAdapter().doDropTables(c);
getAdapter().setUseExternalMessageReferences(isUseExternalMessageReferences());
getAdapter().doCreateTables(c);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create(e);
} finally {
c.close();
}
}
public boolean isUseExternalMessageReferences() {
return useExternalMessageReferences;
}
public void setUseExternalMessageReferences(boolean useExternalMessageReferences) {
this.useExternalMessageReferences = useExternalMessageReferences;
}
public boolean isCreateTablesOnStartup() {
return createTablesOnStartup;
}
/**
* Sets whether or not tables are created on startup
*/
public void setCreateTablesOnStartup(boolean createTablesOnStartup) {
this.createTablesOnStartup = createTablesOnStartup;
}
public boolean isUseDatabaseLock() {
return useDatabaseLock;
}
/**
* Sets whether or not an exclusive database lock should be used to enable
* JDBC Master/Slave. Enabled by default.
*/
public void setUseDatabaseLock(boolean useDatabaseLock) {
this.useDatabaseLock = useDatabaseLock;
}
public static void log(String msg, SQLException e) {
String s = msg + e.getMessage();
while (e.getNextException() != null) {
e = e.getNextException();
s += ", due to: " + e.getMessage();
}
LOG.debug(s, e);
}
public Statements getStatements() {
if (statements == null) {
statements = new Statements();
}
return statements;
}
public void setStatements(Statements statements) {
this.statements = statements;
}
/**
* @param usageManager The UsageManager that is controlling the
* destination's memory usage.
*/
public void setUsageManager(SystemUsage usageManager) {
}
protected void databaseLockKeepAlive() {
boolean stop = false;
try {
DatabaseLocker locker = getDatabaseLocker();
if (locker != null) {
if (!locker.keepAlive()) {
stop = true;
}
}
} catch (IOException e) {
LOG.error("Failed to get database when trying keepalive: " + e, e);
}
if (stop) {
stopBroker();
}
}
protected void stopBroker() {
// we can no longer keep the lock so lets fail
LOG.info("No longer able to keep the exclusive lock so giving up being a master");
try {
brokerService.stop();
} catch (Exception e) {
LOG.warn("Failure occured while stopping broker");
}
}
protected DatabaseLocker loadDataBaseLocker() throws IOException {
DatabaseLocker locker = (DefaultDatabaseLocker) loadAdapter(lockFactoryFinder, "lock");
if (locker == null) {
locker = new DefaultDatabaseLocker();
LOG.debug("Using default JDBC Locker: " + locker);
}
return locker;
}
public void setBrokerName(String brokerName) {
}
public String toString() {
return "JDBCPersistenceAdapter(" + super.toString() + ")";
}
public void setDirectory(File dir) {
}
public void checkpoint(boolean sync) throws IOException {
}
public long size(){
return 0;
}
public long getLockKeepAlivePeriod() {
return lockKeepAlivePeriod;
}
public void setLockKeepAlivePeriod(long lockKeepAlivePeriod) {
this.lockKeepAlivePeriod = lockKeepAlivePeriod;
}
public long getLockAcquireSleepInterval() {
return lockAcquireSleepInterval;
}
/**
* millisecond interval between lock acquire attempts, applied to newly created DefaultDatabaseLocker
* not applied if DataBaseLocker is injected.
*/
public void setLockAcquireSleepInterval(long lockAcquireSleepInterval) {
this.lockAcquireSleepInterval = lockAcquireSleepInterval;
}
/**
* set the Transaction isolation level to something other that TRANSACTION_READ_UNCOMMITTED
* This allowable dirty isolation level may not be achievable in clustered DB environments
* so a more restrictive and expensive option may be needed like TRANSACTION_REPEATABE_READ
* see isolation level constants in {@link java.sql.Connection}
* @param transactionIsolation the isolation level to use
*/
public void setTransactionIsolation(int transactionIsolation) {
this.transactionIsolation = transactionIsolation;
}
}
| activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.store.jdbc;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.BrokerServiceAware;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.openwire.OpenWireFormat;
import org.apache.activemq.store.MessageStore;
import org.apache.activemq.store.PersistenceAdapter;
import org.apache.activemq.store.TopicMessageStore;
import org.apache.activemq.store.TransactionStore;
import org.apache.activemq.store.jdbc.adapter.DefaultJDBCAdapter;
import org.apache.activemq.store.memory.MemoryTransactionStore;
import org.apache.activemq.usage.SystemUsage;
import org.apache.activemq.util.FactoryFinder;
import org.apache.activemq.util.IOExceptionSupport;
import org.apache.activemq.wireformat.WireFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A {@link PersistenceAdapter} implementation using JDBC for persistence
* storage.
*
* This persistence adapter will correctly remember prepared XA transactions,
* but it will not keep track of local transaction commits so that operations
* performed against the Message store are done as a single uow.
*
* @org.apache.xbean.XBean element="jdbcPersistenceAdapter"
*
* @version $Revision: 1.9 $
*/
public class JDBCPersistenceAdapter extends DataSourceSupport implements PersistenceAdapter,
BrokerServiceAware {
private static final Log LOG = LogFactory.getLog(JDBCPersistenceAdapter.class);
private static FactoryFinder adapterFactoryFinder = new FactoryFinder(
"META-INF/services/org/apache/activemq/store/jdbc/");
private static FactoryFinder lockFactoryFinder = new FactoryFinder(
"META-INF/services/org/apache/activemq/store/jdbc/lock/");
private WireFormat wireFormat = new OpenWireFormat();
private BrokerService brokerService;
private Statements statements;
private JDBCAdapter adapter;
private MemoryTransactionStore transactionStore;
private ScheduledThreadPoolExecutor clockDaemon;
private ScheduledFuture<?> cleanupTicket, keepAliveTicket;
private int cleanupPeriod = 1000 * 60 * 5;
private boolean useExternalMessageReferences;
private boolean useDatabaseLock = true;
private long lockKeepAlivePeriod = 1000*30;
private long lockAcquireSleepInterval = DefaultDatabaseLocker.DEFAULT_LOCK_ACQUIRE_SLEEP_INTERVAL;
private DatabaseLocker databaseLocker;
private boolean createTablesOnStartup = true;
private DataSource lockDataSource;
private int transactionIsolation;
public JDBCPersistenceAdapter() {
}
public JDBCPersistenceAdapter(DataSource ds, WireFormat wireFormat) {
super(ds);
this.wireFormat = wireFormat;
}
public Set<ActiveMQDestination> getDestinations() {
// Get a connection and insert the message into the DB.
TransactionContext c = null;
try {
c = getTransactionContext();
return getAdapter().doGetDestinations(c);
} catch (IOException e) {
return emptyDestinationSet();
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
return emptyDestinationSet();
} finally {
if (c != null) {
try {
c.close();
} catch (Throwable e) {
}
}
}
}
@SuppressWarnings("unchecked")
private Set<ActiveMQDestination> emptyDestinationSet() {
return Collections.EMPTY_SET;
}
public MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException {
MessageStore rc = new JDBCMessageStore(this, getAdapter(), wireFormat, destination);
if (transactionStore != null) {
rc = transactionStore.proxy(rc);
}
return rc;
}
public TopicMessageStore createTopicMessageStore(ActiveMQTopic destination) throws IOException {
TopicMessageStore rc = new JDBCTopicMessageStore(this, getAdapter(), wireFormat, destination);
if (transactionStore != null) {
rc = transactionStore.proxy(rc);
}
return rc;
}
/**
* Cleanup method to remove any state associated with the given destination
* No state retained.... nothing to do
*
* @param destination Destination to forget
*/
public void removeQueueMessageStore(ActiveMQQueue destination) {
}
/**
* Cleanup method to remove any state associated with the given destination
* No state retained.... nothing to do
*
* @param destination Destination to forget
*/
public void removeTopicMessageStore(ActiveMQTopic destination) {
}
public TransactionStore createTransactionStore() throws IOException {
if (transactionStore == null) {
transactionStore = new MemoryTransactionStore(this);
}
return this.transactionStore;
}
public long getLastMessageBrokerSequenceId() throws IOException {
// Get a connection and insert the message into the DB.
TransactionContext c = getTransactionContext();
try {
return getAdapter().doGetLastMessageBrokerSequenceId(c);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create("Failed to get last broker message id: " + e, e);
} finally {
c.close();
}
}
public void start() throws Exception {
getAdapter().setUseExternalMessageReferences(isUseExternalMessageReferences());
if (isCreateTablesOnStartup()) {
TransactionContext transactionContext = getTransactionContext();
transactionContext.begin();
try {
try {
getAdapter().doCreateTables(transactionContext);
} catch (SQLException e) {
LOG.warn("Cannot create tables due to: " + e);
JDBCPersistenceAdapter.log("Failure Details: ", e);
}
} finally {
transactionContext.commit();
}
}
if (isUseDatabaseLock()) {
DatabaseLocker service = getDatabaseLocker();
if (service == null) {
LOG.warn("No databaseLocker configured for the JDBC Persistence Adapter");
} else {
service.start();
if (lockKeepAlivePeriod > 0) {
keepAliveTicket = getScheduledThreadPoolExecutor().scheduleAtFixedRate(new Runnable() {
public void run() {
databaseLockKeepAlive();
}
}, lockKeepAlivePeriod, lockKeepAlivePeriod, TimeUnit.MILLISECONDS);
}
if (brokerService != null) {
brokerService.getBroker().nowMasterBroker();
}
}
}
cleanup();
// Cleanup the db periodically.
if (cleanupPeriod > 0) {
cleanupTicket = getScheduledThreadPoolExecutor().scheduleWithFixedDelay(new Runnable() {
public void run() {
cleanup();
}
}, cleanupPeriod, cleanupPeriod, TimeUnit.MILLISECONDS);
}
}
public synchronized void stop() throws Exception {
if (cleanupTicket != null) {
cleanupTicket.cancel(true);
cleanupTicket = null;
}
if (keepAliveTicket != null) {
keepAliveTicket.cancel(false);
keepAliveTicket = null;
}
// do not shutdown clockDaemon as it may kill the thread initiating shutdown
DatabaseLocker service = getDatabaseLocker();
if (service != null) {
service.stop();
}
}
public void cleanup() {
TransactionContext c = null;
try {
LOG.debug("Cleaning up old messages.");
c = getTransactionContext();
getAdapter().doDeleteOldMessages(c);
} catch (IOException e) {
LOG.warn("Old message cleanup failed due to: " + e, e);
} catch (SQLException e) {
LOG.warn("Old message cleanup failed due to: " + e);
JDBCPersistenceAdapter.log("Failure Details: ", e);
} finally {
if (c != null) {
try {
c.close();
} catch (Throwable e) {
}
}
LOG.debug("Cleanup done.");
}
}
public void setScheduledThreadPoolExecutor(ScheduledThreadPoolExecutor clockDaemon) {
this.clockDaemon = clockDaemon;
}
public ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor() {
if (clockDaemon == null) {
clockDaemon = new ScheduledThreadPoolExecutor(5, new ThreadFactory() {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "ActiveMQ Cleanup Timer");
thread.setDaemon(true);
return thread;
}
});
}
return clockDaemon;
}
public JDBCAdapter getAdapter() throws IOException {
if (adapter == null) {
setAdapter(createAdapter());
}
return adapter;
}
public DatabaseLocker getDatabaseLocker() throws IOException {
if (databaseLocker == null && isUseDatabaseLock()) {
setDatabaseLocker(loadDataBaseLocker());
}
return databaseLocker;
}
/**
* Sets the database locker strategy to use to lock the database on startup
* @throws IOException
*/
public void setDatabaseLocker(DatabaseLocker locker) throws IOException {
databaseLocker = locker;
databaseLocker.setPersistenceAdapter(this);
databaseLocker.setLockAcquireSleepInterval(getLockAcquireSleepInterval());
}
public DataSource getLockDataSource() throws IOException {
if (lockDataSource == null) {
lockDataSource = getDataSource();
if (lockDataSource == null) {
throw new IllegalArgumentException(
"No dataSource property has been configured");
}
} else {
LOG.info("Using a separate dataSource for locking: "
+ lockDataSource);
}
return lockDataSource;
}
public void setLockDataSource(DataSource dataSource) {
this.lockDataSource = dataSource;
}
public BrokerService getBrokerService() {
return brokerService;
}
public void setBrokerService(BrokerService brokerService) {
this.brokerService = brokerService;
}
/**
* @throws IOException
*/
protected JDBCAdapter createAdapter() throws IOException {
adapter = (JDBCAdapter) loadAdapter(adapterFactoryFinder, "adapter");
// Use the default JDBC adapter if the
// Database type is not recognized.
if (adapter == null) {
adapter = new DefaultJDBCAdapter();
LOG.debug("Using default JDBC Adapter: " + adapter);
}
return adapter;
}
private Object loadAdapter(FactoryFinder finder, String kind) throws IOException {
Object adapter = null;
TransactionContext c = getTransactionContext();
try {
try {
// Make the filename file system safe.
String dirverName = c.getConnection().getMetaData().getDriverName();
dirverName = dirverName.replaceAll("[^a-zA-Z0-9\\-]", "_").toLowerCase();
try {
adapter = finder.newInstance(dirverName);
LOG.info("Database " + kind + " driver override recognized for : [" + dirverName + "] - adapter: " + adapter.getClass());
} catch (Throwable e) {
LOG.warn("Database " + kind + " driver override not found for : [" + dirverName
+ "]. Will use default implementation.");
}
} catch (SQLException e) {
LOG.warn("JDBC error occurred while trying to detect database type for overrides. Will use default implementations: "
+ e.getMessage());
JDBCPersistenceAdapter.log("Failure Details: ", e);
}
} finally {
c.close();
}
return adapter;
}
public void setAdapter(JDBCAdapter adapter) {
this.adapter = adapter;
this.adapter.setStatements(getStatements());
}
public WireFormat getWireFormat() {
return wireFormat;
}
public void setWireFormat(WireFormat wireFormat) {
this.wireFormat = wireFormat;
}
public TransactionContext getTransactionContext(ConnectionContext context) throws IOException {
if (context == null) {
return getTransactionContext();
} else {
TransactionContext answer = (TransactionContext)context.getLongTermStoreContext();
if (answer == null) {
answer = getTransactionContext();
context.setLongTermStoreContext(answer);
}
return answer;
}
}
public TransactionContext getTransactionContext() throws IOException {
TransactionContext answer = new TransactionContext(getDataSource());
if (transactionIsolation > 0) {
answer.setTransactionIsolation(transactionIsolation);
}
return answer;
}
public void beginTransaction(ConnectionContext context) throws IOException {
TransactionContext transactionContext = getTransactionContext(context);
transactionContext.begin();
}
public void commitTransaction(ConnectionContext context) throws IOException {
TransactionContext transactionContext = getTransactionContext(context);
transactionContext.commit();
}
public void rollbackTransaction(ConnectionContext context) throws IOException {
TransactionContext transactionContext = getTransactionContext(context);
transactionContext.rollback();
}
public int getCleanupPeriod() {
return cleanupPeriod;
}
/**
* Sets the number of milliseconds until the database is attempted to be
* cleaned up for durable topics
*/
public void setCleanupPeriod(int cleanupPeriod) {
this.cleanupPeriod = cleanupPeriod;
}
public void deleteAllMessages() throws IOException {
TransactionContext c = getTransactionContext();
try {
getAdapter().doDropTables(c);
getAdapter().setUseExternalMessageReferences(isUseExternalMessageReferences());
getAdapter().doCreateTables(c);
} catch (SQLException e) {
JDBCPersistenceAdapter.log("JDBC Failure: ", e);
throw IOExceptionSupport.create(e);
} finally {
c.close();
}
}
public boolean isUseExternalMessageReferences() {
return useExternalMessageReferences;
}
public void setUseExternalMessageReferences(boolean useExternalMessageReferences) {
this.useExternalMessageReferences = useExternalMessageReferences;
}
public boolean isCreateTablesOnStartup() {
return createTablesOnStartup;
}
/**
* Sets whether or not tables are created on startup
*/
public void setCreateTablesOnStartup(boolean createTablesOnStartup) {
this.createTablesOnStartup = createTablesOnStartup;
}
public boolean isUseDatabaseLock() {
return useDatabaseLock;
}
/**
* Sets whether or not an exclusive database lock should be used to enable
* JDBC Master/Slave. Enabled by default.
*/
public void setUseDatabaseLock(boolean useDatabaseLock) {
this.useDatabaseLock = useDatabaseLock;
}
public static void log(String msg, SQLException e) {
String s = msg + e.getMessage();
while (e.getNextException() != null) {
e = e.getNextException();
s += ", due to: " + e.getMessage();
}
LOG.debug(s, e);
}
public Statements getStatements() {
if (statements == null) {
statements = new Statements();
}
return statements;
}
public void setStatements(Statements statements) {
this.statements = statements;
}
/**
* @param usageManager The UsageManager that is controlling the
* destination's memory usage.
*/
public void setUsageManager(SystemUsage usageManager) {
}
protected void databaseLockKeepAlive() {
boolean stop = false;
try {
DatabaseLocker locker = getDatabaseLocker();
if (locker != null) {
if (!locker.keepAlive()) {
stop = true;
}
}
} catch (IOException e) {
LOG.error("Failed to get database when trying keepalive: " + e, e);
}
if (stop) {
stopBroker();
}
}
protected void stopBroker() {
// we can no longer keep the lock so lets fail
LOG.info("No longer able to keep the exclusive lock so giving up being a master");
try {
brokerService.stop();
} catch (Exception e) {
LOG.warn("Failure occured while stopping broker");
}
}
protected DatabaseLocker loadDataBaseLocker() throws IOException {
DatabaseLocker locker = (DefaultDatabaseLocker) loadAdapter(lockFactoryFinder, "lock");
if (locker == null) {
locker = new DefaultDatabaseLocker();
LOG.debug("Using default JDBC Locker: " + locker);
}
return locker;
}
public void setBrokerName(String brokerName) {
}
public String toString() {
return "JDBCPersistenceAdapter(" + super.toString() + ")";
}
public void setDirectory(File dir) {
}
public void checkpoint(boolean sync) throws IOException {
}
public long size(){
return 0;
}
public long getLockKeepAlivePeriod() {
return lockKeepAlivePeriod;
}
public void setLockKeepAlivePeriod(long lockKeepAlivePeriod) {
this.lockKeepAlivePeriod = lockKeepAlivePeriod;
}
public long getLockAcquireSleepInterval() {
return lockAcquireSleepInterval;
}
/**
* millisecond interval between lock acquire attempts, applied to newly created DefaultDatabaseLocker
* not applied if DataBaseLocker is injected.
*/
public void setLockAcquireSleepInterval(long lockAcquireSleepInterval) {
this.lockAcquireSleepInterval = lockAcquireSleepInterval;
}
/**
* set the Transaction isolation level to something other that TRANSACTION_READ_UNCOMMITTED
* This allowable dirty isolation level may not be achievable in clustered DB environments
* so a more restrictive and expensive option may be needed like TRANSACTION_REPEATABE_READ
* see isolation level constants in {@link java.sql.Connection}
* @param transactionIsolation the isolation level to use
*/
public void setTransactionIsolation(int transactionIsolation) {
this.transactionIsolation = transactionIsolation;
}
}
| resolve https://issues.apache.org/activemq/browse/AMQ-2493 - patch applied with thanks
git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@880696 13f79535-47bb-0310-9956-ffa450edef68
| activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java | resolve https://issues.apache.org/activemq/browse/AMQ-2493 - patch applied with thanks | <ide><path>ctivemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java
<ide> adapter = finder.newInstance(dirverName);
<ide> LOG.info("Database " + kind + " driver override recognized for : [" + dirverName + "] - adapter: " + adapter.getClass());
<ide> } catch (Throwable e) {
<del> LOG.warn("Database " + kind + " driver override not found for : [" + dirverName
<add> LOG.info("Database " + kind + " driver override not found for : [" + dirverName
<ide> + "]. Will use default implementation.");
<ide> }
<ide> } catch (SQLException e) { |
|
Java | apache-2.0 | 82d071f75c8fb9b1423c212ad073ece6e7b04ee9 | 0 | ecsec/open-ecard,ecsec/open-ecard,ecsec/open-ecard | /****************************************************************************
* Copyright (C) 2013-2018 HS Coburg.
* All rights reserved.
* Contact: ecsec GmbH ([email protected])
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License version 3.0 as published by the Free Software Foundation
* and appearing in the file LICENSE.GPL included in the packaging of
* this file. Please review the following information to ensure the
* GNU General Public License version 3.0 requirements will be met:
* http://www.gnu.org/copyleft/gpl.html.
*
* Other Usage
* Alternatively, this file may be used in accordance with the terms
* and conditions contained in a signed written agreement between
* you and ecsec GmbH.
*
***************************************************************************/
package org.openecard.addons.activate;
import iso.std.iso_iec._24727.tech.schema.PowerDownDevices;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import org.openecard.addon.AddonManager;
import org.openecard.addon.AddonNotFoundException;
import org.openecard.addon.Context;
import org.openecard.addon.bind.AppExtensionAction;
import org.openecard.addon.bind.AppExtensionException;
import org.openecard.addon.bind.AppPluginAction;
import org.openecard.addon.bind.Attachment;
import org.openecard.addon.bind.BindingResult;
import org.openecard.addon.bind.BindingResultCode;
import org.openecard.addon.bind.Headers;
import org.openecard.addon.bind.RequestBody;
import org.openecard.addon.manifest.AddonSpecification;
import org.openecard.binding.tctoken.TCTokenHandler;
import org.openecard.binding.tctoken.TCTokenResponse;
import org.openecard.binding.tctoken.TR03112Keys;
import org.openecard.binding.tctoken.ex.ActivationError;
import static org.openecard.binding.tctoken.ex.ErrorTranslations.*;
import org.openecard.binding.tctoken.ex.FatalActivationError;
import org.openecard.binding.tctoken.ex.NonGuiException;
import org.openecard.common.DynamicContext;
import org.openecard.common.ECardConstants;
import org.openecard.common.I18n;
import org.openecard.common.OpenecardProperties;
import org.openecard.common.ThreadTerminateException;
import org.openecard.common.WSHelper;
import org.openecard.common.interfaces.Dispatcher;
import org.openecard.gui.UserConsent;
import org.openecard.gui.definition.ViewController;
import org.openecard.gui.message.DialogType;
import org.openecard.httpcore.cookies.CookieManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of a plugin action performing a client activation with a TCToken.
*
* @author Dirk Petrautzki
* @author Benedikt Biallowons
* @author Tobias Wich
* @author Hans-Martin Haase
*/
public class ActivateAction implements AppPluginAction {
private static final Logger LOG = LoggerFactory.getLogger(ActivateAction.class);
private static final Semaphore SEMAPHORE = new Semaphore(1);
private final I18n lang = I18n.getTranslation("tr03112");
private TCTokenHandler tokenHandler;
private AppPluginAction statusAction;
private AppExtensionAction pinManAction;
private UserConsent gui;
private AddonManager manager;
private ViewController settingsAndDefaultView;
private Dispatcher dispatcher;
private Context ctx;
@Override
public void init(Context ctx) {
tokenHandler = new TCTokenHandler(ctx);
this.ctx = ctx;
gui = ctx.getUserConsent();
dispatcher = ctx.getDispatcher();
manager = ctx.getManager();
settingsAndDefaultView = ctx.getViewController();
try {
AddonSpecification addonSpecStatus = manager.getRegistry().search("Status");
statusAction = manager.getAppPluginAction(addonSpecStatus, "getStatus");
AddonSpecification addonSpecPinMngmt = manager.getRegistry().search("PIN-Plugin");
pinManAction = manager.getAppExtensionAction(addonSpecPinMngmt, "GetCardsAndPINStatusAction");
} catch (AddonNotFoundException ex) {
// this should never happen because the status and pin plugin are always available
String msg = "Failed to get Status or PIN Plugin.";
LOG.error(msg, ex);
throw new RuntimeException(msg, ex);
}
}
@Override
public void destroy(boolean force) {
tokenHandler = null;
manager.returnAppPluginAction(statusAction);
manager.returnAppExtensionAction(pinManAction);
}
@Override
public BindingResult execute(RequestBody body, Map<String, String> params, Headers headers, List<Attachment> attachments) {
DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY);
try {
BindingResult response;
if (SEMAPHORE.tryAcquire()) {
try {
response = checkRequestParameters(body, params, headers, attachments);
} finally {
try {
this.dispatcher.safeDeliver(new PowerDownDevices());
} catch(Exception e) {
}
SEMAPHORE.release();
}
} else {
response = new BindingResult(BindingResultCode.RESOURCE_LOCKED);
response.setResultMessage("An authentication process is already running.");
}
return response;
} catch (Throwable t) {
LOG.error("Unexpected error returned from eID-Client Activation.", t);
if (t instanceof Error) {
// don't handle errors, they are reserved for unhandleable errors
throw t;
} else {
return new BindingResult(BindingResultCode.INTERNAL_ERROR);
}
} finally {
// clean up context
dynCtx.clear();
DynamicContext.remove();
}
}
private boolean isShowRemoveCard() {
String str = OpenecardProperties.getProperty("notification.omit_show_remove_card");
return ! Boolean.valueOf(str);
}
/**
* Use the {@link UserConsent} to display the success message.
*/
private void showFinishMessage(TCTokenResponse response) {
// show the finish message just if we have a major ok
if (ECardConstants.Major.OK.equals(response.getResult().getResultMajor()) && isShowRemoveCard()) {
String title = lang.translationForKey(FINISH_TITLE);
String msg = lang.translationForKey(REMOVE_CARD);
showBackgroundMessage(msg, title, DialogType.INFORMATION_MESSAGE);
}
}
/**
* Display a dialog in a separate thread.
*
* @param msg The message which shall be displayed.
* @param title Title of the dialog window.
* @param dialogType Type of the dialog.
*/
private void showBackgroundMessage(final String msg, final String title, final DialogType dialogType) {
new Thread(new Runnable() {
@Override
public void run() {
gui.obtainMessageDialog().showMessageDialog(msg, title, dialogType);
}
}, "Background_MsgBox").start();
}
/**
* Use the {@link UserConsent} to display the given error message.
*
* @param errMsg Error message to display.
*/
private void showErrorMessage(String errMsg) {
String title = lang.translationForKey(ERROR_TITLE);
String baseHeader = lang.translationForKey(ERROR_HEADER);
String exceptionPart = lang.translationForKey(ERROR_MSG_IND);
String removeCard = lang.translationForKey(REMOVE_CARD);
String msg = String.format("%s\n\n%s\n%s\n\n%s", baseHeader, exceptionPart, errMsg, removeCard);
showBackgroundMessage(msg, title, DialogType.ERROR_MESSAGE);
}
/**
* Check the request for correct parameters and invoke their processing if they are ok.
*
* @param body The body of the request.
* @param params The query parameters and their values.
* @param attachments Attachments of the request.
* @return A {@link BindingResult} with an error if the parameters are not correct or one depending on the processing
* of the parameters.
*/
private BindingResult checkRequestParameters(RequestBody body, Map<String, String> params, Headers headers,
List<Attachment> attachments) {
BindingResult response;
boolean emptyParms, tokenUrl, status, showUI;
emptyParms = tokenUrl = status = showUI = false;
if (params.isEmpty()) {
emptyParms = true;
}
if (params.containsKey("tcTokenURL")) {
tokenUrl = true;
}
if (params.containsKey("Status")) {
status = true;
}
if (params.containsKey("ShowUI")) {
showUI = true;
}
// only continue, when there are known parameters in the request
if (emptyParms || !(tokenUrl || status || showUI)) {
response = new BindingResult(BindingResultCode.MISSING_PARAMETER);
response.setResultMessage(lang.translationForKey(NO_ACTIVATION_PARAMETERS));
showErrorMessage(lang.translationForKey(NO_ACTIVATION_PARAMETERS));
return response;
}
// check illegal parameter combination
if ((tokenUrl && showUI) || (tokenUrl && status) || (showUI && status)) {
response = new BindingResult(BindingResultCode.WRONG_PARAMETER);
response.setResultMessage(lang.translationForKey(NO_PARAMS));
showErrorMessage(lang.translationForKey(NO_PARAMS));
return response;
}
return processRequest(body, params, headers, attachments, tokenUrl, showUI, status);
}
/**
* Process the request.
*
* @param body Body of the request.
* @param params Query parameters of the request.
* @param attachments Attachments of the request.
* @param tokenUrl {@code TRUE} if {@code params} contains a TCTokenURL.
* @param showUI {@code TRUE} if {@code params} contains a ShowUI parameter.
* @param status {@code TRUE} if {@code params} contains a Status parameter.
* @return A {@link BindingResult} representing the result of the request processing.
*/
private BindingResult processRequest(RequestBody body, Map<String, String> params, Headers headers,
List<Attachment> attachments, boolean tokenUrl, boolean showUI, boolean status) {
BindingResult response = null;
if (tokenUrl) {
response = processTcToken(params);
return response;
}
if (status) {
response = processStatus(body, params, headers, attachments);
return response;
}
if (showUI) {
String requestedUI = params.get("ShowUI");
response = processShowUI(requestedUI);
return response;
}
return response;
}
/**
* Open the requested UI if no supported UI element is stated the default view is opened.
*
* @param requestedUI String containing the name of the UI component to open. Currently supported UI components are
* {@code Settings} and {@code PINManagement}. All other values are ignored and the default view is opened also if
* the value is null.
* @return A {@link BindingResult} object containing {@link BindingResultCode#OK} because the UIs do not return
* results.
*/
private BindingResult processShowUI(String requestedUI) {
BindingResult response;
if (requestedUI != null) {
switch (requestedUI) {
case "Settings":
response = processShowSettings();
break;
case "PINManagement":
response = processShowPinManagement();
break;
default:
response = processShowDefault();
}
} else {
// open default gui
response = processShowDefault();
}
return response;
}
/**
* Display the default view of the Open eCard App.
*
* There is no real default view that's a term used by the eID-Client specification BSI-TR-03124-1 v1.2 so we display
* the About dialog.
*
* @return A {@link BindingResult} object containing {@link BindingResultCode#OK} because the gui does not return any
* result.
*/
private BindingResult processShowDefault() {
Thread defautlViewThread = new Thread(settingsAndDefaultView::showDefaultViewUI, "ShowDefaultView");
defautlViewThread.start();
return new BindingResult(BindingResultCode.OK);
}
/**
* Opens the PINManagement dialog.
*
* @return A {@link BindingResult} object containing {@link BindingResultCode#OK} because the gui does not return any
* result.
*/
private BindingResult processShowPinManagement() {
// submit thread
ExecutorService es = Executors.newSingleThreadExecutor((Runnable action) -> new Thread(action, "ShowPINManagement"));
Future<Void> guiThread = es.submit(() -> {
pinManAction.execute();
return null;
});
try {
guiThread.get();
return new BindingResult(BindingResultCode.OK);
} catch (InterruptedException ex) {
guiThread.cancel(true);
return new BindingResult(BindingResultCode.INTERRUPTED);
} catch (ExecutionException ex) {
Throwable cause = ex.getCause();
if (cause instanceof AppExtensionException) {
AppExtensionException appEx = (AppExtensionException) cause;
if (WSHelper.minorIsOneOf(appEx, ECardConstants.Minor.SAL.CANCELLATION_BY_USER,
ECardConstants.Minor.IFD.CANCELLATION_BY_USER)) {
LOG.info("PIN Management got cancelled.");
return new BindingResult(BindingResultCode.INTERRUPTED);
}
} else if (cause instanceof ThreadTerminateException) {
return new BindingResult(BindingResultCode.INTERRUPTED);
}
// just count as normal error
LOG.warn("Failed to execute PIN Management.", ex);
return new BindingResult(BindingResultCode.INTERNAL_ERROR);
} finally {
// clean up executor
es.shutdown();
}
}
/**
* Opens the Settings dialog.
*
* @return A {@link BindingResult} object containing {@link BindingResultCode#OK} because the gui does not return any
* result.
*/
private BindingResult processShowSettings() {
Thread settingsThread = new Thread(settingsAndDefaultView::showSettingsUI, "ShowSettings");
settingsThread.start();
return new BindingResult(BindingResultCode.OK);
}
/**
* Gets a BindingResult object containing the current status of the client.
*
* @param body Original RequestBody.
* @param params Original Parameters.
* @param attachments Original list of Attachment object.
* @return A {@link BindingResult} object containing the current status of the App as XML structure.
*/
private BindingResult processStatus(RequestBody body, Map<String, String> params, Headers headers, List<Attachment> attachments) {
BindingResult response = statusAction.execute(body, params, headers, attachments);
return response;
}
/**
* Process the tcTokenURL or the activation object and perform a authentication.
*
* @param params Parameters of the request.
* @return A {@link BindingResult} representing the result of the authentication.
*/
private BindingResult processTcToken(Map<String, String> params) {
BindingResult response;
DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY);
dynCtx.put(TR03112Keys.COOKIE_MANAGER, new CookieManager());
try {
try {
response = tokenHandler.handleActivate(params, ctx);
// Show success message. If we get here we have a valid StartPAOSResponse and a valid refreshURL
showFinishMessage((TCTokenResponse) response);
} catch (ActivationError ex) {
if (ex instanceof NonGuiException) {
// error already displayed to the user so do not repeat it here
} else {
if (ex.getMessage().equals("Invalid HTTP message received.")) {
showErrorMessage(lang.translationForKey(ACTIVATION_INVALID_REFRESH_ADDRESS));
} else {
showErrorMessage(ex.getLocalizedMessage());
}
}
LOG.error(ex.getMessage());
LOG.debug(ex.getMessage(), ex); // stack trace only in debug level
LOG.debug("Returning result: \n{}", ex.getBindingResult());
if (ex instanceof FatalActivationError) {
LOG.info("Authentication failed, displaying error in Browser.");
} else {
LOG.info("Authentication failed, redirecting to with errors attached to the URL.");
}
response = ex.getBindingResult();
}
} catch (RuntimeException e) {
if(e instanceof ThreadTerminateException){
response = new BindingResult(BindingResultCode.INTERRUPTED);
} else {
response = new BindingResult(BindingResultCode.INTERNAL_ERROR);
}
LOG.error(e.getMessage(), e);
}
return response;
}
}
| addons/tr03112/src/main/java/org/openecard/addons/activate/ActivateAction.java | /****************************************************************************
* Copyright (C) 2013-2018 HS Coburg.
* All rights reserved.
* Contact: ecsec GmbH ([email protected])
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License version 3.0 as published by the Free Software Foundation
* and appearing in the file LICENSE.GPL included in the packaging of
* this file. Please review the following information to ensure the
* GNU General Public License version 3.0 requirements will be met:
* http://www.gnu.org/copyleft/gpl.html.
*
* Other Usage
* Alternatively, this file may be used in accordance with the terms
* and conditions contained in a signed written agreement between
* you and ecsec GmbH.
*
***************************************************************************/
package org.openecard.addons.activate;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import org.openecard.addon.AddonManager;
import org.openecard.addon.AddonNotFoundException;
import org.openecard.addon.Context;
import org.openecard.addon.bind.AppExtensionAction;
import org.openecard.addon.bind.AppExtensionException;
import org.openecard.addon.bind.AppPluginAction;
import org.openecard.addon.bind.Attachment;
import org.openecard.addon.bind.BindingResult;
import org.openecard.addon.bind.BindingResultCode;
import org.openecard.addon.bind.Headers;
import org.openecard.addon.bind.RequestBody;
import org.openecard.addon.manifest.AddonSpecification;
import org.openecard.binding.tctoken.TCTokenHandler;
import org.openecard.binding.tctoken.TCTokenResponse;
import org.openecard.binding.tctoken.TR03112Keys;
import org.openecard.binding.tctoken.ex.ActivationError;
import static org.openecard.binding.tctoken.ex.ErrorTranslations.*;
import org.openecard.binding.tctoken.ex.FatalActivationError;
import org.openecard.binding.tctoken.ex.NonGuiException;
import org.openecard.common.DynamicContext;
import org.openecard.common.ECardConstants;
import org.openecard.common.I18n;
import org.openecard.common.OpenecardProperties;
import org.openecard.common.ThreadTerminateException;
import org.openecard.common.WSHelper;
import org.openecard.common.interfaces.Dispatcher;
import org.openecard.gui.UserConsent;
import org.openecard.gui.definition.ViewController;
import org.openecard.gui.message.DialogType;
import org.openecard.httpcore.cookies.CookieManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of a plugin action performing a client activation with a TCToken.
*
* @author Dirk Petrautzki
* @author Benedikt Biallowons
* @author Tobias Wich
* @author Hans-Martin Haase
*/
public class ActivateAction implements AppPluginAction {
private static final Logger LOG = LoggerFactory.getLogger(ActivateAction.class);
private static final Semaphore SEMAPHORE = new Semaphore(1);
private final I18n lang = I18n.getTranslation("tr03112");
private TCTokenHandler tokenHandler;
private AppPluginAction statusAction;
private AppExtensionAction pinManAction;
private UserConsent gui;
private AddonManager manager;
private ViewController settingsAndDefaultView;
private Dispatcher dispatcher;
private Context ctx;
@Override
public void init(Context ctx) {
tokenHandler = new TCTokenHandler(ctx);
this.ctx = ctx;
gui = ctx.getUserConsent();
dispatcher = ctx.getDispatcher();
manager = ctx.getManager();
settingsAndDefaultView = ctx.getViewController();
try {
AddonSpecification addonSpecStatus = manager.getRegistry().search("Status");
statusAction = manager.getAppPluginAction(addonSpecStatus, "getStatus");
AddonSpecification addonSpecPinMngmt = manager.getRegistry().search("PIN-Plugin");
pinManAction = manager.getAppExtensionAction(addonSpecPinMngmt, "GetCardsAndPINStatusAction");
} catch (AddonNotFoundException ex) {
// this should never happen because the status and pin plugin are always available
String msg = "Failed to get Status or PIN Plugin.";
LOG.error(msg, ex);
throw new RuntimeException(msg, ex);
}
}
@Override
public void destroy(boolean force) {
tokenHandler = null;
manager.returnAppPluginAction(statusAction);
manager.returnAppExtensionAction(pinManAction);
}
@Override
public BindingResult execute(RequestBody body, Map<String, String> params, Headers headers, List<Attachment> attachments) {
DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY);
try {
BindingResult response;
if (SEMAPHORE.tryAcquire()) {
try {
response = checkRequestParameters(body, params, headers, attachments);
} finally {
SEMAPHORE.release();
}
} else {
response = new BindingResult(BindingResultCode.RESOURCE_LOCKED);
response.setResultMessage("An authentication process is already running.");
}
return response;
} catch (Throwable t) {
LOG.error("Unexpected error returned from eID-Client Activation.", t);
if (t instanceof Error) {
// don't handle errors, they are reserved for unhandleable errors
throw t;
} else {
return new BindingResult(BindingResultCode.INTERNAL_ERROR);
}
} finally {
// clean up context
dynCtx.clear();
DynamicContext.remove();
}
}
private boolean isShowRemoveCard() {
String str = OpenecardProperties.getProperty("notification.omit_show_remove_card");
return ! Boolean.valueOf(str);
}
/**
* Use the {@link UserConsent} to display the success message.
*/
private void showFinishMessage(TCTokenResponse response) {
// show the finish message just if we have a major ok
if (ECardConstants.Major.OK.equals(response.getResult().getResultMajor()) && isShowRemoveCard()) {
String title = lang.translationForKey(FINISH_TITLE);
String msg = lang.translationForKey(REMOVE_CARD);
showBackgroundMessage(msg, title, DialogType.INFORMATION_MESSAGE);
}
}
/**
* Display a dialog in a separate thread.
*
* @param msg The message which shall be displayed.
* @param title Title of the dialog window.
* @param dialogType Type of the dialog.
*/
private void showBackgroundMessage(final String msg, final String title, final DialogType dialogType) {
new Thread(new Runnable() {
@Override
public void run() {
gui.obtainMessageDialog().showMessageDialog(msg, title, dialogType);
}
}, "Background_MsgBox").start();
}
/**
* Use the {@link UserConsent} to display the given error message.
*
* @param errMsg Error message to display.
*/
private void showErrorMessage(String errMsg) {
String title = lang.translationForKey(ERROR_TITLE);
String baseHeader = lang.translationForKey(ERROR_HEADER);
String exceptionPart = lang.translationForKey(ERROR_MSG_IND);
String removeCard = lang.translationForKey(REMOVE_CARD);
String msg = String.format("%s\n\n%s\n%s\n\n%s", baseHeader, exceptionPart, errMsg, removeCard);
showBackgroundMessage(msg, title, DialogType.ERROR_MESSAGE);
}
/**
* Check the request for correct parameters and invoke their processing if they are ok.
*
* @param body The body of the request.
* @param params The query parameters and their values.
* @param attachments Attachments of the request.
* @return A {@link BindingResult} with an error if the parameters are not correct or one depending on the processing
* of the parameters.
*/
private BindingResult checkRequestParameters(RequestBody body, Map<String, String> params, Headers headers,
List<Attachment> attachments) {
BindingResult response;
boolean emptyParms, tokenUrl, status, showUI;
emptyParms = tokenUrl = status = showUI = false;
if (params.isEmpty()) {
emptyParms = true;
}
if (params.containsKey("tcTokenURL")) {
tokenUrl = true;
}
if (params.containsKey("Status")) {
status = true;
}
if (params.containsKey("ShowUI")) {
showUI = true;
}
// only continue, when there are known parameters in the request
if (emptyParms || !(tokenUrl || status || showUI)) {
response = new BindingResult(BindingResultCode.MISSING_PARAMETER);
response.setResultMessage(lang.translationForKey(NO_ACTIVATION_PARAMETERS));
showErrorMessage(lang.translationForKey(NO_ACTIVATION_PARAMETERS));
return response;
}
// check illegal parameter combination
if ((tokenUrl && showUI) || (tokenUrl && status) || (showUI && status)) {
response = new BindingResult(BindingResultCode.WRONG_PARAMETER);
response.setResultMessage(lang.translationForKey(NO_PARAMS));
showErrorMessage(lang.translationForKey(NO_PARAMS));
return response;
}
return processRequest(body, params, headers, attachments, tokenUrl, showUI, status);
}
/**
* Process the request.
*
* @param body Body of the request.
* @param params Query parameters of the request.
* @param attachments Attachments of the request.
* @param tokenUrl {@code TRUE} if {@code params} contains a TCTokenURL.
* @param showUI {@code TRUE} if {@code params} contains a ShowUI parameter.
* @param status {@code TRUE} if {@code params} contains a Status parameter.
* @return A {@link BindingResult} representing the result of the request processing.
*/
private BindingResult processRequest(RequestBody body, Map<String, String> params, Headers headers,
List<Attachment> attachments, boolean tokenUrl, boolean showUI, boolean status) {
BindingResult response = null;
if (tokenUrl) {
response = processTcToken(params);
return response;
}
if (status) {
response = processStatus(body, params, headers, attachments);
return response;
}
if (showUI) {
String requestedUI = params.get("ShowUI");
response = processShowUI(requestedUI);
return response;
}
return response;
}
/**
* Open the requested UI if no supported UI element is stated the default view is opened.
*
* @param requestedUI String containing the name of the UI component to open. Currently supported UI components are
* {@code Settings} and {@code PINManagement}. All other values are ignored and the default view is opened also if
* the value is null.
* @return A {@link BindingResult} object containing {@link BindingResultCode#OK} because the UIs do not return
* results.
*/
private BindingResult processShowUI(String requestedUI) {
BindingResult response;
if (requestedUI != null) {
switch (requestedUI) {
case "Settings":
response = processShowSettings();
break;
case "PINManagement":
response = processShowPinManagement();
break;
default:
response = processShowDefault();
}
} else {
// open default gui
response = processShowDefault();
}
return response;
}
/**
* Display the default view of the Open eCard App.
*
* There is no real default view that's a term used by the eID-Client specification BSI-TR-03124-1 v1.2 so we display
* the About dialog.
*
* @return A {@link BindingResult} object containing {@link BindingResultCode#OK} because the gui does not return any
* result.
*/
private BindingResult processShowDefault() {
Thread defautlViewThread = new Thread(settingsAndDefaultView::showDefaultViewUI, "ShowDefaultView");
defautlViewThread.start();
return new BindingResult(BindingResultCode.OK);
}
/**
* Opens the PINManagement dialog.
*
* @return A {@link BindingResult} object containing {@link BindingResultCode#OK} because the gui does not return any
* result.
*/
private BindingResult processShowPinManagement() {
// submit thread
ExecutorService es = Executors.newSingleThreadExecutor((Runnable action) -> new Thread(action, "ShowPINManagement"));
Future<Void> guiThread = es.submit(() -> {
pinManAction.execute();
return null;
});
try {
guiThread.get();
return new BindingResult(BindingResultCode.OK);
} catch (InterruptedException ex) {
guiThread.cancel(true);
return new BindingResult(BindingResultCode.INTERRUPTED);
} catch (ExecutionException ex) {
Throwable cause = ex.getCause();
if (cause instanceof AppExtensionException) {
AppExtensionException appEx = (AppExtensionException) cause;
if (WSHelper.minorIsOneOf(appEx, ECardConstants.Minor.SAL.CANCELLATION_BY_USER,
ECardConstants.Minor.IFD.CANCELLATION_BY_USER)) {
LOG.info("PIN Management got cancelled.");
return new BindingResult(BindingResultCode.INTERRUPTED);
}
} else if (cause instanceof ThreadTerminateException) {
return new BindingResult(BindingResultCode.INTERRUPTED);
}
// just count as normal error
LOG.warn("Failed to execute PIN Management.", ex);
return new BindingResult(BindingResultCode.INTERNAL_ERROR);
} finally {
// clean up executor
es.shutdown();
}
}
/**
* Opens the Settings dialog.
*
* @return A {@link BindingResult} object containing {@link BindingResultCode#OK} because the gui does not return any
* result.
*/
private BindingResult processShowSettings() {
Thread settingsThread = new Thread(settingsAndDefaultView::showSettingsUI, "ShowSettings");
settingsThread.start();
return new BindingResult(BindingResultCode.OK);
}
/**
* Gets a BindingResult object containing the current status of the client.
*
* @param body Original RequestBody.
* @param params Original Parameters.
* @param attachments Original list of Attachment object.
* @return A {@link BindingResult} object containing the current status of the App as XML structure.
*/
private BindingResult processStatus(RequestBody body, Map<String, String> params, Headers headers, List<Attachment> attachments) {
BindingResult response = statusAction.execute(body, params, headers, attachments);
return response;
}
/**
* Process the tcTokenURL or the activation object and perform a authentication.
*
* @param params Parameters of the request.
* @return A {@link BindingResult} representing the result of the authentication.
*/
private BindingResult processTcToken(Map<String, String> params) {
BindingResult response;
DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY);
dynCtx.put(TR03112Keys.COOKIE_MANAGER, new CookieManager());
try {
try {
response = tokenHandler.handleActivate(params, ctx);
// Show success message. If we get here we have a valid StartPAOSResponse and a valid refreshURL
showFinishMessage((TCTokenResponse) response);
} catch (ActivationError ex) {
if (ex instanceof NonGuiException) {
// error already displayed to the user so do not repeat it here
} else {
if (ex.getMessage().equals("Invalid HTTP message received.")) {
showErrorMessage(lang.translationForKey(ACTIVATION_INVALID_REFRESH_ADDRESS));
} else {
showErrorMessage(ex.getLocalizedMessage());
}
}
LOG.error(ex.getMessage());
LOG.debug(ex.getMessage(), ex); // stack trace only in debug level
LOG.debug("Returning result: \n{}", ex.getBindingResult());
if (ex instanceof FatalActivationError) {
LOG.info("Authentication failed, displaying error in Browser.");
} else {
LOG.info("Authentication failed, redirecting to with errors attached to the URL.");
}
response = ex.getBindingResult();
}
} catch (RuntimeException e) {
if(e instanceof ThreadTerminateException){
response = new BindingResult(BindingResultCode.INTERRUPTED);
} else {
response = new BindingResult(BindingResultCode.INTERNAL_ERROR);
}
LOG.error(e.getMessage(), e);
}
return response;
}
}
| Ensure iOS overlay disappears upon completion
| addons/tr03112/src/main/java/org/openecard/addons/activate/ActivateAction.java | Ensure iOS overlay disappears upon completion | <ide><path>ddons/tr03112/src/main/java/org/openecard/addons/activate/ActivateAction.java
<ide>
<ide> package org.openecard.addons.activate;
<ide>
<add>import iso.std.iso_iec._24727.tech.schema.PowerDownDevices;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.concurrent.ExecutionException;
<ide> try {
<ide> response = checkRequestParameters(body, params, headers, attachments);
<ide> } finally {
<add> try {
<add> this.dispatcher.safeDeliver(new PowerDownDevices());
<add> } catch(Exception e) {
<add> }
<ide> SEMAPHORE.release();
<ide> }
<ide> } else { |
|
Java | apache-2.0 | 4f0f68f74dd4abd9f4695020acba60fb5ab7bb9e | 0 | OpenHFT/Chronicle-Queue,OpenHFT/Chronicle-Queue | package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.values.LongValue;
import net.openhft.chronicle.wire.Sequence;
class RollCycleEncodeSequence implements Sequence {
private final LongValue sequenceValue;
private int cycleShift = 0;
private long sequenceMask = 0;
RollCycleEncodeSequence(LongValue sequenceValue, int indexCount, int indexSpacing) {
this.sequenceValue = sequenceValue;
cycleShift = Math.max(32, Maths.intLog2(indexCount) * 2 + Maths.intLog2(indexSpacing));
sequenceMask = (1L << cycleShift) - 1;
}
@Override
public void setSequence(long sequence, long position) {
if (sequenceValue == null)
return;
long value = toLongValue((int) position, sequence);
sequenceValue.setOrderedValue(value);
}
@Override
public long toIndex(long headerNumber, long sequence) {
int cycle = Maths.toUInt31(headerNumber >> cycleShift);
return toLongValue(cycle, sequence);
}
/**
* gets the sequence for a writePosition
* <p>
* This method will only return a valid sequence number of the write position if the write position is the
* last write position in the queue. YOU CAN NOT USE THIS METHOD TO LOOK UP RANDOM SEQUENCES FOR ANY WRITE POSITION.
* NOT_FOUND_RETRY will be return if a sequence number can not be found ( so can retry )
* or NOT_FOUND when you should not retry
*
* @param forWritePosition the last write position, expected to be the end of queue
* @return NOT_FOUND_RETRY if the sequence for this write position can not be found, or NOT_FOUND if sequenceValue==null or the sequence for this {@code writePosition}
*/
public long getSequence(long forWritePosition) {
if (sequenceValue == null)
return Sequence.NOT_FOUND;
// todo optimize the maths in the method below
final long sequenceValue = this.sequenceValue.getVolatileValue();
if (sequenceValue == 0)
return Sequence.NOT_FOUND;
final int lowerBitsOfWp = toLowerBitsWritePosition(toLongValue((int) forWritePosition, 0));
final int toLowerBitsWritePosition = toLowerBitsWritePosition(sequenceValue);
if (lowerBitsOfWp == toLowerBitsWritePosition)
return toSequenceNumber(sequenceValue);
return Sequence.NOT_FOUND_RETRY;
}
private long toLongValue(int cycle, long sequenceNumber) {
return ((long) cycle << cycleShift) + (sequenceNumber & sequenceMask);
}
private long toSequenceNumber(long index) {
return index & sequenceMask;
}
private int toLowerBitsWritePosition(long index) {
return Maths.toUInt31(index >> cycleShift);
}
}
| src/main/java/net/openhft/chronicle/queue/impl/single/RollCycleEncodeSequence.java | package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.values.LongValue;
import net.openhft.chronicle.wire.Sequence;
class RollCycleEncodeSequence implements Sequence {
private final LongValue sequenceValue;
private int cycleShift = 0;
private long sequenceMask = 0;
RollCycleEncodeSequence(LongValue sequenceValue, int indexCount, int indexSpacing) {
this.sequenceValue = sequenceValue;
cycleShift = Math.max(32, Maths.intLog2(indexCount) * 2 + Maths.intLog2(indexSpacing));
sequenceMask = (1L << cycleShift) - 1;
}
@Override
public void setSequence(long sequence, long position) {
if (sequenceValue == null)
return;
long value = toLongValue((int) position, sequence);
sequenceValue.setOrderedValue(value);
}
@Override
public long toIndex(long headerNumber, long sequence) {
int cycle = Maths.toUInt31(headerNumber >> cycleShift);
return toLongValue(cycle, sequence);
}
/**
* gets the sequence for a writePosition
* <p>
* This method will only return a valid sequence number of the write position if the write position is the
* last write position in the queue. YOU CAN NOT USE THIS METHOD TO LOOK UP RANDOM SEQUENCES FOR ANY WRITE POSITION.
* Long.MIN_VALUE will be return if a sequence number can not be found ( so can retry )
* or -1 when you should not retry
*
* @param forWritePosition the last write position, expected to be the end of queue
* @return Long.MIN_VALUE if the sequence for this write position can not be found, or -1 if sequenceValue==null or the sequence for this {@code writePosition}
*/
public long getSequence(long forWritePosition) {
if (sequenceValue == null)
return -1;
// todo optimize the maths in the method below
final long sequenceValue = this.sequenceValue.getVolatileValue();
if (sequenceValue == 0)
return -1;
final int lowerBitsOfWp = toLowerBitsWritePosition(toLongValue((int) forWritePosition, 0));
final int toLowerBitsWritePosition = toLowerBitsWritePosition(sequenceValue);
if (lowerBitsOfWp == toLowerBitsWritePosition)
return toSequenceNumber(sequenceValue);
return Long.MIN_VALUE;
}
private long toLongValue(int cycle, long sequenceNumber) {
return ((long) cycle << cycleShift) + (sequenceNumber & sequenceMask);
}
private long toSequenceNumber(long index) {
return index & sequenceMask;
}
private int toLowerBitsWritePosition(long index) {
return Maths.toUInt31(index >> cycleShift);
}
}
| comments and constants
| src/main/java/net/openhft/chronicle/queue/impl/single/RollCycleEncodeSequence.java | comments and constants | <ide><path>rc/main/java/net/openhft/chronicle/queue/impl/single/RollCycleEncodeSequence.java
<ide> * <p>
<ide> * This method will only return a valid sequence number of the write position if the write position is the
<ide> * last write position in the queue. YOU CAN NOT USE THIS METHOD TO LOOK UP RANDOM SEQUENCES FOR ANY WRITE POSITION.
<del> * Long.MIN_VALUE will be return if a sequence number can not be found ( so can retry )
<del> * or -1 when you should not retry
<add> * NOT_FOUND_RETRY will be return if a sequence number can not be found ( so can retry )
<add> * or NOT_FOUND when you should not retry
<ide> *
<ide> * @param forWritePosition the last write position, expected to be the end of queue
<del> * @return Long.MIN_VALUE if the sequence for this write position can not be found, or -1 if sequenceValue==null or the sequence for this {@code writePosition}
<add> * @return NOT_FOUND_RETRY if the sequence for this write position can not be found, or NOT_FOUND if sequenceValue==null or the sequence for this {@code writePosition}
<ide> */
<ide> public long getSequence(long forWritePosition) {
<ide>
<ide> if (sequenceValue == null)
<del> return -1;
<add> return Sequence.NOT_FOUND;
<ide>
<ide> // todo optimize the maths in the method below
<ide>
<ide> final long sequenceValue = this.sequenceValue.getVolatileValue();
<ide> if (sequenceValue == 0)
<del> return -1;
<add> return Sequence.NOT_FOUND;
<ide>
<ide> final int lowerBitsOfWp = toLowerBitsWritePosition(toLongValue((int) forWritePosition, 0));
<ide> final int toLowerBitsWritePosition = toLowerBitsWritePosition(sequenceValue);
<ide> if (lowerBitsOfWp == toLowerBitsWritePosition)
<ide> return toSequenceNumber(sequenceValue);
<ide>
<del> return Long.MIN_VALUE;
<add> return Sequence.NOT_FOUND_RETRY;
<ide> }
<ide>
<ide> private long toLongValue(int cycle, long sequenceNumber) { |
|
Java | mit | error: pathspec 'src/test/java/org/sqldroid/DriverUnitTest.java' did not match any file(s) known to git
| 1f6c8f3d21c440ef843941aaf6e7c3e401102b4b | 1 | dperiwal/SQLDroid,SQLDroid/SQLDroid,SQLDroid/SQLDroid,dperiwal/SQLDroid | package org.sqldroid;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(sdk = 16)
public class DriverUnitTest {
/** Going to use SQLDroid JDBC Driver */
protected String driverName = "org.sqldroid.SQLDroidDriver";
/** Common prefix for creating JDBC URL */
protected String JDBC_URL_PREFIX = "jdbc:sqlite:";
/** Package name of this app */
protected String packageName = "org.sqldroid";
/** Database file directory for this app on Android */
protected String DB_DIRECTORY = "/data/data/" + packageName + "/databases/";
/** Name of an in-memory database */
protected String dummyDatabase = "dummydatabase.db";
/** The URL to the in-memory database. */
protected String databaseURL = JDBC_URL_PREFIX + dummyDatabase;
/** The table create statement. */
protected String createTable = "CREATE TABLE dummytable (name VARCHAR(254), value int)";
/** Some data for the table. */
protected String[] inserts = {
"INSERT INTO dummytable(name,value) VALUES('Apple', 100)",
"INSERT INTO dummytable(name,value) VALUES('Orange', 200)",
"INSERT INTO dummytable(name,value) VALUES('Banana', 300)",
"INSERT INTO dummytable(name,value) VALUES('Kiwi', 400)"};
/** A select statement. */
protected String select = "SELECT * FROM dummytable WHERE value < 250";
/**
* Creates the directory structure for the database file and loads the JDBC driver.
* @param dbFile the database file name
* @throws Exception
*/
protected void setupDatabaseFileAndJDBCDriver(String dbFile) throws Exception {
// If the database file already exists, delete it, else create the parent directory for it.
File f = new File(dbFile);
if ( f.exists() ) {
f.delete();
} else {
if (null != f.getParent()) {
f.getParentFile().mkdirs();
}
}
// Loads and registers the JDBC driver
DriverManager.registerDriver((Driver)(Class.forName(driverName, true, getClass().getClassLoader()).newInstance()));
}
public Blob selectBlob (Connection con, int key) throws Exception {
PreparedStatement stmt = con.prepareStatement("SELECT value,key FROM blobtest where key = ?");
stmt.setInt(1, key);
ResultSet rs = stmt.executeQuery();
assertTrue ("Executed", rs != null);
rs.next();
System.err.println ("blob record \"" + rs.getBlob(1).toString() + "\" key " + rs.getString(2) );
assertTrue (" Only one record ", rs.isLast());
Blob b = rs.getBlob(1);
return b;
}
/** Test the serialization of the various value objects. */
@Test
public void testBlob () throws Exception {
String dbName = "bolbtest.db";
String dbFile = DB_DIRECTORY + dbName;
setupDatabaseFileAndJDBCDriver(dbFile);
Connection con = DriverManager.getConnection(JDBC_URL_PREFIX + dbFile);
con.createStatement().execute("create table blobtest (key int, value blob)");
// create a blob
final int blobSize = 70000;
byte[] aBlob = new byte[blobSize];
for ( int counter = 0 ; counter < blobSize ; counter++ ) {
aBlob[counter] = (byte)(counter %10);
}
final int blobSize1 = 1024;
byte[] aBlob1 = new byte[blobSize1];
for ( int counter = 0 ; counter < blobSize1 ; counter++ ) {
aBlob1[counter] = (byte)(counter %10 + 0x30);
}
final String stringBlob = "ABlob";
/** Some data for the table. */
final String[] blobInserts = {
"INSERT INTO blobtest(key,value) VALUES (101, '"+stringBlob+"')",
"INSERT INTO blobtest(key,value) VALUES (?, ?)",
"INSERT INTO blobtest(key,value) VALUES (?, ?)",
"INSERT INTO blobtest(key,value) VALUES (401, ?)"};
System.out.println("Insert statement is:" + blobInserts[0]);
con.createStatement().execute(blobInserts[0]);
Blob b = selectBlob(con, 101);
// FAILS - was this already a problem?
//assertEquals ("String blob", stringBlob, new String(b.getBytes(1, (int)b.length())));
PreparedStatement stmt = con.prepareStatement(blobInserts[1]);
stmt.setInt(1, blobSize);
stmt.setBinaryStream(2, new ByteArrayInputStream(aBlob),aBlob.length);
stmt.execute();
b = selectBlob(con, blobSize);
assertEquals (" Correct Length ", blobSize, b.length());
byte[] bytes = b.getBytes(0, blobSize);
for ( int counter = 0 ; counter < blobSize ; counter++ ) {
assertEquals(" Blob Element "+ counter, (counter %10), bytes[counter]);
}
stmt = con.prepareStatement(blobInserts[2]);
stmt.setInt(1, blobSize1);
stmt.setBinaryStream(2, new ByteArrayInputStream(aBlob1),aBlob1.length);
stmt.execute();
b = selectBlob(con, blobSize1);
assertEquals (" Correct 1 Length ", blobSize1, b.length());
byte[] bytes1 = b.getBytes(0, blobSize1);
for ( int counter = 0 ; counter < blobSize1 ; counter++ ) {
assertEquals(" Blob1 Element "+ counter, (counter %10 + 0x30), bytes1[counter]);
}
stmt = con.prepareStatement(blobInserts[3]);
stmt.setBinaryStream(1, new ByteArrayInputStream(aBlob),aBlob.length);
stmt.execute();
b = selectBlob(con, 401);
assertEquals (" Correct Length ", blobSize, b.length());
bytes = b.getBytes(0, blobSize);
for ( int counter = 0 ; counter < blobSize ; counter++ ) {
assertEquals(" Blob Element "+ counter, (counter %10), bytes[counter]);
}
}
@Test
public void testCursors () throws Exception {
String dbName = "cursortest.db";
String dbFile = DB_DIRECTORY + dbName;
setupDatabaseFileAndJDBCDriver(dbFile);
Connection con = DriverManager.getConnection(JDBC_URL_PREFIX + dbFile);
con.createStatement().execute(createTable);
for ( String insertSQL : inserts ) {
con.createStatement().execute(insertSQL);
}
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM dummytable order by value");
checkResultSet ( rs, false, true, false, false, false);
rs.next();
checkResultSet ( rs, false, false, false, true, false);
checkValues (rs, "Apple", 100);
rs.next();
checkResultSet ( rs, false, false, false, false, false);
checkValues (rs, "Orange", 200);
rs.next();
checkResultSet ( rs, false, false, false, false, false);
checkValues (rs, "Banana", 300);
rs.next(); // to last
checkResultSet ( rs, false, false, false, false, true);
checkValues (rs, "Kiwi", 400);
rs.next(); // after last
checkResultSet ( rs, false, false, true, false, false);
rs.first();
checkResultSet ( rs, false, false, false, true, false);
rs.last();
checkResultSet ( rs, false, false, false, false, true);
rs.afterLast();
checkResultSet ( rs, false, false, true, false, false);
rs.beforeFirst();
checkResultSet ( rs, false, true, false, false, false);
rs.close();
checkResultSet ( rs, true, false, false, false, false);
PreparedStatement stmt = con.prepareStatement("SELECT ?,? FROM dummytable order by ?");
stmt.setString(1, "name");
stmt.setString(2, "value");
stmt.setString(3, "value");
rs = stmt.executeQuery();
assertTrue ("Executed", rs != null);
rs.last();
assertEquals("Enough rows ", 4, rs.getRow());
rs.close();
// Add a null value for name
con.createStatement().execute("INSERT INTO dummytable(name, value) VALUES(null, 500)");
rs = con.createStatement().executeQuery("SELECT name, value FROM dummytable order by value");
assertEquals("Name column position", 1, rs.findColumn("name"));
assertEquals("Value column position", 2, rs.findColumn("value"));
// In the first row, name is Apple and value is 100.
assertTrue("Cursor on the first row", rs.first());
assertEquals("Name in the first row using column name", "Apple", rs.getString("name"));
assertFalse("Current name is null", rs.wasNull());
assertEquals("Value in the first row using column name", 100, rs.getInt("value"));
assertFalse("Current value is null", rs.wasNull());
assertEquals("Name in the first row using column number", "Apple", rs.getString(1));
assertEquals("Value in the first row using column number", 100, rs.getInt(2));
assertFalse("Current value for Apple is null", rs.wasNull());
// In the second row, name is Orange and value is 200.
rs.next();
assertEquals("Name in the second row using column name", "Orange", rs.getString("name"));
assertEquals("Value in the second row using column name", 200, rs.getInt("value"));
assertFalse("Current value for Banana is null", rs.wasNull());
assertEquals("Name in the second row using column number", "Orange", rs.getString(1));
assertEquals("Value in the second row using column number", 200, rs.getInt(2));
assertFalse("Current value for Banana is null", rs.wasNull());
// In the last row, name is null and value is 500.
rs.last();
assertEquals("Name in the last row using column name", null, rs.getString("name"));
assertTrue("Current name is not null", rs.wasNull());
assertEquals("Value in the last row using column name", 500, rs.getInt("value"));
assertFalse("Current value is null", rs.wasNull());
assertEquals("Name in the last row using column number", null, rs.getString(1));
assertTrue("Current name is not null", rs.wasNull());
assertEquals("Value in the last row using column number", 500, rs.getInt(2));
assertFalse("Current value is null", rs.wasNull());
rs.close();
}
@Test
public void testResultSets() throws Exception {
String dbName = "resultsetstest.db";
String dbFile = DB_DIRECTORY + dbName;
setupDatabaseFileAndJDBCDriver(dbFile);
Connection con = DriverManager.getConnection(JDBC_URL_PREFIX + dbFile);
String createTableStatement = "CREATE TABLE dummytable (id int, aString VARCHAR(254), aByte byte, "
+ "aShort short, anInt int, aLong long, aBool boolean, aFloat float, aDouble, double, aText text)";
final String[] insertStatements = {
"INSERT INTO dummytable(id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText) VALUES "
+ "(1, 'string1', 1, 1, 10, 100, 0, 1.0, 10.0, 'text1')",
"INSERT INTO dummytable(id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText) VALUES "
+ "(2, 'string2', 2, 2, 20, 200, 1, 2.0, 20.0, 'text2')",
"INSERT INTO dummytable(id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText) VALUES "
+ "(3, null, null, null, 30, 300, 0, 3.0, 30.0, null)",
"INSERT INTO dummytable(id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText) VALUES "
+ "(4, 'string4', 4, 4, null, null, null, 4.0, 40.0, 'text4')",
"INSERT INTO dummytable(id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText) VALUES "
+ "(5, 'string5', 5, 5, 50, 500, 1, null, null, 'text5')" };
con.createStatement().execute(createTableStatement);
for (String insertSQL : insertStatements) {
con.createStatement().execute(insertSQL);
}
ResultSet rs = con.createStatement().executeQuery(
"SELECT id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText FROM dummytable order by id");
rs.first();
try {
rs.findColumn("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex1) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
try {
rs.getString("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex2) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
try {
rs.getByte("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex2) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
try {
rs.getShort("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex3) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
try {
rs.getInt("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex4) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
try {
rs.getLong("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex5) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
try {
rs.getBoolean("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex6) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
try {
rs.getFloat("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex7) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
try {
rs.getDouble("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex8) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
try {
rs.getBlob("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex9) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
try {
rs.getObject("blahblah");
fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
} catch (IllegalArgumentException ex10) {
// OK
} catch (Exception e) {
fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
}
assertEquals("Value for id", 1, rs.getInt("id"));
assertEquals("Value for aString", "string1", rs.getString("aString"));
assertEquals("Value for aByte", 1, rs.getByte("aByte"));
assertEquals("Value for aShort", 1, rs.getShort("aShort"));
assertEquals("Value for anInt", 10, rs.getInt("anInt"));
assertEquals("Value for aLong", 100, rs.getLong("aLong"));
assertEquals("Value for aBool", false, rs.getBoolean("aBool"));
// Compare strings to avoid Float precision problems
assertEquals("Value for aFloat", "1.0",
Float.valueOf(rs.getFloat("aFloat")).toString());
assertFalse("Current value for aFloat is null", rs.wasNull());
assertEquals("Value for aDouble", 10.0, rs.getDouble("aDouble"), 0.01);
assertFalse("Current value for aDouble is null", rs.wasNull());
assertEquals("Value for aText", "text1", rs.getString("aText"));
rs.next(); // 2nd Row
// No values should be null in this row
assertEquals("Value for id", 2, rs.getInt(1));
assertEquals("Value for aString", "string2", rs.getString(2));
assertEquals("Value for aByte", 2, rs.getByte(3));
assertEquals("Value for aShort", 2, rs.getShort(4));
assertEquals("Value for anInt", 20, rs.getInt(5));
assertEquals("Value for aLong", 200, rs.getLong(6));
assertEquals("Value for aBool", true, rs.getBoolean(7));
// Compare strings to avoid Float precision problems
assertEquals("Value for aFloat", "2.0",
Float.valueOf(rs.getFloat(8)).toString());
assertFalse("Current value for aFloat is null", rs.wasNull());
assertEquals("Value for aDouble", 20.0, rs.getDouble(9), 0.01);
assertFalse("Current value for aDouble is null", rs.wasNull());
assertEquals("Value for aText", "text2", rs.getString(10));
rs.next(); // 3rd row
// Values for aString, aByte, aShort and aText should be null in this row
assertEquals("Value for id", 3, rs.getInt(1));
assertEquals("Value for aString", null, rs.getString(2));
assertTrue("Current value for aStrnig is not null", rs.wasNull());
assertEquals("Value for aByte", null, rs.getString(3));
assertTrue("Current value for aByte is not null", rs.wasNull());
assertEquals("Value for aShort", null, rs.getString("aShort"));
assertTrue("Current value for aShort is not null", rs.wasNull());
assertEquals("Value for aText", null, rs.getString("aText"));
assertTrue("Current value for aText is not null", rs.wasNull());
rs.last(); // 5th row
// Values for aFloat and aDouble columns should be null in this row
assertEquals("Value for id", 5, rs.getInt(1));
assertEquals("Value for aString", "string5", rs.getString(2));
assertFalse("Current value is null", rs.wasNull());
assertEquals("Value for aBool", true, rs.getBoolean("aBool"));
assertFalse("Current value is null", rs.wasNull());
// Compare strings to avoid Float precision problems
assertEquals("Value for aFloat", "0.0",
Float.valueOf(rs.getFloat("aFloat")).toString()); // a null float column value is returned as 0.0
assertTrue("Current value for aFloat is not null", rs.wasNull());
assertEquals("Value for aDouble", 0.0, rs.getDouble("aDouble"), 0.01); // a null double column value is returned as 0.0
assertTrue("Current value for aDouble is not null", rs.wasNull());
assertEquals("Enough rows ", insertStatements.length, rs.getRow());
rs.previous(); // 4th row
// Values for anInt, aLong and aBool columns should be null in this row
assertEquals("Value for id", 4, rs.getInt(1));
rs.getInt("anInt");
assertTrue("Current value for anInt is not null", rs.wasNull());
rs.getLong("aLong");
assertTrue("Current value for aLong is not null", rs.wasNull());
rs.getBoolean("aBool");
assertTrue("Current value for aBool is not null", rs.wasNull());
rs.close();
}
@Test
public void testExecute () throws Exception {
String dbName = "executetest.db";
String dbFile = DB_DIRECTORY + dbName;
setupDatabaseFileAndJDBCDriver(dbFile);
Connection con = DriverManager.getConnection(JDBC_URL_PREFIX + dbFile);
con.createStatement().execute(createTable);
for ( String insertSQL : inserts ) {
con.createStatement().execute(insertSQL);
}
Statement statement = con.createStatement();
boolean hasResultSet = statement.execute("SELECT * FROM dummytable order by value");
assertTrue("Should return a result set", hasResultSet);
assertEquals ("Should be -1 ", -1, statement.getUpdateCount());
assertNotNull ("Result Set should be non-null ", statement.getResultSet());
// second time this will be true.
boolean noMoreResults = ((statement.getMoreResults() == false) && (statement.getUpdateCount() == -1));
assertTrue("Should be no more results ", noMoreResults);
assertNull ("Result Set should be non-null ", statement.getResultSet());
statement.close();
statement = con.createStatement();
hasResultSet = statement.execute("SELECT * FROM dummytable where name = 'fig'"); // no matching result
assertNotNull ("Result Set should not be null ", statement.getResultSet());
assertEquals ("Should not be -1 ", -1, statement.getUpdateCount());
// second time this will be true.
noMoreResults = ((statement.getMoreResults() == false) && (statement.getUpdateCount() == -1));
assertTrue("Should be no more results ", noMoreResults);
assertNull ("Result Set should be null - no results ", statement.getResultSet());
statement.close();
PreparedStatement stmt = con.prepareStatement("SELECT ?,? FROM dummytable order by ?");
stmt.setString(1, "name");
stmt.setString(2, "value");
stmt.setString(3, "value");
hasResultSet = stmt.execute();
assertTrue("Should return a result set", hasResultSet);
assertEquals ("Should not be -1 ", -1, stmt.getUpdateCount());
// second time this will be true.
noMoreResults = ((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1));
assertTrue("Should be no more results ", noMoreResults);
assertNull ("Result Set should be null ", stmt.getResultSet()); // no more results
stmt.close();
stmt = con.prepareStatement("SELECT * FROM dummytable where name = 'fig'");
hasResultSet = stmt.execute(); // no matching result but an empty Result Set should be returned
assertTrue("Should return a result set", hasResultSet);
assertNotNull ("Result Set should not be null ", stmt.getResultSet());
assertEquals ("Should not be -1 ", -1, stmt.getUpdateCount());
// second time this will be true.
noMoreResults = ((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1));
assertTrue("Should be no more results ", noMoreResults);
assertNull ("Result Set should be null - no results ", stmt.getResultSet());
stmt.close();
stmt = con.prepareStatement("update dummytable set name='Kumquat' where name = 'Orange' OR name = 'Kiwi'");
stmt.execute();
assertEquals ("To Rows updated ", 2, stmt.getUpdateCount());
for ( String insertSQL : inserts ) {
Statement s = con.createStatement();
s.execute(insertSQL);
assertEquals ("To Rows updated ", 1, s.getUpdateCount());
}
int rows = stmt.executeUpdate();
assertEquals ("To Rows updated ", 2, rows);
assertEquals ("To Rows updated ", 2, stmt.getUpdateCount());
stmt.close();
for ( String insertSQL : inserts ) {
stmt = con.prepareStatement(insertSQL);
stmt.execute();
assertEquals ("To Rows updated ", 1, stmt.getUpdateCount());
}
statement = con.createStatement();
hasResultSet = statement.execute("update dummytable set name='Kumquat' where name = 'Orange' OR name = 'Kiwi'"); // no matching result
assertFalse("Should not return a result set", hasResultSet);
for ( String insertSQL : inserts ) {
con.createStatement().execute(insertSQL);
}
int r1 = statement.executeUpdate("update dummytable set name='Kumquat' where name = 'Orange' OR name = 'Kiwi'"); // no matching result
assertEquals ("To Rows updated ", 2, statement.getUpdateCount());
assertEquals ("To Rows updated ", 2, r1);
statement.close();
statement = con.createStatement();
for ( String insertSQL : inserts ) {
con.createStatement().execute(insertSQL);
}
int numRows = statement.executeUpdate("DELETE FROM dummytable where name = 'Orange' OR name = 'Kiwi'"); // 2 rows should be deleted
assertEquals ("Two Rows deleted ", 2, numRows);
stmt = con.prepareStatement("SELECT * FROM dummytable where name = 'Banana'");
ResultSet rs = stmt.executeQuery();
int rowCount = 0;
if (rs.last()) {
rowCount = rs.getRow();
}
rs.close();
// System.out.println("Num Banana rows=" + rowCount);
numRows = statement.executeUpdate("DELETE FROM dummytable where name = 'Banana'");
assertEquals ("Banana rows deleted ", rowCount, numRows);
}
public void checkResultSet ( ResultSet rs, boolean isClosed, boolean isBeforeFirst, boolean isAfterLast,boolean isFirst,boolean isLast) throws Exception {
assertEquals ("Is Closed", isClosed, rs.isClosed());
assertEquals ("Is Before First", isBeforeFirst, rs.isBeforeFirst());
assertEquals ("Is after Last", isAfterLast, rs.isAfterLast());
assertEquals("Is First", isFirst, rs.isFirst());
assertEquals ("Is Laset", isLast, rs.isLast());
}
public void checkValues (ResultSet rs, String fruit, int value ) throws Exception {
assertEquals ("Fruit", fruit, rs.getString(1));
assertEquals ("Value", value, rs.getInt(2));
}
@Test
public void testMetaData () throws Exception {
String dbName = "schematest.db";
String dbFile = DB_DIRECTORY + dbName;
setupDatabaseFileAndJDBCDriver(dbFile);
Connection con = DriverManager.getConnection(JDBC_URL_PREFIX + dbFile);
// drop the tables - database is new so this isn't necessary
// con.createStatement().execute("DROP TABLE PASTIMES");
// con.createStatement().execute("DROP TABLE STRIP_PASTIMES");
// con.createStatement().execute("DROP VIEW PERCENTAGES");
con.createStatement().execute("CREATE TABLE PASTIMES (count INT, pastime CHAR(200))");
con.createStatement().execute("CREATE TABLE STRIP_PASTIMES (count INT, pastime CHAR(200))");
// "pingpong", "4,750,000 " "1,360,000" on 5/16/2011
// "chess" "90,500,000", "6,940,000"
// "poker" "353,000,000", "9,230,000"
con.createStatement().execute("INSERT INTO PASTIMES (count, pastime) VALUES (4750000, 'pingpong')");
con.createStatement().execute("INSERT INTO PASTIMES (count, pastime) VALUES (90500000, 'chess')");
con.createStatement().execute("INSERT INTO PASTIMES (count, pastime) VALUES (353000000, 'poker')");
con.createStatement().execute("INSERT INTO STRIP_PASTIMES (count, pastime) VALUES (1360000, 'pingpong')");
con.createStatement().execute("INSERT INTO STRIP_PASTIMES (count, pastime) VALUES (6940000, 'chess')");
con.createStatement().execute("INSERT INTO STRIP_PASTIMES (count, pastime) VALUES (9230000, 'poker')");
con.createStatement().execute("CREATE VIEW PERCENTAGES AS SELECT PASTIMES.pastime, PASTIMES.count , STRIP_PASTIMES.count as stripcount, "+
" (CAST(STRIP_PASTIMES.count AS REAL)/PASTIMES.count*100.00) as percent FROM PASTIMES, STRIP_PASTIMES " +
" WHERE PASTIMES.pastime = STRIP_PASTIMES.pastime");
ResultSet rs = con.getMetaData().getTables(null, null, "%", new String[] {"table"});
// rs.next() returns true is there is 1 or more rows
// should be two tables
List<String> tableNames = new ArrayList<String>(Arrays.asList(new String[]{"PASTIMES", "STRIP_PASTIMES"}));
while ( rs.next() ) {
System.err.println ("Table Name \"" + rs.getString("TABLE_NAME") + "\" also \"" + rs.getString(3) + "\"");
assertTrue ("Table must be in the list" , tableNames.remove(rs.getString(3)) );
}
assertEquals ("All tables accounted for", 0, tableNames.size());
rs = con.getMetaData().getTables(null, null, "%", new String[] {"view"});
List<String> viewNames = new ArrayList<String>(Arrays.asList(new String[]{"PERCENTAGES"})); // only one, not a very good test
while ( rs.next() ) {
assertTrue ("View must be in the list" , viewNames.remove(rs.getString("TABLE_NAME")) ); // mix up name and index
System.err.println ("View Name \"" + rs.getString("TABLE_NAME") + "\" also \"" + rs.getString(3) + "\"");
}
assertEquals ("All views accounted for", 0, viewNames.size());
rs = con.getMetaData().getTables(null, null, "%", new String[] {"view","table"});
List<String> allNames = new ArrayList<String>(Arrays.asList(new String[]{"PERCENTAGES","PASTIMES", "STRIP_PASTIMES"})); // all of the views and tables.
while ( rs.next() ) {
System.err.println ("View or Table Name \"" + rs.getString("TABLE_NAME") + "\" also \"" + rs.getString(3) + "\"");
assertTrue ("View/Table must be in the list" , allNames.remove(rs.getString("TABLE_NAME")) ); // mix up name and index
}
assertEquals ("All views/tables accounted for", 0, viewNames.size());
rs = con.getMetaData().getColumns(null, null, "%", "%");
String[] columnNames = new String[]{"count","pastime","count","pastime","pastime","count","stripcount","percent"}; // I think I should get these, but I'm not sure
int columnCounter = 0;
while ( rs.next() ) {
System.err.println ("Column Name \"" + rs.getString("COLUMN_NAME") + "\" also \"" + rs.getString(4) + "\" type " + rs.getInt(5));
// Column Name "count" also "count" type 4
// Column Name "pastime" also "pastime" type 12
// Column Name "count" also "count" type 4
// Column Name "pastime" also "pastime" type 12
// Column Name "pastime" also "pastime" type 12
// Column Name "count" also "count" type 4
// Column Name "stripcount" also "stripcount" type 4
// Column Name "percent" also "percent" type 0
assertEquals ("All columns accounted for", columnNames[columnCounter], rs.getString("COLUMN_NAME"));
assertEquals ("All columns accounted for", columnNames[columnCounter], rs.getString(4));
columnCounter++;
}
rs = con.createStatement().executeQuery("SELECT * FROM PERCENTAGES ORDER BY percent");
while(rs.next()) {
int count = rs.getMetaData().getColumnCount();
List<String> viewColumnNames = new ArrayList<String>(Arrays.asList(new String[]{"pastime", "count", "stripcount"}));
for ( int counter = 0 ; counter < count ; counter++ ) {
System.err.print(" " + rs.getMetaData().getColumnName(counter+1) + " = " + rs.getString(counter+1));
// pastime = poker count = 353000000 stripcount = 9230000 percent = 2.61473087818697
// pastime = chess count = 90500000 stripcount = 6940000 percent = 7.66850828729282
// pastime = pingpong count = 4750000 stripcount = 1360000 percent = 28.6315789473684
//assertTrue ("Column Name must be in the list" , viewColumnNames.remove(rs.getString("COLUMN_NAME")) ); // mix up name and index
}
// assertEquals ("All columns accounted for", 0, viewColumnNames.size());
System.err.println ();
}
rs.close();
rs = con.createStatement().executeQuery("SELECT * FROM PASTIMES");
List<String> tableColumnNames = new ArrayList<String>(Arrays.asList(new String[]{"pastime", "count"}));
while(rs.next()) {
int count = rs.getMetaData().getColumnCount();
for ( int counter = 0 ; counter < count ; counter++ ) {
//assertTrue ("Table Column Name must be in the list" , tableColumnNames.remove(rs.getString(4)) ); // mix up name and index
System.err.print(" " + rs.getMetaData().getColumnName(counter+1) + " = " + rs.getString(counter+1));
}
//assertEquals ("All columns accounted for", 0, tableColumnNames.size());
System.err.println ();
}
rs.close();
}
@Test
public void testAutoCommit() throws Exception {
String dbName = "autocommittest.db";
String dbFile = DB_DIRECTORY + dbName;
setupDatabaseFileAndJDBCDriver(dbFile);
String jdbcURL = JDBC_URL_PREFIX + dbFile;
Properties removeLocale = new Properties();
removeLocale.put(SQLDroidDriver.ADDITONAL_DATABASE_FLAGS, android.database.sqlite.SQLiteDatabase.NO_LOCALIZED_COLLATORS);
Connection conn1 = DriverManager.getConnection(jdbcURL,removeLocale);
System.out.println("After getting connection...1");
conn1.setAutoCommit(true);
Connection conn2 = DriverManager.getConnection(jdbcURL);
System.out.println("After getting connection...2");
conn1.setAutoCommit(false);
Connection conn3 = DriverManager.getConnection(jdbcURL);
System.out.println("After getting connection...3");
Statement stat = conn1.createStatement();
// Create table if not already there
stat.executeUpdate("create table if not exists primes (number int);");
// Delete any existing records
stat.executeUpdate("delete from primes;");
// Populate table
stat.executeUpdate("insert into primes values (2);");
stat.executeUpdate("insert into primes values (3);");
stat.executeUpdate("insert into primes values (5);");
stat.executeUpdate("insert into primes values (7);");
// Retrieve records
ResultSet rs = stat.executeQuery("select * from primes");
boolean b = rs.first();
while (b) {
String info = "Prime=" + rs.getInt(1);
System.out.println(info);
b = rs.next();
}
conn1.close();
conn2.close();
conn3.close();
}
}
| src/test/java/org/sqldroid/DriverUnitTest.java | Port existing tests to Robolectric | src/test/java/org/sqldroid/DriverUnitTest.java | Port existing tests to Robolectric | <ide><path>rc/test/java/org/sqldroid/DriverUnitTest.java
<add>package org.sqldroid;
<add>
<add>import java.io.ByteArrayInputStream;
<add>import java.io.File;
<add>import java.sql.Blob;
<add>import java.sql.Connection;
<add>import java.sql.Driver;
<add>import java.sql.DriverManager;
<add>import java.sql.PreparedStatement;
<add>import java.sql.ResultSet;
<add>import java.sql.Statement;
<add>import java.util.ArrayList;
<add>import java.util.Arrays;
<add>import java.util.List;
<add>import java.util.Properties;
<add>
<add>
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>import static org.junit.Assert.*;
<add>import org.robolectric.RobolectricTestRunner;
<add>import org.robolectric.annotation.Config;
<add>
<add>
<add>@RunWith(RobolectricTestRunner.class)
<add>@Config(sdk = 16)
<add>public class DriverUnitTest {
<add>
<add> /** Going to use SQLDroid JDBC Driver */
<add> protected String driverName = "org.sqldroid.SQLDroidDriver";
<add>
<add> /** Common prefix for creating JDBC URL */
<add> protected String JDBC_URL_PREFIX = "jdbc:sqlite:";
<add>
<add> /** Package name of this app */
<add> protected String packageName = "org.sqldroid";
<add>
<add> /** Database file directory for this app on Android */
<add> protected String DB_DIRECTORY = "/data/data/" + packageName + "/databases/";
<add>
<add> /** Name of an in-memory database */
<add> protected String dummyDatabase = "dummydatabase.db";
<add>
<add> /** The URL to the in-memory database. */
<add> protected String databaseURL = JDBC_URL_PREFIX + dummyDatabase;
<add>
<add> /** The table create statement. */
<add> protected String createTable = "CREATE TABLE dummytable (name VARCHAR(254), value int)";
<add>
<add> /** Some data for the table. */
<add> protected String[] inserts = {
<add> "INSERT INTO dummytable(name,value) VALUES('Apple', 100)",
<add> "INSERT INTO dummytable(name,value) VALUES('Orange', 200)",
<add> "INSERT INTO dummytable(name,value) VALUES('Banana', 300)",
<add> "INSERT INTO dummytable(name,value) VALUES('Kiwi', 400)"};
<add>
<add> /** A select statement. */
<add> protected String select = "SELECT * FROM dummytable WHERE value < 250";
<add>
<add> /**
<add> * Creates the directory structure for the database file and loads the JDBC driver.
<add> * @param dbFile the database file name
<add> * @throws Exception
<add> */
<add> protected void setupDatabaseFileAndJDBCDriver(String dbFile) throws Exception {
<add> // If the database file already exists, delete it, else create the parent directory for it.
<add> File f = new File(dbFile);
<add> if ( f.exists() ) {
<add> f.delete();
<add> } else {
<add> if (null != f.getParent()) {
<add> f.getParentFile().mkdirs();
<add> }
<add> }
<add> // Loads and registers the JDBC driver
<add> DriverManager.registerDriver((Driver)(Class.forName(driverName, true, getClass().getClassLoader()).newInstance()));
<add> }
<add>
<add> public Blob selectBlob (Connection con, int key) throws Exception {
<add> PreparedStatement stmt = con.prepareStatement("SELECT value,key FROM blobtest where key = ?");
<add> stmt.setInt(1, key);
<add> ResultSet rs = stmt.executeQuery();
<add> assertTrue ("Executed", rs != null);
<add> rs.next();
<add> System.err.println ("blob record \"" + rs.getBlob(1).toString() + "\" key " + rs.getString(2) );
<add> assertTrue (" Only one record ", rs.isLast());
<add> Blob b = rs.getBlob(1);
<add> return b;
<add> }
<add>
<add> /** Test the serialization of the various value objects. */
<add> @Test
<add> public void testBlob () throws Exception {
<add> String dbName = "bolbtest.db";
<add> String dbFile = DB_DIRECTORY + dbName;
<add> setupDatabaseFileAndJDBCDriver(dbFile);
<add>
<add> Connection con = DriverManager.getConnection(JDBC_URL_PREFIX + dbFile);
<add>
<add> con.createStatement().execute("create table blobtest (key int, value blob)");
<add>
<add> // create a blob
<add> final int blobSize = 70000;
<add> byte[] aBlob = new byte[blobSize];
<add> for ( int counter = 0 ; counter < blobSize ; counter++ ) {
<add> aBlob[counter] = (byte)(counter %10);
<add> }
<add> final int blobSize1 = 1024;
<add> byte[] aBlob1 = new byte[blobSize1];
<add> for ( int counter = 0 ; counter < blobSize1 ; counter++ ) {
<add> aBlob1[counter] = (byte)(counter %10 + 0x30);
<add> }
<add>
<add> final String stringBlob = "ABlob";
<add> /** Some data for the table. */
<add> final String[] blobInserts = {
<add> "INSERT INTO blobtest(key,value) VALUES (101, '"+stringBlob+"')",
<add> "INSERT INTO blobtest(key,value) VALUES (?, ?)",
<add> "INSERT INTO blobtest(key,value) VALUES (?, ?)",
<add> "INSERT INTO blobtest(key,value) VALUES (401, ?)"};
<add>
<add> System.out.println("Insert statement is:" + blobInserts[0]);
<add> con.createStatement().execute(blobInserts[0]);
<add> Blob b = selectBlob(con, 101);
<add>
<add> // FAILS - was this already a problem?
<add> //assertEquals ("String blob", stringBlob, new String(b.getBytes(1, (int)b.length())));
<add>
<add> PreparedStatement stmt = con.prepareStatement(blobInserts[1]);
<add> stmt.setInt(1, blobSize);
<add> stmt.setBinaryStream(2, new ByteArrayInputStream(aBlob),aBlob.length);
<add> stmt.execute();
<add> b = selectBlob(con, blobSize);
<add> assertEquals (" Correct Length ", blobSize, b.length());
<add> byte[] bytes = b.getBytes(0, blobSize);
<add> for ( int counter = 0 ; counter < blobSize ; counter++ ) {
<add> assertEquals(" Blob Element "+ counter, (counter %10), bytes[counter]);
<add> }
<add>
<add> stmt = con.prepareStatement(blobInserts[2]);
<add> stmt.setInt(1, blobSize1);
<add> stmt.setBinaryStream(2, new ByteArrayInputStream(aBlob1),aBlob1.length);
<add> stmt.execute();
<add> b = selectBlob(con, blobSize1);
<add> assertEquals (" Correct 1 Length ", blobSize1, b.length());
<add> byte[] bytes1 = b.getBytes(0, blobSize1);
<add> for ( int counter = 0 ; counter < blobSize1 ; counter++ ) {
<add> assertEquals(" Blob1 Element "+ counter, (counter %10 + 0x30), bytes1[counter]);
<add> }
<add>
<add> stmt = con.prepareStatement(blobInserts[3]);
<add> stmt.setBinaryStream(1, new ByteArrayInputStream(aBlob),aBlob.length);
<add> stmt.execute();
<add> b = selectBlob(con, 401);
<add> assertEquals (" Correct Length ", blobSize, b.length());
<add> bytes = b.getBytes(0, blobSize);
<add> for ( int counter = 0 ; counter < blobSize ; counter++ ) {
<add> assertEquals(" Blob Element "+ counter, (counter %10), bytes[counter]);
<add> }
<add>
<add> }
<add>
<add> @Test
<add> public void testCursors () throws Exception {
<add> String dbName = "cursortest.db";
<add> String dbFile = DB_DIRECTORY + dbName;
<add> setupDatabaseFileAndJDBCDriver(dbFile);
<add>
<add> Connection con = DriverManager.getConnection(JDBC_URL_PREFIX + dbFile);
<add>
<add> con.createStatement().execute(createTable);
<add>
<add> for ( String insertSQL : inserts ) {
<add> con.createStatement().execute(insertSQL);
<add> }
<add>
<add> ResultSet rs = con.createStatement().executeQuery("SELECT * FROM dummytable order by value");
<add> checkResultSet ( rs, false, true, false, false, false);
<add> rs.next();
<add> checkResultSet ( rs, false, false, false, true, false);
<add> checkValues (rs, "Apple", 100);
<add> rs.next();
<add> checkResultSet ( rs, false, false, false, false, false);
<add> checkValues (rs, "Orange", 200);
<add> rs.next();
<add> checkResultSet ( rs, false, false, false, false, false);
<add> checkValues (rs, "Banana", 300);
<add> rs.next(); // to last
<add> checkResultSet ( rs, false, false, false, false, true);
<add> checkValues (rs, "Kiwi", 400);
<add> rs.next(); // after last
<add> checkResultSet ( rs, false, false, true, false, false);
<add> rs.first();
<add> checkResultSet ( rs, false, false, false, true, false);
<add> rs.last();
<add> checkResultSet ( rs, false, false, false, false, true);
<add> rs.afterLast();
<add> checkResultSet ( rs, false, false, true, false, false);
<add> rs.beforeFirst();
<add> checkResultSet ( rs, false, true, false, false, false);
<add> rs.close();
<add> checkResultSet ( rs, true, false, false, false, false);
<add> PreparedStatement stmt = con.prepareStatement("SELECT ?,? FROM dummytable order by ?");
<add> stmt.setString(1, "name");
<add> stmt.setString(2, "value");
<add> stmt.setString(3, "value");
<add> rs = stmt.executeQuery();
<add> assertTrue ("Executed", rs != null);
<add> rs.last();
<add> assertEquals("Enough rows ", 4, rs.getRow());
<add> rs.close();
<add>
<add> // Add a null value for name
<add> con.createStatement().execute("INSERT INTO dummytable(name, value) VALUES(null, 500)");
<add>
<add> rs = con.createStatement().executeQuery("SELECT name, value FROM dummytable order by value");
<add> assertEquals("Name column position", 1, rs.findColumn("name"));
<add> assertEquals("Value column position", 2, rs.findColumn("value"));
<add>
<add> // In the first row, name is Apple and value is 100.
<add> assertTrue("Cursor on the first row", rs.first());
<add> assertEquals("Name in the first row using column name", "Apple", rs.getString("name"));
<add> assertFalse("Current name is null", rs.wasNull());
<add> assertEquals("Value in the first row using column name", 100, rs.getInt("value"));
<add> assertFalse("Current value is null", rs.wasNull());
<add> assertEquals("Name in the first row using column number", "Apple", rs.getString(1));
<add> assertEquals("Value in the first row using column number", 100, rs.getInt(2));
<add> assertFalse("Current value for Apple is null", rs.wasNull());
<add>
<add> // In the second row, name is Orange and value is 200.
<add> rs.next();
<add> assertEquals("Name in the second row using column name", "Orange", rs.getString("name"));
<add> assertEquals("Value in the second row using column name", 200, rs.getInt("value"));
<add> assertFalse("Current value for Banana is null", rs.wasNull());
<add> assertEquals("Name in the second row using column number", "Orange", rs.getString(1));
<add> assertEquals("Value in the second row using column number", 200, rs.getInt(2));
<add> assertFalse("Current value for Banana is null", rs.wasNull());
<add>
<add> // In the last row, name is null and value is 500.
<add> rs.last();
<add> assertEquals("Name in the last row using column name", null, rs.getString("name"));
<add> assertTrue("Current name is not null", rs.wasNull());
<add> assertEquals("Value in the last row using column name", 500, rs.getInt("value"));
<add> assertFalse("Current value is null", rs.wasNull());
<add> assertEquals("Name in the last row using column number", null, rs.getString(1));
<add> assertTrue("Current name is not null", rs.wasNull());
<add> assertEquals("Value in the last row using column number", 500, rs.getInt(2));
<add> assertFalse("Current value is null", rs.wasNull());
<add>
<add> rs.close();
<add> }
<add>
<add> @Test
<add> public void testResultSets() throws Exception {
<add> String dbName = "resultsetstest.db";
<add> String dbFile = DB_DIRECTORY + dbName;
<add> setupDatabaseFileAndJDBCDriver(dbFile);
<add>
<add> Connection con = DriverManager.getConnection(JDBC_URL_PREFIX + dbFile);
<add>
<add> String createTableStatement = "CREATE TABLE dummytable (id int, aString VARCHAR(254), aByte byte, "
<add> + "aShort short, anInt int, aLong long, aBool boolean, aFloat float, aDouble, double, aText text)";
<add>
<add> final String[] insertStatements = {
<add> "INSERT INTO dummytable(id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText) VALUES "
<add> + "(1, 'string1', 1, 1, 10, 100, 0, 1.0, 10.0, 'text1')",
<add> "INSERT INTO dummytable(id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText) VALUES "
<add> + "(2, 'string2', 2, 2, 20, 200, 1, 2.0, 20.0, 'text2')",
<add> "INSERT INTO dummytable(id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText) VALUES "
<add> + "(3, null, null, null, 30, 300, 0, 3.0, 30.0, null)",
<add> "INSERT INTO dummytable(id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText) VALUES "
<add> + "(4, 'string4', 4, 4, null, null, null, 4.0, 40.0, 'text4')",
<add> "INSERT INTO dummytable(id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText) VALUES "
<add> + "(5, 'string5', 5, 5, 50, 500, 1, null, null, 'text5')" };
<add>
<add> con.createStatement().execute(createTableStatement);
<add> for (String insertSQL : insertStatements) {
<add> con.createStatement().execute(insertSQL);
<add> }
<add>
<add> ResultSet rs = con.createStatement().executeQuery(
<add> "SELECT id, aString, aByte, aShort, anInt, aLong, aBool, aFloat, aDouble, aText FROM dummytable order by id");
<add>
<add> rs.first();
<add> try {
<add> rs.findColumn("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex1) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> try {
<add> rs.getString("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex2) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> try {
<add> rs.getByte("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex2) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> try {
<add> rs.getShort("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex3) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> try {
<add> rs.getInt("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex4) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> try {
<add> rs.getLong("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex5) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> try {
<add> rs.getBoolean("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex6) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> try {
<add> rs.getFloat("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex7) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> try {
<add> rs.getDouble("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex8) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> try {
<add> rs.getBlob("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex9) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> try {
<add> rs.getObject("blahblah");
<add> fail("Should have thrown an IllegalArgumentException because of an non-existent column name blahblah");
<add> } catch (IllegalArgumentException ex10) {
<add> // OK
<add> } catch (Exception e) {
<add> fail("Only IllegalArgumentException expected for a non-existent column name blahblah");
<add> }
<add>
<add> assertEquals("Value for id", 1, rs.getInt("id"));
<add> assertEquals("Value for aString", "string1", rs.getString("aString"));
<add> assertEquals("Value for aByte", 1, rs.getByte("aByte"));
<add> assertEquals("Value for aShort", 1, rs.getShort("aShort"));
<add> assertEquals("Value for anInt", 10, rs.getInt("anInt"));
<add> assertEquals("Value for aLong", 100, rs.getLong("aLong"));
<add> assertEquals("Value for aBool", false, rs.getBoolean("aBool"));
<add>
<add> // Compare strings to avoid Float precision problems
<add> assertEquals("Value for aFloat", "1.0",
<add> Float.valueOf(rs.getFloat("aFloat")).toString());
<add> assertFalse("Current value for aFloat is null", rs.wasNull());
<add>
<add> assertEquals("Value for aDouble", 10.0, rs.getDouble("aDouble"), 0.01);
<add> assertFalse("Current value for aDouble is null", rs.wasNull());
<add> assertEquals("Value for aText", "text1", rs.getString("aText"));
<add>
<add> rs.next(); // 2nd Row
<add> // No values should be null in this row
<add> assertEquals("Value for id", 2, rs.getInt(1));
<add> assertEquals("Value for aString", "string2", rs.getString(2));
<add> assertEquals("Value for aByte", 2, rs.getByte(3));
<add> assertEquals("Value for aShort", 2, rs.getShort(4));
<add> assertEquals("Value for anInt", 20, rs.getInt(5));
<add> assertEquals("Value for aLong", 200, rs.getLong(6));
<add> assertEquals("Value for aBool", true, rs.getBoolean(7));
<add>
<add> // Compare strings to avoid Float precision problems
<add> assertEquals("Value for aFloat", "2.0",
<add> Float.valueOf(rs.getFloat(8)).toString());
<add> assertFalse("Current value for aFloat is null", rs.wasNull());
<add>
<add> assertEquals("Value for aDouble", 20.0, rs.getDouble(9), 0.01);
<add> assertFalse("Current value for aDouble is null", rs.wasNull());
<add> assertEquals("Value for aText", "text2", rs.getString(10));
<add>
<add> rs.next(); // 3rd row
<add> // Values for aString, aByte, aShort and aText should be null in this row
<add> assertEquals("Value for id", 3, rs.getInt(1));
<add> assertEquals("Value for aString", null, rs.getString(2));
<add> assertTrue("Current value for aStrnig is not null", rs.wasNull());
<add> assertEquals("Value for aByte", null, rs.getString(3));
<add> assertTrue("Current value for aByte is not null", rs.wasNull());
<add> assertEquals("Value for aShort", null, rs.getString("aShort"));
<add> assertTrue("Current value for aShort is not null", rs.wasNull());
<add> assertEquals("Value for aText", null, rs.getString("aText"));
<add> assertTrue("Current value for aText is not null", rs.wasNull());
<add>
<add> rs.last(); // 5th row
<add> // Values for aFloat and aDouble columns should be null in this row
<add> assertEquals("Value for id", 5, rs.getInt(1));
<add> assertEquals("Value for aString", "string5", rs.getString(2));
<add> assertFalse("Current value is null", rs.wasNull());
<add> assertEquals("Value for aBool", true, rs.getBoolean("aBool"));
<add> assertFalse("Current value is null", rs.wasNull());
<add>
<add> // Compare strings to avoid Float precision problems
<add> assertEquals("Value for aFloat", "0.0",
<add> Float.valueOf(rs.getFloat("aFloat")).toString()); // a null float column value is returned as 0.0
<add>
<add> assertTrue("Current value for aFloat is not null", rs.wasNull());
<add>
<add> assertEquals("Value for aDouble", 0.0, rs.getDouble("aDouble"), 0.01); // a null double column value is returned as 0.0
<add> assertTrue("Current value for aDouble is not null", rs.wasNull());
<add>
<add> assertEquals("Enough rows ", insertStatements.length, rs.getRow());
<add>
<add> rs.previous(); // 4th row
<add> // Values for anInt, aLong and aBool columns should be null in this row
<add> assertEquals("Value for id", 4, rs.getInt(1));
<add> rs.getInt("anInt");
<add> assertTrue("Current value for anInt is not null", rs.wasNull());
<add> rs.getLong("aLong");
<add> assertTrue("Current value for aLong is not null", rs.wasNull());
<add> rs.getBoolean("aBool");
<add> assertTrue("Current value for aBool is not null", rs.wasNull());
<add>
<add> rs.close();
<add> }
<add>
<add> @Test
<add> public void testExecute () throws Exception {
<add> String dbName = "executetest.db";
<add> String dbFile = DB_DIRECTORY + dbName;
<add> setupDatabaseFileAndJDBCDriver(dbFile);
<add>
<add> Connection con = DriverManager.getConnection(JDBC_URL_PREFIX + dbFile);
<add>
<add> con.createStatement().execute(createTable);
<add>
<add> for ( String insertSQL : inserts ) {
<add> con.createStatement().execute(insertSQL);
<add> }
<add>
<add> Statement statement = con.createStatement();
<add> boolean hasResultSet = statement.execute("SELECT * FROM dummytable order by value");
<add> assertTrue("Should return a result set", hasResultSet);
<add> assertEquals ("Should be -1 ", -1, statement.getUpdateCount());
<add> assertNotNull ("Result Set should be non-null ", statement.getResultSet());
<add> // second time this will be true.
<add> boolean noMoreResults = ((statement.getMoreResults() == false) && (statement.getUpdateCount() == -1));
<add> assertTrue("Should be no more results ", noMoreResults);
<add> assertNull ("Result Set should be non-null ", statement.getResultSet());
<add> statement.close();
<add>
<add> statement = con.createStatement();
<add> hasResultSet = statement.execute("SELECT * FROM dummytable where name = 'fig'"); // no matching result
<add> assertNotNull ("Result Set should not be null ", statement.getResultSet());
<add> assertEquals ("Should not be -1 ", -1, statement.getUpdateCount());
<add> // second time this will be true.
<add> noMoreResults = ((statement.getMoreResults() == false) && (statement.getUpdateCount() == -1));
<add> assertTrue("Should be no more results ", noMoreResults);
<add> assertNull ("Result Set should be null - no results ", statement.getResultSet());
<add> statement.close();
<add>
<add> PreparedStatement stmt = con.prepareStatement("SELECT ?,? FROM dummytable order by ?");
<add> stmt.setString(1, "name");
<add> stmt.setString(2, "value");
<add> stmt.setString(3, "value");
<add> hasResultSet = stmt.execute();
<add> assertTrue("Should return a result set", hasResultSet);
<add> assertEquals ("Should not be -1 ", -1, stmt.getUpdateCount());
<add> // second time this will be true.
<add> noMoreResults = ((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1));
<add> assertTrue("Should be no more results ", noMoreResults);
<add> assertNull ("Result Set should be null ", stmt.getResultSet()); // no more results
<add> stmt.close();
<add>
<add> stmt = con.prepareStatement("SELECT * FROM dummytable where name = 'fig'");
<add> hasResultSet = stmt.execute(); // no matching result but an empty Result Set should be returned
<add> assertTrue("Should return a result set", hasResultSet);
<add> assertNotNull ("Result Set should not be null ", stmt.getResultSet());
<add> assertEquals ("Should not be -1 ", -1, stmt.getUpdateCount());
<add> // second time this will be true.
<add> noMoreResults = ((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1));
<add> assertTrue("Should be no more results ", noMoreResults);
<add> assertNull ("Result Set should be null - no results ", stmt.getResultSet());
<add> stmt.close();
<add>
<add> stmt = con.prepareStatement("update dummytable set name='Kumquat' where name = 'Orange' OR name = 'Kiwi'");
<add> stmt.execute();
<add> assertEquals ("To Rows updated ", 2, stmt.getUpdateCount());
<add> for ( String insertSQL : inserts ) {
<add> Statement s = con.createStatement();
<add> s.execute(insertSQL);
<add> assertEquals ("To Rows updated ", 1, s.getUpdateCount());
<add> }
<add> int rows = stmt.executeUpdate();
<add> assertEquals ("To Rows updated ", 2, rows);
<add> assertEquals ("To Rows updated ", 2, stmt.getUpdateCount());
<add> stmt.close();
<add>
<add> for ( String insertSQL : inserts ) {
<add> stmt = con.prepareStatement(insertSQL);
<add> stmt.execute();
<add> assertEquals ("To Rows updated ", 1, stmt.getUpdateCount());
<add> }
<add>
<add> statement = con.createStatement();
<add> hasResultSet = statement.execute("update dummytable set name='Kumquat' where name = 'Orange' OR name = 'Kiwi'"); // no matching result
<add> assertFalse("Should not return a result set", hasResultSet);
<add> for ( String insertSQL : inserts ) {
<add> con.createStatement().execute(insertSQL);
<add> }
<add> int r1 = statement.executeUpdate("update dummytable set name='Kumquat' where name = 'Orange' OR name = 'Kiwi'"); // no matching result
<add> assertEquals ("To Rows updated ", 2, statement.getUpdateCount());
<add> assertEquals ("To Rows updated ", 2, r1);
<add> statement.close();
<add>
<add> statement = con.createStatement();
<add> for ( String insertSQL : inserts ) {
<add> con.createStatement().execute(insertSQL);
<add> }
<add> int numRows = statement.executeUpdate("DELETE FROM dummytable where name = 'Orange' OR name = 'Kiwi'"); // 2 rows should be deleted
<add> assertEquals ("Two Rows deleted ", 2, numRows);
<add>
<add> stmt = con.prepareStatement("SELECT * FROM dummytable where name = 'Banana'");
<add> ResultSet rs = stmt.executeQuery();
<add> int rowCount = 0;
<add> if (rs.last()) {
<add> rowCount = rs.getRow();
<add> }
<add> rs.close();
<add> // System.out.println("Num Banana rows=" + rowCount);
<add>
<add> numRows = statement.executeUpdate("DELETE FROM dummytable where name = 'Banana'");
<add> assertEquals ("Banana rows deleted ", rowCount, numRows);
<add> }
<add>
<add> public void checkResultSet ( ResultSet rs, boolean isClosed, boolean isBeforeFirst, boolean isAfterLast,boolean isFirst,boolean isLast) throws Exception {
<add> assertEquals ("Is Closed", isClosed, rs.isClosed());
<add> assertEquals ("Is Before First", isBeforeFirst, rs.isBeforeFirst());
<add> assertEquals ("Is after Last", isAfterLast, rs.isAfterLast());
<add> assertEquals("Is First", isFirst, rs.isFirst());
<add> assertEquals ("Is Laset", isLast, rs.isLast());
<add> }
<add>
<add> public void checkValues (ResultSet rs, String fruit, int value ) throws Exception {
<add> assertEquals ("Fruit", fruit, rs.getString(1));
<add> assertEquals ("Value", value, rs.getInt(2));
<add> }
<add>
<add> @Test
<add> public void testMetaData () throws Exception {
<add> String dbName = "schematest.db";
<add> String dbFile = DB_DIRECTORY + dbName;
<add> setupDatabaseFileAndJDBCDriver(dbFile);
<add>
<add> Connection con = DriverManager.getConnection(JDBC_URL_PREFIX + dbFile);
<add>
<add> // drop the tables - database is new so this isn't necessary
<add> // con.createStatement().execute("DROP TABLE PASTIMES");
<add> // con.createStatement().execute("DROP TABLE STRIP_PASTIMES");
<add> // con.createStatement().execute("DROP VIEW PERCENTAGES");
<add>
<add> con.createStatement().execute("CREATE TABLE PASTIMES (count INT, pastime CHAR(200))");
<add> con.createStatement().execute("CREATE TABLE STRIP_PASTIMES (count INT, pastime CHAR(200))");
<add> // "pingpong", "4,750,000 " "1,360,000" on 5/16/2011
<add> // "chess" "90,500,000", "6,940,000"
<add> // "poker" "353,000,000", "9,230,000"
<add> con.createStatement().execute("INSERT INTO PASTIMES (count, pastime) VALUES (4750000, 'pingpong')");
<add> con.createStatement().execute("INSERT INTO PASTIMES (count, pastime) VALUES (90500000, 'chess')");
<add> con.createStatement().execute("INSERT INTO PASTIMES (count, pastime) VALUES (353000000, 'poker')");
<add> con.createStatement().execute("INSERT INTO STRIP_PASTIMES (count, pastime) VALUES (1360000, 'pingpong')");
<add> con.createStatement().execute("INSERT INTO STRIP_PASTIMES (count, pastime) VALUES (6940000, 'chess')");
<add> con.createStatement().execute("INSERT INTO STRIP_PASTIMES (count, pastime) VALUES (9230000, 'poker')");
<add>
<add> con.createStatement().execute("CREATE VIEW PERCENTAGES AS SELECT PASTIMES.pastime, PASTIMES.count , STRIP_PASTIMES.count as stripcount, "+
<add> " (CAST(STRIP_PASTIMES.count AS REAL)/PASTIMES.count*100.00) as percent FROM PASTIMES, STRIP_PASTIMES " +
<add> " WHERE PASTIMES.pastime = STRIP_PASTIMES.pastime");
<add>
<add> ResultSet rs = con.getMetaData().getTables(null, null, "%", new String[] {"table"});
<add> // rs.next() returns true is there is 1 or more rows
<add> // should be two tables
<add> List<String> tableNames = new ArrayList<String>(Arrays.asList(new String[]{"PASTIMES", "STRIP_PASTIMES"}));
<add> while ( rs.next() ) {
<add> System.err.println ("Table Name \"" + rs.getString("TABLE_NAME") + "\" also \"" + rs.getString(3) + "\"");
<add> assertTrue ("Table must be in the list" , tableNames.remove(rs.getString(3)) );
<add> }
<add> assertEquals ("All tables accounted for", 0, tableNames.size());
<add>
<add> rs = con.getMetaData().getTables(null, null, "%", new String[] {"view"});
<add> List<String> viewNames = new ArrayList<String>(Arrays.asList(new String[]{"PERCENTAGES"})); // only one, not a very good test
<add> while ( rs.next() ) {
<add> assertTrue ("View must be in the list" , viewNames.remove(rs.getString("TABLE_NAME")) ); // mix up name and index
<add> System.err.println ("View Name \"" + rs.getString("TABLE_NAME") + "\" also \"" + rs.getString(3) + "\"");
<add> }
<add> assertEquals ("All views accounted for", 0, viewNames.size());
<add>
<add> rs = con.getMetaData().getTables(null, null, "%", new String[] {"view","table"});
<add> List<String> allNames = new ArrayList<String>(Arrays.asList(new String[]{"PERCENTAGES","PASTIMES", "STRIP_PASTIMES"})); // all of the views and tables.
<add> while ( rs.next() ) {
<add> System.err.println ("View or Table Name \"" + rs.getString("TABLE_NAME") + "\" also \"" + rs.getString(3) + "\"");
<add> assertTrue ("View/Table must be in the list" , allNames.remove(rs.getString("TABLE_NAME")) ); // mix up name and index
<add> }
<add> assertEquals ("All views/tables accounted for", 0, viewNames.size());
<add>
<add> rs = con.getMetaData().getColumns(null, null, "%", "%");
<add> String[] columnNames = new String[]{"count","pastime","count","pastime","pastime","count","stripcount","percent"}; // I think I should get these, but I'm not sure
<add> int columnCounter = 0;
<add> while ( rs.next() ) {
<add> System.err.println ("Column Name \"" + rs.getString("COLUMN_NAME") + "\" also \"" + rs.getString(4) + "\" type " + rs.getInt(5));
<add> // Column Name "count" also "count" type 4
<add> // Column Name "pastime" also "pastime" type 12
<add> // Column Name "count" also "count" type 4
<add> // Column Name "pastime" also "pastime" type 12
<add> // Column Name "pastime" also "pastime" type 12
<add> // Column Name "count" also "count" type 4
<add> // Column Name "stripcount" also "stripcount" type 4
<add> // Column Name "percent" also "percent" type 0
<add> assertEquals ("All columns accounted for", columnNames[columnCounter], rs.getString("COLUMN_NAME"));
<add> assertEquals ("All columns accounted for", columnNames[columnCounter], rs.getString(4));
<add> columnCounter++;
<add> }
<add>
<add> rs = con.createStatement().executeQuery("SELECT * FROM PERCENTAGES ORDER BY percent");
<add>
<add> while(rs.next()) {
<add> int count = rs.getMetaData().getColumnCount();
<add> List<String> viewColumnNames = new ArrayList<String>(Arrays.asList(new String[]{"pastime", "count", "stripcount"}));
<add> for ( int counter = 0 ; counter < count ; counter++ ) {
<add> System.err.print(" " + rs.getMetaData().getColumnName(counter+1) + " = " + rs.getString(counter+1));
<add> // pastime = poker count = 353000000 stripcount = 9230000 percent = 2.61473087818697
<add> // pastime = chess count = 90500000 stripcount = 6940000 percent = 7.66850828729282
<add> // pastime = pingpong count = 4750000 stripcount = 1360000 percent = 28.6315789473684
<add> //assertTrue ("Column Name must be in the list" , viewColumnNames.remove(rs.getString("COLUMN_NAME")) ); // mix up name and index
<add> }
<add> // assertEquals ("All columns accounted for", 0, viewColumnNames.size());
<add> System.err.println ();
<add> }
<add> rs.close();
<add>
<add> rs = con.createStatement().executeQuery("SELECT * FROM PASTIMES");
<add> List<String> tableColumnNames = new ArrayList<String>(Arrays.asList(new String[]{"pastime", "count"}));
<add> while(rs.next()) {
<add> int count = rs.getMetaData().getColumnCount();
<add> for ( int counter = 0 ; counter < count ; counter++ ) {
<add> //assertTrue ("Table Column Name must be in the list" , tableColumnNames.remove(rs.getString(4)) ); // mix up name and index
<add> System.err.print(" " + rs.getMetaData().getColumnName(counter+1) + " = " + rs.getString(counter+1));
<add> }
<add> //assertEquals ("All columns accounted for", 0, tableColumnNames.size());
<add> System.err.println ();
<add> }
<add>
<add> rs.close();
<add> }
<add>
<add> @Test
<add> public void testAutoCommit() throws Exception {
<add> String dbName = "autocommittest.db";
<add> String dbFile = DB_DIRECTORY + dbName;
<add> setupDatabaseFileAndJDBCDriver(dbFile);
<add>
<add> String jdbcURL = JDBC_URL_PREFIX + dbFile;
<add>
<add> Properties removeLocale = new Properties();
<add> removeLocale.put(SQLDroidDriver.ADDITONAL_DATABASE_FLAGS, android.database.sqlite.SQLiteDatabase.NO_LOCALIZED_COLLATORS);
<add> Connection conn1 = DriverManager.getConnection(jdbcURL,removeLocale);
<add> System.out.println("After getting connection...1");
<add>
<add> conn1.setAutoCommit(true);
<add>
<add> Connection conn2 = DriverManager.getConnection(jdbcURL);
<add> System.out.println("After getting connection...2");
<add>
<add> conn1.setAutoCommit(false);
<add>
<add> Connection conn3 = DriverManager.getConnection(jdbcURL);
<add> System.out.println("After getting connection...3");
<add>
<add> Statement stat = conn1.createStatement();
<add>
<add> // Create table if not already there
<add> stat.executeUpdate("create table if not exists primes (number int);");
<add>
<add> // Delete any existing records
<add> stat.executeUpdate("delete from primes;");
<add>
<add> // Populate table
<add> stat.executeUpdate("insert into primes values (2);");
<add> stat.executeUpdate("insert into primes values (3);");
<add> stat.executeUpdate("insert into primes values (5);");
<add> stat.executeUpdate("insert into primes values (7);");
<add>
<add> // Retrieve records
<add> ResultSet rs = stat.executeQuery("select * from primes");
<add> boolean b = rs.first();
<add> while (b) {
<add> String info = "Prime=" + rs.getInt(1);
<add> System.out.println(info);
<add> b = rs.next();
<add> }
<add>
<add> conn1.close();
<add> conn2.close();
<add> conn3.close();
<add> }
<add>} |
|
Java | mit | 188c8a75f33346591b466878e214a75986bf65e2 | 0 | Tookmund/ConwaysLife | // Created to test the difference between SparseMatrix and standard Array
public class ArrayMatrix<anyType> implements Matrixable<anyType>, Cloneable
{
private Object[][] ar;
private char bl = '-';
public ArrayMatrix(int r, int c)
{
ar = new Object[r][c];
}
private ArrayMatrix(Object[][] b)
{
ar = b;
}
public anyType get(int r, int c) //returns the element at row r, col c
{
return (anyType)(ar[r][c]);
}
public anyType set(int r, int c, anyType x) //changes element at (r,c), returns old value
{
anyType tmp = (anyType)(ar[r][c]);
ar[r][c] = x;
return tmp;
}
public void add(int r, int c, anyType x) //adds obj at row r, col c
{
ar[r][c] = x;
}
public anyType remove(int r, int c)
{
anyType tmp = (anyType)(ar[r][c]);
ar[r][c] = null;
return tmp;
}
public int size() //returns # actual elements stored
{
int s = 0;
for (int r = 0; r < ar.length; r++)
{
for (int c = 0; c < ar[0].length; c++)
{
if (ar[r][c] != null) s++;
}
}
return s;
}
public int numRows() //returns # rows set in constructor
{
return ar.length;
}
public int numColumns() //returns # cols set in constructor
{
return ar[0].length;
}
public Object[][] toArray() //returns equivalent structure in 2-D array form
{
return ar;
}
public boolean contains(anyType x) //true if x exists in list
{
for (int r = 0; r < ar.length; r++)
{
for (int c = 0; c < ar.length; c++)
{
if ( ((anyType)ar[r][c]).equals(x)) return true;
}
}
return false;
}
public int[] getLocation(anyType x) //returns location [r,c] of where x exists in list, null otherwise
{
int[] i = null;
for (int r = 0; r < ar.length; r++)
{
for (int c = 0; c < ar.length; c++)
{
if ( ((anyType)ar[r][c]).equals(x))
{
i = new int[2];
i[0] = r;
i[1] = c;
return i;
}
}
}
return i;
}
public boolean isEmpty() //returns true if there are no actual elements stored
{
if (ar.length == 0) return true;
return false;
}
public void clear() //clears all elements out of the list
{
ar = new Object[ar.length][ar[0].length];
}
public void setBlank(char blank) //allows the client to set the character that a blank spot in the array is
//represented by in String toString()
{
bl = blank;
}
public Matrixable<anyType> clone() //clone a Matrixable
{
Object [][] obj = new Object[ar.length][];
for(int i = 0; i < ar.length; i++)
{
Object[] m = ar[i];
int ml = m.length;
obj[i] = new Object[ml];
System.arraycopy(m, 0, obj[i], 0, ml);
}
return new ArrayMatrix(obj);
}
public String toString()
{
String s = "";
for (int r = 0; r < numRows(); r++)
{
for (int c = 0; c < numColumns(); c++)
{
anyType t = get(r,c);
if (t != null) s+= t+" ";
else s+=bl+" ";
}
s+="\n";
}
return s;
}
} | ArrayMatrix.java | // Created to test the difference between SparseMatrix and standard Array
// Not used
public class ArrayMatrix<anyType> implements Matrixable<anyType>, Cloneable
{
private Object[][] ar;
private char bl = '-';
public ArrayMatrix(int r, int c)
{
ar = new Object[r][c];
}
private ArrayMatrix(Object[][] b)
{
ar = b;
}
public anyType get(int r, int c) //returns the element at row r, col c
{
return (anyType)(ar[r][c]);
}
public anyType set(int r, int c, anyType x) //changes element at (r,c), returns old value
{
anyType tmp = (anyType)(ar[r][c]);
ar[r][c] = x;
return tmp;
}
public void add(int r, int c, anyType x) //adds obj at row r, col c
{
ar[r][c] = x;
}
public anyType remove(int r, int c)
{
anyType tmp = (anyType)(ar[r][c]);
ar[r][c] = null;
return tmp;
}
public int size() //returns # actual elements stored
{
int s = 0;
for (int r = 0; r < ar.length; r++)
{
for (int c = 0; c < ar[0].length; c++)
{
if (ar[r][c] != null) s++;
}
}
return s;
}
public int numRows() //returns # rows set in constructor
{
return ar.length;
}
public int numColumns() //returns # cols set in constructor
{
return ar[0].length;
}
public Object[][] toArray() //returns equivalent structure in 2-D array form
{
return ar;
}
public boolean contains(anyType x) //true if x exists in list
{
for (int r = 0; r < ar.length; r++)
{
for (int c = 0; c < ar.length; c++)
{
if ( ((anyType)ar[r][c]).equals(x)) return true;
}
}
return false;
}
public int[] getLocation(anyType x) //returns location [r,c] of where x exists in list, null otherwise
{
int[] i = null;
for (int r = 0; r < ar.length; r++)
{
for (int c = 0; c < ar.length; c++)
{
if ( ((anyType)ar[r][c]).equals(x))
{
i = new int[2];
i[0] = r;
i[1] = c;
return i;
}
}
}
return i;
}
public boolean isEmpty() //returns true if there are no actual elements stored
{
if (ar.length == 0) return true;
return false;
}
public void clear() //clears all elements out of the list
{
ar = new Object[ar.length][ar[0].length];
}
public void setBlank(char blank) //allows the client to set the character that a blank spot in the array is
//represented by in String toString()
{
bl = blank;
}
public Matrixable<anyType> clone() //clone a Matrixable
{
Object [][] obj = new Object[ar.length][];
for(int i = 0; i < ar.length; i++)
{
Object[] m = ar[i];
int ml = m.length;
obj[i] = new Object[ml];
System.arraycopy(m, 0, obj[i], 0, ml);
}
return new ArrayMatrix(obj);
}
public String toString()
{
String s = "";
for (int r = 0; r < numRows(); r++)
{
for (int c = 0; c < numColumns(); c++)
{
anyType t = get(r,c);
if (t != null) s+= t+" ";
else s+=bl+" ";
}
s+="\n";
}
return s;
}
} | ArrayMatrix: Now used so remove not used comment
| ArrayMatrix.java | ArrayMatrix: Now used so remove not used comment | <ide><path>rrayMatrix.java
<ide> // Created to test the difference between SparseMatrix and standard Array
<del>// Not used
<add>
<ide> public class ArrayMatrix<anyType> implements Matrixable<anyType>, Cloneable
<ide> {
<ide> private Object[][] ar; |
|
Java | bsd-2-clause | 9e34438d8907532deeee3a98a97ff506ca7fe1b2 | 0 | biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej | //
// Prefs.java
//
/*
ImageJ software for multidimensional image processing and analysis.
Copyright (c) 2010, ImageJDev.org.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of the ImageJDev.org developers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package imagej.util;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
/**
* Simple utility class that stores and retrieves user preferences.
*
* @author Curtis Rueden
*/
public final class Prefs {
private Prefs() {
// prevent instantiation of utility class
}
// -- Global preferences --
public static String get(final String name) {
return get((Class<?>) null, name);
}
public static String get(final String name, final String defaultValue) {
return get(null, name, defaultValue);
}
public static boolean getBoolean(final String name,
final boolean defaultValue)
{
return getBoolean(null, name, defaultValue);
}
public static double getDouble(final String name, final double defaultValue)
{
return getDouble(null, name, defaultValue);
}
public static float getFloat(final String name, final float defaultValue) {
return getFloat(null, name, defaultValue);
}
public static int getInt(final String name, final int defaultValue) {
return getInt(null, name, defaultValue);
}
public static long getLong(final String name, final long defaultValue) {
return getLong(null, name, defaultValue);
}
public static void put(final String name, final String value) {
put(null, name, value);
}
public static void put(final String name, final boolean value) {
put(null, name, value);
}
public static void put(final String name, final double value) {
put(null, name, value);
}
public static void put(final String name, final float value) {
put(null, name, value);
}
public static void put(final String name, final int value) {
put(null, name, value);
}
public static void put(final String name, final long value) {
put(null, name, value);
}
// -- Class-specific preferences --
public static String get(final Class<?> c, final String name) {
return get(c, name, null);
}
public static String get(final Class<?> c, final String name,
final String defaultValue)
{
return prefs(c).get(key(c, name), defaultValue);
}
public static boolean getBoolean(final Class<?> c, final String name,
final boolean defaultValue)
{
return prefs(c).getBoolean(key(c, name), defaultValue);
}
public static double getDouble(final Class<?> c, final String name,
final double defaultValue)
{
return prefs(c).getDouble(key(c, name), defaultValue);
}
public static float getFloat(final Class<?> c, final String name,
final float defaultValue)
{
return prefs(c).getFloat(key(c, name), defaultValue);
}
public static int getInt(final Class<?> c, final String name,
final int defaultValue)
{
return prefs(c).getInt(key(c, name), defaultValue);
}
public static long getLong(final Class<?> c, final String name,
final long defaultValue)
{
return prefs(c).getLong(key(c, name), defaultValue);
}
public static void put(final Class<?> c, final String name,
final String value)
{
prefs(c).put(key(c, name), value);
}
public static void put(final Class<?> c, final String name,
final boolean value)
{
prefs(c).putBoolean(key(c, name), value);
}
public static void put(final Class<?> c, final String name,
final double value)
{
prefs(c).putDouble(key(c, name), value);
}
public static void
put(final Class<?> c, final String name, final float value)
{
prefs(c).putFloat(key(c, name), value);
}
public static void put(final Class<?> c, final String name, final int value)
{
prefs(c).putInt(key(c, name), value);
}
public static void
put(final Class<?> c, final String name, final long value)
{
prefs(c).putLong(key(c, name), value);
}
public static void clear(final Class<?> c)
{
try { prefs(c).clear(); } catch (BackingStoreException e) {/**/}
}
public static void clearAll()
{
try {
String[] childNames = Preferences.userRoot().childrenNames();
for (String name : childNames)
Preferences.userRoot().node(name).removeNode();
}
catch (BackingStoreException e) {
// do nothing
}
}
// -- Helper methods --
private static Preferences prefs(final Class<?> c) {
return Preferences.userNodeForPackage(c == null ? Prefs.class : c);
}
private static String key(final Class<?> c, final String name) {
return c == null ? name : c.getSimpleName() + "." + name;
}
}
| core/core/src/main/java/imagej/util/Prefs.java | //
// Prefs.java
//
/*
ImageJ software for multidimensional image processing and analysis.
Copyright (c) 2010, ImageJDev.org.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of the ImageJDev.org developers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package imagej.util;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
/**
* Simple utility class that stores and retrieves user preferences.
*
* @author Curtis Rueden
*/
public final class Prefs {
private Prefs() {
// prevent instantiation of utility class
}
// -- Global preferences --
public static String get(final String name) {
return get((Class<?>) null, name);
}
public static String get(final String name, final String defaultValue) {
return get(null, name, defaultValue);
}
public static boolean getBoolean(final String name,
final boolean defaultValue)
{
return getBoolean(null, name, defaultValue);
}
public static double getDouble(final String name, final double defaultValue)
{
return getDouble(null, name, defaultValue);
}
public static float getFloat(final String name, final float defaultValue) {
return getFloat(null, name, defaultValue);
}
public static int getInt(final String name, final int defaultValue) {
return getInt(null, name, defaultValue);
}
public static long getLong(final String name, final long defaultValue) {
return getLong(null, name, defaultValue);
}
public static void put(final String name, final String value) {
put(null, name, value);
}
public static void put(final String name, final boolean value) {
put(null, name, value);
}
public static void put(final String name, final double value) {
put(null, name, value);
}
public static void put(final String name, final float value) {
put(null, name, value);
}
public static void put(final String name, final int value) {
put(null, name, value);
}
public static void put(final String name, final long value) {
put(null, name, value);
}
// -- Class-specific preferences --
public static String get(final Class<?> c, final String name) {
return get(c, name, null);
}
public static String get(final Class<?> c, final String name,
final String defaultValue)
{
return prefs(c).get(key(c, name), defaultValue);
}
public static boolean getBoolean(final Class<?> c, final String name,
final boolean defaultValue)
{
return prefs(c).getBoolean(key(c, name), defaultValue);
}
public static double getDouble(final Class<?> c, final String name,
final double defaultValue)
{
return prefs(c).getDouble(key(c, name), defaultValue);
}
public static float getFloat(final Class<?> c, final String name,
final float defaultValue)
{
return prefs(c).getFloat(key(c, name), defaultValue);
}
public static int getInt(final Class<?> c, final String name,
final int defaultValue)
{
return prefs(c).getInt(key(c, name), defaultValue);
}
public static long getLong(final Class<?> c, final String name,
final long defaultValue)
{
return prefs(c).getLong(key(c, name), defaultValue);
}
public static void put(final Class<?> c, final String name,
final String value)
{
prefs(c).put(key(c, name), value);
}
public static void put(final Class<?> c, final String name,
final boolean value)
{
prefs(c).putBoolean(key(c, name), value);
}
public static void put(final Class<?> c, final String name,
final double value)
{
prefs(c).putDouble(key(c, name), value);
}
public static void
put(final Class<?> c, final String name, final float value)
{
prefs(c).putFloat(key(c, name), value);
}
public static void put(final Class<?> c, final String name, final int value)
{
prefs(c).putInt(key(c, name), value);
}
public static void
put(final Class<?> c, final String name, final long value)
{
prefs(c).putLong(key(c, name), value);
}
public static void
clear(final Class<?> c)
{
try { prefs(c).clear(); } catch (BackingStoreException e) {/**/}
}
// -- Helper methods --
private static Preferences prefs(final Class<?> c) {
return Preferences.userNodeForPackage(c == null ? Prefs.class : c);
}
private static String key(final Class<?> c, final String name) {
return c == null ? name : c.getSimpleName() + "." + name;
}
}
| add clearAll() method
This used to be revision r4373.
| core/core/src/main/java/imagej/util/Prefs.java | add clearAll() method | <ide><path>ore/core/src/main/java/imagej/util/Prefs.java
<ide> prefs(c).putLong(key(c, name), value);
<ide> }
<ide>
<del> public static void
<del> clear(final Class<?> c)
<add> public static void clear(final Class<?> c)
<ide> {
<ide> try { prefs(c).clear(); } catch (BackingStoreException e) {/**/}
<add> }
<add>
<add> public static void clearAll()
<add> {
<add> try {
<add> String[] childNames = Preferences.userRoot().childrenNames();
<add> for (String name : childNames)
<add> Preferences.userRoot().node(name).removeNode();
<add> }
<add> catch (BackingStoreException e) {
<add> // do nothing
<add> }
<ide> }
<ide>
<ide> // -- Helper methods -- |
|
Java | mit | 3185ea3484cd3c643e8d48c2c10bb5f6d79794b1 | 0 | dbwiddis/oshi,hazendaz/oshi | /**
* MIT License
*
* Copyright (c) 2010 - 2021 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package oshi.software.os.windows;
import static oshi.software.os.OSProcess.State.INVALID;
import static oshi.software.os.OSProcess.State.RUNNING;
import static oshi.util.Memoizer.memoize;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jna.Native;
import com.sun.jna.Pointer; // NOSONAR squid:S1191
import com.sun.jna.platform.win32.Advapi32;
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.Advapi32Util.Account;
import com.sun.jna.platform.win32.BaseTSD.ULONG_PTRByReference;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Kernel32Util;
import com.sun.jna.platform.win32.VersionHelpers;
import com.sun.jna.platform.win32.W32Errors;
import com.sun.jna.platform.win32.Win32Exception;
import com.sun.jna.platform.win32.WinError;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.platform.win32.WinNT.HANDLEByReference;
import com.sun.jna.platform.win32.WinNT.PSID;
import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiResult;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;
import oshi.annotation.concurrent.ThreadSafe;
import oshi.driver.windows.registry.ProcessPerformanceData;
import oshi.driver.windows.registry.ProcessPerformanceData.PerfCounterBlock;
import oshi.driver.windows.registry.ProcessWtsData;
import oshi.driver.windows.registry.ProcessWtsData.WtsInfo;
import oshi.driver.windows.registry.ThreadPerformanceData;
import oshi.driver.windows.wmi.Win32Process;
import oshi.driver.windows.wmi.Win32Process.CommandLineProperty;
import oshi.driver.windows.wmi.Win32ProcessCached;
import oshi.software.common.AbstractOSProcess;
import oshi.software.os.OSThread;
import oshi.util.Constants;
import oshi.util.GlobalConfig;
import oshi.util.platform.windows.WmiUtil;
import oshi.util.tuples.Pair;
/**
* OSProcess implemenation
*/
@ThreadSafe
public class WindowsOSProcess extends AbstractOSProcess {
private static final Logger LOG = LoggerFactory.getLogger(WindowsOSProcess.class);
// Config param to enable cache
public static final String OSHI_OS_WINDOWS_COMMANDLINE_BATCH = "oshi.os.windows.commandline.batch";
private static final boolean USE_BATCH_COMMANDLINE = GlobalConfig.get(OSHI_OS_WINDOWS_COMMANDLINE_BATCH, false);
private static final boolean IS_VISTA_OR_GREATER = VersionHelpers.IsWindowsVistaOrGreater();
private static final boolean IS_WINDOWS7_OR_GREATER = VersionHelpers.IsWindows7OrGreater();
private Supplier<Pair<String, String>> userInfo = memoize(this::queryUserInfo);
private Supplier<Pair<String, String>> groupInfo = memoize(this::queryGroupInfo);
private Supplier<String> commandLine = memoize(this::queryCommandLine);
private String name;
private String path;
private String currentWorkingDirectory;
private State state = INVALID;
private int parentProcessID;
private int threadCount;
private int priority;
private long virtualSize;
private long residentSetSize;
private long kernelTime;
private long userTime;
private long startTime;
private long upTime;
private long bytesRead;
private long bytesWritten;
private long openFiles;
private int bitness;
private long pageFaults;
public WindowsOSProcess(int pid, WindowsOperatingSystem os, Map<Integer, PerfCounterBlock> processMap,
Map<Integer, WtsInfo> processWtsMap) {
super(pid);
// For executing process, set CWD
if (pid == os.getProcessId()) {
String cwd = new File(".").getAbsolutePath();
// trim off trailing "."
this.currentWorkingDirectory = cwd.isEmpty() ? "" : cwd.substring(0, cwd.length() - 1);
}
// There is no easy way to get ExecutuionState for a process.
// The WMI value is null. It's possible to get thread Execution
// State and possibly roll up.
this.state = RUNNING;
// Initially set to match OS bitness. If 64 will check later for 32-bit process
this.bitness = os.getBitness();
updateAttributes(processMap.get(pid), processWtsMap.get(pid));
}
@Override
public String getName() {
return this.name;
}
@Override
public String getPath() {
return this.path;
}
@Override
public String getCommandLine() {
return this.commandLine.get();
}
@Override
public String getCurrentWorkingDirectory() {
return this.currentWorkingDirectory;
}
@Override
public String getUser() {
return userInfo.get().getA();
}
@Override
public String getUserID() {
return userInfo.get().getB();
}
@Override
public String getGroup() {
return groupInfo.get().getA();
}
@Override
public String getGroupID() {
return groupInfo.get().getB();
}
@Override
public State getState() {
return this.state;
}
@Override
public int getParentProcessID() {
return this.parentProcessID;
}
@Override
public int getThreadCount() {
return this.threadCount;
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public long getVirtualSize() {
return this.virtualSize;
}
@Override
public long getResidentSetSize() {
return this.residentSetSize;
}
@Override
public long getKernelTime() {
return this.kernelTime;
}
@Override
public long getUserTime() {
return this.userTime;
}
@Override
public long getUpTime() {
return this.upTime;
}
@Override
public long getStartTime() {
return this.startTime;
}
@Override
public long getBytesRead() {
return this.bytesRead;
}
@Override
public long getBytesWritten() {
return this.bytesWritten;
}
@Override
public long getOpenFiles() {
return this.openFiles;
}
@Override
public int getBitness() {
return this.bitness;
}
@Override
public long getAffinityMask() {
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION, false, getProcessID());
if (pHandle != null) {
try {
ULONG_PTRByReference processAffinity = new ULONG_PTRByReference();
ULONG_PTRByReference systemAffinity = new ULONG_PTRByReference();
if (Kernel32.INSTANCE.GetProcessAffinityMask(pHandle, processAffinity, systemAffinity)) {
return Pointer.nativeValue(processAffinity.getValue().toPointer());
}
} finally {
Kernel32.INSTANCE.CloseHandle(pHandle);
}
Kernel32.INSTANCE.CloseHandle(pHandle);
}
return 0L;
}
@Override
public long getMinorFaults() {
return this.pageFaults;
}
@Override
public List<OSThread> getThreadDetails() {
// Get data from the registry if possible
Map<Integer, ThreadPerformanceData.PerfCounterBlock> threads = ThreadPerformanceData
.buildThreadMapFromRegistry(Collections.singleton(getProcessID()));
// otherwise performance counters with WMI backup
if (threads != null) {
threads = ThreadPerformanceData.buildThreadMapFromPerfCounters(Collections.singleton(this.getProcessID()));
}
if (threads == null) {
return Collections.emptyList();
}
return threads.entrySet().stream()
.map(entry -> new WindowsOSThread(getProcessID(), entry.getKey(), this.name, entry.getValue()))
.collect(Collectors.toList());
}
@Override
public boolean updateAttributes() {
Set<Integer> pids = Collections.singleton(this.getProcessID());
// Get data from the registry if possible
Map<Integer, PerfCounterBlock> pcb = ProcessPerformanceData.buildProcessMapFromRegistry(null);
// otherwise performance counters with WMI backup
if (pcb == null) {
pcb = ProcessPerformanceData.buildProcessMapFromPerfCounters(pids);
}
Map<Integer, WtsInfo> wts = ProcessWtsData.queryProcessWtsMap(pids);
return updateAttributes(pcb.get(this.getProcessID()), wts.get(this.getProcessID()));
}
private boolean updateAttributes(PerfCounterBlock pcb, WtsInfo wts) {
this.name = pcb.getName();
this.path = wts.getPath(); // Empty string for Win7+
this.parentProcessID = pcb.getParentProcessID();
this.threadCount = wts.getThreadCount();
this.priority = pcb.getPriority();
this.virtualSize = wts.getVirtualSize();
this.residentSetSize = pcb.getResidentSetSize();
this.kernelTime = wts.getKernelTime();
this.userTime = wts.getUserTime();
this.startTime = pcb.getStartTime();
this.upTime = pcb.getUpTime();
this.bytesRead = pcb.getBytesRead();
this.bytesWritten = pcb.getBytesWritten();
this.openFiles = wts.getOpenFiles();
this.pageFaults = pcb.getPageFaults();
// Get a handle to the process for various extended info. Only gets
// current user unless running as administrator
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION, false, getProcessID());
if (pHandle != null) {
try {
// Test for 32-bit process on 64-bit windows
if (IS_VISTA_OR_GREATER && this.bitness == 64) {
IntByReference wow64 = new IntByReference(0);
if (Kernel32.INSTANCE.IsWow64Process(pHandle, wow64) && wow64.getValue() > 0) {
this.bitness = 32;
}
}
// Full path
final HANDLEByReference phToken = new HANDLEByReference();
try { // EXECUTABLEPATH
if (IS_WINDOWS7_OR_GREATER) {
this.path = Kernel32Util.QueryFullProcessImageName(pHandle, 0);
}
} catch (Win32Exception e) {
this.state = INVALID;
} finally {
final HANDLE token = phToken.getValue();
if (token != null) {
Kernel32.INSTANCE.CloseHandle(token);
}
}
} finally {
Kernel32.INSTANCE.CloseHandle(pHandle);
}
}
return !this.state.equals(INVALID);
}
private String queryCommandLine() {
// If using batch mode fetch from WMI Cache
if (USE_BATCH_COMMANDLINE) {
return Win32ProcessCached.getInstance().getCommandLine(getProcessID(), getStartTime());
}
// If no cache enabled, query line by line
WmiResult<CommandLineProperty> commandLineProcs = Win32Process
.queryCommandLines(Collections.singleton(getProcessID()));
if (commandLineProcs.getResultCount() > 0) {
return WmiUtil.getString(commandLineProcs, CommandLineProperty.COMMANDLINE, 0);
}
return Constants.UNKNOWN;
}
private Pair<String, String> queryUserInfo() {
Pair<String, String> pair = null;
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION, false, getProcessID());
if (pHandle != null) {
final HANDLEByReference phToken = new HANDLEByReference();
try {
if (Advapi32.INSTANCE.OpenProcessToken(pHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)) {
Account account = getTokenAccount(phToken.getValue());
pair = new Pair<>(account.name, account.sidString);
} else {
int error = Kernel32.INSTANCE.GetLastError();
// Access denied errors are common. Fail silently.
if (error != WinError.ERROR_ACCESS_DENIED) {
LOG.error("Failed to get process token for process {}: {}", getProcessID(),
Kernel32.INSTANCE.GetLastError());
}
}
} catch (Win32Exception e) {
LOG.warn("Failed to query user info for process {} ({}): {}", getProcessID(), getName(),
e.getMessage());
} finally {
final HANDLE token = phToken.getValue();
if (token != null) {
Kernel32.INSTANCE.CloseHandle(token);
}
Kernel32.INSTANCE.CloseHandle(pHandle);
}
}
if (pair == null) {
return new Pair<>(Constants.UNKNOWN, Constants.UNKNOWN);
}
return pair;
}
// Temporary for debugging
private static Account getTokenAccount(HANDLE hToken) {
// get token group information size
IntByReference tokenInformationLength = new IntByReference();
if (Advapi32.INSTANCE.GetTokenInformation(hToken, WinNT.TOKEN_INFORMATION_CLASS.TokenUser, null, 0,
tokenInformationLength)) {
throw new RuntimeException("Expected GetTokenInformation to fail with ERROR_INSUFFICIENT_BUFFER");
}
int rc = Kernel32.INSTANCE.GetLastError();
if (rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
// get token user information
WinNT.TOKEN_USER user = new WinNT.TOKEN_USER(tokenInformationLength.getValue());
if (!Advapi32.INSTANCE.GetTokenInformation(hToken, WinNT.TOKEN_INFORMATION_CLASS.TokenUser, user,
tokenInformationLength.getValue(), tokenInformationLength)) {
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
return getAccountBySid(null, user.User.Sid);
}
// Temporary for debugging
public static Account getAccountBySid(String systemName, PSID sid) {
IntByReference cchName = new IntByReference();
IntByReference cchDomainName = new IntByReference();
PointerByReference peUse = new PointerByReference();
if (Advapi32.INSTANCE.LookupAccountSid(systemName, sid, null, cchName, null, cchDomainName, peUse)) {
throw new RuntimeException("LookupAccountSidW was expected to fail with ERROR_INSUFFICIENT_BUFFER");
}
int rc = Kernel32.INSTANCE.GetLastError();
if (cchName.getValue() == 0 || rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
throw new Win32Exception(rc);
}
char[] domainName = new char[cchDomainName.getValue()];
char[] name = new char[cchName.getValue()];
if (!Advapi32.INSTANCE.LookupAccountSid(systemName, sid, name, cchName, domainName, cchDomainName, peUse)) {
LOG.warn("Failed LookupAccountSid: Sid={}, cchName={}, cchDomainName={}. Trying again.", sid,
cchName.getValue(), cchDomainName.getValue());
if (Advapi32.INSTANCE.LookupAccountSid(systemName, sid, null, cchName, null, cchDomainName, peUse)) {
throw new RuntimeException("LookupAccountSidW was expected to fail with ERROR_INSUFFICIENT_BUFFER");
}
LOG.warn("Trying LookupAccountSid: Sid={}, cchName={}, cchDomainName={}.", sid, cchName.getValue(),
cchDomainName.getValue());
domainName = new char[cchDomainName.getValue()];
name = new char[cchName.getValue()];
if (!Advapi32.INSTANCE.LookupAccountSid(systemName, sid, name, cchName, domainName, cchDomainName, peUse)) {
LOG.warn("Failed LookupAccountSid: Sid={}, cchName={}, cchDomainName={}. Bailing out.", sid,
cchName.getValue(), cchDomainName.getValue());
throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
}
}
Account account = new Account();
account.accountType = peUse.getPointer().getInt(0);
account.name = Native.toString(name);
if (cchDomainName.getValue() > 0) {
account.domain = Native.toString(domainName);
account.fqn = account.domain + "\\" + account.name;
} else {
account.fqn = account.name;
}
account.sid = sid.getBytes();
account.sidString = Advapi32Util.convertSidToStringSid(sid);
return account;
}
private Pair<String, String> queryGroupInfo() {
Pair<String, String> pair = null;
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION, false, getProcessID());
if (pHandle != null) {
final HANDLEByReference phToken = new HANDLEByReference();
if (Advapi32.INSTANCE.OpenProcessToken(pHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)) {
Account account = Advapi32Util.getTokenPrimaryGroup(phToken.getValue());
pair = new Pair<>(account.name, account.sidString);
} else {
int error = Kernel32.INSTANCE.GetLastError();
// Access denied errors are common. Fail silently.
if (error != WinError.ERROR_ACCESS_DENIED) {
LOG.error("Failed to get process token for process {}: {}", getProcessID(),
Kernel32.INSTANCE.GetLastError());
}
}
final HANDLE token = phToken.getValue();
if (token != null) {
Kernel32.INSTANCE.CloseHandle(token);
}
Kernel32.INSTANCE.CloseHandle(pHandle);
}
if (pair == null) {
return new Pair<>(Constants.UNKNOWN, Constants.UNKNOWN);
}
return pair;
}
}
| oshi-core/src/main/java/oshi/software/os/windows/WindowsOSProcess.java | /**
* MIT License
*
* Copyright (c) 2010 - 2021 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package oshi.software.os.windows;
import static oshi.software.os.OSProcess.State.INVALID;
import static oshi.software.os.OSProcess.State.RUNNING;
import static oshi.util.Memoizer.memoize;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jna.Pointer; // NOSONAR squid:S1191
import com.sun.jna.platform.win32.Advapi32;
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.Advapi32Util.Account;
import com.sun.jna.platform.win32.BaseTSD.ULONG_PTRByReference;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Kernel32Util;
import com.sun.jna.platform.win32.VersionHelpers;
import com.sun.jna.platform.win32.Win32Exception;
import com.sun.jna.platform.win32.WinError;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.platform.win32.WinNT.HANDLEByReference;
import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiResult;
import com.sun.jna.ptr.IntByReference;
import oshi.annotation.concurrent.ThreadSafe;
import oshi.driver.windows.registry.ProcessPerformanceData;
import oshi.driver.windows.registry.ProcessPerformanceData.PerfCounterBlock;
import oshi.driver.windows.registry.ProcessWtsData;
import oshi.driver.windows.registry.ProcessWtsData.WtsInfo;
import oshi.driver.windows.registry.ThreadPerformanceData;
import oshi.driver.windows.wmi.Win32Process;
import oshi.driver.windows.wmi.Win32Process.CommandLineProperty;
import oshi.driver.windows.wmi.Win32ProcessCached;
import oshi.software.common.AbstractOSProcess;
import oshi.software.os.OSThread;
import oshi.util.Constants;
import oshi.util.GlobalConfig;
import oshi.util.platform.windows.WmiUtil;
import oshi.util.tuples.Pair;
/**
* OSProcess implemenation
*/
@ThreadSafe
public class WindowsOSProcess extends AbstractOSProcess {
private static final Logger LOG = LoggerFactory.getLogger(WindowsOSProcess.class);
// Config param to enable cache
public static final String OSHI_OS_WINDOWS_COMMANDLINE_BATCH = "oshi.os.windows.commandline.batch";
private static final boolean USE_BATCH_COMMANDLINE = GlobalConfig.get(OSHI_OS_WINDOWS_COMMANDLINE_BATCH, false);
private static final boolean IS_VISTA_OR_GREATER = VersionHelpers.IsWindowsVistaOrGreater();
private static final boolean IS_WINDOWS7_OR_GREATER = VersionHelpers.IsWindows7OrGreater();
private Supplier<Pair<String, String>> userInfo = memoize(this::queryUserInfo);
private Supplier<Pair<String, String>> groupInfo = memoize(this::queryGroupInfo);
private Supplier<String> commandLine = memoize(this::queryCommandLine);
private String name;
private String path;
private String currentWorkingDirectory;
private State state = INVALID;
private int parentProcessID;
private int threadCount;
private int priority;
private long virtualSize;
private long residentSetSize;
private long kernelTime;
private long userTime;
private long startTime;
private long upTime;
private long bytesRead;
private long bytesWritten;
private long openFiles;
private int bitness;
private long pageFaults;
public WindowsOSProcess(int pid, WindowsOperatingSystem os, Map<Integer, PerfCounterBlock> processMap,
Map<Integer, WtsInfo> processWtsMap) {
super(pid);
// For executing process, set CWD
if (pid == os.getProcessId()) {
String cwd = new File(".").getAbsolutePath();
// trim off trailing "."
this.currentWorkingDirectory = cwd.isEmpty() ? "" : cwd.substring(0, cwd.length() - 1);
}
// There is no easy way to get ExecutuionState for a process.
// The WMI value is null. It's possible to get thread Execution
// State and possibly roll up.
this.state = RUNNING;
// Initially set to match OS bitness. If 64 will check later for 32-bit process
this.bitness = os.getBitness();
updateAttributes(processMap.get(pid), processWtsMap.get(pid));
}
@Override
public String getName() {
return this.name;
}
@Override
public String getPath() {
return this.path;
}
@Override
public String getCommandLine() {
return this.commandLine.get();
}
@Override
public String getCurrentWorkingDirectory() {
return this.currentWorkingDirectory;
}
@Override
public String getUser() {
return userInfo.get().getA();
}
@Override
public String getUserID() {
return userInfo.get().getB();
}
@Override
public String getGroup() {
return groupInfo.get().getA();
}
@Override
public String getGroupID() {
return groupInfo.get().getB();
}
@Override
public State getState() {
return this.state;
}
@Override
public int getParentProcessID() {
return this.parentProcessID;
}
@Override
public int getThreadCount() {
return this.threadCount;
}
@Override
public int getPriority() {
return this.priority;
}
@Override
public long getVirtualSize() {
return this.virtualSize;
}
@Override
public long getResidentSetSize() {
return this.residentSetSize;
}
@Override
public long getKernelTime() {
return this.kernelTime;
}
@Override
public long getUserTime() {
return this.userTime;
}
@Override
public long getUpTime() {
return this.upTime;
}
@Override
public long getStartTime() {
return this.startTime;
}
@Override
public long getBytesRead() {
return this.bytesRead;
}
@Override
public long getBytesWritten() {
return this.bytesWritten;
}
@Override
public long getOpenFiles() {
return this.openFiles;
}
@Override
public int getBitness() {
return this.bitness;
}
@Override
public long getAffinityMask() {
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION, false, getProcessID());
if (pHandle != null) {
try {
ULONG_PTRByReference processAffinity = new ULONG_PTRByReference();
ULONG_PTRByReference systemAffinity = new ULONG_PTRByReference();
if (Kernel32.INSTANCE.GetProcessAffinityMask(pHandle, processAffinity, systemAffinity)) {
return Pointer.nativeValue(processAffinity.getValue().toPointer());
}
} finally {
Kernel32.INSTANCE.CloseHandle(pHandle);
}
Kernel32.INSTANCE.CloseHandle(pHandle);
}
return 0L;
}
@Override
public long getMinorFaults() {
return this.pageFaults;
}
@Override
public List<OSThread> getThreadDetails() {
// Get data from the registry if possible
Map<Integer, ThreadPerformanceData.PerfCounterBlock> threads = ThreadPerformanceData
.buildThreadMapFromRegistry(Collections.singleton(getProcessID()));
// otherwise performance counters with WMI backup
if (threads != null) {
threads = ThreadPerformanceData.buildThreadMapFromPerfCounters(Collections.singleton(this.getProcessID()));
}
if (threads == null) {
return Collections.emptyList();
}
return threads.entrySet().stream()
.map(entry -> new WindowsOSThread(getProcessID(), entry.getKey(), this.name, entry.getValue()))
.collect(Collectors.toList());
}
@Override
public boolean updateAttributes() {
Set<Integer> pids = Collections.singleton(this.getProcessID());
// Get data from the registry if possible
Map<Integer, PerfCounterBlock> pcb = ProcessPerformanceData.buildProcessMapFromRegistry(null);
// otherwise performance counters with WMI backup
if (pcb == null) {
pcb = ProcessPerformanceData.buildProcessMapFromPerfCounters(pids);
}
Map<Integer, WtsInfo> wts = ProcessWtsData.queryProcessWtsMap(pids);
return updateAttributes(pcb.get(this.getProcessID()), wts.get(this.getProcessID()));
}
private boolean updateAttributes(PerfCounterBlock pcb, WtsInfo wts) {
this.name = pcb.getName();
this.path = wts.getPath(); // Empty string for Win7+
this.parentProcessID = pcb.getParentProcessID();
this.threadCount = wts.getThreadCount();
this.priority = pcb.getPriority();
this.virtualSize = wts.getVirtualSize();
this.residentSetSize = pcb.getResidentSetSize();
this.kernelTime = wts.getKernelTime();
this.userTime = wts.getUserTime();
this.startTime = pcb.getStartTime();
this.upTime = pcb.getUpTime();
this.bytesRead = pcb.getBytesRead();
this.bytesWritten = pcb.getBytesWritten();
this.openFiles = wts.getOpenFiles();
this.pageFaults = pcb.getPageFaults();
// Get a handle to the process for various extended info. Only gets
// current user unless running as administrator
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION, false, getProcessID());
if (pHandle != null) {
try {
// Test for 32-bit process on 64-bit windows
if (IS_VISTA_OR_GREATER && this.bitness == 64) {
IntByReference wow64 = new IntByReference(0);
if (Kernel32.INSTANCE.IsWow64Process(pHandle, wow64) && wow64.getValue() > 0) {
this.bitness = 32;
}
}
// Full path
final HANDLEByReference phToken = new HANDLEByReference();
try { // EXECUTABLEPATH
if (IS_WINDOWS7_OR_GREATER) {
this.path = Kernel32Util.QueryFullProcessImageName(pHandle, 0);
}
} catch (Win32Exception e) {
this.state = INVALID;
} finally {
final HANDLE token = phToken.getValue();
if (token != null) {
Kernel32.INSTANCE.CloseHandle(token);
}
}
} finally {
Kernel32.INSTANCE.CloseHandle(pHandle);
}
}
return !this.state.equals(INVALID);
}
private String queryCommandLine() {
// If using batch mode fetch from WMI Cache
if (USE_BATCH_COMMANDLINE) {
return Win32ProcessCached.getInstance().getCommandLine(getProcessID(), getStartTime());
}
// If no cache enabled, query line by line
WmiResult<CommandLineProperty> commandLineProcs = Win32Process
.queryCommandLines(Collections.singleton(getProcessID()));
if (commandLineProcs.getResultCount() > 0) {
return WmiUtil.getString(commandLineProcs, CommandLineProperty.COMMANDLINE, 0);
}
return Constants.UNKNOWN;
}
private Pair<String, String> queryUserInfo() {
Pair<String, String> pair = null;
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION, false, getProcessID());
if (pHandle != null) {
final HANDLEByReference phToken = new HANDLEByReference();
try {
if (Advapi32.INSTANCE.OpenProcessToken(pHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)) {
Account account = Advapi32Util.getTokenAccount(phToken.getValue());
pair = new Pair<>(account.name, account.sidString);
} else {
int error = Kernel32.INSTANCE.GetLastError();
// Access denied errors are common. Fail silently.
if (error != WinError.ERROR_ACCESS_DENIED) {
LOG.error("Failed to get process token for process {}: {}", getProcessID(),
Kernel32.INSTANCE.GetLastError());
}
}
} catch (Win32Exception e) {
LOG.warn("Failed to query user info for process {} ({}): {}", getProcessID(), getName(),
e.getMessage());
} finally {
final HANDLE token = phToken.getValue();
if (token != null) {
Kernel32.INSTANCE.CloseHandle(token);
}
Kernel32.INSTANCE.CloseHandle(pHandle);
}
}
if (pair == null) {
return new Pair<>(Constants.UNKNOWN, Constants.UNKNOWN);
}
return pair;
}
private Pair<String, String> queryGroupInfo() {
Pair<String, String> pair = null;
final HANDLE pHandle = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_QUERY_INFORMATION, false, getProcessID());
if (pHandle != null) {
final HANDLEByReference phToken = new HANDLEByReference();
if (Advapi32.INSTANCE.OpenProcessToken(pHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)) {
Account account = Advapi32Util.getTokenPrimaryGroup(phToken.getValue());
pair = new Pair<>(account.name, account.sidString);
} else {
int error = Kernel32.INSTANCE.GetLastError();
// Access denied errors are common. Fail silently.
if (error != WinError.ERROR_ACCESS_DENIED) {
LOG.error("Failed to get process token for process {}: {}", getProcessID(),
Kernel32.INSTANCE.GetLastError());
}
}
final HANDLE token = phToken.getValue();
if (token != null) {
Kernel32.INSTANCE.CloseHandle(token);
}
Kernel32.INSTANCE.CloseHandle(pHandle);
}
if (pair == null) {
return new Pair<>(Constants.UNKNOWN, Constants.UNKNOWN);
}
return pair;
}
}
| Instrument queryUserInfo for debugging | oshi-core/src/main/java/oshi/software/os/windows/WindowsOSProcess.java | Instrument queryUserInfo for debugging | <ide><path>shi-core/src/main/java/oshi/software/os/windows/WindowsOSProcess.java
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide>
<add>import com.sun.jna.Native;
<ide> import com.sun.jna.Pointer; // NOSONAR squid:S1191
<ide> import com.sun.jna.platform.win32.Advapi32;
<ide> import com.sun.jna.platform.win32.Advapi32Util;
<ide> import com.sun.jna.platform.win32.Kernel32;
<ide> import com.sun.jna.platform.win32.Kernel32Util;
<ide> import com.sun.jna.platform.win32.VersionHelpers;
<add>import com.sun.jna.platform.win32.W32Errors;
<ide> import com.sun.jna.platform.win32.Win32Exception;
<ide> import com.sun.jna.platform.win32.WinError;
<ide> import com.sun.jna.platform.win32.WinNT;
<ide> import com.sun.jna.platform.win32.WinNT.HANDLE;
<ide> import com.sun.jna.platform.win32.WinNT.HANDLEByReference;
<add>import com.sun.jna.platform.win32.WinNT.PSID;
<ide> import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiResult;
<ide> import com.sun.jna.ptr.IntByReference;
<add>import com.sun.jna.ptr.PointerByReference;
<ide>
<ide> import oshi.annotation.concurrent.ThreadSafe;
<ide> import oshi.driver.windows.registry.ProcessPerformanceData;
<ide> final HANDLEByReference phToken = new HANDLEByReference();
<ide> try {
<ide> if (Advapi32.INSTANCE.OpenProcessToken(pHandle, WinNT.TOKEN_DUPLICATE | WinNT.TOKEN_QUERY, phToken)) {
<del> Account account = Advapi32Util.getTokenAccount(phToken.getValue());
<add> Account account = getTokenAccount(phToken.getValue());
<ide> pair = new Pair<>(account.name, account.sidString);
<ide> } else {
<ide> int error = Kernel32.INSTANCE.GetLastError();
<ide> return new Pair<>(Constants.UNKNOWN, Constants.UNKNOWN);
<ide> }
<ide> return pair;
<add> }
<add>
<add> // Temporary for debugging
<add> private static Account getTokenAccount(HANDLE hToken) {
<add> // get token group information size
<add> IntByReference tokenInformationLength = new IntByReference();
<add> if (Advapi32.INSTANCE.GetTokenInformation(hToken, WinNT.TOKEN_INFORMATION_CLASS.TokenUser, null, 0,
<add> tokenInformationLength)) {
<add> throw new RuntimeException("Expected GetTokenInformation to fail with ERROR_INSUFFICIENT_BUFFER");
<add> }
<add> int rc = Kernel32.INSTANCE.GetLastError();
<add> if (rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
<add> throw new Win32Exception(rc);
<add> }
<add> // get token user information
<add> WinNT.TOKEN_USER user = new WinNT.TOKEN_USER(tokenInformationLength.getValue());
<add> if (!Advapi32.INSTANCE.GetTokenInformation(hToken, WinNT.TOKEN_INFORMATION_CLASS.TokenUser, user,
<add> tokenInformationLength.getValue(), tokenInformationLength)) {
<add> throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
<add> }
<add> return getAccountBySid(null, user.User.Sid);
<add> }
<add>
<add> // Temporary for debugging
<add> public static Account getAccountBySid(String systemName, PSID sid) {
<add> IntByReference cchName = new IntByReference();
<add> IntByReference cchDomainName = new IntByReference();
<add> PointerByReference peUse = new PointerByReference();
<add>
<add> if (Advapi32.INSTANCE.LookupAccountSid(systemName, sid, null, cchName, null, cchDomainName, peUse)) {
<add> throw new RuntimeException("LookupAccountSidW was expected to fail with ERROR_INSUFFICIENT_BUFFER");
<add> }
<add>
<add> int rc = Kernel32.INSTANCE.GetLastError();
<add> if (cchName.getValue() == 0 || rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) {
<add> throw new Win32Exception(rc);
<add> }
<add>
<add> char[] domainName = new char[cchDomainName.getValue()];
<add> char[] name = new char[cchName.getValue()];
<add>
<add> if (!Advapi32.INSTANCE.LookupAccountSid(systemName, sid, name, cchName, domainName, cchDomainName, peUse)) {
<add> LOG.warn("Failed LookupAccountSid: Sid={}, cchName={}, cchDomainName={}. Trying again.", sid,
<add> cchName.getValue(), cchDomainName.getValue());
<add> if (Advapi32.INSTANCE.LookupAccountSid(systemName, sid, null, cchName, null, cchDomainName, peUse)) {
<add> throw new RuntimeException("LookupAccountSidW was expected to fail with ERROR_INSUFFICIENT_BUFFER");
<add> }
<add> LOG.warn("Trying LookupAccountSid: Sid={}, cchName={}, cchDomainName={}.", sid, cchName.getValue(),
<add> cchDomainName.getValue());
<add> domainName = new char[cchDomainName.getValue()];
<add> name = new char[cchName.getValue()];
<add> if (!Advapi32.INSTANCE.LookupAccountSid(systemName, sid, name, cchName, domainName, cchDomainName, peUse)) {
<add> LOG.warn("Failed LookupAccountSid: Sid={}, cchName={}, cchDomainName={}. Bailing out.", sid,
<add> cchName.getValue(), cchDomainName.getValue());
<add> throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
<add> }
<add> }
<add>
<add> Account account = new Account();
<add> account.accountType = peUse.getPointer().getInt(0);
<add> account.name = Native.toString(name);
<add>
<add> if (cchDomainName.getValue() > 0) {
<add> account.domain = Native.toString(domainName);
<add> account.fqn = account.domain + "\\" + account.name;
<add> } else {
<add> account.fqn = account.name;
<add> }
<add>
<add> account.sid = sid.getBytes();
<add> account.sidString = Advapi32Util.convertSidToStringSid(sid);
<add> return account;
<ide> }
<ide>
<ide> private Pair<String, String> queryGroupInfo() { |
|
JavaScript | mit | 906caebb3f3bc542904a94846e778aa8d71c0575 | 0 | roytoo/jquery,jquery/jquery,jquery/jquery,jquery/jquery,roytoo/jquery,roytoo/jquery | (function() {
if ( !jQuery.fn.width ) {
return;
}
module("dimensions", { teardown: moduleTeardown });
function pass( val ) {
return val;
}
function fn( val ) {
return function() {
return val;
};
}
/*
======== local reference =======
pass and fn can be used to test passing functions to setters
See testWidth below for an example
pass( value );
This function returns whatever value is passed in
fn( value );
Returns a function that returns the value
*/
function testWidth( val ) {
expect(9);
var $div, blah;
$div = jQuery("#nothiddendiv");
$div.width( val(30) );
equal($div.width(), 30, "Test set to 30 correctly");
$div.hide();
equal($div.width(), 30, "Test hidden div");
$div.show();
$div.width( val(-1) ); // handle negative numbers by setting to 0 #11604
equal($div.width(), 0, "Test negative width normalized to 0");
$div.css("padding", "20px");
equal($div.width(), 0, "Test padding specified with pixels");
$div.css("border", "2px solid #fff");
equal($div.width(), 0, "Test border specified with pixels");
$div.css({ "display": "", "border": "", "padding": "" });
jQuery("#nothiddendivchild").css({ "width": 20, "padding": "3px", "border": "2px solid #fff" });
equal(jQuery("#nothiddendivchild").width(), 20, "Test child width with border and padding");
jQuery("#nothiddendiv, #nothiddendivchild").css({ "border": "", "padding": "", "width": "" });
blah = jQuery("blah");
equal( blah.width( val(10) ), blah, "Make sure that setting a width on an empty set returns the set." );
equal( blah.width(), null, "Make sure 'null' is returned on an empty set");
equal( jQuery(window).width(), document.documentElement.clientWidth, "Window width is equal to width reported by window/document." );
QUnit.expectJqData( this, $div[0], "olddisplay" );
}
test("width()", function() {
testWidth( pass );
});
test("width(Function)", function() {
testWidth( fn );
});
test("width(Function(args))", function() {
expect( 2 );
var $div = jQuery("#nothiddendiv");
$div.width( 30 ).width(function(i, width) {
equal( width, 30, "Make sure previous value is correct." );
return width + 1;
});
equal( $div.width(), 31, "Make sure value was modified correctly." );
});
function testHeight( val ) {
expect(9);
var $div, blah;
$div = jQuery("#nothiddendiv");
$div.height( val(30) );
equal($div.height(), 30, "Test set to 30 correctly");
$div.hide();
equal($div.height(), 30, "Test hidden div");
$div.show();
$div.height( val(-1) ); // handle negative numbers by setting to 0 #11604
equal($div.height(), 0, "Test negative height normalized to 0");
$div.css("padding", "20px");
equal($div.height(), 0, "Test padding specified with pixels");
$div.css("border", "2px solid #fff");
equal($div.height(), 0, "Test border specified with pixels");
$div.css({ "display": "", "border": "", "padding": "", "height": "1px" });
jQuery("#nothiddendivchild").css({ "height": 20, "padding": "3px", "border": "2px solid #fff" });
equal(jQuery("#nothiddendivchild").height(), 20, "Test child height with border and padding");
jQuery("#nothiddendiv, #nothiddendivchild").css({ "border": "", "padding": "", "height": "" });
blah = jQuery("blah");
equal( blah.height( val(10) ), blah, "Make sure that setting a height on an empty set returns the set." );
equal( blah.height(), null, "Make sure 'null' is returned on an empty set");
equal( jQuery(window).height(), document.documentElement.clientHeight, "Window width is equal to width reported by window/document." );
QUnit.expectJqData( this, $div[0], "olddisplay" );
}
test("height()", function() {
testHeight( pass );
});
test("height(Function)", function() {
testHeight( fn );
});
test("height(Function(args))", function() {
expect( 2 );
var $div = jQuery("#nothiddendiv");
$div.height( 30 ).height(function(i, height) {
equal( height, 30, "Make sure previous value is correct." );
return height + 1;
});
equal( $div.height(), 31, "Make sure value was modified correctly." );
});
test("innerWidth()", function() {
expect( 6 );
var $div, div,
$win = jQuery( window ),
$doc = jQuery( document );
equal( jQuery( window ).innerWidth(), $win.width(), "Test on window" );
equal( jQuery( document ).innerWidth(), $doc.width(), "Test on document" );
$div = jQuery( "#nothiddendiv" );
$div.css({
"margin": 10,
"border": "2px solid #fff",
"width": 30
});
equal( $div.innerWidth(), 30, "Test with margin and border" );
$div.css( "padding", "20px" );
equal( $div.innerWidth(), 70, "Test with margin, border and padding" );
$div.hide();
equal( $div.innerWidth(), 70, "Test hidden div" );
// reset styles
$div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" });
div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.innerWidth(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
QUnit.expectJqData( this, $div[ 0 ], "olddisplay" );
});
test("innerHeight()", function() {
expect( 6 );
var $div, div,
$win = jQuery( window ),
$doc = jQuery( document );
equal( jQuery( window ).innerHeight(), $win.height(), "Test on window" );
equal( jQuery( document ).innerHeight(), $doc.height(), "Test on document" );
$div = jQuery( "#nothiddendiv" );
$div.css({
"margin": 10,
"border": "2px solid #fff",
"height": 30
});
equal( $div.innerHeight(), 30, "Test with margin and border" );
$div.css( "padding", "20px" );
equal( $div.innerHeight(), 70, "Test with margin, border and padding" );
$div.hide();
equal( $div.innerHeight(), 70, "Test hidden div" );
// reset styles
$div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" });
div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.innerHeight(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
QUnit.expectJqData( this, $div[ 0 ], "olddisplay" );
});
test("outerWidth()", function() {
expect( 11 );
var $div, div,
$win = jQuery( window ),
$doc = jQuery( document );
equal( jQuery( window ).outerWidth(), $win.width(), "Test on window without margin option" );
equal( jQuery( window ).outerWidth( true ), $win.width(), "Test on window with margin option" );
equal( jQuery( document ).outerWidth(), $doc.width(), "Test on document without margin option" );
equal( jQuery( document ).outerWidth( true ), $doc.width(), "Test on document with margin option" );
$div = jQuery( "#nothiddendiv" );
$div.css( "width", 30 );
equal( $div.outerWidth(), 30, "Test with only width set" );
$div.css( "padding", "20px" );
equal( $div.outerWidth(), 70, "Test with padding" );
$div.css( "border", "2px solid #fff" );
equal( $div.outerWidth(), 74, "Test with padding and border" );
$div.css( "margin", "10px" );
equal( $div.outerWidth(), 74, "Test with padding, border and margin without margin option" );
$div.css( "position", "absolute" );
equal( $div.outerWidth( true ), 94, "Test with padding, border and margin with margin option" );
$div.hide();
equal( $div.outerWidth( true ), 94, "Test hidden div with padding, border and margin with margin option" );
// reset styles
$div.css({ "position": "", "display": "", "border": "", "padding": "", "width": "", "height": "" });
div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.outerWidth(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
QUnit.expectJqData( this, $div[ 0 ], "olddisplay" );
});
test("child of a hidden elem (or unconnected node) has accurate inner/outer/Width()/Height() see #9441 #9300", function() {
expect(16);
// setup html
var $divNormal = jQuery("<div>").css({ "width": "100px", "height": "100px", "border": "10px solid white", "padding": "2px", "margin": "3px" }),
$divChild = $divNormal.clone(),
$divUnconnected = $divNormal.clone(),
$divHiddenParent = jQuery("<div>").css( "display", "none" ).append( $divChild ).appendTo("body");
$divNormal.appendTo("body");
// tests that child div of a hidden div works the same as a normal div
equal( $divChild.width(), $divNormal.width(), "child of a hidden element width() is wrong see #9441" );
equal( $divChild.innerWidth(), $divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see #9441" );
equal( $divChild.outerWidth(), $divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see #9441" );
equal( $divChild.outerWidth(true), $divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see #9300" );
equal( $divChild.height(), $divNormal.height(), "child of a hidden element height() is wrong see #9441" );
equal( $divChild.innerHeight(), $divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see #9441" );
equal( $divChild.outerHeight(), $divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see #9441" );
equal( $divChild.outerHeight(true), $divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see #9300" );
// tests that child div of an unconnected div works the same as a normal div
equal( $divUnconnected.width(), $divNormal.width(), "unconnected element width() is wrong see #9441" );
equal( $divUnconnected.innerWidth(), $divNormal.innerWidth(), "unconnected element innerWidth() is wrong see #9441" );
equal( $divUnconnected.outerWidth(), $divNormal.outerWidth(), "unconnected element outerWidth() is wrong see #9441" );
equal( $divUnconnected.outerWidth(true), $divNormal.outerWidth( true ), "unconnected element outerWidth( true ) is wrong see #9300" );
equal( $divUnconnected.height(), $divNormal.height(), "unconnected element height() is wrong see #9441" );
equal( $divUnconnected.innerHeight(), $divNormal.innerHeight(), "unconnected element innerHeight() is wrong see #9441" );
equal( $divUnconnected.outerHeight(), $divNormal.outerHeight(), "unconnected element outerHeight() is wrong see #9441" );
equal( $divUnconnected.outerHeight(true), $divNormal.outerHeight( true ), "unconnected element outerHeight( true ) is wrong see #9300" );
// teardown html
$divHiddenParent.remove();
$divNormal.remove();
});
test("getting dimensions shouldn't modify runtimeStyle see #9233", function() {
expect( 1 );
var $div = jQuery( "<div>" ).appendTo( "#qunit-fixture" ),
div = $div.get( 0 ),
runtimeStyle = div.runtimeStyle;
if ( runtimeStyle ) {
div.runtimeStyle.marginLeft = "12em";
div.runtimeStyle.left = "11em";
}
$div.outerWidth( true );
if ( runtimeStyle ) {
equal( div.runtimeStyle.left, "11em", "getting dimensions modifies runtimeStyle, see #9233" );
} else {
ok( true, "this browser doesn't support runtimeStyle, see #9233" );
}
$div.remove();
});
test( "table dimensions", 2, function() {
var table = jQuery("<table><colgroup><col/><col/></colgroup><tbody><tr><td></td><td>a</td></tr><tr><td></td><td>a</td></tr></tbody></table>").appendTo("#qunit-fixture"),
tdElem = table.find("td").first(),
colElem = table.find("col").first().width( 300 );
table.find("td").css({ "margin": 0, "padding": 0 });
equal( tdElem.width(), tdElem.width(), "width() doesn't alter dimension values of empty cells, see #11293" );
equal( colElem.width(), 300, "col elements have width(), see #12243" );
});
test("box-sizing:border-box child of a hidden elem (or unconnected node) has accurate inner/outer/Width()/Height() see #10413", function() {
expect(16);
// setup html
var $divNormal = jQuery("<div>").css({ "boxSizing": "border-box", "width": "100px", "height": "100px", "border": "10px solid white", "padding": "2px", "margin": "3px" }),
$divChild = $divNormal.clone(),
$divUnconnected = $divNormal.clone(),
$divHiddenParent = jQuery("<div>").css( "display", "none" ).append( $divChild ).appendTo("body");
$divNormal.appendTo("body");
// tests that child div of a hidden div works the same as a normal div
equal( $divChild.width(), $divNormal.width(), "child of a hidden element width() is wrong see #10413" );
equal( $divChild.innerWidth(), $divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see #10413" );
equal( $divChild.outerWidth(), $divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see #10413" );
equal( $divChild.outerWidth(true), $divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see #10413" );
equal( $divChild.height(), $divNormal.height(), "child of a hidden element height() is wrong see #10413" );
equal( $divChild.innerHeight(), $divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see #10413" );
equal( $divChild.outerHeight(), $divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see #10413" );
equal( $divChild.outerHeight(true), $divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see #10413" );
// tests that child div of an unconnected div works the same as a normal div
equal( $divUnconnected.width(), $divNormal.width(), "unconnected element width() is wrong see #10413" );
equal( $divUnconnected.innerWidth(), $divNormal.innerWidth(), "unconnected element innerWidth() is wrong see #10413" );
equal( $divUnconnected.outerWidth(), $divNormal.outerWidth(), "unconnected element outerWidth() is wrong see #10413" );
equal( $divUnconnected.outerWidth(true), $divNormal.outerWidth( true ), "unconnected element outerWidth( true ) is wrong see #10413" );
equal( $divUnconnected.height(), $divNormal.height(), "unconnected element height() is wrong see #10413" );
equal( $divUnconnected.innerHeight(), $divNormal.innerHeight(), "unconnected element innerHeight() is wrong see #10413" );
equal( $divUnconnected.outerHeight(), $divNormal.outerHeight(), "unconnected element outerHeight() is wrong see #10413" );
equal( $divUnconnected.outerHeight(true), $divNormal.outerHeight( true ), "unconnected element outerHeight( true ) is wrong see #10413" );
// teardown html
$divHiddenParent.remove();
$divNormal.remove();
});
test("outerHeight()", function() {
expect( 11 );
var $div, div,
$win = jQuery( window ),
$doc = jQuery( document );
equal( jQuery( window ).outerHeight(), $win.height(), "Test on window without margin option" );
equal( jQuery( window ).outerHeight( true ), $win.height(), "Test on window with margin option" );
equal( jQuery( document ).outerHeight(), $doc.height(), "Test on document without margin option" );
equal( jQuery( document ).outerHeight( true ), $doc.height(), "Test on document with margin option" );
$div = jQuery( "#nothiddendiv" );
$div.css( "height", 30 );
equal( $div.outerHeight(), 30, "Test with only width set" );
$div.css( "padding", "20px" );
equal( $div.outerHeight(), 70, "Test with padding" );
$div.css( "border", "2px solid #fff" );
equal( $div.outerHeight(), 74, "Test with padding and border" );
$div.css( "margin", "10px" );
equal( $div.outerHeight(), 74, "Test with padding, border and margin without margin option" );
equal( $div.outerHeight( true ), 94, "Test with padding, border and margin with margin option" );
$div.hide();
equal( $div.outerHeight( true ), 94, "Test hidden div with padding, border and margin with margin option" );
// reset styles
$div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" });
div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.outerHeight(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
QUnit.expectJqData( this, $div[ 0 ], "olddisplay" );
});
test("passing undefined is a setter #5571", function() {
expect(4);
equal(jQuery("#nothiddendiv").height(30).height(undefined).height(), 30, ".height(undefined) is chainable (#5571)");
equal(jQuery("#nothiddendiv").height(30).innerHeight(undefined).height(), 30, ".innerHeight(undefined) is chainable (#5571)");
equal(jQuery("#nothiddendiv").height(30).outerHeight(undefined).height(), 30, ".outerHeight(undefined) is chainable (#5571)");
equal(jQuery("#nothiddendiv").width(30).width(undefined).width(), 30, ".width(undefined) is chainable (#5571)");
});
test( "getters on non elements should return null", function() {
expect( 8 );
var nonElem = jQuery("notAnElement");
strictEqual( nonElem.width(), null, ".width() is not null (#12283)" );
strictEqual( nonElem.innerWidth(), null, ".innerWidth() is not null (#12283)" );
strictEqual( nonElem.outerWidth(), null, ".outerWidth() is not null (#12283)" );
strictEqual( nonElem.outerWidth( true ), null, ".outerWidth(true) is not null (#12283)" );
strictEqual( nonElem.height(), null, ".height() is not null (#12283)" );
strictEqual( nonElem.innerHeight(), null, ".innerHeight() is not null (#12283)" );
strictEqual( nonElem.outerHeight(), null, ".outerHeight() is not null (#12283)" );
strictEqual( nonElem.outerHeight( true ), null, ".outerHeight(true) is not null (#12283)" );
});
test("setters with and without box-sizing:border-box", function(){
expect(20);
// Support: Android 2.3 (-webkit-box-sizing).
var el_bb = jQuery("<div style='width:114px;height:114px;margin:5px;padding:3px;border:4px solid white;-webkit-box-sizing:border-box;box-sizing:border-box;'>test</div>").appendTo("#qunit-fixture"),
el = jQuery("<div style='width:100px;height:100px;margin:5px;padding:3px;border:4px solid white;'>test</div>").appendTo("#qunit-fixture"),
expected = 100;
equal( el_bb.width( 101 ).width(), expected + 1, "test border-box width(int) by roundtripping" );
equal( el_bb.innerWidth( 108 ).width(), expected + 2, "test border-box innerWidth(int) by roundtripping" );
equal( el_bb.outerWidth( 117 ).width(), expected + 3, "test border-box outerWidth(int) by roundtripping" );
equal( el_bb.outerWidth( 118, false ).width(), expected + 4, "test border-box outerWidth(int, false) by roundtripping" );
equal( el_bb.outerWidth( 129, true ).width(), expected + 5, "test border-box innerWidth(int, true) by roundtripping" );
equal( el_bb.height( 101 ).height(), expected + 1, "test border-box height(int) by roundtripping" );
equal( el_bb.innerHeight( 108 ).height(), expected + 2, "test border-box innerHeight(int) by roundtripping" );
equal( el_bb.outerHeight( 117 ).height(), expected + 3, "test border-box outerHeight(int) by roundtripping" );
equal( el_bb.outerHeight( 118, false ).height(), expected + 4, "test border-box outerHeight(int, false) by roundtripping" );
equal( el_bb.outerHeight( 129, true ).height(), expected + 5, "test border-box innerHeight(int, true) by roundtripping" );
equal( el.width( 101 ).width(), expected + 1, "test border-box width(int) by roundtripping" );
equal( el.innerWidth( 108 ).width(), expected + 2, "test border-box innerWidth(int) by roundtripping" );
equal( el.outerWidth( 117 ).width(), expected + 3, "test border-box outerWidth(int) by roundtripping" );
equal( el.outerWidth( 118, false ).width(), expected + 4, "test border-box outerWidth(int, false) by roundtripping" );
equal( el.outerWidth( 129, true ).width(), expected + 5, "test border-box innerWidth(int, true) by roundtripping" );
equal( el.height( 101 ).height(), expected + 1, "test border-box height(int) by roundtripping" );
equal( el.innerHeight( 108 ).height(), expected + 2, "test border-box innerHeight(int) by roundtripping" );
equal( el.outerHeight( 117 ).height(), expected + 3, "test border-box outerHeight(int) by roundtripping" );
equal( el.outerHeight( 118, false ).height(), expected + 4, "test border-box outerHeight(int, false) by roundtripping" );
equal( el.outerHeight( 129, true ).height(), expected + 5, "test border-box innerHeight(int, true) by roundtripping" );
});
testIframe( "dimensions/documentLarge", "window vs. large document", function( jQuery, window, document ) {
expect(2);
ok( jQuery( document ).height() > jQuery( window ).height(), "document height is larger than window height" );
ok( jQuery( document ).width() > jQuery( window ).width(), "document width is larger than window width" );
});
test( "allow modification of coordinates argument (gh-1848)", 1, function() {
var element = jQuery( "<div/>" ).appendTo( "#qunit-fixture" );
element.offset(function( index, coords ) {
coords.top = 100;
return coords;
});
equal( element.offset().top, 100, "coordinates are modified" );
});
})();
| test/unit/dimensions.js | (function() {
if ( !jQuery.fn.width ) {
return;
}
module("dimensions", { teardown: moduleTeardown });
function pass( val ) {
return val;
}
function fn( val ) {
return function() {
return val;
};
}
/*
======== local reference =======
pass and fn can be used to test passing functions to setters
See testWidth below for an example
pass( value );
This function returns whatever value is passed in
fn( value );
Returns a function that returns the value
*/
function testWidth( val ) {
expect(9);
var $div, blah;
$div = jQuery("#nothiddendiv");
$div.width( val(30) );
equal($div.width(), 30, "Test set to 30 correctly");
$div.hide();
equal($div.width(), 30, "Test hidden div");
$div.show();
$div.width( val(-1) ); // handle negative numbers by setting to 0 #11604
equal($div.width(), 0, "Test negative width normalized to 0");
$div.css("padding", "20px");
equal($div.width(), 0, "Test padding specified with pixels");
$div.css("border", "2px solid #fff");
equal($div.width(), 0, "Test border specified with pixels");
$div.css({ "display": "", "border": "", "padding": "" });
jQuery("#nothiddendivchild").css({ "width": 20, "padding": "3px", "border": "2px solid #fff" });
equal(jQuery("#nothiddendivchild").width(), 20, "Test child width with border and padding");
jQuery("#nothiddendiv, #nothiddendivchild").css({ "border": "", "padding": "", "width": "" });
blah = jQuery("blah");
equal( blah.width( val(10) ), blah, "Make sure that setting a width on an empty set returns the set." );
equal( blah.width(), null, "Make sure 'null' is returned on an empty set");
equal( jQuery(window).width(), document.documentElement.clientWidth, "Window width is equal to width reported by window/document." );
QUnit.expectJqData( this, $div[0], "olddisplay" );
}
test("width()", function() {
testWidth( pass );
});
test("width(Function)", function() {
testWidth( fn );
});
test("width(Function(args))", function() {
expect( 2 );
var $div = jQuery("#nothiddendiv");
$div.width( 30 ).width(function(i, width) {
equal( width, 30, "Make sure previous value is correct." );
return width + 1;
});
equal( $div.width(), 31, "Make sure value was modified correctly." );
});
function testHeight( val ) {
expect(9);
var $div, blah;
$div = jQuery("#nothiddendiv");
$div.height( val(30) );
equal($div.height(), 30, "Test set to 30 correctly");
$div.hide();
equal($div.height(), 30, "Test hidden div");
$div.show();
$div.height( val(-1) ); // handle negative numbers by setting to 0 #11604
equal($div.height(), 0, "Test negative height normalized to 0");
$div.css("padding", "20px");
equal($div.height(), 0, "Test padding specified with pixels");
$div.css("border", "2px solid #fff");
equal($div.height(), 0, "Test border specified with pixels");
$div.css({ "display": "", "border": "", "padding": "", "height": "1px" });
jQuery("#nothiddendivchild").css({ "height": 20, "padding": "3px", "border": "2px solid #fff" });
equal(jQuery("#nothiddendivchild").height(), 20, "Test child height with border and padding");
jQuery("#nothiddendiv, #nothiddendivchild").css({ "border": "", "padding": "", "height": "" });
blah = jQuery("blah");
equal( blah.height( val(10) ), blah, "Make sure that setting a height on an empty set returns the set." );
equal( blah.height(), null, "Make sure 'null' is returned on an empty set");
equal( jQuery(window).height(), document.documentElement.clientHeight, "Window width is equal to width reported by window/document." );
QUnit.expectJqData( this, $div[0], "olddisplay" );
}
test("height()", function() {
testHeight( pass );
});
test("height(Function)", function() {
testHeight( fn );
});
test("height(Function(args))", function() {
expect( 2 );
var $div = jQuery("#nothiddendiv");
$div.height( 30 ).height(function(i, height) {
equal( height, 30, "Make sure previous value is correct." );
return height + 1;
});
equal( $div.height(), 31, "Make sure value was modified correctly." );
});
test("innerWidth()", function() {
expect(6);
var $div, div,
$win = jQuery( window ),
$doc = jQuery( document );
equal( jQuery( window ).innerWidth(), $win.width(), "Test on window" );
equal( jQuery( document ).innerWidth(), $doc.width(), "Test on document" );
$div = jQuery("#nothiddendiv");
// set styles
$div.css({
"margin": 10,
"border": "2px solid #fff",
"width": 30
});
equal($div.innerWidth(), 30, "Test with margin and border");
$div.css("padding", "20px");
equal($div.innerWidth(), 70, "Test with margin, border and padding");
$div.hide();
equal($div.innerWidth(), 70, "Test hidden div");
// reset styles
$div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" });
div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.innerWidth(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
QUnit.expectJqData( this, $div[0], "olddisplay" );
});
test("innerHeight()", function() {
expect(6);
var $div, div,
$win = jQuery( window ),
$doc = jQuery( document );
equal( jQuery( window ).innerHeight(), $win.height(), "Test on window" );
equal( jQuery( document ).innerHeight(), $doc.height(), "Test on document" );
$div = jQuery("#nothiddendiv");
// set styles
$div.css({
"margin": 10,
"border": "2px solid #fff",
"height": 30
});
equal($div.innerHeight(), 30, "Test with margin and border");
$div.css("padding", "20px");
equal($div.innerHeight(), 70, "Test with margin, border and padding");
$div.hide();
equal($div.innerHeight(), 70, "Test hidden div");
// reset styles
$div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" });
div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.innerHeight(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
QUnit.expectJqData( this, $div[0], "olddisplay" );
});
test("outerWidth()", function() {
expect(11);
var $div, div,
$win = jQuery( window ),
$doc = jQuery( document );
equal( jQuery( window ).outerWidth(), $win.width(), "Test on window without margin option" );
equal( jQuery( window ).outerWidth( true ), $win.width(), "Test on window with margin option" );
equal( jQuery( document ).outerWidth(), $doc.width(), "Test on document without margin option" );
equal( jQuery( document ).outerWidth( true ), $doc.width(), "Test on document with margin option" );
$div = jQuery("#nothiddendiv");
$div.css("width", 30);
equal($div.outerWidth(), 30, "Test with only width set");
$div.css("padding", "20px");
equal($div.outerWidth(), 70, "Test with padding");
$div.css("border", "2px solid #fff");
equal($div.outerWidth(), 74, "Test with padding and border");
$div.css("margin", "10px");
equal($div.outerWidth(), 74, "Test with padding, border and margin without margin option");
$div.css("position", "absolute");
equal($div.outerWidth(true), 94, "Test with padding, border and margin with margin option");
$div.hide();
equal($div.outerWidth(true), 94, "Test hidden div with padding, border and margin with margin option");
// reset styles
$div.css({ "position": "", "display": "", "border": "", "padding": "", "width": "", "height": "" });
div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.outerWidth(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
QUnit.expectJqData( this, $div[0], "olddisplay" );
});
test("child of a hidden elem (or unconnected node) has accurate inner/outer/Width()/Height() see #9441 #9300", function() {
expect(16);
// setup html
var $divNormal = jQuery("<div>").css({ "width": "100px", "height": "100px", "border": "10px solid white", "padding": "2px", "margin": "3px" }),
$divChild = $divNormal.clone(),
$divUnconnected = $divNormal.clone(),
$divHiddenParent = jQuery("<div>").css( "display", "none" ).append( $divChild ).appendTo("body");
$divNormal.appendTo("body");
// tests that child div of a hidden div works the same as a normal div
equal( $divChild.width(), $divNormal.width(), "child of a hidden element width() is wrong see #9441" );
equal( $divChild.innerWidth(), $divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see #9441" );
equal( $divChild.outerWidth(), $divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see #9441" );
equal( $divChild.outerWidth(true), $divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see #9300" );
equal( $divChild.height(), $divNormal.height(), "child of a hidden element height() is wrong see #9441" );
equal( $divChild.innerHeight(), $divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see #9441" );
equal( $divChild.outerHeight(), $divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see #9441" );
equal( $divChild.outerHeight(true), $divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see #9300" );
// tests that child div of an unconnected div works the same as a normal div
equal( $divUnconnected.width(), $divNormal.width(), "unconnected element width() is wrong see #9441" );
equal( $divUnconnected.innerWidth(), $divNormal.innerWidth(), "unconnected element innerWidth() is wrong see #9441" );
equal( $divUnconnected.outerWidth(), $divNormal.outerWidth(), "unconnected element outerWidth() is wrong see #9441" );
equal( $divUnconnected.outerWidth(true), $divNormal.outerWidth( true ), "unconnected element outerWidth( true ) is wrong see #9300" );
equal( $divUnconnected.height(), $divNormal.height(), "unconnected element height() is wrong see #9441" );
equal( $divUnconnected.innerHeight(), $divNormal.innerHeight(), "unconnected element innerHeight() is wrong see #9441" );
equal( $divUnconnected.outerHeight(), $divNormal.outerHeight(), "unconnected element outerHeight() is wrong see #9441" );
equal( $divUnconnected.outerHeight(true), $divNormal.outerHeight( true ), "unconnected element outerHeight( true ) is wrong see #9300" );
// teardown html
$divHiddenParent.remove();
$divNormal.remove();
});
test("getting dimensions shouldn't modify runtimeStyle see #9233", function() {
expect( 1 );
var $div = jQuery( "<div>" ).appendTo( "#qunit-fixture" ),
div = $div.get( 0 ),
runtimeStyle = div.runtimeStyle;
if ( runtimeStyle ) {
div.runtimeStyle.marginLeft = "12em";
div.runtimeStyle.left = "11em";
}
$div.outerWidth( true );
if ( runtimeStyle ) {
equal( div.runtimeStyle.left, "11em", "getting dimensions modifies runtimeStyle, see #9233" );
} else {
ok( true, "this browser doesn't support runtimeStyle, see #9233" );
}
$div.remove();
});
test( "table dimensions", 2, function() {
var table = jQuery("<table><colgroup><col/><col/></colgroup><tbody><tr><td></td><td>a</td></tr><tr><td></td><td>a</td></tr></tbody></table>").appendTo("#qunit-fixture"),
tdElem = table.find("td").first(),
colElem = table.find("col").first().width( 300 );
table.find("td").css({ "margin": 0, "padding": 0 });
equal( tdElem.width(), tdElem.width(), "width() doesn't alter dimension values of empty cells, see #11293" );
equal( colElem.width(), 300, "col elements have width(), see #12243" );
});
test("box-sizing:border-box child of a hidden elem (or unconnected node) has accurate inner/outer/Width()/Height() see #10413", function() {
expect(16);
// setup html
var $divNormal = jQuery("<div>").css({ "boxSizing": "border-box", "width": "100px", "height": "100px", "border": "10px solid white", "padding": "2px", "margin": "3px" }),
$divChild = $divNormal.clone(),
$divUnconnected = $divNormal.clone(),
$divHiddenParent = jQuery("<div>").css( "display", "none" ).append( $divChild ).appendTo("body");
$divNormal.appendTo("body");
// tests that child div of a hidden div works the same as a normal div
equal( $divChild.width(), $divNormal.width(), "child of a hidden element width() is wrong see #10413" );
equal( $divChild.innerWidth(), $divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see #10413" );
equal( $divChild.outerWidth(), $divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see #10413" );
equal( $divChild.outerWidth(true), $divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see #10413" );
equal( $divChild.height(), $divNormal.height(), "child of a hidden element height() is wrong see #10413" );
equal( $divChild.innerHeight(), $divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see #10413" );
equal( $divChild.outerHeight(), $divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see #10413" );
equal( $divChild.outerHeight(true), $divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see #10413" );
// tests that child div of an unconnected div works the same as a normal div
equal( $divUnconnected.width(), $divNormal.width(), "unconnected element width() is wrong see #10413" );
equal( $divUnconnected.innerWidth(), $divNormal.innerWidth(), "unconnected element innerWidth() is wrong see #10413" );
equal( $divUnconnected.outerWidth(), $divNormal.outerWidth(), "unconnected element outerWidth() is wrong see #10413" );
equal( $divUnconnected.outerWidth(true), $divNormal.outerWidth( true ), "unconnected element outerWidth( true ) is wrong see #10413" );
equal( $divUnconnected.height(), $divNormal.height(), "unconnected element height() is wrong see #10413" );
equal( $divUnconnected.innerHeight(), $divNormal.innerHeight(), "unconnected element innerHeight() is wrong see #10413" );
equal( $divUnconnected.outerHeight(), $divNormal.outerHeight(), "unconnected element outerHeight() is wrong see #10413" );
equal( $divUnconnected.outerHeight(true), $divNormal.outerHeight( true ), "unconnected element outerHeight( true ) is wrong see #10413" );
// teardown html
$divHiddenParent.remove();
$divNormal.remove();
});
test("outerHeight()", function() {
expect(11);
var $div, div,
$win = jQuery( window ),
$doc = jQuery( document );
equal( jQuery( window ).outerHeight(), $win.height(), "Test on window without margin option" );
equal( jQuery( window ).outerHeight( true ), $win.height(), "Test on window with margin option" );
equal( jQuery( document ).outerHeight(), $doc.height(), "Test on document without margin option" );
equal( jQuery( document ).outerHeight( true ), $doc.height(), "Test on document with margin option" );
$div = jQuery("#nothiddendiv");
$div.css("height", 30);
equal($div.outerHeight(), 30, "Test with only width set");
$div.css("padding", "20px");
equal($div.outerHeight(), 70, "Test with padding");
$div.css("border", "2px solid #fff");
equal($div.outerHeight(), 74, "Test with padding and border");
$div.css("margin", "10px");
equal($div.outerHeight(), 74, "Test with padding, border and margin without margin option");
equal($div.outerHeight(true), 94, "Test with padding, border and margin with margin option");
$div.hide();
equal($div.outerHeight(true), 94, "Test hidden div with padding, border and margin with margin option");
// reset styles
$div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" });
div = jQuery( "<div>" );
// Temporarily require 0 for backwards compat - should be auto
equal( div.outerHeight(), 0, "Make sure that disconnected nodes are handled." );
div.remove();
QUnit.expectJqData( this, $div[0], "olddisplay" );
});
test("passing undefined is a setter #5571", function() {
expect(4);
equal(jQuery("#nothiddendiv").height(30).height(undefined).height(), 30, ".height(undefined) is chainable (#5571)");
equal(jQuery("#nothiddendiv").height(30).innerHeight(undefined).height(), 30, ".innerHeight(undefined) is chainable (#5571)");
equal(jQuery("#nothiddendiv").height(30).outerHeight(undefined).height(), 30, ".outerHeight(undefined) is chainable (#5571)");
equal(jQuery("#nothiddendiv").width(30).width(undefined).width(), 30, ".width(undefined) is chainable (#5571)");
});
test( "getters on non elements should return null", function() {
expect( 8 );
var nonElem = jQuery("notAnElement");
strictEqual( nonElem.width(), null, ".width() is not null (#12283)" );
strictEqual( nonElem.innerWidth(), null, ".innerWidth() is not null (#12283)" );
strictEqual( nonElem.outerWidth(), null, ".outerWidth() is not null (#12283)" );
strictEqual( nonElem.outerWidth( true ), null, ".outerWidth(true) is not null (#12283)" );
strictEqual( nonElem.height(), null, ".height() is not null (#12283)" );
strictEqual( nonElem.innerHeight(), null, ".innerHeight() is not null (#12283)" );
strictEqual( nonElem.outerHeight(), null, ".outerHeight() is not null (#12283)" );
strictEqual( nonElem.outerHeight( true ), null, ".outerHeight(true) is not null (#12283)" );
});
test("setters with and without box-sizing:border-box", function(){
expect(20);
// Support: Android 2.3 (-webkit-box-sizing).
var el_bb = jQuery("<div style='width:114px;height:114px;margin:5px;padding:3px;border:4px solid white;-webkit-box-sizing:border-box;box-sizing:border-box;'>test</div>").appendTo("#qunit-fixture"),
el = jQuery("<div style='width:100px;height:100px;margin:5px;padding:3px;border:4px solid white;'>test</div>").appendTo("#qunit-fixture"),
expected = 100;
equal( el_bb.width( 101 ).width(), expected + 1, "test border-box width(int) by roundtripping" );
equal( el_bb.innerWidth( 108 ).width(), expected + 2, "test border-box innerWidth(int) by roundtripping" );
equal( el_bb.outerWidth( 117 ).width(), expected + 3, "test border-box outerWidth(int) by roundtripping" );
equal( el_bb.outerWidth( 118, false ).width(), expected + 4, "test border-box outerWidth(int, false) by roundtripping" );
equal( el_bb.outerWidth( 129, true ).width(), expected + 5, "test border-box innerWidth(int, true) by roundtripping" );
equal( el_bb.height( 101 ).height(), expected + 1, "test border-box height(int) by roundtripping" );
equal( el_bb.innerHeight( 108 ).height(), expected + 2, "test border-box innerHeight(int) by roundtripping" );
equal( el_bb.outerHeight( 117 ).height(), expected + 3, "test border-box outerHeight(int) by roundtripping" );
equal( el_bb.outerHeight( 118, false ).height(), expected + 4, "test border-box outerHeight(int, false) by roundtripping" );
equal( el_bb.outerHeight( 129, true ).height(), expected + 5, "test border-box innerHeight(int, true) by roundtripping" );
equal( el.width( 101 ).width(), expected + 1, "test border-box width(int) by roundtripping" );
equal( el.innerWidth( 108 ).width(), expected + 2, "test border-box innerWidth(int) by roundtripping" );
equal( el.outerWidth( 117 ).width(), expected + 3, "test border-box outerWidth(int) by roundtripping" );
equal( el.outerWidth( 118, false ).width(), expected + 4, "test border-box outerWidth(int, false) by roundtripping" );
equal( el.outerWidth( 129, true ).width(), expected + 5, "test border-box innerWidth(int, true) by roundtripping" );
equal( el.height( 101 ).height(), expected + 1, "test border-box height(int) by roundtripping" );
equal( el.innerHeight( 108 ).height(), expected + 2, "test border-box innerHeight(int) by roundtripping" );
equal( el.outerHeight( 117 ).height(), expected + 3, "test border-box outerHeight(int) by roundtripping" );
equal( el.outerHeight( 118, false ).height(), expected + 4, "test border-box outerHeight(int, false) by roundtripping" );
equal( el.outerHeight( 129, true ).height(), expected + 5, "test border-box innerHeight(int, true) by roundtripping" );
});
testIframe( "dimensions/documentLarge", "window vs. large document", function( jQuery, window, document ) {
expect(2);
ok( jQuery( document ).height() > jQuery( window ).height(), "document height is larger than window height" );
ok( jQuery( document ).width() > jQuery( window ).width(), "document width is larger than window width" );
});
test( "allow modification of coordinates argument (gh-1848)", 1, function() {
var element = jQuery( "<div/>" ).appendTo( "#qunit-fixture" );
element.offset(function( index, coords ) {
coords.top = 100;
return coords;
});
equal( element.offset().top, 100, "coordinates are modified" );
});
})();
| Tests: Tilt at a few style guide windmills
Ref 3c13f4c6297566a71102c2362347987f6d6a636e
| test/unit/dimensions.js | Tests: Tilt at a few style guide windmills | <ide><path>est/unit/dimensions.js
<ide> });
<ide>
<ide> test("innerWidth()", function() {
<del> expect(6);
<add> expect( 6 );
<ide>
<ide> var $div, div,
<ide> $win = jQuery( window ),
<ide> equal( jQuery( window ).innerWidth(), $win.width(), "Test on window" );
<ide> equal( jQuery( document ).innerWidth(), $doc.width(), "Test on document" );
<ide>
<del> $div = jQuery("#nothiddendiv");
<del> // set styles
<add> $div = jQuery( "#nothiddendiv" );
<ide> $div.css({
<ide> "margin": 10,
<ide> "border": "2px solid #fff",
<ide> "width": 30
<ide> });
<ide>
<del> equal($div.innerWidth(), 30, "Test with margin and border");
<del> $div.css("padding", "20px");
<del> equal($div.innerWidth(), 70, "Test with margin, border and padding");
<del> $div.hide();
<del> equal($div.innerWidth(), 70, "Test hidden div");
<add> equal( $div.innerWidth(), 30, "Test with margin and border" );
<add> $div.css( "padding", "20px" );
<add> equal( $div.innerWidth(), 70, "Test with margin, border and padding" );
<add> $div.hide();
<add> equal( $div.innerWidth(), 70, "Test hidden div" );
<ide>
<ide> // reset styles
<ide> $div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" });
<ide> equal( div.innerWidth(), 0, "Make sure that disconnected nodes are handled." );
<ide>
<ide> div.remove();
<del> QUnit.expectJqData( this, $div[0], "olddisplay" );
<add> QUnit.expectJqData( this, $div[ 0 ], "olddisplay" );
<ide> });
<ide>
<ide> test("innerHeight()", function() {
<del> expect(6);
<add> expect( 6 );
<ide>
<ide> var $div, div,
<ide> $win = jQuery( window ),
<ide> equal( jQuery( window ).innerHeight(), $win.height(), "Test on window" );
<ide> equal( jQuery( document ).innerHeight(), $doc.height(), "Test on document" );
<ide>
<del> $div = jQuery("#nothiddendiv");
<del> // set styles
<add> $div = jQuery( "#nothiddendiv" );
<ide> $div.css({
<ide> "margin": 10,
<ide> "border": "2px solid #fff",
<ide> "height": 30
<ide> });
<ide>
<del> equal($div.innerHeight(), 30, "Test with margin and border");
<del> $div.css("padding", "20px");
<del> equal($div.innerHeight(), 70, "Test with margin, border and padding");
<del> $div.hide();
<del> equal($div.innerHeight(), 70, "Test hidden div");
<add> equal( $div.innerHeight(), 30, "Test with margin and border" );
<add> $div.css( "padding", "20px" );
<add> equal( $div.innerHeight(), 70, "Test with margin, border and padding" );
<add> $div.hide();
<add> equal( $div.innerHeight(), 70, "Test hidden div" );
<ide>
<ide> // reset styles
<ide> $div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" });
<ide> equal( div.innerHeight(), 0, "Make sure that disconnected nodes are handled." );
<ide>
<ide> div.remove();
<del> QUnit.expectJqData( this, $div[0], "olddisplay" );
<add> QUnit.expectJqData( this, $div[ 0 ], "olddisplay" );
<ide> });
<ide>
<ide> test("outerWidth()", function() {
<del> expect(11);
<add> expect( 11 );
<ide>
<ide> var $div, div,
<ide> $win = jQuery( window ),
<ide> equal( jQuery( document ).outerWidth(), $doc.width(), "Test on document without margin option" );
<ide> equal( jQuery( document ).outerWidth( true ), $doc.width(), "Test on document with margin option" );
<ide>
<del> $div = jQuery("#nothiddendiv");
<del> $div.css("width", 30);
<del>
<del> equal($div.outerWidth(), 30, "Test with only width set");
<del> $div.css("padding", "20px");
<del> equal($div.outerWidth(), 70, "Test with padding");
<del> $div.css("border", "2px solid #fff");
<del> equal($div.outerWidth(), 74, "Test with padding and border");
<del> $div.css("margin", "10px");
<del> equal($div.outerWidth(), 74, "Test with padding, border and margin without margin option");
<del> $div.css("position", "absolute");
<del> equal($div.outerWidth(true), 94, "Test with padding, border and margin with margin option");
<del> $div.hide();
<del> equal($div.outerWidth(true), 94, "Test hidden div with padding, border and margin with margin option");
<add> $div = jQuery( "#nothiddendiv" );
<add> $div.css( "width", 30 );
<add>
<add> equal( $div.outerWidth(), 30, "Test with only width set" );
<add> $div.css( "padding", "20px" );
<add> equal( $div.outerWidth(), 70, "Test with padding" );
<add> $div.css( "border", "2px solid #fff" );
<add> equal( $div.outerWidth(), 74, "Test with padding and border" );
<add> $div.css( "margin", "10px" );
<add> equal( $div.outerWidth(), 74, "Test with padding, border and margin without margin option" );
<add> $div.css( "position", "absolute" );
<add> equal( $div.outerWidth( true ), 94, "Test with padding, border and margin with margin option" );
<add> $div.hide();
<add> equal( $div.outerWidth( true ), 94, "Test hidden div with padding, border and margin with margin option" );
<ide>
<ide> // reset styles
<ide> $div.css({ "position": "", "display": "", "border": "", "padding": "", "width": "", "height": "" });
<ide> equal( div.outerWidth(), 0, "Make sure that disconnected nodes are handled." );
<ide>
<ide> div.remove();
<del> QUnit.expectJqData( this, $div[0], "olddisplay" );
<add> QUnit.expectJqData( this, $div[ 0 ], "olddisplay" );
<ide> });
<ide>
<ide> test("child of a hidden elem (or unconnected node) has accurate inner/outer/Width()/Height() see #9441 #9300", function() {
<ide> });
<ide>
<ide> test("outerHeight()", function() {
<del> expect(11);
<add> expect( 11 );
<ide>
<ide> var $div, div,
<ide> $win = jQuery( window ),
<ide> equal( jQuery( document ).outerHeight(), $doc.height(), "Test on document without margin option" );
<ide> equal( jQuery( document ).outerHeight( true ), $doc.height(), "Test on document with margin option" );
<ide>
<del> $div = jQuery("#nothiddendiv");
<del> $div.css("height", 30);
<del>
<del> equal($div.outerHeight(), 30, "Test with only width set");
<del> $div.css("padding", "20px");
<del> equal($div.outerHeight(), 70, "Test with padding");
<del> $div.css("border", "2px solid #fff");
<del> equal($div.outerHeight(), 74, "Test with padding and border");
<del> $div.css("margin", "10px");
<del> equal($div.outerHeight(), 74, "Test with padding, border and margin without margin option");
<del> equal($div.outerHeight(true), 94, "Test with padding, border and margin with margin option");
<del> $div.hide();
<del> equal($div.outerHeight(true), 94, "Test hidden div with padding, border and margin with margin option");
<add> $div = jQuery( "#nothiddendiv" );
<add> $div.css( "height", 30 );
<add>
<add> equal( $div.outerHeight(), 30, "Test with only width set" );
<add> $div.css( "padding", "20px" );
<add> equal( $div.outerHeight(), 70, "Test with padding" );
<add> $div.css( "border", "2px solid #fff" );
<add> equal( $div.outerHeight(), 74, "Test with padding and border" );
<add> $div.css( "margin", "10px" );
<add> equal( $div.outerHeight(), 74, "Test with padding, border and margin without margin option" );
<add> equal( $div.outerHeight( true ), 94, "Test with padding, border and margin with margin option" );
<add> $div.hide();
<add> equal( $div.outerHeight( true ), 94, "Test hidden div with padding, border and margin with margin option" );
<ide>
<ide> // reset styles
<ide> $div.css({ "display": "", "border": "", "padding": "", "width": "", "height": "" });
<ide> equal( div.outerHeight(), 0, "Make sure that disconnected nodes are handled." );
<ide>
<ide> div.remove();
<del> QUnit.expectJqData( this, $div[0], "olddisplay" );
<add> QUnit.expectJqData( this, $div[ 0 ], "olddisplay" );
<ide> });
<ide>
<ide> test("passing undefined is a setter #5571", function() { |
|
Java | apache-2.0 | eae821ea38ddf4bef983d170b0fe40b15dfd47bb | 0 | dflemstr/helios,molindo/helios,skinzer/helios,molindo/helios,udomsak/helios,mattnworb/helios,DagensNyheter/helios,dflemstr/helios,udomsak/helios,DagensNyheter/helios,skinzer/helios,mattnworb/helios,spotify/helios,gtonic/helios,skinzer/helios,mbruggmann/helios,gtonic/helios,spotify/helios,stewnorriss/helios,kidaa/helios,mbruggmann/helios,mavenraven/helios,mbruggmann/helios,kidaa/helios,kidaa/helios,mavenraven/helios,molindo/helios,dflemstr/helios,stewnorriss/helios,mavenraven/helios,DagensNyheter/helios,mattnworb/helios,spotify/helios,udomsak/helios,stewnorriss/helios,gtonic/helios | /*
* Copyright (c) 2014 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.helios.testing;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.descriptors.Job;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.common.descriptors.JobStatus;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
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.ThreadPoolExecutor;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.containsPattern;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Lists.newArrayList;
import static com.spotify.helios.testing.Jobs.undeploy;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.fail;
public class TemporaryJobs implements TestRule {
private static final Logger log = LoggerFactory.getLogger(TemporaryJob.class);
private static final String DEFAULT_USER = System.getProperty("user.name");
private static final Prober DEFAULT_PROBER = new DefaultProber();
private static final String DEFAULT_LOCAL_HOST_FILTER = ".*";
private static final String DEFAULT_HOST_FILTER = System.getenv("HELIOS_HOST_FILTER");
private static final String DEFAULT_PREFIX_DIRECTORY = "/tmp/helios-temp-jobs";
private static final long JOB_HEALTH_CHECK_INTERVAL_MILLIS = SECONDS.toMillis(5);
private final HeliosClient client;
private final Prober prober;
private final String defaultHostFilter;
private final JobPrefixFile jobPrefixFile;
private final List<TemporaryJob> jobs = Lists.newCopyOnWriteArrayList();
private final ExecutorService executor = MoreExecutors.getExitingExecutorService(
(ThreadPoolExecutor) Executors.newFixedThreadPool(
1, new ThreadFactoryBuilder()
.setNameFormat("helios-temporary-jobs-test-runner-%d")
.setDaemon(true)
.build()),
0, SECONDS);
private final TemporaryJob.Deployer deployer = new TemporaryJob.Deployer() {
@Override
public TemporaryJob deploy(final Job job, final String hostFilter,
final Set<String> waitPorts) {
if (isNullOrEmpty(hostFilter)) {
fail("a host filter pattern must be passed to hostFilter(), " +
"or one must be specified in HELIOS_HOST_FILTER");
}
final List<String> hosts;
try {
log.info("Getting list of hosts");
hosts = client.listHosts().get();
} catch (InterruptedException | ExecutionException e) {
throw new AssertionError("Failed to get list of Helios hosts", e);
}
final List<String> filteredHosts = FluentIterable.from(hosts)
.filter(containsPattern(hostFilter))
.toList();
if (filteredHosts.isEmpty()) {
fail(format("no hosts matched the filter pattern - %s", hostFilter));
}
final String chosenHost = filteredHosts.get(new Random().nextInt(filteredHosts.size()));
return deploy(job, asList(chosenHost), waitPorts);
}
@Override
public TemporaryJob deploy(final Job job, final List<String> hosts,
final Set<String> waitPorts) {
if (!started) {
fail("deploy() must be called in a @Before or in the test method, or perhaps you forgot"
+ " to put @Rule before TemporaryJobs");
}
if (hosts.isEmpty()) {
fail("at least one host must be explicitly specified, or deploy() must be called with " +
"no arguments to automatically select a host");
}
log.info("Deploying {} to {}", job.getImage(), Joiner.on(", ").skipNulls().join(hosts));
final TemporaryJob temporaryJob = new TemporaryJob(client, prober, job, hosts, waitPorts);
jobs.add(temporaryJob);
temporaryJob.deploy();
return temporaryJob;
}
};
private boolean started;
TemporaryJobs(final Builder builder) {
this.client = checkNotNull(builder.client, "client");
this.prober = checkNotNull(builder.prober, "prober");
this.defaultHostFilter = checkNotNull(builder.hostFilter, "hostFilter");
final Path prefixDirectory = Paths.get(Optional.fromNullable(builder.prefixDirectory)
.or(DEFAULT_PREFIX_DIRECTORY));
try {
removeOldJobs(prefixDirectory);
this.jobPrefixFile = JobPrefixFile.create(prefixDirectory);
} catch (IOException | ExecutionException | InterruptedException e) {
throw Throwables.propagate(e);
}
}
public TemporaryJobBuilder job() {
return new TemporaryJobBuilder(deployer, jobPrefixFile.prefix())
.hostFilter(defaultHostFilter);
}
/**
* Creates a new instance of TemporaryJobs. Will attempt to connect to a helios master at
* http://localhost:5801 by default. This can be overridden by setting one of two environment
* variables.
* <ul>
* <li>HELIOS_DOMAIN - any domain which contains a helios master</li>
* <li>HELIOS_ENDPOINTS - a comma separated list of helios master endpoints</li>
* </ul>
* If both variables are set, HELIOS_DOMAIN will take precedence.
* @return an instance of TemporaryJobs
*/
public static TemporaryJobs create() {
final String domain = System.getenv("HELIOS_DOMAIN");
if (!isNullOrEmpty(domain)) {
return create(domain);
}
final String endpoints = System.getenv("HELIOS_ENDPOINTS");
final Builder builder = builder();
if (!isNullOrEmpty(endpoints)) {
builder.endpointStrings(Splitter.on(',').splitToList(endpoints));
} else {
// We're running locally
builder.hostFilter(Optional.fromNullable(DEFAULT_HOST_FILTER).or(DEFAULT_LOCAL_HOST_FILTER));
builder.endpoints("http://localhost:5801");
}
return builder.build();
}
public static TemporaryJobs create(final HeliosClient client) {
return builder().client(client).build();
}
public static TemporaryJobs create(final String domain) {
return builder().domain(domain).build();
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
before();
try {
perform(base);
} finally {
after();
}
}
};
}
private void perform(final Statement base)
throws InterruptedException {// Run the actual test on a thread
final Future<Object> future = executor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
try {
base.evaluate();
} catch (Throwable throwable) {
Throwables.propagateIfPossible(throwable, Exception.class);
throw Throwables.propagate(throwable);
}
return null;
}
});
// Monitor jobs while test is running
while (!future.isDone()) {
Thread.sleep(JOB_HEALTH_CHECK_INTERVAL_MILLIS);
verifyJobsHealthy();
}
// Rethrow test failure, if any
try {
future.get();
} catch (ExecutionException e) {
final Throwable cause = (e.getCause() == null) ? e : e.getCause();
throw Throwables.propagate(cause);
}
}
private void verifyJobsHealthy() throws AssertionError {
for (TemporaryJob job : jobs) {
job.verifyHealthy();
}
}
private void before() {
started = true;
}
private void after() {
// Stop the test runner thread
executor.shutdownNow();
try {
final boolean terminated = executor.awaitTermination(30, SECONDS);
if (!terminated) {
log.warn("Failed to stop test runner thread");
}
} catch (InterruptedException ignore) {
}
final List<AssertionError> errors = newArrayList();
log.info("Undeploying temporary jobs");
for (TemporaryJob job : jobs) {
job.undeploy(errors);
}
for (AssertionError error : errors) {
log.error(error.getMessage());
}
// Don't delete the prefix file if any errors occurred during undeployment, so that we'll
// try to undeploy them the next time TemporaryJobs is run.
if (errors.isEmpty()) {
jobPrefixFile.delete();
}
}
/**
* Undeploys and deletes jobs leftover from previous runs of TemporaryJobs. This would happen if
* the test was terminated before the cleanup code was called. This method will iterate over each
* file in the specified directory. Each filename is the prefix that was used for job names
* during previous runs. The method will undeploy and delete any jobs that have a matching
* prefix, and the delete the file. If the file is locked, it is currently in use, and will be
* skipped.
* @throws ExecutionException
* @throws InterruptedException
* @throws IOException
*/
private void removeOldJobs(final Path prefixDirectory)
throws ExecutionException, InterruptedException, IOException {
final File[] files = prefixDirectory.toFile().listFiles();
if (files == null) {
return;
}
log.info("Removing old temporary jobs");
final Map<JobId, Job> jobs = client.jobs().get();
// Iterate over all files in the directory
for (File file : files) {
// Skip .tmp files which are generated when JobPrefixFiles are created. Also skip
// directories. We don't expect any, but skip them just in case.
if (file.getName().endsWith(".tmp") || file.isDirectory()) {
continue;
}
// If we can't obtain a lock for the file, it either has already been deleted, or is being
// used by another process. In either case, skip over it.
try (
JobPrefixFile prefixFile = JobPrefixFile.tryFromExistingFile(file.toPath())
) {
if (prefixFile == null) {
log.debug("Unable to create JobPrefixFile for {}", file.getPath());
continue;
}
boolean jobRemovalFailed = false;
// Iterate over jobs, looking for ones with a matching prefix.
for (Map.Entry<JobId, Job> entry : jobs.entrySet()) {
final JobId jobId = entry.getKey();
// Skip over job if the id doesn't start with current filename.
if (!jobId.getName().startsWith(prefixFile.prefix())) {
continue;
}
// Get list of all hosts where this job is deployed, and undeploy
log.info("Getting status for job {}", jobId);
final JobStatus status = client.jobStatus(entry.getKey()).get();
final List<String> hosts = ImmutableList.copyOf(status.getDeployments().keySet());
log.info("Undeploying job {} from hosts {}",
jobId,
Joiner.on(", ").skipNulls().join(hosts));
final List<AssertionError> errors =
undeploy(client, jobId, hosts, new ArrayList<AssertionError>());
// Set flag indicating if any errors occur
if (!errors.isEmpty()) {
jobRemovalFailed = true;
}
}
// If all jobs were removed successfully, then delete the prefix file. Otherwise,
// leave it there so we can try again next time.
if (!jobRemovalFailed) {
prefixFile.delete();
}
} catch (Exception e) {
// log exception and continue on to next file
log.warn("Exception processing file {}", file.getPath(), e);
}
}
}
public JobPrefixFile jobPrefixFile() {
return jobPrefixFile;
}
public String prefix() {
return jobPrefixFile.prefix();
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
Builder() {
}
private String user = DEFAULT_USER;
private Prober prober = DEFAULT_PROBER;
private String hostFilter = DEFAULT_HOST_FILTER;
private HeliosClient client;
private String prefixDirectory;
public Builder domain(final String domain) {
return client(HeliosClient.newBuilder()
.setUser(user)
.setDomain(domain)
.build());
}
public Builder endpoints(final String... endpoints) {
return endpointStrings(asList(endpoints));
}
public Builder endpointStrings(final List<String> endpoints) {
return client(HeliosClient.newBuilder()
.setUser(user)
.setEndpointStrings(endpoints)
.build());
}
public Builder endpoints(final URI... endpoints) {
return endpoints(asList(endpoints));
}
public Builder endpoints(final List<URI> endpoints) {
return client(HeliosClient.newBuilder()
.setUser(user)
.setEndpoints(endpoints)
.build());
}
public Builder user(final String user) {
this.user = user;
return this;
}
public Builder prober(final Prober prober) {
this.prober = prober;
return this;
}
public Builder client(final HeliosClient client) {
this.client = client;
return this;
}
public Builder hostFilter(final String hostFilter) {
this.hostFilter = hostFilter;
return this;
}
public Builder prefixDirectory(final String prefixDirectory) {
this.prefixDirectory = prefixDirectory;
return this;
}
public TemporaryJobs build() {
return new TemporaryJobs(this);
}
}
}
| helios-testing/src/main/java/com/spotify/helios/testing/TemporaryJobs.java | /*
* Copyright (c) 2014 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.helios.testing;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.descriptors.Job;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.common.descriptors.JobStatus;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
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.ThreadPoolExecutor;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.containsPattern;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Lists.newArrayList;
import static com.spotify.helios.testing.Jobs.undeploy;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.fail;
public class TemporaryJobs implements TestRule {
private static final Logger log = LoggerFactory.getLogger(TemporaryJob.class);
private static final String DEFAULT_USER = System.getProperty("user.name");
private static final Prober DEFAULT_PROBER = new DefaultProber();
private static final String DEFAULT_LOCAL_HOST_FILTER = ".*";
private static final String DEFAULT_HOST_FILTER = System.getenv("HELIOS_HOST_FILTER");
private static final String DEFAULT_PREFIX_DIRECTORY = "/tmp/helios-temp-jobs";
private static final long JOB_HEALTH_CHECK_INTERVAL_MILLIS = SECONDS.toMillis(5);
private final HeliosClient client;
private final Prober prober;
private final String defaultHostFilter;
private final JobPrefixFile jobPrefixFile;
private final List<TemporaryJob> jobs = Lists.newCopyOnWriteArrayList();
private final ExecutorService executor = MoreExecutors.getExitingExecutorService(
(ThreadPoolExecutor) Executors.newFixedThreadPool(
1, new ThreadFactoryBuilder()
.setNameFormat("helios-temporary-jobs-test-runner-%d")
.setDaemon(true)
.build()),
0, SECONDS);
private final TemporaryJob.Deployer deployer = new TemporaryJob.Deployer() {
@Override
public TemporaryJob deploy(final Job job, final String hostFilter,
final Set<String> waitPorts) {
if (isNullOrEmpty(hostFilter)) {
fail("a host filter pattern must be passed to hostFilter(), " +
"or one must be specified in HELIOS_HOST_FILTER");
}
final List<String> hosts;
try {
log.info("Getting list of hosts");
hosts = client.listHosts().get();
} catch (InterruptedException | ExecutionException e) {
throw new AssertionError("Failed to get list of Helios hosts", e);
}
final List<String> filteredHosts = FluentIterable.from(hosts)
.filter(containsPattern(hostFilter))
.toList();
if (filteredHosts.isEmpty()) {
fail(format("no hosts matched the filter pattern - %s", hostFilter));
}
final String chosenHost = filteredHosts.get(new Random().nextInt(filteredHosts.size()));
return deploy(job, asList(chosenHost), waitPorts);
}
@Override
public TemporaryJob deploy(final Job job, final List<String> hosts,
final Set<String> waitPorts) {
if (!started) {
fail("deploy() must be called in a @Before or in the test method, or perhaps you forgot"
+ " to put @Rule before TemporaryJobs");
}
if (hosts.isEmpty()) {
fail("at least one host must be explicitly specified, or deploy() must be called with " +
"no arguments to automatically select a host");
}
log.info("Deploying {} to {}", job.getImage(), Joiner.on(", ").skipNulls().join(hosts));
final TemporaryJob temporaryJob = new TemporaryJob(client, prober, job, hosts, waitPorts);
jobs.add(temporaryJob);
temporaryJob.deploy();
return temporaryJob;
}
};
private boolean started;
TemporaryJobs(final Builder builder) {
this.client = checkNotNull(builder.client, "client");
this.prober = checkNotNull(builder.prober, "prober");
this.defaultHostFilter = checkNotNull(builder.hostFilter, "hostFilter");
final Path prefixDirectory = Paths.get(Optional.fromNullable(builder.prefixDirectory)
.or(DEFAULT_PREFIX_DIRECTORY));
try {
removeOldJobs(prefixDirectory);
this.jobPrefixFile = JobPrefixFile.create(prefixDirectory);
} catch (IOException | ExecutionException | InterruptedException e) {
throw Throwables.propagate(e);
}
}
public TemporaryJobBuilder job() {
return new TemporaryJobBuilder(deployer, jobPrefixFile.prefix())
.hostFilter(defaultHostFilter);
}
/**
* Creates a new instance of TemporaryJobs. Will attempt to connect to a helios master at
* http://localhost:5801 by default. This can be overridden by setting one of two environment
* variables.
* <ul>
* <li>HELIOS_DOMAIN - any domain which contains a helios master</li>
* <li>HELIOS_ENDPOINTS - a comma separated list of helios master endpoints</li>
* </ul>
* If both variables are set, HELIOS_DOMAIN will take precedence.
* @return an instance of TemporaryJobs
*/
public static TemporaryJobs create() {
final String domain = System.getenv("HELIOS_DOMAIN");
if (!isNullOrEmpty(domain)) {
return create(domain);
}
final String endpoints = System.getenv("HELIOS_ENDPOINTS");
final Builder builder = builder();
if (!isNullOrEmpty(endpoints)) {
builder.endpointStrings(Splitter.on(',').splitToList(endpoints));
} else {
// We're running locally
builder.hostFilter(Optional.fromNullable(DEFAULT_HOST_FILTER).or(DEFAULT_LOCAL_HOST_FILTER));
builder.endpoints("http://localhost:5801");
}
return builder.build();
}
public static TemporaryJobs create(final HeliosClient client) {
return builder().client(client).build();
}
public static TemporaryJobs create(final String domain) {
return builder().domain(domain).build();
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
// Run the actual test on a thread
final Future<Object> future = executor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
before();
try {
try {
base.evaluate();
} catch (Throwable throwable) {
Throwables.propagateIfPossible(throwable, Exception.class);
throw Throwables.propagate(throwable);
}
} finally {
after();
}
return null;
}
});
// Monitor jobs while test is running
while (!future.isDone()) {
Thread.sleep(JOB_HEALTH_CHECK_INTERVAL_MILLIS);
verifyJobsHealthy();
}
// Rethrow test failure, if any
try {
future.get();
} catch (ExecutionException e) {
final Throwable cause = (e.getCause() == null) ? e : e.getCause();
throw Throwables.propagate(cause);
}
}
};
}
private void verifyJobsHealthy() throws AssertionError {
for (TemporaryJob job : jobs) {
job.verifyHealthy();
}
}
private void before() {
started = true;
}
private void after() {
// Stop the test runner thread
executor.shutdownNow();
try {
final boolean terminated = executor.awaitTermination(30, SECONDS);
if (!terminated) {
log.warn("Failed to stop test runner thread");
}
} catch (InterruptedException ignore) {
}
final List<AssertionError> errors = newArrayList();
log.info("Undeploying temporary jobs");
for (TemporaryJob job : jobs) {
job.undeploy(errors);
}
for (AssertionError error : errors) {
log.error(error.getMessage());
}
// Don't delete the prefix file if any errors occurred during undeployment, so that we'll
// try to undeploy them the next time TemporaryJobs is run.
if (errors.isEmpty()) {
jobPrefixFile.delete();
}
}
/**
* Undeploys and deletes jobs leftover from previous runs of TemporaryJobs. This would happen if
* the test was terminated before the cleanup code was called. This method will iterate over each
* file in the specified directory. Each filename is the prefix that was used for job names
* during previous runs. The method will undeploy and delete any jobs that have a matching
* prefix, and the delete the file. If the file is locked, it is currently in use, and will be
* skipped.
* @throws ExecutionException
* @throws InterruptedException
* @throws IOException
*/
private void removeOldJobs(final Path prefixDirectory)
throws ExecutionException, InterruptedException, IOException {
final File[] files = prefixDirectory.toFile().listFiles();
if (files == null) {
return;
}
log.info("Removing old temporary jobs");
final Map<JobId, Job> jobs = client.jobs().get();
// Iterate over all files in the directory
for (File file : files) {
// Skip .tmp files which are generated when JobPrefixFiles are created. Also skip
// directories. We don't expect any, but skip them just in case.
if (file.getName().endsWith(".tmp") || file.isDirectory()) {
continue;
}
// If we can't obtain a lock for the file, it either has already been deleted, or is being
// used by another process. In either case, skip over it.
try (
JobPrefixFile prefixFile = JobPrefixFile.tryFromExistingFile(file.toPath())
) {
if (prefixFile == null) {
log.debug("Unable to create JobPrefixFile for {}", file.getPath());
continue;
}
boolean jobRemovalFailed = false;
// Iterate over jobs, looking for ones with a matching prefix.
for (Map.Entry<JobId, Job> entry : jobs.entrySet()) {
final JobId jobId = entry.getKey();
// Skip over job if the id doesn't start with current filename.
if (!jobId.getName().startsWith(prefixFile.prefix())) {
continue;
}
// Get list of all hosts where this job is deployed, and undeploy
log.info("Getting status for job {}", jobId);
final JobStatus status = client.jobStatus(entry.getKey()).get();
final List<String> hosts = ImmutableList.copyOf(status.getDeployments().keySet());
log.info("Undeploying job {} from hosts {}",
jobId,
Joiner.on(", ").skipNulls().join(hosts));
final List<AssertionError> errors =
undeploy(client, jobId, hosts, new ArrayList<AssertionError>());
// Set flag indicating if any errors occur
if (!errors.isEmpty()) {
jobRemovalFailed = true;
}
}
// If all jobs were removed successfully, then delete the prefix file. Otherwise,
// leave it there so we can try again next time.
if (!jobRemovalFailed) {
prefixFile.delete();
}
} catch (Exception e) {
// log exception and continue on to next file
log.warn("Exception processing file {}", file.getPath(), e);
}
}
}
public JobPrefixFile jobPrefixFile() {
return jobPrefixFile;
}
public String prefix() {
return jobPrefixFile.prefix();
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
Builder() {
}
private String user = DEFAULT_USER;
private Prober prober = DEFAULT_PROBER;
private String hostFilter = DEFAULT_HOST_FILTER;
private HeliosClient client;
private String prefixDirectory;
public Builder domain(final String domain) {
return client(HeliosClient.newBuilder()
.setUser(user)
.setDomain(domain)
.build());
}
public Builder endpoints(final String... endpoints) {
return endpointStrings(asList(endpoints));
}
public Builder endpointStrings(final List<String> endpoints) {
return client(HeliosClient.newBuilder()
.setUser(user)
.setEndpointStrings(endpoints)
.build());
}
public Builder endpoints(final URI... endpoints) {
return endpoints(asList(endpoints));
}
public Builder endpoints(final List<URI> endpoints) {
return client(HeliosClient.newBuilder()
.setUser(user)
.setEndpoints(endpoints)
.build());
}
public Builder user(final String user) {
this.user = user;
return this;
}
public Builder prober(final Prober prober) {
this.prober = prober;
return this;
}
public Builder client(final HeliosClient client) {
this.client = client;
return this;
}
public Builder hostFilter(final String hostFilter) {
this.hostFilter = hostFilter;
return this;
}
public Builder prefixDirectory(final String prefixDirectory) {
this.prefixDirectory = prefixDirectory;
return this;
}
public TemporaryJobs build() {
return new TemporaryJobs(this);
}
}
}
| TemporaryJobs: fix executor cleanup on job failure
* Run after() and before() on main thread instead of test thread.
* call after() in a finally to ensure that the executor is terminated. | helios-testing/src/main/java/com/spotify/helios/testing/TemporaryJobs.java | TemporaryJobs: fix executor cleanup on job failure | <ide><path>elios-testing/src/main/java/com/spotify/helios/testing/TemporaryJobs.java
<ide> return new Statement() {
<ide> @Override
<ide> public void evaluate() throws Throwable {
<del>
<del> // Run the actual test on a thread
<del> final Future<Object> future = executor.submit(new Callable<Object>() {
<del> @Override
<del> public Object call() throws Exception {
<del> before();
<del> try {
<del> try {
<del> base.evaluate();
<del> } catch (Throwable throwable) {
<del> Throwables.propagateIfPossible(throwable, Exception.class);
<del> throw Throwables.propagate(throwable);
<del> }
<del> } finally {
<del> after();
<del> }
<del> return null;
<del> }
<del> });
<del>
<del> // Monitor jobs while test is running
<del> while (!future.isDone()) {
<del> Thread.sleep(JOB_HEALTH_CHECK_INTERVAL_MILLIS);
<del> verifyJobsHealthy();
<add> before();
<add> try {
<add> perform(base);
<add> } finally {
<add> after();
<ide> }
<del>
<del> // Rethrow test failure, if any
<add> }
<add> };
<add> }
<add>
<add> private void perform(final Statement base)
<add> throws InterruptedException {// Run the actual test on a thread
<add> final Future<Object> future = executor.submit(new Callable<Object>() {
<add> @Override
<add> public Object call() throws Exception {
<ide> try {
<del> future.get();
<del> } catch (ExecutionException e) {
<del> final Throwable cause = (e.getCause() == null) ? e : e.getCause();
<del> throw Throwables.propagate(cause);
<add> base.evaluate();
<add> } catch (Throwable throwable) {
<add> Throwables.propagateIfPossible(throwable, Exception.class);
<add> throw Throwables.propagate(throwable);
<ide> }
<del> }
<del> };
<add> return null;
<add> }
<add> });
<add>
<add> // Monitor jobs while test is running
<add> while (!future.isDone()) {
<add> Thread.sleep(JOB_HEALTH_CHECK_INTERVAL_MILLIS);
<add> verifyJobsHealthy();
<add> }
<add>
<add> // Rethrow test failure, if any
<add> try {
<add> future.get();
<add> } catch (ExecutionException e) {
<add> final Throwable cause = (e.getCause() == null) ? e : e.getCause();
<add> throw Throwables.propagate(cause);
<add> }
<ide> }
<ide>
<ide> private void verifyJobsHealthy() throws AssertionError { |
|
Java | apache-2.0 | 3efb3a279e18d02f9bce5b6ad53708f411be91ad | 0 | shimib/scala,felixmulder/scala,felixmulder/scala,slothspot/scala,martijnhoekstra/scala,slothspot/scala,lrytz/scala,lrytz/scala,lrytz/scala,martijnhoekstra/scala,jvican/scala,slothspot/scala,felixmulder/scala,scala/scala,shimib/scala,jvican/scala,slothspot/scala,shimib/scala,martijnhoekstra/scala,lrytz/scala,felixmulder/scala,felixmulder/scala,shimib/scala,slothspot/scala,lrytz/scala,felixmulder/scala,shimib/scala,martijnhoekstra/scala,jvican/scala,jvican/scala,felixmulder/scala,scala/scala,slothspot/scala,shimib/scala,scala/scala,martijnhoekstra/scala,slothspot/scala,jvican/scala,jvican/scala,martijnhoekstra/scala,scala/scala,jvican/scala,scala/scala,scala/scala,lrytz/scala | /* ____ ____ ____ ____ ______ *\
** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL **
** /_____/\____/\___/\____/____/ **
\* */
// $Id$
package scalac.transformer;
import scalac.Global;
import scalac.util.Name;
import scalac.util.Names;
import scalac.ast.Tree;
import Tree.*;
import scalac.ast.Transformer;
import scalac.symtab.Type;
import scalac.symtab.Symbol;
import scalac.symtab.TermSymbol;
import scalac.symtab.Scope;
import scalac.symtab.Kinds;
import scalac.symtab.Modifiers;
import java.util.HashMap;
import java.util.HashSet;
import java.util.ArrayList;
import scalac.util.Debug;
/**
* 1. For each class add a single method (DefDef) designated as
* constructor whose parameters are the class parameters. The
* constructor contains:
* - call to the constructor of the supertype with the appropriate arguments
* - initialize the fields corresponding to the class ValDefs
* - the bodies of the class level expressions;
* they are also removed from the ClassDef body
*
* 2. The right hand sides of the ValDefs are left empty
*
* 3. Substitute the appropriate constructor symbol into the
* 'new' expressions
*
* @author Nikolay Mihaylov
* @version 1.2
*/
public class AddConstructors extends Transformer {
public final static Name CTOR_N = Names.CONSTRUCTOR;
// True iff we generate code for INT backend.
protected final boolean forINT;
// True iff we generate code for JVM backend.
protected final boolean forJVM;
// True iff we generate code for MSIL backend.
protected final boolean forMSIL;
final HashMap constructors;
public AddConstructors(Global global, HashMap constructors) {
super(global);
this.constructors = constructors;
this.forINT = global.target == global.TARGET_INT;
this.forJVM = global.target == global.TARGET_JVM;
this.forMSIL = global.target == global.TARGET_MSIL;
}
/** return new constructor symbol if it isn't already defined
*/
Symbol getConstructor(Symbol classConstr) {
return getConstructor(classConstr,
(((Type.MethodType)classConstr.info()).vparams),
classConstr.primaryConstructorClass());
}
Symbol getConstructor(Symbol classConstr, Symbol[] paramSyms, Symbol owner) {
assert classConstr.isConstructor() :
"Class constructor expected: " + Debug.show(classConstr);
Symbol constr = (Symbol) constructors.get(classConstr);
if (constr == null) {
assert !owner.isInterface() : Debug.show(owner) + " is interface";
int flags = forJVM
? classConstr.flags & (Modifiers.PRIVATE | Modifiers.PROTECTED)
: classConstr.flags;
constr =
new TermSymbol(classConstr.pos, CTOR_N, owner, flags);
Type constrType = Type.MethodType
(paramSyms, forJVM ?
global.definitions.UNIT_TYPE : owner.type()).erasure();
constr.setInfo(constrType.erasure());
constructors.put(classConstr, constr);
constructors.put(constr, constr);
}
return constr;
}
/** process the tree
*/
public Tree transform(Tree tree) {
Symbol treeSym = tree.symbol();
switch (tree) {
case ClassDef(_, _, _, ValDef[][] vparams, _, //:
Template(Tree[] baseClasses, Tree[] body)):
assert treeSym.name.isTypeName();
if (treeSym.isInterface())
return super.transform(tree);
Symbol[] paramSyms = new Symbol[vparams[0].length];
for (int i = 0; i < paramSyms.length; i++)
paramSyms[i] = vparams[0][i].symbol();
ArrayList constrBody = new ArrayList();
ArrayList classBody = new ArrayList();
Symbol constrSym =
getConstructor(treeSym.constructor(), paramSyms, treeSym);
Scope classScope = new Scope();
classScope.enter(constrSym);
assert constrSym.owner() == treeSym :
"Wrong owner of the constructor: \n\tfound: " +
Debug.show(constrSym.owner()) + "\n\texpected: " +
Debug.show(treeSym);
// inline the call to the super constructor
Type superType = treeSym.parents()[0];
if ( !forINT || !superType.symbol().isJava()) {
switch (baseClasses[0]) {
case Apply(Tree fun, Tree[] args):
int pos = baseClasses[0].pos;
Tree superConstr = gen.Select
(gen.Super(pos, superType),
getConstructor(fun.symbol()));
constrBody.add(gen.Apply(superConstr, transform(args)));
break;
default:
new scalac.ast.printer.TextTreePrinter().print(baseClasses[0]).println().end();
assert false;
}
}
// inline initialization of module values
if (forINT && treeSym.isModuleClass()) {
Symbol module = treeSym.module();
if (module.isGlobalModule()) {
constrBody.add(
gen.Assign(
gen.mkRef(tree.pos, module),
gen.This(tree.pos, treeSym)));
} else {
Symbol owner = module.owner();
Name module_eqname = module.name.append(Names._EQ);
Symbol module_eq = owner.lookup(module_eqname);
assert module != Symbol.NONE :Debug.show(treeSym.module());
if (owner.isModuleClass() && owner.module().isStable()) {
constrBody.add(
gen.Apply(
gen.mkRef(tree.pos, module_eq),
new Tree[] {gen.This(tree.pos, treeSym)}));
} else {
// !!! module_eq must be accessed via some outer field
}
}
}
// for every ValDef move the initialization code into the constructor
for (int i = 0; i < body.length; i++) {
Tree t = body[i];
if (t.definesSymbol()) {
Symbol sym = t.symbol();
switch (t) {
case ValDef(_, _, _, Tree rhs):
if (rhs != Tree.Empty) {
// !!!FIXME: revert to this.whatever when the bug is fixed
//Tree ident = gen.Select(gen.This(t.pos, treeSym), sym);
Tree ident = gen.Ident(sym);
constrBody.add
(gen.Assign(t.pos, ident, transform(rhs)));
t = gen.ValDef(sym, Tree.Empty);
}
break;
}
classBody.add(transform(t));
classScope.enterOrOverload(sym);
} else
// move every class-level expression into the constructor
constrBody.add(transform(t));
}
// add result expression consistent with the
// result type of the constructor
if (! forJVM)
constrBody.add(gen.This(tree.pos, treeSym));
Tree constrTree = constrBody.size() > 1 ?
gen.Block((Tree[])constrBody.
toArray(new Tree[constrBody.size()])):
(Tree) constrBody.get(0);
classBody.add(gen.DefDef(tree.pos, constrSym, constrTree));
// strip off the class constructor from parameters
switch (treeSym.constructor().info()) {
case MethodType(_, Type result):
treeSym.constructor().
updateInfo(Type.MethodType(Symbol.EMPTY_ARRAY, result));
break;
default : assert false;
}
Type classType =
Type.compoundType(treeSym.parents(), classScope, treeSym);
Symbol classSym = treeSym.updateInfo(classType);
Tree[] newBody = (Tree[]) classBody.toArray(Tree.EMPTY_ARRAY);
return gen.ClassDef(classSym, baseClasses, newBody);
// Substitute the constructor into the 'new' expressions
case New(Template(Tree[] baseClasses, _)):
Tree base = baseClasses[0];
switch (base) {
case Apply(Tree fun, Tree[] args):
return gen.New(copy.Apply
(base,
gen.Ident(base.pos, getConstructor(fun.symbol())),
transform(args)));
default:
assert false;
}
break;
} // switch(tree)
return super.transform(tree);
} // transform()
} // class AddConstructors
| sources/scalac/transformer/AddConstructors.java | /* ____ ____ ____ ____ ______ *\
** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL **
** /_____/\____/\___/\____/____/ **
\* */
// $Id$
package scalac.transformer;
import scalac.Global;
import scalac.util.Name;
import scalac.util.Names;
import scalac.ast.Tree;
import Tree.*;
import scalac.ast.Transformer;
import scalac.symtab.Type;
import scalac.symtab.Symbol;
import scalac.symtab.TermSymbol;
import scalac.symtab.Scope;
import scalac.symtab.Kinds;
import scalac.symtab.Modifiers;
import java.util.HashMap;
import java.util.HashSet;
import java.util.ArrayList;
import scalac.util.Debug;
/**
* 1. For each class add a single method (DefDef) designated as
* constructor whose parameters are the class parameters. The
* constructor contains:
* - call to the constructor of the supertype with the appropriate arguments
* - initialize the fields corresponding to the class ValDefs
* - the bodies of the class level expressions;
* they are also removed from the ClassDef body
*
* 2. The right hand sides of the ValDefs are left empty
*
* 3. Substitute the appropriate constructor symbol into the
* 'new' expressions
*
* @author Nikolay Mihaylov
* @version 1.2
*/
public class AddConstructors extends Transformer {
public final static Name CTOR_N = Names.CONSTRUCTOR;
// True iff we generate code for INT backend.
protected final boolean forINT;
// True iff we generate code for JVM backend.
protected final boolean forJVM;
// True iff we generate code for MSIL backend.
protected final boolean forMSIL;
final HashMap constructors;
public AddConstructors(Global global, HashMap constructors) {
super(global);
this.constructors = constructors;
this.forINT = global.target == global.TARGET_INT;
this.forJVM = global.target == global.TARGET_JVM;
this.forMSIL = global.target == global.TARGET_MSIL;
}
/** return new constructor symbol if it isn't already defined
*/
Symbol getConstructor(Symbol classConstr) {
return getConstructor(classConstr,
(((Type.MethodType)classConstr.info()).vparams),
classConstr.primaryConstructorClass());
}
Symbol getConstructor(Symbol classConstr, Symbol[] paramSyms, Symbol owner) {
assert classConstr.isConstructor() :
"Class constructor expected: " + Debug.show(classConstr);
Symbol constr = (Symbol) constructors.get(classConstr);
if (constr == null) {
assert !owner.isInterface() : Debug.show(owner) + " is interface";
int flags = forJVM
? classConstr.flags & (Modifiers.PRIVATE | Modifiers.PROTECTED)
: classConstr.flags;
constr =
new TermSymbol(classConstr.pos, CTOR_N, owner, flags);
Type constrType = Type.MethodType
(paramSyms, forJVM ?
global.definitions.UNIT_TYPE : owner.type()).erasure();
constr.setInfo(constrType.erasure());
constructors.put(classConstr, constr);
constructors.put(constr, constr);
}
return constr;
}
/** process the tree
*/
public Tree transform(Tree tree) {
Symbol treeSym = tree.symbol();
switch (tree) {
case ClassDef(_, _, _, ValDef[][] vparams, _, //:
Template(Tree[] baseClasses, Tree[] body)):
assert treeSym.name.isTypeName();
if (treeSym.isInterface())
return super.transform(tree);
Symbol[] paramSyms = new Symbol[vparams[0].length];
for (int i = 0; i < paramSyms.length; i++)
paramSyms[i] = vparams[0][i].symbol();
ArrayList constrBody = new ArrayList();
ArrayList classBody = new ArrayList();
Symbol constrSym =
getConstructor(treeSym.constructor(), paramSyms, treeSym);
Scope classScope = new Scope();
classScope.enter(constrSym);
assert constrSym.owner() == treeSym :
"Wrong owner of the constructor: \n\tfound: " +
Debug.show(constrSym.owner()) + "\n\texpected: " +
Debug.show(treeSym);
// inline the call to the super constructor
Type superType = treeSym.parents()[0];
if ( !forINT || !superType.symbol().isJava()) {
switch (baseClasses[0]) {
case Apply(Tree fun, Tree[] args):
int pos = baseClasses[0].pos;
Tree superConstr = gen.Select
(gen.Super(pos, superType),
getConstructor(fun.symbol()));
constrBody.add(gen.Apply(superConstr, transform(args)));
break;
default:
new scalac.ast.printer.TextTreePrinter().print(baseClasses[0]).println().end();
assert false;
}
}
// inline initialization of module values
if (forINT && treeSym.isModuleClass()) {
constrBody.add(
gen.Assign(
gen.mkRef(tree.pos, treeSym.module()),
gen.This(tree.pos, treeSym)));
}
// for every ValDef move the initialization code into the constructor
for (int i = 0; i < body.length; i++) {
Tree t = body[i];
if (t.definesSymbol()) {
Symbol sym = t.symbol();
switch (t) {
case ValDef(_, _, _, Tree rhs):
if (rhs != Tree.Empty) {
// !!!FIXME: revert to this.whatever when the bug is fixed
//Tree ident = gen.Select(gen.This(t.pos, treeSym), sym);
Tree ident = gen.Ident(sym);
constrBody.add
(gen.Assign(t.pos, ident, transform(rhs)));
t = gen.ValDef(sym, Tree.Empty);
}
break;
}
classBody.add(transform(t));
classScope.enterOrOverload(sym);
} else
// move every class-level expression into the constructor
constrBody.add(transform(t));
}
// add result expression consistent with the
// result type of the constructor
if (! forJVM)
constrBody.add(gen.This(tree.pos, treeSym));
Tree constrTree = constrBody.size() > 1 ?
gen.Block((Tree[])constrBody.
toArray(new Tree[constrBody.size()])):
(Tree) constrBody.get(0);
classBody.add(gen.DefDef(tree.pos, constrSym, constrTree));
// strip off the class constructor from parameters
switch (treeSym.constructor().info()) {
case MethodType(_, Type result):
treeSym.constructor().
updateInfo(Type.MethodType(Symbol.EMPTY_ARRAY, result));
break;
default : assert false;
}
Type classType =
Type.compoundType(treeSym.parents(), classScope, treeSym);
Symbol classSym = treeSym.updateInfo(classType);
Tree[] newBody = (Tree[]) classBody.toArray(Tree.EMPTY_ARRAY);
return gen.ClassDef(classSym, baseClasses, newBody);
// Substitute the constructor into the 'new' expressions
case New(Template(Tree[] baseClasses, _)):
Tree base = baseClasses[0];
switch (base) {
case Apply(Tree fun, Tree[] args):
return gen.New(copy.Apply
(base,
gen.Ident(base.pos, getConstructor(fun.symbol())),
transform(args)));
default:
assert false;
}
break;
} // switch(tree)
return super.transform(tree);
} // transform()
} // class AddConstructors
| - Fixed early initialization of module variable...
- Fixed early initialization of module variables (there are still
problems with some local modules).
| sources/scalac/transformer/AddConstructors.java | - Fixed early initialization of module variable... | <ide><path>ources/scalac/transformer/AddConstructors.java
<ide>
<ide> // inline initialization of module values
<ide> if (forINT && treeSym.isModuleClass()) {
<del> constrBody.add(
<del> gen.Assign(
<del> gen.mkRef(tree.pos, treeSym.module()),
<del> gen.This(tree.pos, treeSym)));
<add> Symbol module = treeSym.module();
<add> if (module.isGlobalModule()) {
<add> constrBody.add(
<add> gen.Assign(
<add> gen.mkRef(tree.pos, module),
<add> gen.This(tree.pos, treeSym)));
<add> } else {
<add> Symbol owner = module.owner();
<add> Name module_eqname = module.name.append(Names._EQ);
<add> Symbol module_eq = owner.lookup(module_eqname);
<add> assert module != Symbol.NONE :Debug.show(treeSym.module());
<add> if (owner.isModuleClass() && owner.module().isStable()) {
<add> constrBody.add(
<add> gen.Apply(
<add> gen.mkRef(tree.pos, module_eq),
<add> new Tree[] {gen.This(tree.pos, treeSym)}));
<add> } else {
<add> // !!! module_eq must be accessed via some outer field
<add> }
<add> }
<ide> }
<ide>
<ide> // for every ValDef move the initialization code into the constructor |
|
Java | apache-2.0 | 6aca74452eb798b4d39dfbd431ce40a996dc586c | 0 | samie/vaadin-ga-tracker | package org.vaadin.googleanalytics.tracking.demo;
import com.vaadin.annotations.VaadinServletConfiguration;
import org.vaadin.googleanalytics.tracking.GoogleAnalyticsTracker;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.UI;
import javax.servlet.annotation.WebServlet;
public class GoogleAnalyticsTrackerDemo extends UI {
private static final long serialVersionUID = 1L;
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = GoogleAnalyticsTrackerDemo.class)
public static class Servlet extends VaadinServlet {
}
@Override
protected void init(VaadinRequest request) {
// Create a tracker for vaadin.com domain and "ga-demo" prefix
GoogleAnalyticsTracker tracker = new GoogleAnalyticsTracker(
"UA-658457-8", "none", "/ga-demo/");
// Use this if you still haven't upgraded to Universal tracking API
// tracker.setUniversalTracking(false);
// Example: Create a tracker for vaadin.com domain.
// GoogleAnalyticsTracker tracker = new GoogleAnalyticsTracker(
// "UA-658457-8", "vaadin.com");
tracker.setUserId("12345"); //optional: set the User-ID. Must also enable User-ID tracking within Google Analytics admin.
// attach the GA tracker to this UI
tracker.extend(this);
// simple view navigator sample
Navigator n = new Navigator(this, this);
n.addView("", MainView.class);
n.addView("second", SecondView.class);
n.addView("third", ThirdView.class);
// attach the tracker to the Navigator to automatically track all views
// To use the tracker without the Navigator, just call the
// tracker.trackPageview(pageId) separately when tracking is needed.
getNavigator().addViewChangeListener(tracker);
// Examples how to track page views. Note that the "trackingPrefix" is added to these.
tracker.trackPageview("mydemo/init");
tracker.trackPageview("edit/customer");
// Examples how to track events
tracker.trackEvent("GoogleAnalyticsTrackerDemo","init");
tracker.trackEvent("GoogleAnalyticsTrackerDemo","start", "Demo Campaign");
tracker.trackEvent("GoogleAnalyticsTrackerDemo","run", "Demo Campaign",3);
}
}
| demo/src/main/java/org/vaadin/googleanalytics/tracking/demo/GoogleAnalyticsTrackerDemo.java | package org.vaadin.googleanalytics.tracking.demo;
import com.vaadin.annotations.VaadinServletConfiguration;
import org.vaadin.googleanalytics.tracking.GoogleAnalyticsTracker;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.UI;
import javax.servlet.annotation.WebServlet;
public class GoogleAnalyticsTrackerDemo extends UI {
private static final long serialVersionUID = 1L;
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = GoogleAnalyticsTrackerDemo.class)
public static class Servlet extends VaadinServlet {
}
@Override
protected void init(VaadinRequest request) {
// Create a tracker for vaadin.com domain and "ga-demo" prefix
GoogleAnalyticsTracker tracker = new GoogleAnalyticsTracker(
"UA-658457-8", "none", "/ga-demo/");
// Use this if you still haven't upgraded to Universal tracking API
// tracker.setUniversalTracking(false);
// Example: Create a tracker for vaadin.com domain.
// GoogleAnalyticsTracker tracker = new GoogleAnalyticsTracker(
// "UA-658457-8", "vaadin.com");
tracker.setUserId("12345"); //optional: set the User-ID. Must also enable User-ID tracking within Google Analytics admin.
// attach the GA tracker to this UI
tracker.extend(this);
// simple view navigator sample
Navigator n = new Navigator(this, this);
n.addView("", MainView.class);
n.addView("second", SecondView.class);
n.addView("third", ThirdView.class);
// attach the tracker to the Navigator to automatically track all views
// To use the tracker without the Navigator, just call the
// tracker.trackPageview(pageId) separately when tracking is needed.
getNavigator().addViewChangeListener(tracker);
// Track
tracker.trackEvent("someCategory","someAction", "someLabel");
}
}
| Better examples on page tracking and event tracking.
| demo/src/main/java/org/vaadin/googleanalytics/tracking/demo/GoogleAnalyticsTrackerDemo.java | Better examples on page tracking and event tracking. | <ide><path>emo/src/main/java/org/vaadin/googleanalytics/tracking/demo/GoogleAnalyticsTrackerDemo.java
<ide> // tracker.trackPageview(pageId) separately when tracking is needed.
<ide> getNavigator().addViewChangeListener(tracker);
<ide>
<del> // Track
<del> tracker.trackEvent("someCategory","someAction", "someLabel");
<add> // Examples how to track page views. Note that the "trackingPrefix" is added to these.
<add> tracker.trackPageview("mydemo/init");
<add> tracker.trackPageview("edit/customer");
<add>
<add> // Examples how to track events
<add> tracker.trackEvent("GoogleAnalyticsTrackerDemo","init");
<add> tracker.trackEvent("GoogleAnalyticsTrackerDemo","start", "Demo Campaign");
<add> tracker.trackEvent("GoogleAnalyticsTrackerDemo","run", "Demo Campaign",3);
<ide> }
<ide> } |
|
JavaScript | mit | 6f0e06f409845213c82ba598c06a550b6b2b80ce | 0 | CorruptedHelix/Pokemon-Showdown,Pikachuun/Joimmon-Showdown,CorruptedHelix/Pokemon-Showdown,Pikachuun/Joimmon-Showdown | exports.BattlePokedex = {
bulbasaur:{num:1,species:"Bulbasaur",types:["Grass","Poison"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:49,def:49,spa:65,spd:65,spe:45},abilities:{0:"Aftermath",1:"Adaptability"},heightm:0.7,weightkg:6.9,color:"Green",evos:["ivysaur"],eggGroups:["Monster","Plant"]},
ivysaur:{num:2,species:"Ivysaur",types:["Grass","Poison"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:62,def:63,spa:80,spd:80,spe:60},abilities:{0:"Regenerator",1:"Sturdy"},heightm:1,weightkg:13,color:"Green",prevo:"bulbasaur",evos:["venusaur"],evoLevel:16,eggGroups:["Monster","Plant"]},
venusaur:{num:3,species:"Venusaur",types:["Grass","Poison"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:82,def:83,spa:100,spd:100,spe:80},abilities:{0:"Heatproof",1:"Flare Boost"},heightm:2,weightkg:100,color:"Green",prevo:"ivysaur",evoLevel:32,eggGroups:["Monster","Plant"]},
charmander:{num:4,species:"Charmander",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:39,atk:52,def:43,spa:60,spd:50,spe:65},abilities:{0:"Infiltrator",1:"Cute Charm"},heightm:0.6,weightkg:8.5,color:"Red",evos:["charmeleon"],eggGroups:["Monster","Dragon"]},
charmeleon:{num:5,species:"Charmeleon",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:58,atk:64,def:58,spa:80,spd:65,spe:80},abilities:{0:"Technician",1:"Sand Force"},heightm:1.1,weightkg:19,color:"Red",prevo:"charmander",evos:["charizard"],evoLevel:16,eggGroups:["Monster","Dragon"]},
charizard:{num:6,species:"Charizard",types:["Fire","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:78,atk:84,def:78,spa:109,spd:85,spe:100},abilities:{0:"Sand Stream",1:"Regenerator"},heightm:1.7,weightkg:90.5,color:"Red",prevo:"charmeleon",evoLevel:36,eggGroups:["Monster","Dragon"]},
squirtle:{num:7,species:"Squirtle",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:44,atk:48,def:65,spa:50,spd:64,spe:43},abilities:{0:"Clear Body",1:"Lightningrod"},heightm:0.5,weightkg:9,color:"Blue",evos:["wartortle"],eggGroups:["Monster","Water 1"]},
wartortle:{num:8,species:"Wartortle",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:59,atk:63,def:80,spa:65,spd:80,spe:58},abilities:{0:"No Guard",1:"Poison Point"},heightm:1,weightkg:22.5,color:"Blue",prevo:"squirtle",evos:["blastoise"],evoLevel:16,eggGroups:["Monster","Water 1"]},
blastoise:{num:9,species:"Blastoise",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:79,atk:83,def:100,spa:85,spd:105,spe:78},abilities:{0:"Early Bird",1:"Overcoat"},heightm:1.6,weightkg:85.5,color:"Blue",prevo:"wartortle",evoLevel:36,eggGroups:["Monster","Water 1"]},
caterpie:{num:10,species:"Caterpie",types:["Bug"],baseStats:{hp:45,atk:30,def:35,spa:20,spd:20,spe:45},abilities:{0:"Iron Barbs",1:"Swift Swim"},heightm:0.3,weightkg:2.9,color:"Green",evos:["metapod"],eggGroups:["Bug"]},
metapod:{num:11,species:"Metapod",types:["Bug"],baseStats:{hp:50,atk:20,def:55,spa:25,spd:25,spe:30},abilities:{0:"Tinted Lens",1:"Shadow Tag"},heightm:0.7,weightkg:9.9,color:"Green",prevo:"caterpie",evos:["butterfree"],evoLevel:7,eggGroups:["Bug"]},
butterfree:{num:12,species:"Butterfree",types:["Bug","Flying"],baseStats:{hp:60,atk:45,def:50,spa:80,spd:80,spe:70},abilities:{0:"Sap Sipper",1:"Water Absorb"},heightm:1.1,weightkg:32,color:"White",prevo:"metapod",evoLevel:10,eggGroups:["Bug"]},
weedle:{num:13,species:"Weedle",types:["Bug","Poison"],baseStats:{hp:40,atk:35,def:30,spa:20,spd:20,spe:50},abilities:{0:"Damp",1:"Sheer Force"},heightm:0.3,weightkg:3.2,color:"Brown",evos:["kakuna"],eggGroups:["Bug"]},
kakuna:{num:14,species:"Kakuna",types:["Bug","Poison"],baseStats:{hp:45,atk:25,def:50,spa:25,spd:25,spe:35},abilities:{0:"Early Bird",1:"Light Metal"},heightm:0.6,weightkg:10,color:"Yellow",prevo:"weedle",evos:["beedrill"],evoLevel:7,eggGroups:["Bug"]},
beedrill:{num:15,species:"Beedrill",types:["Bug","Poison"],baseStats:{hp:65,atk:80,def:40,spa:45,spd:80,spe:75},abilities:{0:"Effect Spore",1:"Harvest"},heightm:1,weightkg:29.5,color:"Yellow",prevo:"kakuna",evoLevel:10,eggGroups:["Bug"]},
pidgey:{num:16,species:"Pidgey",types:["Normal","Flying"],baseStats:{hp:40,atk:45,def:40,spa:35,spd:35,spe:56},abilities:{0:"Bad Dreams",1:"Marvel Scale"},heightm:0.3,weightkg:1.8,color:"Brown",evos:["pidgeotto"],eggGroups:["Flying"]},
pidgeotto:{num:17,species:"Pidgeotto",types:["Normal","Flying"],baseStats:{hp:63,atk:60,def:55,spa:50,spd:50,spe:71},abilities:{0:"Soundproof",1:"Oblivious"},heightm:1.1,weightkg:30,color:"Brown",prevo:"pidgey",evos:["pidgeot"],evoLevel:18,eggGroups:["Flying"]},
pidgeot:{num:18,species:"Pidgeot",types:["Normal","Flying"],baseStats:{hp:83,atk:80,def:75,spa:70,spd:70,spe:91},abilities:{0:"Cute Charm",1:"Magma Armor"},heightm:1.5,weightkg:39.5,color:"Brown",prevo:"pidgeotto",evoLevel:36,eggGroups:["Flying"]},
rattata:{num:19,species:"Rattata",types:["Normal"],baseStats:{hp:30,atk:56,def:35,spa:25,spd:35,spe:72},abilities:{0:"Mummy",1:"Toxic Boost"},heightm:0.3,weightkg:3.5,color:"Purple",evos:["raticate"],eggGroups:["Ground"]},
raticate:{num:20,species:"Raticate",types:["Normal"],baseStats:{hp:55,atk:81,def:60,spa:50,spd:70,spe:97},abilities:{0:"Compoundeyes",1:"Illusion"},heightm:0.7,weightkg:18.5,color:"Brown",prevo:"rattata",evoLevel:20,eggGroups:["Ground"]},
spearow:{num:21,species:"Spearow",types:["Normal","Flying"],baseStats:{hp:40,atk:60,def:30,spa:31,spd:31,spe:70},abilities:{0:"Moxie",1:"Flame Body"},heightm:0.3,weightkg:2,color:"Brown",evos:["fearow"],eggGroups:["Flying"]},
fearow:{num:22,species:"Fearow",types:["Normal","Flying"],baseStats:{hp:65,atk:90,def:65,spa:61,spd:61,spe:100},abilities:{0:"Clear Body",1:"Trace"},heightm:1.2,weightkg:38,color:"Brown",prevo:"spearow",evoLevel:20,eggGroups:["Flying"]},
ekans:{num:23,species:"Ekans",types:["Poison"],baseStats:{hp:35,atk:60,def:44,spa:40,spd:54,spe:55},abilities:{0:"Defiant",1:"Shield Dust"},heightm:2,weightkg:6.9,color:"Purple",evos:["arbok"],eggGroups:["Ground","Dragon"]},
arbok:{num:24,species:"Arbok",types:["Poison"],baseStats:{hp:60,atk:85,def:69,spa:65,spd:79,spe:80},abilities:{0:"Thick Fat",1:"Quick Feet"},heightm:3.5,weightkg:65,color:"Purple",prevo:"ekans",evoLevel:22,eggGroups:["Ground","Dragon"]},
pikachu:{num:25,species:"Pikachu",types:["Electric"],baseStats:{hp:35,atk:55,def:30,spa:50,spd:40,spe:90},abilities:{0:"Infiltrator",1:"Sturdy"},heightm:0.4,weightkg:6,color:"Yellow",prevo:"pichu",evos:["raichu"],evoLevel:1,eggGroups:["Ground","Fairy"]},
raichu:{num:26,species:"Raichu",types:["Electric"],baseStats:{hp:60,atk:90,def:55,spa:90,spd:80,spe:100},abilities:{0:"Magic Bounce",1:"Battle Armor"},heightm:0.8,weightkg:30,color:"Yellow",prevo:"pikachu",evoLevel:1,eggGroups:["Ground","Fairy"]},
sandshrew:{num:27,species:"Sandshrew",types:["Ground"],baseStats:{hp:50,atk:75,def:85,spa:20,spd:30,spe:40},abilities:{0:"Magma Armor",1:"Magic Guard"},heightm:0.6,weightkg:12,color:"Yellow",evos:["sandslash"],eggGroups:["Ground"]},
sandslash:{num:28,species:"Sandslash",types:["Ground"],baseStats:{hp:75,atk:100,def:110,spa:45,spd:55,spe:65},abilities:{0:"Infiltrator",1:"Sheer Force"},heightm:1,weightkg:29.5,color:"Yellow",prevo:"sandshrew",evoLevel:22,eggGroups:["Ground"]},
nidoranf:{num:29,species:"NidoranF",types:["Poison"],gender:"F",baseStats:{hp:55,atk:47,def:52,spa:40,spd:40,spe:41},abilities:{0:"Poison Touch",1:"Bad Dreams"},heightm:0.4,weightkg:7,color:"Blue",evos:["nidorina"],eggGroups:["Monster","Ground"]},
nidorina:{num:30,species:"Nidorina",types:["Poison"],gender:"F",baseStats:{hp:70,atk:62,def:67,spa:55,spd:55,spe:56},abilities:{0:"Rock Head",1:"Chlorophyll"},heightm:0.8,weightkg:20,color:"Blue",prevo:"nidoranf",evos:["nidoqueen"],evoLevel:16,eggGroups:["No Eggs"]},
nidoqueen:{num:31,species:"Nidoqueen",types:["Poison","Ground"],gender:"F",baseStats:{hp:90,atk:82,def:87,spa:75,spd:85,spe:76},abilities:{0:"Pressure",1:"Clear Body"},heightm:1.3,weightkg:60,color:"Blue",prevo:"nidorina",evoLevel:16,eggGroups:["No Eggs"]},
nidoranm:{num:32,species:"NidoranM",types:["Poison"],gender:"M",baseStats:{hp:46,atk:57,def:40,spa:40,spd:40,spe:50},abilities:{0:"Limber",1:"Big Pecks"},heightm:0.5,weightkg:9,color:"Purple",evos:["nidorino"],eggGroups:["Monster","Ground"]},
nidorino:{num:33,species:"Nidorino",types:["Poison"],gender:"M",baseStats:{hp:61,atk:72,def:57,spa:55,spd:55,spe:65},abilities:{0:"Marvel Scale",1:"Drought"},heightm:0.9,weightkg:19.5,color:"Purple",prevo:"nidoranm",evos:["nidoking"],evoLevel:16,eggGroups:["Monster","Ground"]},
nidoking:{num:34,species:"Nidoking",types:["Poison","Ground"],gender:"M",baseStats:{hp:81,atk:92,def:77,spa:85,spd:75,spe:85},abilities:{0:"Shield Dust",1:"Hyper Cutter"},heightm:1.4,weightkg:62,color:"Purple",prevo:"nidorino",evoLevel:16,eggGroups:["Monster","Ground"]},
clefairy:{num:35,species:"Clefairy",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:45,def:48,spa:60,spd:65,spe:35},abilities:{0:"Pickpocket",1:"Prankster"},heightm:0.6,weightkg:7.5,color:"Pink",prevo:"cleffa",evos:["clefable"],evoLevel:1,eggGroups:["Fairy"]},
clefable:{num:36,species:"Clefable",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:95,atk:70,def:73,spa:85,spd:90,spe:60},abilities:{0:"Infiltrator",1:"Suction Cups"},heightm:1.3,weightkg:40,color:"Pink",prevo:"clefairy",evoLevel:1,eggGroups:["Fairy"]},
vulpix:{num:37,species:"Vulpix",types:["Fire"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:38,atk:41,def:40,spa:50,spd:65,spe:65},abilities:{0:"Toxic Boost",1:"Soundproof"},heightm:0.6,weightkg:9.9,color:"Brown",evos:["ninetales"],eggGroups:["Ground"]},
ninetales:{num:38,species:"Ninetales",types:["Fire"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:73,atk:76,def:75,spa:81,spd:100,spe:100},abilities:{0:"Sand Veil",1:"Hyper Cutter"},heightm:1.1,weightkg:19.9,color:"Yellow",prevo:"vulpix",evoLevel:1,eggGroups:["Ground"]},
jigglypuff:{num:39,species:"Jigglypuff",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:115,atk:45,def:20,spa:45,spd:25,spe:20},abilities:{0:"Gluttony",1:"Color Change"},heightm:0.5,weightkg:5.5,color:"Pink",prevo:"igglybuff",evos:["wigglytuff"],evoLevel:1,eggGroups:["Fairy"]},
wigglytuff:{num:40,species:"Wigglytuff",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:140,atk:70,def:45,spa:75,spd:50,spe:45},abilities:{0:"Tinted Lens",1:"Multiscale"},heightm:1,weightkg:12,color:"Pink",prevo:"jigglypuff",evoLevel:1,eggGroups:["Fairy"]},
zubat:{num:41,species:"Zubat",types:["Poison","Flying"],baseStats:{hp:40,atk:45,def:35,spa:30,spd:40,spe:55},abilities:{0:"Prankster",1:"Snow Cloak"},heightm:0.8,weightkg:7.5,color:"Purple",evos:["golbat"],eggGroups:["Flying"]},
golbat:{num:42,species:"Golbat",types:["Poison","Flying"],baseStats:{hp:75,atk:80,def:70,spa:65,spd:75,spe:90},abilities:{0:"Simple",1:"Rock Head"},heightm:1.6,weightkg:55,color:"Purple",prevo:"zubat",evos:["crobat"],evoLevel:22,eggGroups:["Flying"]},
oddish:{num:43,species:"Oddish",types:["Grass","Poison"],baseStats:{hp:45,atk:50,def:55,spa:75,spd:65,spe:30},abilities:{0:"Tinted Lens",1:"Cute Charm"},heightm:0.5,weightkg:5.4,color:"Blue",evos:["gloom"],eggGroups:["Plant"]},
gloom:{num:44,species:"Gloom",types:["Grass","Poison"],baseStats:{hp:60,atk:65,def:70,spa:85,spd:75,spe:40},abilities:{0:"Drought",1:"Volt Absorb"},heightm:0.8,weightkg:8.6,color:"Blue",prevo:"oddish",evos:["vileplume","bellossom"],evoLevel:21,eggGroups:["Plant"]},
vileplume:{num:45,species:"Vileplume",types:["Grass","Poison"],baseStats:{hp:75,atk:80,def:85,spa:100,spd:90,spe:50},abilities:{0:"Thick Fat",1:"Steadfast"},heightm:1.2,weightkg:18.6,color:"Red",prevo:"gloom",evoLevel:21,eggGroups:["Plant"]},
paras:{num:46,species:"Paras",types:["Bug","Grass"],baseStats:{hp:35,atk:70,def:55,spa:45,spd:55,spe:25},abilities:{0:"Stall",1:"Lightningrod"},heightm:0.3,weightkg:5.4,color:"Red",evos:["parasect"],eggGroups:["Bug","Plant"]},
parasect:{num:47,species:"Parasect",types:["Bug","Grass"],baseStats:{hp:60,atk:95,def:80,spa:60,spd:80,spe:30},abilities:{0:"Motor Drive",1:"Quick Feet"},heightm:1,weightkg:29.5,color:"Red",prevo:"paras",evoLevel:24,eggGroups:["Bug","Plant"]},
venonat:{num:48,species:"Venonat",types:["Bug","Poison"],baseStats:{hp:60,atk:55,def:50,spa:40,spd:55,spe:45},abilities:{0:"Heatproof",1:"Quick Feet"},heightm:1,weightkg:30,color:"Purple",evos:["venomoth"],eggGroups:["Bug"]},
venomoth:{num:49,species:"Venomoth",types:["Bug","Poison"],baseStats:{hp:70,atk:65,def:60,spa:90,spd:75,spe:90},abilities:{0:"Thick Fat",1:"Imposter"},heightm:1.5,weightkg:12.5,color:"Purple",prevo:"venonat",evoLevel:31,eggGroups:["Bug"]},
diglett:{num:50,species:"Diglett",types:["Ground"],baseStats:{hp:10,atk:55,def:25,spa:35,spd:45,spe:95},abilities:{0:"Marvel Scale",1:"Stall"},heightm:0.2,weightkg:0.8,color:"Brown",evos:["dugtrio"],eggGroups:["Ground"]},
dugtrio:{num:51,species:"Dugtrio",types:["Ground"],baseStats:{hp:35,atk:80,def:50,spa:50,spd:70,spe:120},abilities:{0:"Poison Heal",1:"Color Change"},heightm:0.7,weightkg:33.3,color:"Brown",prevo:"diglett",evoLevel:26,eggGroups:["Ground"]},
meowth:{num:52,species:"Meowth",types:["Normal"],baseStats:{hp:40,atk:45,def:35,spa:40,spd:40,spe:90},abilities:{0:"Poison Point",1:"Serene Grace"},heightm:0.4,weightkg:4.2,color:"Yellow",evos:["persian"],eggGroups:["Ground"]},
persian:{num:53,species:"Persian",types:["Normal"],baseStats:{hp:65,atk:70,def:60,spa:65,spd:65,spe:115},abilities:{0:"Poison Point",1:"Snow Cloak"},heightm:1,weightkg:32,color:"Yellow",prevo:"meowth",evoLevel:28,eggGroups:["Ground"]},
psyduck:{num:54,species:"Psyduck",types:["Water"],baseStats:{hp:50,atk:52,def:48,spa:65,spd:50,spe:55},abilities:{0:"Trace",1:"Suction Cups"},heightm:0.8,weightkg:19.6,color:"Yellow",evos:["golduck"],eggGroups:["Water 1","Ground"]},
golduck:{num:55,species:"Golduck",types:["Water"],baseStats:{hp:80,atk:82,def:78,spa:95,spd:80,spe:85},abilities:{0:"Drizzle",1:"Immunity"},heightm:1.7,weightkg:76.6,color:"Blue",prevo:"psyduck",evoLevel:33,eggGroups:["Water 1","Ground"]},
mankey:{num:56,species:"Mankey",types:["Fighting"],baseStats:{hp:40,atk:80,def:35,spa:35,spd:45,spe:70},abilities:{0:"Sand Veil",1:"Arena Trap"},heightm:0.5,weightkg:28,color:"Brown",evos:["primeape"],eggGroups:["Ground"]},
primeape:{num:57,species:"Primeape",types:["Fighting"],baseStats:{hp:65,atk:105,def:60,spa:60,spd:70,spe:95},abilities:{0:"Poison Heal",1:"Soundproof"},heightm:1,weightkg:32,color:"Brown",prevo:"mankey",evoLevel:28,eggGroups:["Ground"]},
growlithe:{num:58,species:"Growlithe",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:55,atk:70,def:45,spa:70,spd:50,spe:60},abilities:{0:"Hustle",1:"Shed Skin"},heightm:0.7,weightkg:19,color:"Brown",evos:["arcanine"],eggGroups:["Ground"]},
arcanine:{num:59,species:"Arcanine",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:90,atk:110,def:80,spa:100,spd:80,spe:95},abilities:{0:"Cute Charm",1:"Illusion"},heightm:1.9,weightkg:155,color:"Brown",prevo:"growlithe",evoLevel:1,eggGroups:["Ground"]},
poliwag:{num:60,species:"Poliwag",types:["Water"],baseStats:{hp:40,atk:50,def:40,spa:40,spd:40,spe:90},abilities:{0:"Oblivious",1:"Thick Fat"},heightm:0.6,weightkg:12.4,color:"Blue",evos:["poliwhirl"],eggGroups:["Water 1"]},
poliwhirl:{num:61,species:"Poliwhirl",types:["Water"],baseStats:{hp:65,atk:65,def:65,spa:50,spd:50,spe:90},abilities:{0:"Solid Rock",1:"Magic Guard"},heightm:1,weightkg:20,color:"Blue",prevo:"poliwag",evos:["poliwrath","politoed"],evoLevel:25,eggGroups:["Water 1"]},
poliwrath:{num:62,species:"Poliwrath",types:["Water","Fighting"],baseStats:{hp:90,atk:85,def:95,spa:70,spd:90,spe:70},abilities:{0:"Poison Heal",1:"Magma Armor"},heightm:1.3,weightkg:54,color:"Blue",prevo:"poliwhirl",evoLevel:25,eggGroups:["Water 1"]},
abra:{num:63,species:"Abra",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:25,atk:20,def:15,spa:105,spd:55,spe:90},abilities:{0:"Sand Stream",1:"Anticipation"},heightm:0.9,weightkg:19.5,color:"Brown",evos:["kadabra"],eggGroups:["Humanshape"]},
kadabra:{num:64,species:"Kadabra",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:40,atk:35,def:30,spa:120,spd:70,spe:105},abilities:{0:"Leaf Guard",1:"Hustle"},heightm:1.3,weightkg:56.5,color:"Brown",prevo:"abra",evos:["alakazam"],evoLevel:16,eggGroups:["Humanshape"]},
alakazam:{num:65,species:"Alakazam",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:55,atk:50,def:45,spa:135,spd:85,spe:120},abilities:{0:"Multiscale",1:"Snow Cloak"},heightm:1.5,weightkg:48,color:"Brown",prevo:"kadabra",evoLevel:16,eggGroups:["Humanshape"]},
machop:{num:66,species:"Machop",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:70,atk:80,def:50,spa:35,spd:35,spe:35},abilities:{0:"Frisk",1:"Unburden"},heightm:0.8,weightkg:19.5,color:"Gray",evos:["machoke"],eggGroups:["Humanshape"]},
machoke:{num:67,species:"Machoke",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:80,atk:100,def:70,spa:50,spd:60,spe:45},abilities:{0:"Rain Dish",1:"Infiltrator"},heightm:1.5,weightkg:70.5,color:"Gray",prevo:"machop",evos:["machamp"],evoLevel:28,eggGroups:["Humanshape"]},
machamp:{num:68,species:"Machamp",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:90,atk:130,def:80,spa:65,spd:85,spe:55},abilities:{0:"Iron Barbs",1:"Tangled Feet"},heightm:1.6,weightkg:130,color:"Gray",prevo:"machoke",evoLevel:28,eggGroups:["Humanshape"]},
bellsprout:{num:69,species:"Bellsprout",types:["Grass","Poison"],baseStats:{hp:50,atk:75,def:35,spa:70,spd:30,spe:40},abilities:{0:"Sand Rush",1:"Unnerve"},heightm:0.7,weightkg:4,color:"Green",evos:["weepinbell"],eggGroups:["Plant"]},
weepinbell:{num:70,species:"Weepinbell",types:["Grass","Poison"],baseStats:{hp:65,atk:90,def:50,spa:85,spd:45,spe:55},abilities:{0:"Rattled",1:"Snow Warning"},heightm:1,weightkg:6.4,color:"Green",prevo:"bellsprout",evos:["victreebel"],evoLevel:21,eggGroups:["Plant"]},
victreebel:{num:71,species:"Victreebel",types:["Grass","Poison"],baseStats:{hp:80,atk:105,def:65,spa:100,spd:60,spe:70},abilities:{0:"Magic Bounce",1:"Storm Drain"},heightm:1.7,weightkg:15.5,color:"Green",prevo:"weepinbell",evoLevel:21,eggGroups:["Plant"]},
tentacool:{num:72,species:"Tentacool",types:["Water","Poison"],baseStats:{hp:40,atk:40,def:35,spa:50,spd:100,spe:70},abilities:{0:"Leaf Guard",1:"Storm Drain"},heightm:0.9,weightkg:45.5,color:"Blue",evos:["tentacruel"],eggGroups:["Water 3"]},
tentacruel:{num:73,species:"Tentacruel",types:["Water","Poison"],baseStats:{hp:80,atk:70,def:65,spa:80,spd:120,spe:100},abilities:{0:"Ice Body",1:"No Guard"},heightm:1.6,weightkg:55,color:"Blue",prevo:"tentacool",evoLevel:30,eggGroups:["Water 3"]},
geodude:{num:74,species:"Geodude",types:["Rock","Ground"],baseStats:{hp:40,atk:80,def:100,spa:30,spd:30,spe:20},abilities:{0:"Pure Power",1:"Leaf Guard"},heightm:0.4,weightkg:20,color:"Brown",evos:["graveler"],eggGroups:["Mineral"]},
graveler:{num:75,species:"Graveler",types:["Rock","Ground"],baseStats:{hp:55,atk:95,def:115,spa:45,spd:45,spe:35},abilities:{0:"Steadfast",1:"Water Veil"},heightm:1,weightkg:105,color:"Brown",prevo:"geodude",evos:["golem"],evoLevel:25,eggGroups:["Mineral"]},
golem:{num:76,species:"Golem",types:["Rock","Ground"],baseStats:{hp:80,atk:110,def:130,spa:55,spd:65,spe:45},abilities:{0:"Unburden",1:"Magic Bounce"},heightm:1.4,weightkg:300,color:"Brown",prevo:"graveler",evoLevel:25,eggGroups:["Mineral"]},
ponyta:{num:77,species:"Ponyta",types:["Fire"],baseStats:{hp:50,atk:85,def:55,spa:65,spd:65,spe:90},abilities:{0:"Moxie",1:"Synchronize"},heightm:1,weightkg:30,color:"Yellow",evos:["rapidash"],eggGroups:["Ground"]},
rapidash:{num:78,species:"Rapidash",types:["Fire"],baseStats:{hp:65,atk:100,def:70,spa:80,spd:80,spe:105},abilities:{0:"Intimidate",1:"Hyper Cutter"},heightm:1.7,weightkg:95,color:"Yellow",prevo:"ponyta",evoLevel:40,eggGroups:["Ground"]},
slowpoke:{num:79,species:"Slowpoke",types:["Water","Psychic"],baseStats:{hp:90,atk:65,def:65,spa:40,spd:40,spe:15},abilities:{0:"Prankster",1:"Pickpocket"},heightm:1.2,weightkg:36,color:"Pink",evos:["slowbro","slowking"],eggGroups:["Monster","Water 1"]},
slowbro:{num:80,species:"Slowbro",types:["Water","Psychic"],baseStats:{hp:95,atk:75,def:110,spa:100,spd:80,spe:30},abilities:{0:"Water Veil",1:"Unnerve"},heightm:1.6,weightkg:78.5,color:"Pink",prevo:"slowpoke",evoLevel:37,eggGroups:["Monster","Water 1"]},
magnemite:{num:81,species:"Magnemite",types:["Electric","Steel"],gender:"N",baseStats:{hp:25,atk:35,def:70,spa:95,spd:55,spe:45},abilities:{0:"Liquid Ooze",1:"Insomnia"},heightm:0.3,weightkg:6,color:"Gray",evos:["magneton"],eggGroups:["Mineral"]},
magneton:{num:82,species:"Magneton",types:["Electric","Steel"],gender:"N",baseStats:{hp:50,atk:60,def:95,spa:120,spd:70,spe:70},abilities:{0:"Solid Rock",1:"Sand Force"},heightm:1,weightkg:60,color:"Gray",prevo:"magnemite",evos:["magnezone"],evoLevel:30,eggGroups:["Mineral"]},
farfetchd:{num:83,species:"Farfetch'd",types:["Normal","Flying"],baseStats:{hp:52,atk:65,def:55,spa:58,spd:62,spe:60},abilities:{0:"Marvel Scale",1:"Snow Cloak"},heightm:0.8,weightkg:15,color:"Brown",eggGroups:["Flying","Ground"]},
doduo:{num:84,species:"Doduo",types:["Normal","Flying"],baseStats:{hp:35,atk:85,def:45,spa:35,spd:35,spe:75},abilities:{0:"Flash Fire",1:"Arena Trap"},heightm:1.4,weightkg:39.2,color:"Brown",evos:["dodrio"],eggGroups:["Flying"]},
dodrio:{num:85,species:"Dodrio",types:["Normal","Flying"],baseStats:{hp:60,atk:110,def:70,spa:60,spd:60,spe:100},abilities:{0:"Wonder Guard",1:"Sticky Hold"},heightm:1.8,weightkg:85.2,color:"Brown",prevo:"doduo",evoLevel:31,eggGroups:["Flying"]},
seel:{num:86,species:"Seel",types:["Water"],baseStats:{hp:65,atk:45,def:55,spa:45,spd:70,spe:45},abilities:{0:"Insomnia",1:"Flame Body"},heightm:1.1,weightkg:90,color:"White",evos:["dewgong"],eggGroups:["Water 1","Ground"]},
dewgong:{num:87,species:"Dewgong",types:["Water","Ice"],baseStats:{hp:90,atk:70,def:80,spa:70,spd:95,spe:70},abilities:{0:"Frisk",1:"Sand Veil"},heightm:1.7,weightkg:120,color:"White",prevo:"seel",evoLevel:34,eggGroups:["Water 1","Ground"]},
grimer:{num:88,species:"Grimer",types:["Poison"],baseStats:{hp:80,atk:80,def:50,spa:40,spd:50,spe:25},abilities:{0:"Drizzle",1:"Magic Bounce"},heightm:0.9,weightkg:30,color:"Purple",evos:["muk"],eggGroups:["Indeterminate"]},
muk:{num:89,species:"Muk",types:["Poison"],baseStats:{hp:105,atk:105,def:75,spa:65,spd:100,spe:50},abilities:{0:"Infiltrator",1:"Levitate"},heightm:1.2,weightkg:30,color:"Purple",prevo:"grimer",evoLevel:38,eggGroups:["Indeterminate"]},
shellder:{num:90,species:"Shellder",types:["Water"],baseStats:{hp:30,atk:65,def:100,spa:45,spd:25,spe:40},abilities:{0:"Iron Barbs",1:"Drizzle"},heightm:0.3,weightkg:4,color:"Purple",evos:["cloyster"],eggGroups:["Water 3"]},
cloyster:{num:91,species:"Cloyster",types:["Water","Ice"],baseStats:{hp:50,atk:95,def:180,spa:85,spd:45,spe:70},abilities:{0:"Inner Focus",1:"Wonder Skin"},heightm:1.5,weightkg:132.5,color:"Purple",prevo:"shellder",evoLevel:1,eggGroups:["Water 3"]},
gastly:{num:92,species:"Gastly",types:["Ghost","Poison"],baseStats:{hp:30,atk:35,def:30,spa:100,spd:35,spe:80},abilities:{0:"Sand Veil",1:"Chlorophyll"},heightm:1.3,weightkg:0.1,color:"Purple",evos:["haunter"],eggGroups:["Indeterminate"]},
haunter:{num:93,species:"Haunter",types:["Ghost","Poison"],baseStats:{hp:45,atk:50,def:45,spa:115,spd:55,spe:95},abilities:{0:"Technician",1:"Aftermath"},heightm:1.6,weightkg:0.1,color:"Purple",prevo:"gastly",evos:["gengar"],evoLevel:25,eggGroups:["Indeterminate"]},
gengar:{num:94,species:"Gengar",types:["Ghost","Poison"],baseStats:{hp:60,atk:65,def:60,spa:130,spd:75,spe:110},abilities:{0:"Swift Swim",1:"Heavy Metal"},heightm:1.5,weightkg:40.5,color:"Purple",prevo:"haunter",evoLevel:25,eggGroups:["Indeterminate"]},
onix:{num:95,species:"Onix",types:["Rock","Ground"],baseStats:{hp:35,atk:45,def:160,spa:30,spd:45,spe:70},abilities:{0:"Sand Veil",1:"Cute Charm"},heightm:8.8,weightkg:210,color:"Gray",evos:["steelix"],eggGroups:["Mineral"]},
drowzee:{num:96,species:"Drowzee",types:["Psychic"],baseStats:{hp:60,atk:48,def:45,spa:43,spd:90,spe:42},abilities:{0:"Tangled Feet",1:"Sniper"},heightm:1,weightkg:32.4,color:"Yellow",evos:["hypno"],eggGroups:["Humanshape"]},
hypno:{num:97,species:"Hypno",types:["Psychic"],baseStats:{hp:85,atk:73,def:70,spa:73,spd:115,spe:67},abilities:{0:"Solar Power",1:"Technician"},heightm:1.6,weightkg:75.6,color:"Yellow",prevo:"drowzee",evoLevel:26,eggGroups:["Humanshape"]},
krabby:{num:98,species:"Krabby",types:["Water"],baseStats:{hp:30,atk:105,def:90,spa:25,spd:25,spe:50},abilities:{0:"Iron Barbs",1:"Tangled Feet"},heightm:0.4,weightkg:6.5,color:"Red",evos:["kingler"],eggGroups:["Water 3"]},
kingler:{num:99,species:"Kingler",types:["Water"],baseStats:{hp:55,atk:130,def:115,spa:50,spd:50,spe:75},abilities:{0:"Sturdy",1:"Color Change"},heightm:1.3,weightkg:60,color:"Red",prevo:"krabby",evoLevel:28,eggGroups:["Water 3"]},
voltorb:{num:100,species:"Voltorb",types:["Electric"],gender:"N",baseStats:{hp:40,atk:30,def:50,spa:55,spd:55,spe:100},abilities:{0:"Big Pecks",1:"Early Bird"},heightm:0.5,weightkg:10.4,color:"Red",evos:["electrode"],eggGroups:["Mineral"]},
electrode:{num:101,species:"Electrode",types:["Electric"],gender:"N",baseStats:{hp:60,atk:50,def:70,spa:80,spd:80,spe:140},abilities:{0:"Shadow Tag",1:"Levitate"},heightm:1.2,weightkg:66.6,color:"Red",prevo:"voltorb",evoLevel:30,eggGroups:["Mineral"]},
exeggcute:{num:102,species:"Exeggcute",types:["Grass","Psychic"],baseStats:{hp:60,atk:40,def:80,spa:60,spd:45,spe:40},abilities:{0:"Cute Charm",1:"Forewarn"},heightm:0.4,weightkg:2.5,color:"Pink",evos:["exeggutor"],eggGroups:["Plant"]},
exeggutor:{num:103,species:"Exeggutor",types:["Grass","Psychic"],baseStats:{hp:95,atk:95,def:85,spa:125,spd:65,spe:55},abilities:{0:"Rain Dish",1:"Mold Breaker"},heightm:2,weightkg:120,color:"Yellow",prevo:"exeggcute",evoLevel:1,eggGroups:["Plant"]},
cubone:{num:104,species:"Cubone",types:["Ground"],baseStats:{hp:50,atk:50,def:95,spa:40,spd:50,spe:35},abilities:{0:"Marvel Scale",1:"Blaze"},heightm:0.4,weightkg:6.5,color:"Brown",evos:["marowak"],eggGroups:["Monster"]},
marowak:{num:105,species:"Marowak",types:["Ground"],baseStats:{hp:60,atk:80,def:110,spa:50,spd:80,spe:45},abilities:{0:"Scrappy",1:"Magic Bounce"},heightm:1,weightkg:45,color:"Brown",prevo:"cubone",evoLevel:28,eggGroups:["Monster"]},
hitmonlee:{num:106,species:"Hitmonlee",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:120,def:53,spa:35,spd:110,spe:87},abilities:{0:"Clear Body",1:"Rain Dish"},heightm:1.5,weightkg:49.8,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Humanshape"]},
hitmonchan:{num:107,species:"Hitmonchan",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:105,def:79,spa:35,spd:110,spe:76},abilities:{0:"Weak Armor",1:"Download"},heightm:1.4,weightkg:50.2,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Humanshape"]},
lickitung:{num:108,species:"Lickitung",types:["Normal"],baseStats:{hp:90,atk:55,def:75,spa:60,spd:75,spe:30},abilities:{0:"Sticky Hold",1:"Victory Star"},heightm:1.2,weightkg:65.5,color:"Pink",evos:["lickilicky"],eggGroups:["Monster"]},
koffing:{num:109,species:"Koffing",types:["Poison"],baseStats:{hp:40,atk:65,def:95,spa:60,spd:45,spe:35},abilities:{0:"Rivalry",1:"Dry Skin"},heightm:0.6,weightkg:1,color:"Purple",evos:["weezing"],eggGroups:["Indeterminate"]},
weezing:{num:110,species:"Weezing",types:["Poison"],baseStats:{hp:65,atk:90,def:120,spa:85,spd:70,spe:60},abilities:{0:"Bad Dreams",1:"Super Luck"},heightm:1.2,weightkg:9.5,color:"Purple",prevo:"koffing",evoLevel:35,eggGroups:["Indeterminate"]},
rhyhorn:{num:111,species:"Rhyhorn",types:["Ground","Rock"],baseStats:{hp:80,atk:85,def:95,spa:30,spd:30,spe:25},abilities:{0:"Cloud Nine",1:"Magnet Pull"},heightm:1,weightkg:115,color:"Gray",evos:["rhydon"],eggGroups:["Monster","Ground"]},
rhydon:{num:112,species:"Rhydon",types:["Ground","Rock"],baseStats:{hp:105,atk:130,def:120,spa:45,spd:45,spe:40},abilities:{0:"Pickpocket",1:"Poison Point"},heightm:1.9,weightkg:120,color:"Gray",prevo:"rhyhorn",evos:["rhyperior"],evoLevel:42,eggGroups:["Monster","Ground"]},
chansey:{num:113,species:"Chansey",types:["Normal"],gender:"F",baseStats:{hp:250,atk:5,def:5,spa:35,spd:105,spe:50},abilities:{0:"Liquid Ooze",1:"Static"},heightm:1.1,weightkg:34.6,color:"Pink",prevo:"happiny",evos:["blissey"],evoLevel:1,eggGroups:["Fairy"]},
tangela:{num:114,species:"Tangela",types:["Grass"],baseStats:{hp:65,atk:55,def:115,spa:100,spd:40,spe:60},abilities:{0:"Insomnia",1:"Battle Armor"},heightm:1,weightkg:35,color:"Blue",evos:["tangrowth"],eggGroups:["Plant"]},
kangaskhan:{num:115,species:"Kangaskhan",types:["Normal"],gender:"F",baseStats:{hp:105,atk:95,def:80,spa:40,spd:80,spe:90},abilities:{0:"Light Metal",1:"Bad Dreams"},heightm:2.2,weightkg:80,color:"Brown",eggGroups:["Monster"]},
horsea:{num:116,species:"Horsea",types:["Water"],baseStats:{hp:30,atk:40,def:70,spa:70,spd:25,spe:60},abilities:{0:"Big Pecks",1:"Sand Stream"},heightm:0.4,weightkg:8,color:"Blue",evos:["seadra"],eggGroups:["Water 1","Dragon"]},
seadra:{num:117,species:"Seadra",types:["Water"],baseStats:{hp:55,atk:65,def:95,spa:95,spd:45,spe:85},abilities:{0:"Snow Warning",1:"Rivalry"},heightm:1.2,weightkg:25,color:"Blue",prevo:"horsea",evos:["kingdra"],evoLevel:32,eggGroups:["Water 1","Dragon"]},
goldeen:{num:118,species:"Goldeen",types:["Water"],baseStats:{hp:45,atk:67,def:60,spa:35,spd:50,spe:63},abilities:{0:"Magic Bounce",1:"Overcoat"},heightm:0.6,weightkg:15,color:"Red",evos:["seaking"],eggGroups:["Water 2"]},
seaking:{num:119,species:"Seaking",types:["Water"],baseStats:{hp:80,atk:92,def:65,spa:65,spd:80,spe:68},abilities:{0:"Analytic",1:"Natural Cure"},heightm:1.3,weightkg:39,color:"Red",prevo:"goldeen",evoLevel:33,eggGroups:["Water 2"]},
staryu:{num:120,species:"Staryu",types:["Water"],gender:"N",baseStats:{hp:30,atk:45,def:55,spa:70,spd:55,spe:85},abilities:{0:"Limber",1:"Battle Armor"},heightm:0.8,weightkg:34.5,color:"Brown",evos:["starmie"],eggGroups:["Water 3"]},
starmie:{num:121,species:"Starmie",types:["Water","Psychic"],gender:"N",baseStats:{hp:60,atk:75,def:85,spa:100,spd:85,spe:115},abilities:{0:"Overcoat",1:"Stench"},heightm:1.1,weightkg:80,color:"Purple",prevo:"staryu",evoLevel:1,eggGroups:["Water 3"]},
mrmime:{num:122,species:"Mr. Mime",types:["Psychic"],baseStats:{hp:40,atk:45,def:65,spa:100,spd:120,spe:90},abilities:{0:"Reckless",1:"Pressure"},heightm:1.3,weightkg:54.5,color:"Pink",prevo:"mimejr",evoLevel:1,evoMove:"Mimic",eggGroups:["Humanshape"]},
scyther:{num:123,species:"Scyther",types:["Bug","Flying"],baseStats:{hp:70,atk:110,def:80,spa:55,spd:80,spe:105},abilities:{0:"Synchronize",1:"Unburden"},heightm:1.5,weightkg:56,color:"Green",evos:["scizor"],eggGroups:["Bug"]},
jynx:{num:124,species:"Jynx",types:["Ice","Psychic"],gender:"F",baseStats:{hp:65,atk:50,def:35,spa:115,spd:95,spe:95},abilities:{0:"Reckless",1:"Harvest"},heightm:1.4,weightkg:40.6,color:"Red",prevo:"smoochum",evoLevel:30,eggGroups:["Humanshape"]},
electabuzz:{num:125,species:"Electabuzz",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:65,atk:83,def:57,spa:95,spd:85,spe:105},abilities:{0:"Adaptability",1:"Poison Heal"},heightm:1.1,weightkg:30,color:"Yellow",prevo:"elekid",evos:["electivire"],evoLevel:30,eggGroups:["Humanshape"]},
magmar:{num:126,species:"Magmar",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:65,atk:95,def:57,spa:100,spd:85,spe:93},abilities:{0:"Marvel Scale",1:"Cloud Nine"},heightm:1.3,weightkg:44.5,color:"Red",prevo:"magby",evos:["magmortar"],evoLevel:30,eggGroups:["Humanshape"]},
pinsir:{num:127,species:"Pinsir",types:["Bug"],baseStats:{hp:65,atk:125,def:100,spa:55,spd:70,spe:85},abilities:{0:"Super Luck",1:"Flame Body"},heightm:1.5,weightkg:55,color:"Brown",eggGroups:["Bug"]},
tauros:{num:128,species:"Tauros",types:["Normal"],gender:"M",baseStats:{hp:75,atk:100,def:95,spa:40,spd:70,spe:110},abilities:{0:"Keen Eye",1:"Cloud Nine"},heightm:1.4,weightkg:88.4,color:"Brown",eggGroups:["Ground"]},
magikarp:{num:129,species:"Magikarp",types:["Water"],baseStats:{hp:20,atk:10,def:55,spa:15,spd:20,spe:80},abilities:{0:"Big Pecks",1:"Weak Armor"},heightm:0.9,weightkg:10,color:"Red",evos:["gyarados"],eggGroups:["Water 2","Dragon"]},
gyarados:{num:130,species:"Gyarados",types:["Water","Flying"],baseStats:{hp:95,atk:125,def:79,spa:60,spd:100,spe:81},abilities:{0:"Iron Barbs",1:"Solid Rock"},heightm:6.5,weightkg:235,color:"Blue",prevo:"magikarp",evoLevel:20,eggGroups:["Water 2","Dragon"]},
lapras:{num:131,species:"Lapras",types:["Water","Ice"],baseStats:{hp:130,atk:85,def:80,spa:85,spd:95,spe:60},abilities:{0:"Tangled Feet",1:"Drought"},heightm:2.5,weightkg:220,color:"Blue",eggGroups:["Monster","Water 1"]},
ditto:{num:132,species:"Ditto",types:["Normal"],gender:"N",baseStats:{hp:48,atk:48,def:48,spa:48,spd:48,spe:48},abilities:{0:"Hydration",1:"Forewarn"},heightm:0.3,weightkg:4,color:"Purple",eggGroups:["Ditto"]},
eevee:{num:133,species:"Eevee",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:55,def:50,spa:45,spd:65,spe:55},abilities:{0:"Pure Power",1:"Poison Heal"},heightm:0.3,weightkg:6.5,color:"Brown",evos:["vaporeon","jolteon","flareon","espeon","umbreon","leafeon","glaceon"],eggGroups:["Ground"]},
vaporeon:{num:134,species:"Vaporeon",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:130,atk:65,def:60,spa:110,spd:95,spe:65},abilities:{0:"Stench",1:"Leaf Guard"},heightm:1,weightkg:29,color:"Blue",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
jolteon:{num:135,species:"Jolteon",types:["Electric"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:65,def:60,spa:110,spd:95,spe:130},abilities:{0:"Magnet Pull",1:"Synchronize"},heightm:0.8,weightkg:24.5,color:"Yellow",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
flareon:{num:136,species:"Flareon",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:130,def:60,spa:95,spd:110,spe:65},abilities:{0:"Ice Body",1:"Imposter"},heightm:0.9,weightkg:25,color:"Red",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
porygon:{num:137,species:"Porygon",types:["Normal"],gender:"N",baseStats:{hp:65,atk:60,def:70,spa:85,spd:75,spe:40},abilities:{0:"Thick Fat",1:"Aftermath"},heightm:0.8,weightkg:36.5,color:"Pink",evos:["porygon2"],eggGroups:["Mineral"]},
omanyte:{num:138,species:"Omanyte",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:35,atk:40,def:100,spa:90,spd:55,spe:35},abilities:{0:"Wonder Guard",1:"Aftermath"},heightm:0.4,weightkg:7.5,color:"Blue",evos:["omastar"],eggGroups:["Water 1","Water 3"]},
omastar:{num:139,species:"Omastar",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:60,def:125,spa:115,spd:70,spe:55},abilities:{0:"Light Metal",1:"Klutz"},heightm:1,weightkg:35,color:"Blue",prevo:"omanyte",evoLevel:40,eggGroups:["Water 1","Water 3"]},
kabuto:{num:140,species:"Kabuto",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:80,def:90,spa:55,spd:45,spe:55},abilities:{0:"Own Tempo",1:"Frisk"},heightm:0.5,weightkg:11.5,color:"Brown",evos:["kabutops"],eggGroups:["Water 1","Water 3"]},
kabutops:{num:141,species:"Kabutops",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:115,def:105,spa:65,spd:70,spe:80},abilities:{0:"Justified",1:"Aftermath"},heightm:1.3,weightkg:40.5,color:"Brown",prevo:"kabuto",evoLevel:40,eggGroups:["Water 1","Water 3"]},
aerodactyl:{num:142,species:"Aerodactyl",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:105,def:65,spa:60,spd:75,spe:130},abilities:{0:"Magma Armor",1:"Early Bird"},heightm:1.8,weightkg:59,color:"Purple",eggGroups:["Flying"]},
snorlax:{num:143,species:"Snorlax",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:160,atk:110,def:65,spa:65,spd:110,spe:30},abilities:{0:"Snow Warning",1:"Overcoat"},heightm:2.1,weightkg:460,color:"Black",prevo:"munchlax",evoLevel:1,eggGroups:["Monster"]},
articuno:{num:144,species:"Articuno",types:["Ice","Flying"],gender:"N",baseStats:{hp:90,atk:85,def:100,spa:95,spd:125,spe:85},abilities:{0:"Chlorophyll",1:"Stall"},heightm:1.7,weightkg:55.4,color:"Blue",eggGroups:["No Eggs"]},
zapdos:{num:145,species:"Zapdos",types:["Electric","Flying"],gender:"N",baseStats:{hp:90,atk:90,def:85,spa:125,spd:90,spe:100},abilities:{0:"Sniper",1:"Regenerator"},heightm:1.6,weightkg:52.6,color:"Yellow",eggGroups:["No Eggs"]},
moltres:{num:146,species:"Moltres",types:["Fire","Flying"],gender:"N",baseStats:{hp:90,atk:100,def:90,spa:125,spd:85,spe:90},abilities:{0:"Cursed Body",1:"Hyper Cutter"},heightm:2,weightkg:60,color:"Yellow",eggGroups:["No Eggs"]},
dratini:{num:147,species:"Dratini",types:["Dragon"],baseStats:{hp:41,atk:64,def:45,spa:50,spd:50,spe:50},abilities:{0:"Snow Cloak",1:"Big Pecks"},heightm:1.8,weightkg:3.3,color:"Blue",evos:["dragonair"],eggGroups:["Water 1","Dragon"]},
dragonair:{num:148,species:"Dragonair",types:["Dragon"],baseStats:{hp:61,atk:84,def:65,spa:70,spd:70,spe:70},abilities:{0:"Serene Grace",1:"Blaze"},heightm:4,weightkg:16.5,color:"Blue",prevo:"dratini",evos:["dragonite"],evoLevel:30,eggGroups:["Water 1","Dragon"]},
dragonite:{num:149,species:"Dragonite",types:["Dragon","Flying"],baseStats:{hp:91,atk:134,def:95,spa:100,spd:100,spe:80},abilities:{0:"Sand Stream",1:"Drizzle"},heightm:2.2,weightkg:210,color:"Brown",prevo:"dragonair",evoLevel:55,eggGroups:["Water 1","Dragon"]},
mewtwo:{num:150,species:"Mewtwo",types:["Psychic"],gender:"N",baseStats:{hp:106,atk:110,def:90,spa:154,spd:90,spe:130},abilities:{0:"Drizzle",1:"Prankster"},heightm:2,weightkg:122,color:"Purple",eggGroups:["No Eggs"]},
mew:{num:151,species:"Mew",types:["Psychic"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Liquid Ooze",1:"Victory Star"},heightm:0.4,weightkg:4,color:"Pink",eggGroups:["No Eggs"]},
chikorita:{num:152,species:"Chikorita",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:49,def:65,spa:49,spd:65,spe:45},abilities:{0:"Heatproof",1:"Levitate"},heightm:0.9,weightkg:6.4,color:"Green",evos:["bayleef"],eggGroups:["Monster","Plant"]},
bayleef:{num:153,species:"Bayleef",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:62,def:80,spa:63,spd:80,spe:60},abilities:{0:"Rattled",1:"Immunity"},heightm:1.2,weightkg:15.8,color:"Green",prevo:"chikorita",evos:["meganium"],evoLevel:16,eggGroups:["Monster","Plant"]},
meganium:{num:154,species:"Meganium",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:82,def:100,spa:83,spd:100,spe:80},abilities:{0:"Poison Heal",1:"Overcoat"},heightm:1.8,weightkg:100.5,color:"Green",prevo:"bayleef",evoLevel:32,eggGroups:["Monster","Plant"]},
cyndaquil:{num:155,species:"Cyndaquil",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:39,atk:52,def:43,spa:60,spd:50,spe:65},abilities:{0:"Levitate",1:"Serene Grace"},heightm:0.5,weightkg:7.9,color:"Yellow",evos:["quilava"],eggGroups:["Ground"]},
quilava:{num:156,species:"Quilava",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:58,atk:64,def:58,spa:80,spd:65,spe:80},abilities:{0:"Natural Cure",1:"Weak Armor"},heightm:0.9,weightkg:19,color:"Yellow",prevo:"cyndaquil",evos:["typhlosion"],evoLevel:14,eggGroups:["Ground"]},
typhlosion:{num:157,species:"Typhlosion",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:78,atk:84,def:78,spa:109,spd:85,spe:100},abilities:{0:"Swift Swim",1:"Poison Heal"},heightm:1.7,weightkg:79.5,color:"Yellow",prevo:"quilava",evoLevel:36,eggGroups:["Ground"]},
totodile:{num:158,species:"Totodile",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:65,def:64,spa:44,spd:48,spe:43},abilities:{0:"Technician",1:"Compoundeyes"},heightm:0.6,weightkg:9.5,color:"Blue",evos:["croconaw"],eggGroups:["Monster","Water 1"]},
croconaw:{num:159,species:"Croconaw",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:80,def:80,spa:59,spd:63,spe:58},abilities:{0:"Dry Skin",1:"Regenerator"},heightm:1.1,weightkg:25,color:"Blue",prevo:"totodile",evos:["feraligatr"],evoLevel:18,eggGroups:["Monster","Water 1"]},
feraligatr:{num:160,species:"Feraligatr",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:85,atk:105,def:100,spa:79,spd:83,spe:78},abilities:{0:"Gluttony",1:"Stench"},heightm:2.3,weightkg:88.8,color:"Blue",prevo:"croconaw",evoLevel:30,eggGroups:["Monster","Water 1"]},
sentret:{num:161,species:"Sentret",types:["Normal"],baseStats:{hp:35,atk:46,def:34,spa:35,spd:45,spe:20},abilities:{0:"Sand Rush",1:"Cute Charm"},heightm:0.8,weightkg:6,color:"Brown",evos:["furret"],eggGroups:["Ground"]},
furret:{num:162,species:"Furret",types:["Normal"],baseStats:{hp:85,atk:76,def:64,spa:45,spd:55,spe:90},abilities:{0:"Soundproof",1:"Sturdy"},heightm:1.8,weightkg:32.5,color:"Brown",prevo:"sentret",evoLevel:15,eggGroups:["Ground"]},
hoothoot:{num:163,species:"Hoothoot",types:["Normal","Flying"],baseStats:{hp:60,atk:30,def:30,spa:36,spd:56,spe:50},abilities:{0:"Soundproof",1:"Gluttony"},heightm:0.7,weightkg:21.2,color:"Brown",evos:["noctowl"],eggGroups:["Flying"]},
noctowl:{num:164,species:"Noctowl",types:["Normal","Flying"],baseStats:{hp:100,atk:50,def:50,spa:76,spd:96,spe:70},abilities:{0:"Sap Sipper",1:"Anger Point"},heightm:1.6,weightkg:40.8,color:"Brown",prevo:"hoothoot",evoLevel:20,eggGroups:["Flying"]},
ledyba:{num:165,species:"Ledyba",types:["Bug","Flying"],baseStats:{hp:40,atk:20,def:30,spa:40,spd:80,spe:55},abilities:{0:"Toxic Boost",1:"Cursed Body"},heightm:1,weightkg:10.8,color:"Red",evos:["ledian"],eggGroups:["Bug"]},
ledian:{num:166,species:"Ledian",types:["Bug","Flying"],baseStats:{hp:55,atk:35,def:50,spa:55,spd:110,spe:85},abilities:{0:"Static",1:"Clear Body"},heightm:1.4,weightkg:35.6,color:"Red",prevo:"ledyba",evoLevel:18,eggGroups:["Bug"]},
spinarak:{num:167,species:"Spinarak",types:["Bug","Poison"],baseStats:{hp:40,atk:60,def:40,spa:40,spd:40,spe:30},abilities:{0:"Mold Breaker",1:"Reckless"},heightm:0.5,weightkg:8.5,color:"Green",evos:["ariados"],eggGroups:["Bug"]},
ariados:{num:168,species:"Ariados",types:["Bug","Poison"],baseStats:{hp:70,atk:90,def:70,spa:60,spd:60,spe:40},abilities:{0:"Snow Warning",1:"Super Luck"},heightm:1.1,weightkg:33.5,color:"Red",prevo:"spinarak",evoLevel:22,eggGroups:["Bug"]},
crobat:{num:169,species:"Crobat",types:["Poison","Flying"],baseStats:{hp:85,atk:90,def:80,spa:70,spd:80,spe:130},abilities:{0:"Solid Rock",1:"Trace"},heightm:1.8,weightkg:75,color:"Purple",prevo:"golbat",evoLevel:23,eggGroups:["Flying"]},
chinchou:{num:170,species:"Chinchou",types:["Water","Electric"],baseStats:{hp:75,atk:38,def:38,spa:56,spd:56,spe:67},abilities:{0:"Technician",1:"Sand Veil"},heightm:0.5,weightkg:12,color:"Blue",evos:["lanturn"],eggGroups:["Water 2"]},
lanturn:{num:171,species:"Lanturn",types:["Water","Electric"],baseStats:{hp:125,atk:58,def:58,spa:76,spd:76,spe:67},abilities:{0:"Trace",1:"Clear Body"},heightm:1.2,weightkg:22.5,color:"Blue",prevo:"chinchou",evoLevel:27,eggGroups:["Water 2"]},
pichu:{num:172,species:"Pichu",types:["Electric"],baseStats:{hp:20,atk:40,def:15,spa:35,spd:35,spe:60},abilities:{0:"Soundproof",1:"Analytic"},heightm:0.3,weightkg:2,color:"Yellow",evos:["pikachu"],eggGroups:["No Eggs"]},
cleffa:{num:173,species:"Cleffa",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:25,def:28,spa:45,spd:55,spe:15},abilities:{0:"Gluttony",1:"Sticky Hold"},heightm:0.3,weightkg:3,color:"Pink",evos:["clefairy"],eggGroups:["No Eggs"]},
igglybuff:{num:174,species:"Igglybuff",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:90,atk:30,def:15,spa:40,spd:20,spe:15},abilities:{0:"Gluttony",1:"Overgrow"},heightm:0.3,weightkg:1,color:"Pink",evos:["jigglypuff"],eggGroups:["No Eggs"]},
togepi:{num:175,species:"Togepi",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:35,atk:20,def:65,spa:40,spd:65,spe:20},abilities:{0:"Insomnia",1:"Anger Point"},heightm:0.3,weightkg:1.5,color:"White",evos:["togetic"],eggGroups:["No Eggs"]},
togetic:{num:176,species:"Togetic",types:["Normal","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:40,def:85,spa:80,spd:105,spe:40},abilities:{0:"Damp",1:"Mummy"},heightm:0.6,weightkg:3.2,color:"White",prevo:"togepi",evos:["togekiss"],evoLevel:2,eggGroups:["Flying","Fairy"]},
natu:{num:177,species:"Natu",types:["Psychic","Flying"],baseStats:{hp:40,atk:50,def:45,spa:70,spd:45,spe:70},abilities:{0:"Water Absorb",1:"Mummy"},heightm:0.2,weightkg:2,color:"Green",evos:["xatu"],eggGroups:["Flying"]},
xatu:{num:178,species:"Xatu",types:["Psychic","Flying"],baseStats:{hp:65,atk:75,def:70,spa:95,spd:70,spe:95},abilities:{0:"Shed Skin",1:"Sand Veil"},heightm:1.5,weightkg:15,color:"Green",prevo:"natu",evoLevel:25,eggGroups:["Flying"]},
mareep:{num:179,species:"Mareep",types:["Electric"],baseStats:{hp:55,atk:40,def:40,spa:65,spd:45,spe:35},abilities:{0:"Steadfast",1:"Compoundeyes"},heightm:0.6,weightkg:7.8,color:"White",evos:["flaaffy"],eggGroups:["Monster","Ground"]},
flaaffy:{num:180,species:"Flaaffy",types:["Electric"],baseStats:{hp:70,atk:55,def:55,spa:80,spd:60,spe:45},abilities:{0:"Sand Veil",1:"Volt Absorb"},heightm:0.8,weightkg:13.3,color:"Pink",prevo:"mareep",evos:["ampharos"],evoLevel:15,eggGroups:["Monster","Ground"]},
ampharos:{num:181,species:"Ampharos",types:["Electric"],baseStats:{hp:90,atk:75,def:75,spa:115,spd:90,spe:55},abilities:{0:"Rivalry",1:"Snow Cloak"},heightm:1.4,weightkg:61.5,color:"Yellow",prevo:"flaaffy",evoLevel:30,eggGroups:["Monster","Ground"]},
bellossom:{num:182,species:"Bellossom",types:["Grass"],baseStats:{hp:75,atk:80,def:85,spa:90,spd:100,spe:50},abilities:{0:"Oblivious",1:"Clear Body"},heightm:0.4,weightkg:5.8,color:"Green",prevo:"gloom",evoLevel:21,eggGroups:["Plant"]},
marill:{num:183,species:"Marill",types:["Water"],baseStats:{hp:70,atk:20,def:50,spa:20,spd:50,spe:40},abilities:{0:"Adaptability",1:"Chlorophyll"},heightm:0.4,weightkg:8.5,color:"Blue",prevo:"azurill",evos:["azumarill"],evoLevel:1,eggGroups:["Water 1","Fairy"]},
azumarill:{num:184,species:"Azumarill",types:["Water"],baseStats:{hp:100,atk:50,def:80,spa:50,spd:80,spe:50},abilities:{0:"Pickpocket",1:"Technician"},heightm:0.8,weightkg:28.5,color:"Blue",prevo:"marill",evoLevel:18,eggGroups:["Water 1","Fairy"]},
sudowoodo:{num:185,species:"Sudowoodo",types:["Rock"],baseStats:{hp:70,atk:100,def:115,spa:30,spd:65,spe:30},abilities:{0:"Victory Star",1:"Own Tempo"},heightm:1.2,weightkg:38,color:"Brown",prevo:"bonsly",evoLevel:1,evoMove:"Mimic",eggGroups:["Mineral"]},
politoed:{num:186,species:"Politoed",types:["Water"],baseStats:{hp:90,atk:75,def:75,spa:90,spd:100,spe:70},abilities:{0:"Klutz",1:"Magic Bounce"},heightm:1.1,weightkg:33.9,color:"Green",prevo:"poliwhirl",evoLevel:25,eggGroups:["Water 1"]},
hoppip:{num:187,species:"Hoppip",types:["Grass","Flying"],baseStats:{hp:35,atk:35,def:40,spa:35,spd:55,spe:50},abilities:{0:"Suction Cups",1:"Drought"},heightm:0.4,weightkg:0.5,color:"Pink",evos:["skiploom"],eggGroups:["Fairy","Plant"]},
skiploom:{num:188,species:"Skiploom",types:["Grass","Flying"],baseStats:{hp:55,atk:45,def:50,spa:45,spd:65,spe:80},abilities:{0:"Steadfast",1:"Prankster"},heightm:0.6,weightkg:1,color:"Green",prevo:"hoppip",evos:["jumpluff"],evoLevel:18,eggGroups:["Fairy","Plant"]},
jumpluff:{num:189,species:"Jumpluff",types:["Grass","Flying"],baseStats:{hp:75,atk:55,def:70,spa:55,spd:85,spe:110},abilities:{0:"Magic Bounce",1:"Imposter"},heightm:0.8,weightkg:3,color:"Blue",prevo:"skiploom",evoLevel:27,eggGroups:["Fairy","Plant"]},
aipom:{num:190,species:"Aipom",types:["Normal"],baseStats:{hp:55,atk:70,def:55,spa:40,spd:55,spe:85},abilities:{0:"Forewarn",1:"Light Metal"},heightm:0.8,weightkg:11.5,color:"Purple",evos:["ambipom"],eggGroups:["Ground"]},
sunkern:{num:191,species:"Sunkern",types:["Grass"],baseStats:{hp:30,atk:30,def:30,spa:30,spd:30,spe:30},abilities:{0:"Damp",1:"Serene Grace"},heightm:0.3,weightkg:1.8,color:"Yellow",evos:["sunflora"],eggGroups:["Plant"]},
sunflora:{num:192,species:"Sunflora",types:["Grass"],baseStats:{hp:75,atk:75,def:55,spa:105,spd:85,spe:30},abilities:{0:"Simple",1:"Drizzle"},heightm:0.8,weightkg:8.5,color:"Yellow",prevo:"sunkern",evoLevel:1,eggGroups:["Plant"]},
yanma:{num:193,species:"Yanma",types:["Bug","Flying"],baseStats:{hp:65,atk:65,def:45,spa:75,spd:45,spe:95},abilities:{0:"Flash Fire",1:"Effect Spore"},heightm:1.2,weightkg:38,color:"Red",evos:["yanmega"],eggGroups:["Bug"]},
wooper:{num:194,species:"Wooper",types:["Water","Ground"],baseStats:{hp:55,atk:45,def:45,spa:25,spd:25,spe:15},abilities:{0:"Rain Dish",1:"Weak Armor"},heightm:0.4,weightkg:8.5,color:"Blue",evos:["quagsire"],eggGroups:["Water 1","Ground"]},
quagsire:{num:195,species:"Quagsire",types:["Water","Ground"],baseStats:{hp:95,atk:85,def:85,spa:65,spd:65,spe:35},abilities:{0:"Anticipation",1:"Arena Trap"},heightm:1.4,weightkg:75,color:"Blue",prevo:"wooper",evoLevel:20,eggGroups:["Water 1","Ground"]},
espeon:{num:196,species:"Espeon",types:["Psychic"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:65,def:60,spa:130,spd:95,spe:110},abilities:{0:"Technician",1:"Sand Veil"},heightm:0.9,weightkg:26.5,color:"Purple",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
umbreon:{num:197,species:"Umbreon",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:65,def:110,spa:60,spd:130,spe:65},abilities:{0:"Immunity",1:"Sniper"},heightm:1,weightkg:27,color:"Black",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
murkrow:{num:198,species:"Murkrow",types:["Dark","Flying"],baseStats:{hp:60,atk:85,def:42,spa:85,spd:42,spe:91},abilities:{0:"Cute Charm",1:"Quick Feet"},heightm:0.5,weightkg:2.1,color:"Black",evos:["honchkrow"],eggGroups:["Flying"]},
slowking:{num:199,species:"Slowking",types:["Water","Psychic"],baseStats:{hp:95,atk:75,def:80,spa:100,spd:110,spe:30},abilities:{0:"Harvest",1:"Torrent"},heightm:2,weightkg:79.5,color:"Pink",prevo:"slowpoke",evoLevel:1,eggGroups:["Monster","Water 1"]},
misdreavus:{num:200,species:"Misdreavus",types:["Ghost"],baseStats:{hp:60,atk:60,def:60,spa:85,spd:85,spe:85},abilities:{0:"Shed Skin",1:"Inner Focus"},heightm:0.7,weightkg:1,color:"Gray",evos:["mismagius"],eggGroups:["Indeterminate"]},
unown:{num:201,species:"Unown",baseForme:"A",types:["Psychic"],gender:"N",baseStats:{hp:48,atk:72,def:48,spa:72,spd:48,spe:48},abilities:{0:"Solid Rock",1:"Rain Dish"},heightm:0.5,weightkg:5,color:"Black",eggGroups:["No Eggs"],otherForms:["unownb","unownc","unownd","unowne","unownf","unowng","unownh","unowni","unownj","unownk","unownl","unownm","unownn","unowno","unownp","unownq","unownr","unowns","unownt","unownu","unownv","unownw","unownx","unowny","unownz","unownem","unownqm"]},
wobbuffet:{num:202,species:"Wobbuffet",types:["Psychic"],baseStats:{hp:190,atk:33,def:58,spa:33,spd:58,spe:33},abilities:{0:"Own Tempo",1:"Suction Cups"},heightm:1.3,weightkg:28.5,color:"Blue",prevo:"wynaut",evoLevel:15,eggGroups:["Indeterminate"]},
girafarig:{num:203,species:"Girafarig",types:["Normal","Psychic"],baseStats:{hp:70,atk:80,def:65,spa:90,spd:65,spe:85},abilities:{0:"Color Change",1:"Big Pecks"},heightm:1.5,weightkg:41.5,color:"Yellow",eggGroups:["Ground"]},
pineco:{num:204,species:"Pineco",types:["Bug"],baseStats:{hp:50,atk:65,def:90,spa:35,spd:35,spe:15},abilities:{0:"Damp",1:"Iron Barbs"},heightm:0.6,weightkg:7.2,color:"Gray",evos:["forretress"],eggGroups:["Bug"]},
forretress:{num:205,species:"Forretress",types:["Bug","Steel"],baseStats:{hp:75,atk:90,def:140,spa:60,spd:60,spe:40},abilities:{0:"Imposter",1:"Gluttony"},heightm:1.2,weightkg:125.8,color:"Purple",prevo:"pineco",evoLevel:31,eggGroups:["Bug"]},
dunsparce:{num:206,species:"Dunsparce",types:["Normal"],baseStats:{hp:100,atk:70,def:70,spa:65,spd:65,spe:45},abilities:{0:"Tangled Feet",1:"Speed Boost"},heightm:1.5,weightkg:14,color:"Yellow",eggGroups:["Ground"]},
gligar:{num:207,species:"Gligar",types:["Ground","Flying"],baseStats:{hp:65,atk:75,def:105,spa:35,spd:65,spe:85},abilities:{0:"Flare Boost",1:"Suction Cups"},heightm:1.1,weightkg:64.8,color:"Purple",evos:["gliscor"],eggGroups:["Bug"]},
steelix:{num:208,species:"Steelix",types:["Steel","Ground"],baseStats:{hp:75,atk:85,def:200,spa:55,spd:65,spe:30},abilities:{0:"Multiscale",1:"Anticipation"},heightm:9.2,weightkg:400,color:"Gray",prevo:"onix",evoLevel:1,eggGroups:["Mineral"]},
snubbull:{num:209,species:"Snubbull",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:60,atk:80,def:50,spa:40,spd:40,spe:30},abilities:{0:"Compoundeyes",1:"Hydration"},heightm:0.6,weightkg:7.8,color:"Pink",evos:["granbull"],eggGroups:["Ground","Fairy"]},
granbull:{num:210,species:"Granbull",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:90,atk:120,def:75,spa:60,spd:60,spe:45},abilities:{0:"Poison Heal",1:"Static"},heightm:1.4,weightkg:48.7,color:"Purple",prevo:"snubbull",evoLevel:23,eggGroups:["Ground","Fairy"]},
qwilfish:{num:211,species:"Qwilfish",types:["Water","Poison"],baseStats:{hp:65,atk:95,def:75,spa:55,spd:55,spe:85},abilities:{0:"Storm Drain",1:"Simple"},heightm:0.5,weightkg:3.9,color:"Gray",eggGroups:["Water 2"]},
scizor:{num:212,species:"Scizor",types:["Bug","Steel"],baseStats:{hp:70,atk:130,def:100,spa:55,spd:80,spe:65},abilities:{0:"Iron Barbs",1:"Magma Armor"},heightm:1.8,weightkg:118,color:"Red",prevo:"scyther",evoLevel:1,eggGroups:["Bug"]},
shuckle:{num:213,species:"Shuckle",types:["Bug","Rock"],baseStats:{hp:20,atk:10,def:230,spa:10,spd:230,spe:5},abilities:{0:"Drought",1:"Compoundeyes"},heightm:0.6,weightkg:20.5,color:"Yellow",eggGroups:["Bug"]},
heracross:{num:214,species:"Heracross",types:["Bug","Fighting"],baseStats:{hp:80,atk:125,def:75,spa:40,spd:95,spe:85},abilities:{0:"Heavy Metal",1:"Contrary"},heightm:1.5,weightkg:54,color:"Blue",eggGroups:["Bug"]},
sneasel:{num:215,species:"Sneasel",types:["Dark","Ice"],baseStats:{hp:55,atk:95,def:55,spa:35,spd:75,spe:115},abilities:{0:"Sap Sipper",1:"Compoundeyes"},heightm:0.9,weightkg:28,color:"Black",evos:["weavile"],eggGroups:["Ground"]},
teddiursa:{num:216,species:"Teddiursa",types:["Normal"],baseStats:{hp:60,atk:80,def:50,spa:50,spd:50,spe:40},abilities:{0:"Analytic",1:"Color Change"},heightm:0.6,weightkg:8.8,color:"Brown",evos:["ursaring"],eggGroups:["Ground"]},
ursaring:{num:217,species:"Ursaring",types:["Normal"],baseStats:{hp:90,atk:130,def:75,spa:75,spd:75,spe:55},abilities:{0:"Soundproof",1:"Synchronize"},heightm:1.8,weightkg:125.8,color:"Brown",prevo:"teddiursa",evoLevel:30,eggGroups:["Ground"]},
slugma:{num:218,species:"Slugma",types:["Fire"],baseStats:{hp:40,atk:40,def:40,spa:70,spd:40,spe:20},abilities:{0:"Shield Dust",1:"Intimidate"},heightm:0.7,weightkg:35,color:"Red",evos:["magcargo"],eggGroups:["Indeterminate"]},
magcargo:{num:219,species:"Magcargo",types:["Fire","Rock"],baseStats:{hp:50,atk:50,def:120,spa:80,spd:80,spe:30},abilities:{0:"Clear Body",1:"Tinted Lens"},heightm:0.8,weightkg:55,color:"Red",prevo:"slugma",evoLevel:38,eggGroups:["Indeterminate"]},
swinub:{num:220,species:"Swinub",types:["Ice","Ground"],baseStats:{hp:50,atk:50,def:40,spa:30,spd:30,spe:50},abilities:{0:"Cursed Body",1:"Technician"},heightm:0.4,weightkg:6.5,color:"Brown",evos:["piloswine"],eggGroups:["Ground"]},
piloswine:{num:221,species:"Piloswine",types:["Ice","Ground"],baseStats:{hp:100,atk:100,def:80,spa:60,spd:60,spe:50},abilities:{0:"Simple",1:"Rivalry"},heightm:1.1,weightkg:55.8,color:"Brown",prevo:"swinub",evos:["mamoswine"],evoLevel:33,eggGroups:["Ground"]},
corsola:{num:222,species:"Corsola",types:["Water","Rock"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:55,atk:55,def:85,spa:65,spd:85,spe:35},abilities:{0:"Color Change",1:"Tinted Lens"},heightm:0.6,weightkg:5,color:"Pink",eggGroups:["Water 1","Water 3"]},
remoraid:{num:223,species:"Remoraid",types:["Water"],baseStats:{hp:35,atk:65,def:35,spa:65,spd:35,spe:65},abilities:{0:"Effect Spore",1:"Water Absorb"},heightm:0.6,weightkg:12,color:"Gray",evos:["octillery"],eggGroups:["Water 1","Water 2"]},
octillery:{num:224,species:"Octillery",types:["Water"],baseStats:{hp:75,atk:105,def:75,spa:105,spd:75,spe:45},abilities:{0:"Tangled Feet",1:"Cloud Nine"},heightm:0.9,weightkg:28.5,color:"Red",prevo:"remoraid",evoLevel:25,eggGroups:["Water 1","Water 2"]},
delibird:{num:225,species:"Delibird",types:["Ice","Flying"],baseStats:{hp:45,atk:55,def:45,spa:65,spd:45,spe:75},abilities:{0:"Reckless",1:"Keen Eye"},heightm:0.9,weightkg:16,color:"Red",eggGroups:["Water 1","Ground"]},
mantine:{num:226,species:"Mantine",types:["Water","Flying"],baseStats:{hp:65,atk:40,def:70,spa:80,spd:140,spe:70},abilities:{0:"Chlorophyll",1:"Flare Boost"},heightm:2.1,weightkg:220,color:"Purple",prevo:"mantyke",evoLevel:1,eggGroups:["Water 1"]},
skarmory:{num:227,species:"Skarmory",types:["Steel","Flying"],baseStats:{hp:65,atk:80,def:140,spa:40,spd:70,spe:70},abilities:{0:"Rivalry",1:"Rock Head"},heightm:1.7,weightkg:50.5,color:"Gray",eggGroups:["Flying"]},
houndour:{num:228,species:"Houndour",types:["Dark","Fire"],baseStats:{hp:45,atk:60,def:30,spa:80,spd:50,spe:65},abilities:{0:"Victory Star",1:"Unburden"},heightm:0.6,weightkg:10.8,color:"Black",evos:["houndoom"],eggGroups:["Ground"]},
houndoom:{num:229,species:"Houndoom",types:["Dark","Fire"],baseStats:{hp:75,atk:90,def:50,spa:110,spd:80,spe:95},abilities:{0:"Shed Skin",1:"Sand Force"},heightm:1.4,weightkg:35,color:"Black",prevo:"houndour",evoLevel:24,eggGroups:["Ground"]},
kingdra:{num:230,species:"Kingdra",types:["Water","Dragon"],baseStats:{hp:75,atk:95,def:95,spa:95,spd:95,spe:85},abilities:{0:"Cloud Nine",1:"Pickpocket"},heightm:1.8,weightkg:152,color:"Blue",prevo:"seadra",evoLevel:32,eggGroups:["Water 1","Dragon"]},
phanpy:{num:231,species:"Phanpy",types:["Ground"],baseStats:{hp:90,atk:60,def:60,spa:40,spd:40,spe:40},abilities:{0:"Flash Fire",1:"Levitate"},heightm:0.5,weightkg:33.5,color:"Blue",evos:["donphan"],eggGroups:["Ground"]},
donphan:{num:232,species:"Donphan",types:["Ground"],baseStats:{hp:90,atk:120,def:120,spa:60,spd:60,spe:50},abilities:{0:"Hyper Cutter",1:"Damp"},heightm:1.1,weightkg:120,color:"Gray",prevo:"phanpy",evoLevel:25,eggGroups:["Ground"]},
porygon2:{num:233,species:"Porygon2",types:["Normal"],gender:"N",baseStats:{hp:85,atk:80,def:90,spa:105,spd:95,spe:60},abilities:{0:"Battle Armor",1:"Drought"},heightm:0.6,weightkg:32.5,color:"Red",prevo:"porygon",evos:["porygonz"],evoLevel:1,eggGroups:["Mineral"]},
stantler:{num:234,species:"Stantler",types:["Normal"],baseStats:{hp:73,atk:95,def:62,spa:85,spd:65,spe:85},abilities:{0:"Swarm",1:"Lightningrod"},heightm:1.4,weightkg:71.2,color:"Brown",eggGroups:["Ground"]},
smeargle:{num:235,species:"Smeargle",types:["Normal"],baseStats:{hp:55,atk:20,def:35,spa:20,spd:45,spe:75},abilities:{0:"Gluttony",1:"Super Luck"},heightm:1.2,weightkg:58,color:"White",eggGroups:["Ground"]},
tyrogue:{num:236,species:"Tyrogue",types:["Fighting"],gender:"M",baseStats:{hp:35,atk:35,def:35,spa:35,spd:35,spe:35},abilities:{0:"Flare Boost",1:"Imposter"},heightm:0.7,weightkg:21,color:"Purple",evos:["hitmonlee","hitmonchan","hitmontop"],eggGroups:["No Eggs"]},
hitmontop:{num:237,species:"Hitmontop",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:95,def:95,spa:35,spd:110,spe:70},abilities:{0:"Klutz",1:"Aftermath"},heightm:1.4,weightkg:48,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Humanshape"]},
smoochum:{num:238,species:"Smoochum",types:["Ice","Psychic"],gender:"F",baseStats:{hp:45,atk:30,def:15,spa:85,spd:65,spe:65},abilities:{0:"Rock Head",1:"Water Absorb"},heightm:0.4,weightkg:6,color:"Pink",evos:["jynx"],eggGroups:["No Eggs"]},
elekid:{num:239,species:"Elekid",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:45,atk:63,def:37,spa:65,spd:55,spe:95},abilities:{0:"Wonder Guard",1:"Unaware"},heightm:0.6,weightkg:23.5,color:"Yellow",evos:["electabuzz"],eggGroups:["No Eggs"]},
magby:{num:240,species:"Magby",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:45,atk:75,def:37,spa:70,spd:55,spe:83},abilities:{0:"Static",1:"Adaptability"},heightm:0.7,weightkg:21.4,color:"Red",evos:["magmar"],eggGroups:["No Eggs"]},
miltank:{num:241,species:"Miltank",types:["Normal"],gender:"F",baseStats:{hp:95,atk:80,def:105,spa:40,spd:70,spe:100},abilities:{0:"Defiant",1:"Normalize"},heightm:1.2,weightkg:75.5,color:"Pink",eggGroups:["Ground"]},
blissey:{num:242,species:"Blissey",types:["Normal"],gender:"F",baseStats:{hp:255,atk:10,def:10,spa:75,spd:135,spe:55},abilities:{0:"Shed Skin",1:"Early Bird"},heightm:1.5,weightkg:46.8,color:"Pink",prevo:"chansey",evoLevel:2,eggGroups:["Fairy"]},
raikou:{num:243,species:"Raikou",types:["Electric"],gender:"N",baseStats:{hp:90,atk:85,def:75,spa:115,spd:100,spe:115},abilities:{0:"Lightningrod",1:"Iron Barbs"},heightm:1.9,weightkg:178,color:"Yellow",eggGroups:["No Eggs"]},
entei:{num:244,species:"Entei",types:["Fire"],gender:"N",baseStats:{hp:115,atk:115,def:85,spa:90,spd:75,spe:100},abilities:{0:"Thick Fat",1:"Dry Skin"},heightm:2.1,weightkg:198,color:"Brown",eggGroups:["No Eggs"]},
suicune:{num:245,species:"Suicune",types:["Water"],gender:"N",baseStats:{hp:100,atk:75,def:115,spa:90,spd:115,spe:85},abilities:{0:"Forewarn",1:"Poison Heal"},heightm:2,weightkg:187,color:"Blue",eggGroups:["No Eggs"]},
larvitar:{num:246,species:"Larvitar",types:["Rock","Ground"],baseStats:{hp:50,atk:64,def:50,spa:45,spd:50,spe:41},abilities:{0:"Synchronize",1:"Rock Head"},heightm:0.6,weightkg:72,color:"Green",evos:["pupitar"],eggGroups:["Monster"]},
pupitar:{num:247,species:"Pupitar",types:["Rock","Ground"],baseStats:{hp:70,atk:84,def:70,spa:65,spd:70,spe:51},abilities:{0:"Mummy",1:"Sheer Force"},heightm:1.2,weightkg:152,color:"Gray",prevo:"larvitar",evos:["tyranitar"],evoLevel:30,eggGroups:["Monster"]},
tyranitar:{num:248,species:"Tyranitar",types:["Rock","Dark"],baseStats:{hp:100,atk:134,def:110,spa:95,spd:100,spe:61},abilities:{0:"Anticipation",1:"Rain Dish"},heightm:2,weightkg:202,color:"Green",prevo:"pupitar",evoLevel:55,eggGroups:["Monster"]},
lugia:{num:249,species:"Lugia",types:["Psychic","Flying"],gender:"N",baseStats:{hp:106,atk:90,def:130,spa:90,spd:154,spe:110},abilities:{0:"Sap Sipper",1:"Limber"},heightm:5.2,weightkg:216,color:"White",eggGroups:["No Eggs"]},
hooh:{num:250,species:"Ho-Oh",types:["Fire","Flying"],gender:"N",baseStats:{hp:106,atk:130,def:90,spa:110,spd:154,spe:90},abilities:{0:"Poison Heal",1:"Magnet Pull"},heightm:3.8,weightkg:199,color:"Red",eggGroups:["No Eggs"]},
celebi:{num:251,species:"Celebi",types:["Psychic","Grass"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Soundproof",1:"Simple"},heightm:0.6,weightkg:5,color:"Green",eggGroups:["No Eggs"]},
treecko:{num:252,species:"Treecko",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:45,def:35,spa:65,spd:55,spe:70},abilities:{0:"Overcoat",1:"Thick Fat"},heightm:0.5,weightkg:5,color:"Green",evos:["grovyle"],eggGroups:["Monster","Dragon"]},
grovyle:{num:253,species:"Grovyle",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:65,def:45,spa:85,spd:65,spe:95},abilities:{0:"Rock Head",1:"Clear Body"},heightm:0.9,weightkg:21.6,color:"Green",prevo:"treecko",evos:["sceptile"],evoLevel:16,eggGroups:["Monster","Dragon"]},
sceptile:{num:254,species:"Sceptile",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:85,def:65,spa:105,spd:85,spe:120},abilities:{0:"Tinted Lens",1:"Justified"},heightm:1.7,weightkg:52.2,color:"Green",prevo:"grovyle",evoLevel:36,eggGroups:["Monster","Dragon"]},
torchic:{num:255,species:"Torchic",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:60,def:40,spa:70,spd:50,spe:45},abilities:{0:"Victory Star",1:"Infiltrator"},heightm:0.4,weightkg:2.5,color:"Red",evos:["combusken"],eggGroups:["Ground"]},
combusken:{num:256,species:"Combusken",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:85,def:60,spa:85,spd:60,spe:55},abilities:{0:"Limber",1:"Super Luck"},heightm:0.9,weightkg:19.5,color:"Red",prevo:"torchic",evos:["blaziken"],evoLevel:16,eggGroups:["Ground"]},
blaziken:{num:257,species:"Blaziken",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:120,def:70,spa:110,spd:70,spe:80},abilities:{0:"Justified",1:"Light Metal"},heightm:1.9,weightkg:52,color:"Red",prevo:"combusken",evoLevel:36,eggGroups:["Ground"]},
mudkip:{num:258,species:"Mudkip",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:70,def:50,spa:50,spd:50,spe:40},abilities:{0:"Contrary",1:"Cursed Body"},heightm:0.4,weightkg:7.6,color:"Blue",evos:["marshtomp"],eggGroups:["Monster","Water 1"]},
marshtomp:{num:259,species:"Marshtomp",types:["Water","Ground"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:85,def:70,spa:60,spd:70,spe:50},abilities:{0:"Frisk",1:"Magma Armor"},heightm:0.7,weightkg:28,color:"Blue",prevo:"mudkip",evos:["swampert"],evoLevel:16,eggGroups:["Monster","Water 1"]},
swampert:{num:260,species:"Swampert",types:["Water","Ground"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:100,atk:110,def:90,spa:85,spd:90,spe:60},abilities:{0:"Sturdy",1:"Chlorophyll"},heightm:1.5,weightkg:81.9,color:"Blue",prevo:"marshtomp",evoLevel:36,eggGroups:["Monster","Water 1"]},
poochyena:{num:261,species:"Poochyena",types:["Dark"],baseStats:{hp:35,atk:55,def:35,spa:30,spd:30,spe:35},abilities:{0:"Adaptability",1:"Early Bird"},heightm:0.5,weightkg:13.6,color:"Gray",evos:["mightyena"],eggGroups:["Ground"]},
mightyena:{num:262,species:"Mightyena",types:["Dark"],baseStats:{hp:70,atk:90,def:70,spa:60,spd:60,spe:70},abilities:{0:"Unaware",1:"Hydration"},heightm:1,weightkg:37,color:"Gray",prevo:"poochyena",evoLevel:18,eggGroups:["Ground"]},
zigzagoon:{num:263,species:"Zigzagoon",types:["Normal"],baseStats:{hp:38,atk:30,def:41,spa:30,spd:41,spe:60},abilities:{0:"Volt Absorb",1:"Static"},heightm:0.4,weightkg:17.5,color:"Brown",evos:["linoone"],eggGroups:["Ground"]},
linoone:{num:264,species:"Linoone",types:["Normal"],baseStats:{hp:78,atk:70,def:61,spa:50,spd:61,spe:100},abilities:{0:"Reckless",1:"Water Veil"},heightm:0.5,weightkg:32.5,color:"White",prevo:"zigzagoon",evoLevel:20,eggGroups:["Ground"]},
wurmple:{num:265,species:"Wurmple",types:["Bug"],baseStats:{hp:45,atk:45,def:35,spa:20,spd:30,spe:20},abilities:{0:"Poison Touch",1:"Shadow Tag"},heightm:0.3,weightkg:3.6,color:"Red",evos:["silcoon","cascoon"],eggGroups:["Bug"]},
silcoon:{num:266,species:"Silcoon",types:["Bug"],baseStats:{hp:50,atk:35,def:55,spa:25,spd:25,spe:15},abilities:{0:"Contrary",1:"Unaware"},heightm:0.6,weightkg:10,color:"White",prevo:"wurmple",evos:["beautifly"],evoLevel:7,eggGroups:["Bug"]},
beautifly:{num:267,species:"Beautifly",types:["Bug","Flying"],baseStats:{hp:60,atk:70,def:50,spa:90,spd:50,spe:65},abilities:{0:"Stall",1:"Illusion"},heightm:1,weightkg:28.4,color:"Yellow",prevo:"silcoon",evoLevel:10,eggGroups:["Bug"]},
cascoon:{num:268,species:"Cascoon",types:["Bug"],baseStats:{hp:50,atk:35,def:55,spa:25,spd:25,spe:15},abilities:{0:"Dry Skin",1:"Prankster"},heightm:0.7,weightkg:11.5,color:"Purple",prevo:"wurmple",evos:["dustox"],evoLevel:7,eggGroups:["Bug"]},
dustox:{num:269,species:"Dustox",types:["Bug","Poison"],baseStats:{hp:60,atk:50,def:70,spa:50,spd:90,spe:65},abilities:{0:"Justified",1:"Victory Star"},heightm:1.2,weightkg:31.6,color:"Green",prevo:"cascoon",evoLevel:10,eggGroups:["Bug"]},
lotad:{num:270,species:"Lotad",types:["Water","Grass"],baseStats:{hp:40,atk:30,def:30,spa:40,spd:50,spe:30},abilities:{0:"Technician",1:"Magma Armor"},heightm:0.5,weightkg:2.6,color:"Green",evos:["lombre"],eggGroups:["Water 1","Plant"]},
lombre:{num:271,species:"Lombre",types:["Water","Grass"],baseStats:{hp:60,atk:50,def:50,spa:60,spd:70,spe:50},abilities:{0:"Magic Bounce",1:"Effect Spore"},heightm:1.2,weightkg:32.5,color:"Green",prevo:"lotad",evos:["ludicolo"],evoLevel:14,eggGroups:["Water 1","Plant"]},
ludicolo:{num:272,species:"Ludicolo",types:["Water","Grass"],baseStats:{hp:80,atk:70,def:70,spa:90,spd:100,spe:70},abilities:{0:"Forewarn",1:"Damp"},heightm:1.5,weightkg:55,color:"Green",prevo:"lombre",evoLevel:14,eggGroups:["Water 1","Plant"]},
seedot:{num:273,species:"Seedot",types:["Grass"],baseStats:{hp:40,atk:40,def:50,spa:30,spd:30,spe:30},abilities:{0:"Sturdy",1:"Forewarn"},heightm:0.5,weightkg:4,color:"Brown",evos:["nuzleaf"],eggGroups:["Ground","Plant"]},
nuzleaf:{num:274,species:"Nuzleaf",types:["Grass","Dark"],baseStats:{hp:70,atk:70,def:40,spa:60,spd:40,spe:60},abilities:{0:"Flash Fire",1:"Flame Body"},heightm:1,weightkg:28,color:"Brown",prevo:"seedot",evos:["shiftry"],evoLevel:14,eggGroups:["Ground","Plant"]},
shiftry:{num:275,species:"Shiftry",types:["Grass","Dark"],baseStats:{hp:90,atk:100,def:60,spa:90,spd:60,spe:80},abilities:{0:"Moxie",1:"Sand Veil"},heightm:1.3,weightkg:59.6,color:"Brown",prevo:"nuzleaf",evoLevel:14,eggGroups:["Ground","Plant"]},
taillow:{num:276,species:"Taillow",types:["Normal","Flying"],baseStats:{hp:40,atk:55,def:30,spa:30,spd:30,spe:85},abilities:{0:"Sturdy",1:"Serene Grace"},heightm:0.3,weightkg:2.3,color:"Blue",evos:["swellow"],eggGroups:["Flying"]},
swellow:{num:277,species:"Swellow",types:["Normal","Flying"],baseStats:{hp:60,atk:85,def:60,spa:50,spd:50,spe:125},abilities:{0:"Klutz",1:"Poison Touch"},heightm:0.7,weightkg:19.8,color:"Blue",prevo:"taillow",evoLevel:22,eggGroups:["Flying"]},
wingull:{num:278,species:"Wingull",types:["Water","Flying"],baseStats:{hp:40,atk:30,def:30,spa:55,spd:30,spe:85},abilities:{0:"Defiant",1:"Synchronize"},heightm:0.6,weightkg:9.5,color:"White",evos:["pelipper"],eggGroups:["Water 1","Flying"]},
pelipper:{num:279,species:"Pelipper",types:["Water","Flying"],baseStats:{hp:60,atk:50,def:100,spa:85,spd:70,spe:65},abilities:{0:"Own Tempo",1:"Heatproof"},heightm:1.2,weightkg:28,color:"Yellow",prevo:"wingull",evoLevel:25,eggGroups:["Water 1","Flying"]},
ralts:{num:280,species:"Ralts",types:["Psychic"],baseStats:{hp:28,atk:25,def:25,spa:45,spd:35,spe:40},abilities:{0:"Sand Force",1:"Heatproof"},heightm:0.4,weightkg:6.6,color:"White",evos:["kirlia"],eggGroups:["Indeterminate"]},
kirlia:{num:281,species:"Kirlia",types:["Psychic"],baseStats:{hp:38,atk:35,def:35,spa:65,spd:55,spe:50},abilities:{0:"Static",1:"Hustle"},heightm:0.8,weightkg:20.2,color:"White",prevo:"ralts",evos:["gardevoir","gallade"],evoLevel:20,eggGroups:["Indeterminate"]},
gardevoir:{num:282,species:"Gardevoir",types:["Psychic"],baseStats:{hp:68,atk:65,def:65,spa:125,spd:115,spe:80},abilities:{0:"Battle Armor",1:"Tinted Lens"},heightm:1.6,weightkg:48.4,color:"White",prevo:"kirlia",evoLevel:30,eggGroups:["Indeterminate"]},
surskit:{num:283,species:"Surskit",types:["Bug","Water"],baseStats:{hp:40,atk:30,def:32,spa:50,spd:52,spe:65},abilities:{0:"Thick Fat",1:"Soundproof"},heightm:0.5,weightkg:1.7,color:"Blue",evos:["masquerain"],eggGroups:["Water 1","Bug"]},
masquerain:{num:284,species:"Masquerain",types:["Bug","Flying"],baseStats:{hp:70,atk:60,def:62,spa:80,spd:82,spe:60},abilities:{0:"Frisk",1:"Magic Bounce"},heightm:0.8,weightkg:3.6,color:"Blue",prevo:"surskit",evoLevel:22,eggGroups:["Water 1","Bug"]},
shroomish:{num:285,species:"Shroomish",types:["Grass"],baseStats:{hp:60,atk:40,def:60,spa:40,spd:60,spe:35},abilities:{0:"Heatproof",1:"Oblivious"},heightm:0.4,weightkg:4.5,color:"Brown",evos:["breloom"],eggGroups:["Fairy","Plant"]},
breloom:{num:286,species:"Breloom",types:["Grass","Fighting"],baseStats:{hp:60,atk:130,def:80,spa:60,spd:60,spe:70},abilities:{0:"Simple",1:"Damp"},heightm:1.2,weightkg:39.2,color:"Green",prevo:"shroomish",evoLevel:23,eggGroups:["Fairy","Plant"]},
slakoth:{num:287,species:"Slakoth",types:["Normal"],baseStats:{hp:60,atk:60,def:60,spa:35,spd:35,spe:30},abilities:{0:"Compoundeyes",1:"Tinted Lens"},heightm:0.8,weightkg:24,color:"Brown",evos:["vigoroth"],eggGroups:["Ground"]},
vigoroth:{num:288,species:"Vigoroth",types:["Normal"],baseStats:{hp:80,atk:80,def:80,spa:55,spd:55,spe:90},abilities:{0:"Rock Head",1:"Weak Armor"},heightm:1.4,weightkg:46.5,color:"White",prevo:"slakoth",evos:["slaking"],evoLevel:18,eggGroups:["Ground"]},
slaking:{num:289,species:"Slaking",types:["Normal"],baseStats:{hp:150,atk:160,def:100,spa:95,spd:65,spe:100},abilities:{0:"Skill Link",1:"Levitate"},heightm:2,weightkg:130.5,color:"Brown",prevo:"vigoroth",evoLevel:36,eggGroups:["Ground"]},
nincada:{num:290,species:"Nincada",types:["Bug","Ground"],baseStats:{hp:31,atk:45,def:90,spa:30,spd:30,spe:40},abilities:{0:"Overcoat",1:"Magic Bounce"},heightm:0.5,weightkg:5.5,color:"Gray",evos:["ninjask","shedinja"],eggGroups:["Bug"]},
ninjask:{num:291,species:"Ninjask",types:["Bug","Flying"],baseStats:{hp:61,atk:90,def:45,spa:50,spd:50,spe:160},abilities:{0:"Frisk",1:"Magic Guard"},heightm:0.8,weightkg:12,color:"Yellow",prevo:"nincada",evoLevel:20,eggGroups:["Bug"]},
shedinja:{num:292,species:"Shedinja",types:["Bug","Ghost"],gender:"N",baseStats:{hp:1,atk:90,def:45,spa:30,spd:30,spe:40},abilities:{0:"Skill Link",1:"Leaf Guard"},heightm:0.8,weightkg:1.2,color:"Brown",prevo:"nincada",evoLevel:20,eggGroups:["Mineral"]},
whismur:{num:293,species:"Whismur",types:["Normal"],baseStats:{hp:64,atk:51,def:23,spa:51,spd:23,spe:28},abilities:{0:"Color Change",1:"Contrary"},heightm:0.6,weightkg:16.3,color:"Pink",evos:["loudred"],eggGroups:["Monster","Ground"]},
loudred:{num:294,species:"Loudred",types:["Normal"],baseStats:{hp:84,atk:71,def:43,spa:71,spd:43,spe:48},abilities:{0:"Heatproof",1:"Sand Veil"},heightm:1,weightkg:40.5,color:"Blue",prevo:"whismur",evos:["exploud"],evoLevel:20,eggGroups:["Monster","Ground"]},
exploud:{num:295,species:"Exploud",types:["Normal"],baseStats:{hp:104,atk:91,def:63,spa:91,spd:63,spe:68},abilities:{0:"Clear Body",1:"Infiltrator"},heightm:1.5,weightkg:84,color:"Blue",prevo:"loudred",evoLevel:40,eggGroups:["Monster","Ground"]},
makuhita:{num:296,species:"Makuhita",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:72,atk:60,def:30,spa:20,spd:30,spe:25},abilities:{0:"Poison Heal",1:"Poison Point"},heightm:1,weightkg:86.4,color:"Yellow",evos:["hariyama"],eggGroups:["Humanshape"]},
hariyama:{num:297,species:"Hariyama",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:144,atk:120,def:60,spa:40,spd:60,spe:50},abilities:{0:"Harvest",1:"Battle Armor"},heightm:2.3,weightkg:253.8,color:"Brown",prevo:"makuhita",evoLevel:24,eggGroups:["Humanshape"]},
azurill:{num:298,species:"Azurill",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:20,def:40,spa:20,spd:40,spe:20},abilities:{0:"Flame Body",1:"Early Bird"},heightm:0.2,weightkg:2,color:"Blue",evos:["marill"],eggGroups:["No Eggs"]},
nosepass:{num:299,species:"Nosepass",types:["Rock"],baseStats:{hp:30,atk:45,def:135,spa:45,spd:90,spe:30},abilities:{0:"Motor Drive",1:"Big Pecks"},heightm:1,weightkg:97,color:"Gray",evos:["probopass"],eggGroups:["Mineral"]},
skitty:{num:300,species:"Skitty",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:45,def:45,spa:35,spd:35,spe:50},abilities:{0:"Synchronize",1:"Weak Armor"},heightm:0.6,weightkg:11,color:"Pink",evos:["delcatty"],eggGroups:["Ground","Fairy"]},
delcatty:{num:301,species:"Delcatty",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:65,def:65,spa:55,spd:55,spe:70},abilities:{0:"Magnet Pull",1:"Poison Heal"},heightm:1.1,weightkg:32.6,color:"Purple",prevo:"skitty",evoLevel:1,eggGroups:["Ground","Fairy"]},
sableye:{num:302,species:"Sableye",types:["Dark","Ghost"],baseStats:{hp:50,atk:75,def:75,spa:65,spd:65,spe:50},abilities:{0:"Soundproof",1:"Magic Bounce"},heightm:0.5,weightkg:11,color:"Purple",eggGroups:["Humanshape"]},
mawile:{num:303,species:"Mawile",types:["Steel"],baseStats:{hp:50,atk:85,def:85,spa:55,spd:55,spe:50},abilities:{0:"Solar Power",1:"Guts"},heightm:0.6,weightkg:11.5,color:"Black",eggGroups:["Ground","Fairy"]},
aron:{num:304,species:"Aron",types:["Steel","Rock"],baseStats:{hp:50,atk:70,def:100,spa:40,spd:40,spe:30},abilities:{0:"Harvest",1:"Aftermath"},heightm:0.4,weightkg:60,color:"Gray",evos:["lairon"],eggGroups:["Monster"]},
lairon:{num:305,species:"Lairon",types:["Steel","Rock"],baseStats:{hp:60,atk:90,def:140,spa:50,spd:50,spe:40},abilities:{0:"Iron Barbs",1:"Storm Drain"},heightm:0.9,weightkg:120,color:"Gray",prevo:"aron",evos:["aggron"],evoLevel:32,eggGroups:["Monster"]},
aggron:{num:306,species:"Aggron",types:["Steel","Rock"],baseStats:{hp:70,atk:110,def:180,spa:60,spd:60,spe:50},abilities:{0:"Bad Dreams",1:"Simple"},heightm:2.1,weightkg:360,color:"Gray",prevo:"lairon",evoLevel:42,eggGroups:["Monster"]},
meditite:{num:307,species:"Meditite",types:["Fighting","Psychic"],baseStats:{hp:30,atk:40,def:55,spa:40,spd:55,spe:60},abilities:{0:"Download",1:"Damp"},heightm:0.6,weightkg:11.2,color:"Blue",evos:["medicham"],eggGroups:["Humanshape"]},
medicham:{num:308,species:"Medicham",types:["Fighting","Psychic"],baseStats:{hp:60,atk:60,def:75,spa:60,spd:75,spe:80},abilities:{0:"Pickpocket",1:"Battle Armor"},heightm:1.3,weightkg:31.5,color:"Red",prevo:"meditite",evoLevel:37,eggGroups:["Humanshape"]},
electrike:{num:309,species:"Electrike",types:["Electric"],baseStats:{hp:40,atk:45,def:40,spa:65,spd:40,spe:65},abilities:{0:"Shield Dust",1:"Battle Armor"},heightm:0.6,weightkg:15.2,color:"Green",evos:["manectric"],eggGroups:["Ground"]},
manectric:{num:310,species:"Manectric",types:["Electric"],baseStats:{hp:70,atk:75,def:60,spa:105,spd:60,spe:105},abilities:{0:"Suction Cups",1:"Poison Touch"},heightm:1.5,weightkg:40.2,color:"Yellow",prevo:"electrike",evoLevel:26,eggGroups:["Ground"]},
plusle:{num:311,species:"Plusle",types:["Electric"],baseStats:{hp:60,atk:50,def:40,spa:85,spd:75,spe:95},abilities:{0:"Anger Point",1:"Cursed Body"},heightm:0.4,weightkg:4.2,color:"Yellow",eggGroups:["Fairy"]},
minun:{num:312,species:"Minun",types:["Electric"],baseStats:{hp:60,atk:40,def:50,spa:75,spd:85,spe:95},abilities:{0:"Unnerve",1:"Battle Armor"},heightm:0.4,weightkg:4.2,color:"Yellow",eggGroups:["Fairy"]},
volbeat:{num:313,species:"Volbeat",types:["Bug"],gender:"M",baseStats:{hp:65,atk:73,def:55,spa:47,spd:75,spe:85},abilities:{0:"Rain Dish",1:"Cursed Body"},heightm:0.7,weightkg:17.7,color:"Gray",eggGroups:["Bug","Humanshape"]},
illumise:{num:314,species:"Illumise",types:["Bug"],gender:"F",baseStats:{hp:65,atk:47,def:55,spa:73,spd:75,spe:85},abilities:{0:"Victory Star",1:"Leaf Guard"},heightm:0.6,weightkg:17.7,color:"Purple",eggGroups:["Bug","Humanshape"]},
roselia:{num:315,species:"Roselia",types:["Grass","Poison"],baseStats:{hp:50,atk:60,def:45,spa:100,spd:80,spe:65},abilities:{0:"Adaptability",1:"Stall"},heightm:0.3,weightkg:2,color:"Green",prevo:"budew",evos:["roserade"],evoLevel:1,eggGroups:["Fairy","Plant"]},
gulpin:{num:316,species:"Gulpin",types:["Poison"],baseStats:{hp:70,atk:43,def:53,spa:43,spd:53,spe:40},abilities:{0:"Imposter",1:"Flash Fire"},heightm:0.4,weightkg:10.3,color:"Green",evos:["swalot"],eggGroups:["Indeterminate"]},
swalot:{num:317,species:"Swalot",types:["Poison"],baseStats:{hp:100,atk:73,def:83,spa:73,spd:83,spe:55},abilities:{0:"Iron Barbs",1:"Unnerve"},heightm:1.7,weightkg:80,color:"Purple",prevo:"gulpin",evoLevel:26,eggGroups:["Indeterminate"]},
carvanha:{num:318,species:"Carvanha",types:["Water","Dark"],baseStats:{hp:45,atk:90,def:20,spa:65,spd:20,spe:65},abilities:{0:"Magma Armor",1:"Quick Feet"},heightm:0.8,weightkg:20.8,color:"Red",evos:["sharpedo"],eggGroups:["Water 2"]},
sharpedo:{num:319,species:"Sharpedo",types:["Water","Dark"],baseStats:{hp:70,atk:120,def:40,spa:95,spd:40,spe:95},abilities:{0:"Immunity",1:"Anticipation"},heightm:1.8,weightkg:88.8,color:"Blue",prevo:"carvanha",evoLevel:30,eggGroups:["Water 2"]},
wailmer:{num:320,species:"Wailmer",types:["Water"],baseStats:{hp:130,atk:70,def:35,spa:70,spd:35,spe:60},abilities:{0:"Trace",1:"Tangled Feet"},heightm:2,weightkg:130,color:"Blue",evos:["wailord"],eggGroups:["Ground","Water 2"]},
wailord:{num:321,species:"Wailord",types:["Water"],baseStats:{hp:170,atk:90,def:45,spa:90,spd:45,spe:60},abilities:{0:"Quick Feet",1:"Contrary"},heightm:14.5,weightkg:398,color:"Blue",prevo:"wailmer",evoLevel:40,eggGroups:["Ground","Water 2"]},
numel:{num:322,species:"Numel",types:["Fire","Ground"],baseStats:{hp:60,atk:60,def:40,spa:65,spd:45,spe:35},abilities:{0:"Cloud Nine",1:"Toxic Boost"},heightm:0.7,weightkg:24,color:"Yellow",evos:["camerupt"],eggGroups:["Ground"]},
camerupt:{num:323,species:"Camerupt",types:["Fire","Ground"],baseStats:{hp:70,atk:100,def:70,spa:105,spd:75,spe:40},abilities:{0:"Wonder Guard",1:"Big Pecks"},heightm:1.9,weightkg:220,color:"Red",prevo:"numel",evoLevel:33,eggGroups:["Ground"]},
torkoal:{num:324,species:"Torkoal",types:["Fire"],baseStats:{hp:70,atk:85,def:140,spa:85,spd:70,spe:20},abilities:{0:"Illusion",1:"Sand Force"},heightm:0.5,weightkg:80.4,color:"Brown",eggGroups:["Ground"]},
spoink:{num:325,species:"Spoink",types:["Psychic"],baseStats:{hp:60,atk:25,def:35,spa:70,spd:80,spe:60},abilities:{0:"Cute Charm",1:"Magma Armor"},heightm:0.7,weightkg:30.6,color:"Black",evos:["grumpig"],eggGroups:["Ground"]},
grumpig:{num:326,species:"Grumpig",types:["Psychic"],baseStats:{hp:80,atk:45,def:65,spa:90,spd:110,spe:80},abilities:{0:"Justified",1:"Cursed Body"},heightm:0.9,weightkg:71.5,color:"Purple",prevo:"spoink",evoLevel:32,eggGroups:["Ground"]},
spinda:{num:327,species:"Spinda",types:["Normal"],baseStats:{hp:60,atk:60,def:60,spa:60,spd:60,spe:60},abilities:{0:"Sand Veil",1:"Guts"},heightm:1.1,weightkg:5,color:"Brown",eggGroups:["Ground","Humanshape"]},
trapinch:{num:328,species:"Trapinch",types:["Ground"],baseStats:{hp:45,atk:100,def:45,spa:45,spd:45,spe:10},abilities:{0:"Battle Armor",1:"Serene Grace"},heightm:0.7,weightkg:15,color:"Brown",evos:["vibrava"],eggGroups:["Bug"]},
vibrava:{num:329,species:"Vibrava",types:["Ground","Dragon"],baseStats:{hp:50,atk:70,def:50,spa:50,spd:50,spe:70},abilities:{0:"Damp",1:"Light Metal"},heightm:1.1,weightkg:15.3,color:"Green",prevo:"trapinch",evos:["flygon"],evoLevel:35,eggGroups:["Bug"]},
flygon:{num:330,species:"Flygon",types:["Ground","Dragon"],baseStats:{hp:80,atk:100,def:80,spa:80,spd:80,spe:100},abilities:{0:"Color Change",1:"Solar Power"},heightm:2,weightkg:82,color:"Green",prevo:"vibrava",evoLevel:45,eggGroups:["Bug"]},
cacnea:{num:331,species:"Cacnea",types:["Grass"],baseStats:{hp:50,atk:85,def:40,spa:85,spd:40,spe:35},abilities:{0:"Analytic",1:"Cute Charm"},heightm:0.4,weightkg:51.3,color:"Green",evos:["cacturne"],eggGroups:["Plant","Humanshape"]},
cacturne:{num:332,species:"Cacturne",types:["Grass","Dark"],baseStats:{hp:70,atk:115,def:60,spa:115,spd:60,spe:55},abilities:{0:"Dry Skin",1:"Adaptability"},heightm:1.3,weightkg:77.4,color:"Green",prevo:"cacnea",evoLevel:32,eggGroups:["Plant","Humanshape"]},
swablu:{num:333,species:"Swablu",types:["Normal","Flying"],baseStats:{hp:45,atk:40,def:60,spa:40,spd:75,spe:50},abilities:{0:"Suction Cups",1:"Simple"},heightm:0.4,weightkg:1.2,color:"Blue",evos:["altaria"],eggGroups:["Flying","Dragon"]},
altaria:{num:334,species:"Altaria",types:["Dragon","Flying"],baseStats:{hp:75,atk:70,def:90,spa:70,spd:105,spe:80},abilities:{0:"Leaf Guard",1:"Color Change"},heightm:1.1,weightkg:20.6,color:"Blue",prevo:"swablu",evoLevel:35,eggGroups:["Flying","Dragon"]},
zangoose:{num:335,species:"Zangoose",types:["Normal"],baseStats:{hp:73,atk:115,def:60,spa:60,spd:60,spe:90},abilities:{0:"Infiltrator",1:"Shed Skin"},heightm:1.3,weightkg:40.3,color:"White",eggGroups:["Ground"]},
seviper:{num:336,species:"Seviper",types:["Poison"],baseStats:{hp:73,atk:100,def:60,spa:100,spd:60,spe:65},abilities:{0:"Serene Grace",1:"Sand Rush"},heightm:2.7,weightkg:52.5,color:"Black",eggGroups:["Ground","Dragon"]},
lunatone:{num:337,species:"Lunatone",types:["Rock","Psychic"],gender:"N",baseStats:{hp:70,atk:55,def:65,spa:95,spd:85,spe:70},abilities:{0:"Illusion",1:"Analytic"},heightm:1,weightkg:168,color:"Yellow",eggGroups:["Mineral"]},
solrock:{num:338,species:"Solrock",types:["Rock","Psychic"],gender:"N",baseStats:{hp:70,atk:95,def:85,spa:55,spd:65,spe:70},abilities:{0:"Pressure",1:"Moxie"},heightm:1.2,weightkg:154,color:"Red",eggGroups:["Mineral"]},
barboach:{num:339,species:"Barboach",types:["Water","Ground"],baseStats:{hp:50,atk:48,def:43,spa:46,spd:41,spe:60},abilities:{0:"Intimidate",1:"Rain Dish"},heightm:0.4,weightkg:1.9,color:"Gray",evos:["whiscash"],eggGroups:["Water 2"]},
whiscash:{num:340,species:"Whiscash",types:["Water","Ground"],baseStats:{hp:110,atk:78,def:73,spa:76,spd:71,spe:60},abilities:{0:"Damp",1:"Battle Armor"},heightm:0.9,weightkg:23.6,color:"Blue",prevo:"barboach",evoLevel:30,eggGroups:["Water 2"]},
corphish:{num:341,species:"Corphish",types:["Water"],baseStats:{hp:43,atk:80,def:65,spa:50,spd:35,spe:35},abilities:{0:"Anger Point",1:"Anticipation"},heightm:0.6,weightkg:11.5,color:"Red",evos:["crawdaunt"],eggGroups:["Water 1","Water 3"]},
crawdaunt:{num:342,species:"Crawdaunt",types:["Water","Dark"],baseStats:{hp:63,atk:120,def:85,spa:90,spd:55,spe:55},abilities:{0:"Speed Boost",1:"Oblivious"},heightm:1.1,weightkg:32.8,color:"Red",prevo:"corphish",evoLevel:30,eggGroups:["Water 1","Water 3"]},
baltoy:{num:343,species:"Baltoy",types:["Ground","Psychic"],gender:"N",baseStats:{hp:40,atk:40,def:55,spa:40,spd:70,spe:55},abilities:{0:"Clear Body",1:"Early Bird"},heightm:0.5,weightkg:21.5,color:"Brown",evos:["claydol"],eggGroups:["Mineral"]},
claydol:{num:344,species:"Claydol",types:["Ground","Psychic"],gender:"N",baseStats:{hp:60,atk:70,def:105,spa:70,spd:120,spe:75},abilities:{0:"Rattled",1:"Klutz"},heightm:1.5,weightkg:108,color:"Black",prevo:"baltoy",evoLevel:36,eggGroups:["Mineral"]},
lileep:{num:345,species:"Lileep",types:["Rock","Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:66,atk:41,def:77,spa:61,spd:87,spe:23},abilities:{0:"Skill Link",1:"Rain Dish"},heightm:1,weightkg:23.8,color:"Purple",evos:["cradily"],eggGroups:["Water 3"]},
cradily:{num:346,species:"Cradily",types:["Rock","Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:86,atk:81,def:97,spa:81,spd:107,spe:43},abilities:{0:"Analytic",1:"Serene Grace"},heightm:1.5,weightkg:60.4,color:"Green",prevo:"lileep",evoLevel:40,eggGroups:["Water 3"]},
anorith:{num:347,species:"Anorith",types:["Rock","Bug"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:95,def:50,spa:40,spd:50,spe:75},abilities:{0:"Suction Cups",1:"Reckless"},heightm:0.7,weightkg:12.5,color:"Gray",evos:["armaldo"],eggGroups:["Water 3"]},
armaldo:{num:348,species:"Armaldo",types:["Rock","Bug"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:125,def:100,spa:70,spd:80,spe:45},abilities:{0:"Magma Armor",1:"Stall"},heightm:1.5,weightkg:68.2,color:"Gray",prevo:"anorith",evoLevel:40,eggGroups:["Water 3"]},
feebas:{num:349,species:"Feebas",types:["Water"],baseStats:{hp:20,atk:15,def:20,spa:10,spd:55,spe:80},abilities:{0:"Clear Body",1:"Iron Barbs"},heightm:0.6,weightkg:7.4,color:"Brown",evos:["milotic"],eggGroups:["Water 1","Dragon"]},
milotic:{num:350,species:"Milotic",types:["Water"],baseStats:{hp:95,atk:60,def:79,spa:100,spd:125,spe:81},abilities:{0:"Big Pecks",1:"Snow Warning"},heightm:6.2,weightkg:162,color:"Pink",prevo:"feebas",evoLevel:1,eggGroups:["Water 1","Dragon"]},
castform:{num:351,species:"Castform",types:["Normal"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Wonder Guard",1:"Sap Sipper"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Indeterminate"],otherFormes:["castformsunny","castformrainy","castformsnowy"]},
kecleon:{num:352,species:"Kecleon",types:["Normal"],baseStats:{hp:60,atk:90,def:70,spa:60,spd:120,spe:40},abilities:{0:"Inner Focus",1:"Dry Skin"},heightm:1,weightkg:22,color:"Green",eggGroups:["Ground"]},
shuppet:{num:353,species:"Shuppet",types:["Ghost"],baseStats:{hp:44,atk:75,def:35,spa:63,spd:33,spe:45},abilities:{0:"Chlorophyll",1:"Defiant"},heightm:0.6,weightkg:2.3,color:"Black",evos:["banette"],eggGroups:["Indeterminate"]},
banette:{num:354,species:"Banette",types:["Ghost"],baseStats:{hp:64,atk:115,def:65,spa:83,spd:63,spe:65},abilities:{0:"Clear Body",1:"Volt Absorb"},heightm:1.1,weightkg:12.5,color:"Black",prevo:"shuppet",evoLevel:37,eggGroups:["Indeterminate"]},
duskull:{num:355,species:"Duskull",types:["Ghost"],baseStats:{hp:20,atk:40,def:90,spa:30,spd:90,spe:25},abilities:{0:"Natural Cure",1:"Swift Swim"},heightm:0.8,weightkg:15,color:"Black",evos:["dusclops"],eggGroups:["Indeterminate"]},
dusclops:{num:356,species:"Dusclops",types:["Ghost"],baseStats:{hp:40,atk:70,def:130,spa:60,spd:130,spe:25},abilities:{0:"Oblivious",1:"Wonder Skin"},heightm:1.6,weightkg:30.6,color:"Black",prevo:"duskull",evos:["dusknoir"],evoLevel:37,eggGroups:["Indeterminate"]},
tropius:{num:357,species:"Tropius",types:["Grass","Flying"],baseStats:{hp:99,atk:68,def:83,spa:72,spd:87,spe:51},abilities:{0:"Cursed Body",1:"Immunity"},heightm:2,weightkg:100,color:"Green",eggGroups:["Monster","Plant"]},
chimecho:{num:358,species:"Chimecho",types:["Psychic"],baseStats:{hp:65,atk:50,def:70,spa:95,spd:80,spe:65},abilities:{0:"Swift Swim",1:"Rock Head"},heightm:0.6,weightkg:1,color:"Blue",prevo:"chingling",evoLevel:1,eggGroups:["Indeterminate"]},
absol:{num:359,species:"Absol",types:["Dark"],baseStats:{hp:65,atk:130,def:60,spa:75,spd:60,spe:75},abilities:{0:"Volt Absorb",1:"Sticky Hold"},heightm:1.2,weightkg:47,color:"White",eggGroups:["Ground"]},
wynaut:{num:360,species:"Wynaut",types:["Psychic"],baseStats:{hp:95,atk:23,def:48,spa:23,spd:48,spe:23},abilities:{0:"Mold Breaker",1:"Mummy"},heightm:0.6,weightkg:14,color:"Blue",evos:["wobbuffet"],eggGroups:["No Eggs"]},
snorunt:{num:361,species:"Snorunt",types:["Ice"],baseStats:{hp:50,atk:50,def:50,spa:50,spd:50,spe:50},abilities:{0:"No Guard",1:"Insomnia"},heightm:0.7,weightkg:16.8,color:"Gray",evos:["glalie","froslass"],eggGroups:["Fairy","Mineral"]},
glalie:{num:362,species:"Glalie",types:["Ice"],baseStats:{hp:80,atk:80,def:80,spa:80,spd:80,spe:80},abilities:{0:"Overcoat",1:"Clear Body"},heightm:1.5,weightkg:256.5,color:"Gray",prevo:"snorunt",evoLevel:42,eggGroups:["Fairy","Mineral"]},
spheal:{num:363,species:"Spheal",types:["Ice","Water"],baseStats:{hp:70,atk:40,def:50,spa:55,spd:50,spe:25},abilities:{0:"Multiscale",1:"Static"},heightm:0.8,weightkg:39.5,color:"Blue",evos:["sealeo"],eggGroups:["Water 1","Ground"]},
sealeo:{num:364,species:"Sealeo",types:["Ice","Water"],baseStats:{hp:90,atk:60,def:70,spa:75,spd:70,spe:45},abilities:{0:"Pressure",1:"Drought"},heightm:1.1,weightkg:87.6,color:"Blue",prevo:"spheal",evos:["walrein"],evoLevel:32,eggGroups:["Water 1","Ground"]},
walrein:{num:365,species:"Walrein",types:["Ice","Water"],baseStats:{hp:110,atk:80,def:90,spa:95,spd:90,spe:65},abilities:{0:"Sap Sipper",1:"Mold Breaker"},heightm:1.4,weightkg:150.6,color:"Blue",prevo:"sealeo",evoLevel:44,eggGroups:["Water 1","Ground"]},
clamperl:{num:366,species:"Clamperl",types:["Water"],baseStats:{hp:35,atk:64,def:85,spa:74,spd:55,spe:32},abilities:{0:"Heavy Metal",1:"Sand Rush"},heightm:0.4,weightkg:52.5,color:"Blue",evos:["huntail","gorebyss"],eggGroups:["Water 1"]},
huntail:{num:367,species:"Huntail",types:["Water"],baseStats:{hp:55,atk:104,def:105,spa:94,spd:75,spe:52},abilities:{0:"Anger Point",1:"Marvel Scale"},heightm:1.7,weightkg:27,color:"Blue",prevo:"clamperl",evoLevel:1,eggGroups:["Water 1"]},
gorebyss:{num:368,species:"Gorebyss",types:["Water"],baseStats:{hp:55,atk:84,def:105,spa:114,spd:75,spe:52},abilities:{0:"Cloud Nine",1:"Rivalry"},heightm:1.8,weightkg:22.6,color:"Pink",prevo:"clamperl",evoLevel:1,eggGroups:["Water 1"]},
relicanth:{num:369,species:"Relicanth",types:["Water","Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:100,atk:90,def:130,spa:45,spd:65,spe:55},abilities:{0:"Flare Boost",1:"Anticipation"},heightm:1,weightkg:23.4,color:"Gray",eggGroups:["Water 1","Water 2"]},
luvdisc:{num:370,species:"Luvdisc",types:["Water"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:43,atk:30,def:55,spa:40,spd:65,spe:97},abilities:{0:"Unaware",1:"Adaptability"},heightm:0.6,weightkg:8.7,color:"Pink",eggGroups:["Water 2"]},
bagon:{num:371,species:"Bagon",types:["Dragon"],baseStats:{hp:45,atk:75,def:60,spa:40,spd:30,spe:50},abilities:{0:"Simple",1:"Blaze"},heightm:0.6,weightkg:42.1,color:"Blue",evos:["shelgon"],eggGroups:["Dragon"]},
shelgon:{num:372,species:"Shelgon",types:["Dragon"],baseStats:{hp:65,atk:95,def:100,spa:60,spd:50,spe:50},abilities:{0:"Pressure",1:"Magic Guard"},heightm:1.1,weightkg:110.5,color:"White",prevo:"bagon",evos:["salamence"],evoLevel:30,eggGroups:["Dragon"]},
salamence:{num:373,species:"Salamence",types:["Dragon","Flying"],baseStats:{hp:95,atk:135,def:80,spa:110,spd:80,spe:100},abilities:{0:"Forewarn",1:"Poison Point"},heightm:1.5,weightkg:102.6,color:"Blue",prevo:"shelgon",evoLevel:50,eggGroups:["Dragon"]},
beldum:{num:374,species:"Beldum",types:["Steel","Psychic"],gender:"N",baseStats:{hp:40,atk:55,def:80,spa:35,spd:60,spe:30},abilities:{0:"Snow Warning",1:"Justified"},heightm:0.6,weightkg:95.2,color:"Blue",evos:["metang"],eggGroups:["Mineral"]},
metang:{num:375,species:"Metang",types:["Steel","Psychic"],gender:"N",baseStats:{hp:60,atk:75,def:100,spa:55,spd:80,spe:50},abilities:{0:"Flare Boost",1:"Steadfast"},heightm:1.2,weightkg:202.5,color:"Blue",prevo:"beldum",evos:["metagross"],evoLevel:20,eggGroups:["Mineral"]},
metagross:{num:376,species:"Metagross",types:["Steel","Psychic"],gender:"N",baseStats:{hp:80,atk:135,def:130,spa:95,spd:90,spe:70},abilities:{0:"Tangled Feet",1:"Battle Armor"},heightm:1.6,weightkg:550,color:"Blue",prevo:"metang",evoLevel:45,eggGroups:["Mineral"]},
regirock:{num:377,species:"Regirock",types:["Rock"],gender:"N",baseStats:{hp:80,atk:100,def:200,spa:50,spd:100,spe:50},abilities:{0:"Water Absorb",1:"Dry Skin"},heightm:1.7,weightkg:230,color:"Brown",eggGroups:["No Eggs"]},
regice:{num:378,species:"Regice",types:["Ice"],gender:"N",baseStats:{hp:80,atk:50,def:100,spa:100,spd:200,spe:50},abilities:{0:"Poison Heal",1:"Drought"},heightm:1.8,weightkg:175,color:"Blue",eggGroups:["No Eggs"]},
registeel:{num:379,species:"Registeel",types:["Steel"],gender:"N",baseStats:{hp:80,atk:75,def:150,spa:75,spd:150,spe:50},abilities:{0:"Harvest",1:"Pickpocket"},heightm:1.9,weightkg:205,color:"Gray",eggGroups:["No Eggs"]},
latias:{num:380,species:"Latias",types:["Dragon","Psychic"],gender:"F",baseStats:{hp:80,atk:80,def:90,spa:110,spd:130,spe:110},abilities:{0:"Pickpocket",1:"Limber"},heightm:1.4,weightkg:40,color:"Red",eggGroups:["No Eggs"]},
latios:{num:381,species:"Latios",types:["Dragon","Psychic"],gender:"M",baseStats:{hp:80,atk:90,def:80,spa:130,spd:110,spe:110},abilities:{0:"Harvest",1:"Heavy Metal"},heightm:2,weightkg:60,color:"Blue",eggGroups:["No Eggs"]},
kyogre:{num:382,species:"Kyogre",types:["Water"],gender:"N",baseStats:{hp:100,atk:100,def:90,spa:150,spd:140,spe:90},abilities:{0:"Pickpocket",1:"Sand Veil"},heightm:4.5,weightkg:352,color:"Blue",eggGroups:["No Eggs"]},
groudon:{num:383,species:"Groudon",types:["Ground"],gender:"N",baseStats:{hp:100,atk:150,def:140,spa:100,spd:90,spe:90},abilities:{0:"Simple",1:"Rain Dish"},heightm:3.5,weightkg:950,color:"Red",eggGroups:["No Eggs"]},
rayquaza:{num:384,species:"Rayquaza",types:["Dragon","Flying"],gender:"N",baseStats:{hp:105,atk:150,def:90,spa:150,spd:90,spe:95},abilities:{0:"Rain Dish",1:"Dry Skin"},heightm:7,weightkg:206.5,color:"Green",eggGroups:["No Eggs"]},
jirachi:{num:385,species:"Jirachi",types:["Steel","Psychic"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Snow Cloak",1:"Solar Power"},heightm:0.3,weightkg:1.1,color:"Yellow",eggGroups:["No Eggs"]},
deoxys:{num:386,species:"Deoxys",baseForme:"Normal",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:150,def:50,spa:150,spd:50,spe:150},abilities:{0:"Early Bird",1:"Flare Boost"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["No Eggs"],otherFormes:["deoxysattack","deoxysdefense","deoxysspeed"]},
deoxysattack:{num:386,species:"Deoxys-Attack",baseSpecies:"Deoxys",forme:"Attack",formeLetter:"A",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:180,def:20,spa:180,spd:20,spe:150},abilities:{0:"Cloud Nine",1:"Unaware"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["No Eggs"]},
deoxysdefense:{num:386,species:"Deoxys-Defense",baseSpecies:"Deoxys",forme:"Defense",formeLetter:"D",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:70,def:160,spa:70,spd:160,spe:90},abilities:{0:"Sand Force",1:"Quick Feet"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["No Eggs"]},
deoxysspeed:{num:386,species:"Deoxys-Speed",baseSpecies:"Deoxys",forme:"Speed",formeLetter:"S",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:95,def:90,spa:95,spd:90,spe:180},abilities:{0:"Unburden",1:"Reckless"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["No Eggs"]},
turtwig:{num:387,species:"Turtwig",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:68,def:64,spa:45,spd:55,spe:31},abilities:{0:"Swift Swim",1:"Marvel Scale"},heightm:0.4,weightkg:10.2,color:"Green",evos:["grotle"],eggGroups:["Monster","Plant"]},
grotle:{num:388,species:"Grotle",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:89,def:85,spa:55,spd:65,spe:36},abilities:{0:"Pressure",1:"Stall"},heightm:1.1,weightkg:97,color:"Green",prevo:"turtwig",evos:["torterra"],evoLevel:18,eggGroups:["Monster","Plant"]},
torterra:{num:389,species:"Torterra",types:["Grass","Ground"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:109,def:105,spa:75,spd:85,spe:56},abilities:{0:"Pickpocket",1:"Sand Rush"},heightm:2.2,weightkg:310,color:"Green",prevo:"grotle",evoLevel:32,eggGroups:["Monster","Plant"]},
chimchar:{num:390,species:"Chimchar",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:44,atk:58,def:44,spa:58,spd:44,spe:61},abilities:{0:"Drought",1:"Solid Rock"},heightm:0.5,weightkg:6.2,color:"Brown",evos:["monferno"],eggGroups:["Ground","Humanshape"]},
monferno:{num:391,species:"Monferno",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:64,atk:78,def:52,spa:78,spd:52,spe:81},abilities:{0:"Stall",1:"Unnerve"},heightm:0.9,weightkg:22,color:"Brown",prevo:"chimchar",evos:["infernape"],evoLevel:14,eggGroups:["Ground","Humanshape"]},
infernape:{num:392,species:"Infernape",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:76,atk:104,def:71,spa:104,spd:71,spe:108},abilities:{0:"Super Luck",1:"Intimidate"},heightm:1.2,weightkg:55,color:"Brown",prevo:"monferno",evoLevel:36,eggGroups:["Ground","Humanshape"]},
piplup:{num:393,species:"Piplup",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:53,atk:51,def:53,spa:61,spd:56,spe:40},abilities:{0:"Quick Feet",1:"Heatproof"},heightm:0.4,weightkg:5.2,color:"Blue",evos:["prinplup"],eggGroups:["Water 1","Ground"]},
prinplup:{num:394,species:"Prinplup",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:64,atk:66,def:68,spa:81,spd:76,spe:50},abilities:{0:"Technician",1:"Overgrow"},heightm:0.8,weightkg:23,color:"Blue",prevo:"piplup",evos:["empoleon"],evoLevel:16,eggGroups:["Water 1","Ground"]},
empoleon:{num:395,species:"Empoleon",types:["Water","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:84,atk:86,def:88,spa:111,spd:101,spe:60},abilities:{0:"Rain Dish",1:"Skill Link"},heightm:1.7,weightkg:84.5,color:"Blue",prevo:"prinplup",evoLevel:36,eggGroups:["Water 1","Ground"]},
starly:{num:396,species:"Starly",types:["Normal","Flying"],baseStats:{hp:40,atk:55,def:30,spa:30,spd:30,spe:60},abilities:{0:"Liquid Ooze",1:"Defiant"},heightm:0.3,weightkg:2,color:"Brown",evos:["staravia"],eggGroups:["Flying"]},
staravia:{num:397,species:"Staravia",types:["Normal","Flying"],baseStats:{hp:55,atk:75,def:50,spa:40,spd:40,spe:80},abilities:{0:"Iron Barbs",1:"Multiscale"},heightm:0.6,weightkg:15.5,color:"Brown",prevo:"starly",evos:["staraptor"],evoLevel:14,eggGroups:["Flying"]},
staraptor:{num:398,species:"Staraptor",types:["Normal","Flying"],baseStats:{hp:85,atk:120,def:70,spa:50,spd:50,spe:100},abilities:{0:"Flare Boost",1:"Flash Fire"},heightm:1.2,weightkg:24.9,color:"Brown",prevo:"staravia",evoLevel:34,eggGroups:["Flying"]},
bidoof:{num:399,species:"Bidoof",types:["Normal"],baseStats:{hp:59,atk:45,def:40,spa:35,spd:40,spe:31},abilities:{0:"Pure Power",1:"Ice Body"},heightm:0.5,weightkg:20,color:"Brown",evos:["bibarel"],eggGroups:["Water 1","Ground"]},
bibarel:{num:400,species:"Bibarel",types:["Normal","Water"],baseStats:{hp:79,atk:85,def:60,spa:55,spd:60,spe:71},abilities:{0:"Super Luck",1:"Snow Warning"},heightm:1,weightkg:31.5,color:"Brown",prevo:"bidoof",evoLevel:15,eggGroups:["Water 1","Ground"]},
kricketot:{num:401,species:"Kricketot",types:["Bug"],baseStats:{hp:37,atk:25,def:41,spa:25,spd:41,spe:25},abilities:{0:"Sturdy",1:"Quick Feet"},heightm:0.3,weightkg:2.2,color:"Red",evos:["kricketune"],eggGroups:["Bug"]},
kricketune:{num:402,species:"Kricketune",types:["Bug"],baseStats:{hp:77,atk:85,def:51,spa:55,spd:51,spe:65},abilities:{0:"Steadfast",1:"Clear Body"},heightm:1,weightkg:25.5,color:"Red",prevo:"kricketot",evoLevel:10,eggGroups:["Bug"]},
shinx:{num:403,species:"Shinx",types:["Electric"],baseStats:{hp:45,atk:65,def:34,spa:40,spd:34,spe:45},abilities:{0:"Pickpocket",1:"Sheer Force"},heightm:0.5,weightkg:9.5,color:"Blue",evos:["luxio"],eggGroups:["Ground"]},
luxio:{num:404,species:"Luxio",types:["Electric"],baseStats:{hp:60,atk:85,def:49,spa:60,spd:49,spe:60},abilities:{0:"Motor Drive",1:"Solar Power"},heightm:0.9,weightkg:30.5,color:"Blue",prevo:"shinx",evos:["luxray"],evoLevel:15,eggGroups:["Ground"]},
luxray:{num:405,species:"Luxray",types:["Electric"],baseStats:{hp:80,atk:120,def:79,spa:95,spd:79,spe:70},abilities:{0:"Weak Armor",1:"Insomnia"},heightm:1.4,weightkg:42,color:"Blue",prevo:"luxio",evoLevel:30,eggGroups:["Ground"]},
budew:{num:406,species:"Budew",types:["Grass","Poison"],baseStats:{hp:40,atk:30,def:35,spa:50,spd:70,spe:55},abilities:{0:"Sheer Force",1:"Victory Star"},heightm:0.2,weightkg:1.2,color:"Green",evos:["roselia"],eggGroups:["No Eggs"]},
roserade:{num:407,species:"Roserade",types:["Grass","Poison"],baseStats:{hp:60,atk:70,def:55,spa:125,spd:105,spe:90},abilities:{0:"Victory Star",1:"Gluttony"},heightm:0.9,weightkg:14.5,color:"Green",prevo:"roselia",evoLevel:1,eggGroups:["Fairy","Plant"]},
cranidos:{num:408,species:"Cranidos",types:["Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:67,atk:125,def:40,spa:30,spd:30,spe:58},abilities:{0:"Quick Feet",1:"Color Change"},heightm:0.9,weightkg:31.5,color:"Blue",evos:["rampardos"],eggGroups:["Monster"]},
rampardos:{num:409,species:"Rampardos",types:["Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:97,atk:165,def:60,spa:65,spd:50,spe:58},abilities:{0:"Victory Star",1:"Sniper"},heightm:1.6,weightkg:102.5,color:"Blue",prevo:"cranidos",evoLevel:30,eggGroups:["Monster"]},
shieldon:{num:410,species:"Shieldon",types:["Rock","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:42,def:118,spa:42,spd:88,spe:30},abilities:{0:"Normalize",1:"Sap Sipper"},heightm:0.5,weightkg:57,color:"Gray",evos:["bastiodon"],eggGroups:["Monster"]},
bastiodon:{num:411,species:"Bastiodon",types:["Rock","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:52,def:168,spa:47,spd:138,spe:30},abilities:{0:"Battle Armor",1:"Damp"},heightm:1.3,weightkg:149.5,color:"Gray",prevo:"shieldon",evoLevel:30,eggGroups:["Monster"]},
burmy:{num:412,species:"Burmy",baseForme:"Plant",types:["Bug"],baseStats:{hp:40,atk:29,def:45,spa:29,spd:45,spe:36},abilities:{0:"Light Metal",1:"Inner Focus"},heightm:0.2,weightkg:3.4,color:"Gray",evos:["wormadam","wormadamsandy","wormadamtrash","mothim"],eggGroups:["Bug"],otherForms:["burmysandy","burmytrash"]},
wormadam:{num:413,species:"Wormadam",baseForme:"Plant",types:["Bug","Grass"],gender:"F",baseStats:{hp:60,atk:59,def:85,spa:79,spd:105,spe:36},abilities:{0:"Sand Veil",1:"Sniper"},heightm:0.5,weightkg:6.5,color:"Gray",prevo:"burmy",evoLevel:20,eggGroups:["Bug"],otherFormes:["wormadamsandy","wormadamtrash"]},
wormadamsandy:{num:413,species:"Wormadam-Sandy",baseSpecies:"Wormadam",forme:"Sandy",formeLetter:"G",types:["Bug","Ground"],gender:"F",baseStats:{hp:60,atk:79,def:105,spa:59,spd:85,spe:36},abilities:{0:"Hustle",1:"Sand Force"},heightm:0.5,weightkg:6.5,color:"Gray",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]},
wormadamtrash:{num:413,species:"Wormadam-Trash",baseSpecies:"Wormadam",forme:"Trash",formeLetter:"S",types:["Bug","Steel"],gender:"F",baseStats:{hp:60,atk:69,def:95,spa:69,spd:95,spe:36},abilities:{0:"Limber",1:"Motor Drive"},heightm:0.5,weightkg:6.5,color:"Gray",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]},
mothim:{num:414,species:"Mothim",types:["Bug","Flying"],gender:"M",baseStats:{hp:70,atk:94,def:50,spa:94,spd:50,spe:66},abilities:{0:"Defiant",1:"Unburden"},heightm:0.9,weightkg:23.3,color:"Yellow",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]},
combee:{num:415,species:"Combee",types:["Bug","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:30,def:42,spa:30,spd:42,spe:70},abilities:{0:"Lightningrod",1:"Normalize"},heightm:0.3,weightkg:5.5,color:"Yellow",evos:["vespiquen"],eggGroups:["Bug"]},
vespiquen:{num:416,species:"Vespiquen",types:["Bug","Flying"],gender:"F",baseStats:{hp:70,atk:80,def:102,spa:80,spd:102,spe:40},abilities:{0:"Simple",1:"Tangled Feet"},heightm:1.2,weightkg:38.5,color:"Yellow",prevo:"combee",evoLevel:21,eggGroups:["Bug"]},
pachirisu:{num:417,species:"Pachirisu",types:["Electric"],baseStats:{hp:60,atk:45,def:70,spa:45,spd:90,spe:95},abilities:{0:"Super Luck",1:"Heavy Metal"},heightm:0.4,weightkg:3.9,color:"White",eggGroups:["Ground","Fairy"]},
buizel:{num:418,species:"Buizel",types:["Water"],baseStats:{hp:55,atk:65,def:35,spa:60,spd:30,spe:85},abilities:{0:"Storm Drain",1:"Pressure"},heightm:0.7,weightkg:29.5,color:"Brown",evos:["floatzel"],eggGroups:["Water 1","Ground"]},
floatzel:{num:419,species:"Floatzel",types:["Water"],baseStats:{hp:85,atk:105,def:55,spa:85,spd:50,spe:115},abilities:{0:"Imposter",1:"Mold Breaker"},heightm:1.1,weightkg:33.5,color:"Brown",prevo:"buizel",evoLevel:26,eggGroups:["Water 1","Ground"]},
cherubi:{num:420,species:"Cherubi",types:["Grass"],baseStats:{hp:45,atk:35,def:45,spa:62,spd:53,spe:35},abilities:{0:"Flash Fire",1:"Guts"},heightm:0.4,weightkg:3.3,color:"Pink",evos:["cherrim"],eggGroups:["Fairy","Plant"]},
cherrim:{num:421,species:"Cherrim",baseForme:"Overcast",types:["Grass"],baseStats:{hp:70,atk:60,def:70,spa:87,spd:78,spe:85},abilities:{0:"Leaf Guard",1:"Battle Armor"},heightm:0.5,weightkg:9.3,color:"Pink",prevo:"cherubi",evoLevel:25,eggGroups:["Fairy","Plant"]},
shellos:{num:422,species:"Shellos",baseForme:"West",types:["Water"],baseStats:{hp:76,atk:48,def:48,spa:57,spd:62,spe:34},abilities:{0:"Own Tempo",1:"Swift Swim"},heightm:0.3,weightkg:6.3,color:"Purple",evos:["gastrodon"],eggGroups:["Water 1","Indeterminate"],otherForms:["shelloseast"]},
gastrodon:{num:423,species:"Gastrodon",baseForme:"West",types:["Water","Ground"],baseStats:{hp:111,atk:83,def:68,spa:92,spd:82,spe:39},abilities:{0:"Hustle",1:"Rivalry"},heightm:0.9,weightkg:29.9,color:"Purple",prevo:"shellos",evoLevel:30,eggGroups:["Water 1","Indeterminate"],otherForms:["gastrodoneast"]},
ambipom:{num:424,species:"Ambipom",types:["Normal"],baseStats:{hp:75,atk:100,def:66,spa:60,spd:66,spe:115},abilities:{0:"Unaware",1:"Drizzle"},heightm:1.2,weightkg:20.3,color:"Purple",prevo:"aipom",evoLevel:32,evoMove:"Double Hit",eggGroups:["Ground"]},
drifloon:{num:425,species:"Drifloon",types:["Ghost","Flying"],baseStats:{hp:90,atk:50,def:34,spa:60,spd:44,spe:70},abilities:{0:"Drought",1:"Adaptability"},heightm:0.4,weightkg:1.2,color:"Purple",evos:["drifblim"],eggGroups:["Indeterminate"]},
drifblim:{num:426,species:"Drifblim",types:["Ghost","Flying"],baseStats:{hp:150,atk:80,def:44,spa:90,spd:54,spe:80},abilities:{0:"Bad Dreams",1:"Cute Charm"},heightm:1.2,weightkg:15,color:"Purple",prevo:"drifloon",evoLevel:28,eggGroups:["Indeterminate"]},
buneary:{num:427,species:"Buneary",types:["Normal"],baseStats:{hp:55,atk:66,def:44,spa:44,spd:56,spe:85},abilities:{0:"Rattled",1:"Early Bird"},heightm:0.4,weightkg:5.5,color:"Brown",evos:["lopunny"],eggGroups:["Ground","Humanshape"]},
lopunny:{num:428,species:"Lopunny",types:["Normal"],baseStats:{hp:65,atk:76,def:84,spa:54,spd:96,spe:105},abilities:{0:"Snow Warning",1:"Justified"},heightm:1.2,weightkg:33.3,color:"Brown",prevo:"buneary",evoLevel:2,eggGroups:["Ground","Humanshape"]},
mismagius:{num:429,species:"Mismagius",types:["Ghost"],baseStats:{hp:60,atk:60,def:60,spa:105,spd:105,spe:105},abilities:{0:"Sticky Hold",1:"Defiant"},heightm:0.9,weightkg:4.4,color:"Purple",prevo:"misdreavus",evoLevel:1,eggGroups:["Indeterminate"]},
honchkrow:{num:430,species:"Honchkrow",types:["Dark","Flying"],baseStats:{hp:100,atk:125,def:52,spa:105,spd:52,spe:71},abilities:{0:"Poison Heal",1:"Harvest"},heightm:0.9,weightkg:27.3,color:"Black",prevo:"murkrow",evoLevel:1,eggGroups:["Flying"]},
glameow:{num:431,species:"Glameow",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:49,atk:55,def:42,spa:42,spd:37,spe:85},abilities:{0:"Toxic Boost",1:"Light Metal"},heightm:0.5,weightkg:3.9,color:"Gray",evos:["purugly"],eggGroups:["Ground"]},
purugly:{num:432,species:"Purugly",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:71,atk:82,def:64,spa:64,spd:59,spe:112},abilities:{0:"Shadow Tag",1:"Sturdy"},heightm:1,weightkg:43.8,color:"Gray",prevo:"glameow",evoLevel:38,eggGroups:["Ground"]},
chingling:{num:433,species:"Chingling",types:["Psychic"],baseStats:{hp:45,atk:30,def:50,spa:65,spd:50,spe:45},abilities:{0:"Magnet Pull",1:"Flare Boost"},heightm:0.2,weightkg:0.6,color:"Yellow",evos:["chimecho"],eggGroups:["No Eggs"]},
stunky:{num:434,species:"Stunky",types:["Poison","Dark"],baseStats:{hp:63,atk:63,def:47,spa:41,spd:41,spe:74},abilities:{0:"Super Luck",1:"Download"},heightm:0.4,weightkg:19.2,color:"Purple",evos:["skuntank"],eggGroups:["Ground"]},
skuntank:{num:435,species:"Skuntank",types:["Poison","Dark"],baseStats:{hp:103,atk:93,def:67,spa:71,spd:61,spe:84},abilities:{0:"Wonder Skin",1:"Leaf Guard"},heightm:1,weightkg:38,color:"Purple",prevo:"stunky",evoLevel:34,eggGroups:["Ground"]},
bronzor:{num:436,species:"Bronzor",types:["Steel","Psychic"],gender:"N",baseStats:{hp:57,atk:24,def:86,spa:24,spd:86,spe:23},abilities:{0:"Mummy",1:"Hustle"},heightm:0.5,weightkg:60.5,color:"Green",evos:["bronzong"],eggGroups:["Mineral"]},
bronzong:{num:437,species:"Bronzong",types:["Steel","Psychic"],gender:"N",baseStats:{hp:67,atk:89,def:116,spa:79,spd:116,spe:33},abilities:{0:"Defiant",1:"No Guard"},heightm:1.3,weightkg:187,color:"Green",prevo:"bronzor",evoLevel:33,eggGroups:["Mineral"]},
bonsly:{num:438,species:"Bonsly",types:["Rock"],baseStats:{hp:50,atk:80,def:95,spa:10,spd:45,spe:10},abilities:{0:"Tangled Feet",1:"Soundproof"},heightm:0.5,weightkg:15,color:"Brown",evos:["sudowoodo"],eggGroups:["No Eggs"]},
mimejr:{num:439,species:"Mime Jr.",types:["Psychic"],baseStats:{hp:20,atk:25,def:45,spa:70,spd:90,spe:60},abilities:{0:"Flame Body",1:"Victory Star"},heightm:0.6,weightkg:13,color:"Pink",evos:["mrmime"],eggGroups:["No Eggs"]},
happiny:{num:440,species:"Happiny",types:["Normal"],gender:"F",baseStats:{hp:100,atk:5,def:5,spa:15,spd:65,spe:30},abilities:{0:"Stench",1:"Unnerve"},heightm:0.6,weightkg:24.4,color:"Pink",evos:["chansey"],eggGroups:["No Eggs"]},
chatot:{num:441,species:"Chatot",types:["Normal","Flying"],baseStats:{hp:76,atk:65,def:45,spa:92,spd:42,spe:91},abilities:{0:"Wonder Skin",1:"Sap Sipper"},heightm:0.5,weightkg:1.9,color:"Black",eggGroups:["Flying"]},
spiritomb:{num:442,species:"Spiritomb",types:["Ghost","Dark"],baseStats:{hp:50,atk:92,def:108,spa:92,spd:108,spe:35},abilities:{0:"Effect Spore",1:"Cute Charm"},heightm:1,weightkg:108,color:"Purple",eggGroups:["Indeterminate"]},
gible:{num:443,species:"Gible",types:["Dragon","Ground"],baseStats:{hp:58,atk:70,def:45,spa:40,spd:45,spe:42},abilities:{0:"Drizzle",1:"Magma Armor"},heightm:0.7,weightkg:20.5,color:"Blue",evos:["gabite"],eggGroups:["Monster","Dragon"]},
gabite:{num:444,species:"Gabite",types:["Dragon","Ground"],baseStats:{hp:68,atk:90,def:65,spa:50,spd:55,spe:82},abilities:{0:"Wonder Guard",1:"Bad Dreams"},heightm:1.4,weightkg:56,color:"Blue",prevo:"gible",evos:["garchomp"],evoLevel:24,eggGroups:["Monster","Dragon"]},
garchomp:{num:445,species:"Garchomp",types:["Dragon","Ground"],baseStats:{hp:108,atk:130,def:95,spa:80,spd:85,spe:102},abilities:{0:"Sticky Hold",1:"Normalize"},heightm:1.9,weightkg:95,color:"Blue",prevo:"gabite",evoLevel:48,eggGroups:["Monster","Dragon"]},
munchlax:{num:446,species:"Munchlax",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:135,atk:85,def:40,spa:40,spd:85,spe:5},abilities:{0:"Marvel Scale",1:"Drought"},heightm:0.6,weightkg:105,color:"Black",evos:["snorlax"],eggGroups:["No Eggs"]},
riolu:{num:447,species:"Riolu",types:["Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:70,def:40,spa:35,spd:40,spe:60},abilities:{0:"Analytic",1:"Tangled Feet"},heightm:0.7,weightkg:20.2,color:"Blue",evos:["lucario"],eggGroups:["No Eggs"]},
lucario:{num:448,species:"Lucario",types:["Fighting","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:110,def:70,spa:115,spd:70,spe:90},abilities:{0:"Magnet Pull",1:"Poison Touch"},heightm:1.2,weightkg:54,color:"Blue",prevo:"riolu",evoLevel:2,eggGroups:["Ground","Humanshape"]},
hippopotas:{num:449,species:"Hippopotas",types:["Ground"],baseStats:{hp:68,atk:72,def:78,spa:38,spd:42,spe:32},abilities:{0:"Klutz",1:"Clear Body"},heightm:0.8,weightkg:49.5,color:"Brown",evos:["hippowdon"],eggGroups:["Ground"]},
hippowdon:{num:450,species:"Hippowdon",types:["Ground"],baseStats:{hp:108,atk:112,def:118,spa:68,spd:72,spe:47},abilities:{0:"Swift Swim",1:"Gluttony"},heightm:2,weightkg:300,color:"Brown",prevo:"hippopotas",evoLevel:34,eggGroups:["Ground"]},
skorupi:{num:451,species:"Skorupi",types:["Poison","Bug"],baseStats:{hp:40,atk:50,def:90,spa:30,spd:55,spe:65},abilities:{0:"Cursed Body",1:"Pickpocket"},heightm:0.8,weightkg:12,color:"Purple",evos:["drapion"],eggGroups:["Bug","Water 3"]},
drapion:{num:452,species:"Drapion",types:["Poison","Dark"],baseStats:{hp:70,atk:90,def:110,spa:60,spd:75,spe:95},abilities:{0:"Sheer Force",1:"Suction Cups"},heightm:1.3,weightkg:61.5,color:"Purple",prevo:"skorupi",evoLevel:40,eggGroups:["Bug","Water 3"]},
croagunk:{num:453,species:"Croagunk",types:["Poison","Fighting"],baseStats:{hp:48,atk:61,def:40,spa:61,spd:40,spe:50},abilities:{0:"Oblivious",1:"Sap Sipper"},heightm:0.7,weightkg:23,color:"Blue",evos:["toxicroak"],eggGroups:["Humanshape"]},
toxicroak:{num:454,species:"Toxicroak",types:["Poison","Fighting"],baseStats:{hp:83,atk:106,def:65,spa:86,spd:65,spe:85},abilities:{0:"Iron Fist",1:"Anger Point"},heightm:1.3,weightkg:44.4,color:"Blue",prevo:"croagunk",evoLevel:37,eggGroups:["Humanshape"]},
carnivine:{num:455,species:"Carnivine",types:["Grass"],baseStats:{hp:74,atk:100,def:72,spa:90,spd:72,spe:46},abilities:{0:"Bad Dreams",1:"Defiant"},heightm:1.4,weightkg:27,color:"Green",eggGroups:["Plant"]},
finneon:{num:456,species:"Finneon",types:["Water"],baseStats:{hp:49,atk:49,def:56,spa:49,spd:61,spe:66},abilities:{0:"Leaf Guard",1:"Mummy"},heightm:0.4,weightkg:7,color:"Blue",evos:["lumineon"],eggGroups:["Water 2"]},
lumineon:{num:457,species:"Lumineon",types:["Water"],baseStats:{hp:69,atk:69,def:76,spa:69,spd:86,spe:91},abilities:{0:"Pickpocket",1:"Big Pecks"},heightm:1.2,weightkg:24,color:"Blue",prevo:"finneon",evoLevel:31,eggGroups:["Water 2"]},
mantyke:{num:458,species:"Mantyke",types:["Water","Flying"],baseStats:{hp:45,atk:20,def:50,spa:60,spd:120,spe:50},abilities:{0:"Arena Trap",1:"Battle Armor"},heightm:1,weightkg:65,color:"Blue",evos:["mantine"],eggGroups:["No Eggs"]},
snover:{num:459,species:"Snover",types:["Grass","Ice"],baseStats:{hp:60,atk:62,def:50,spa:62,spd:60,spe:40},abilities:{0:"Storm Drain",1:"Inner Focus"},heightm:1,weightkg:50.5,color:"White",evos:["abomasnow"],eggGroups:["Monster","Plant"]},
abomasnow:{num:460,species:"Abomasnow",types:["Grass","Ice"],baseStats:{hp:90,atk:92,def:75,spa:92,spd:85,spe:60},abilities:{0:"Clear Body",1:"Own Tempo"},heightm:2.2,weightkg:135.5,color:"White",prevo:"snover",evoLevel:40,eggGroups:["Monster","Plant"]},
weavile:{num:461,species:"Weavile",types:["Dark","Ice"],baseStats:{hp:70,atk:120,def:65,spa:45,spd:85,spe:125},abilities:{0:"Solid Rock",1:"Chlorophyll"},heightm:1.1,weightkg:34,color:"Black",prevo:"sneasel",evoLevel:2,eggGroups:["Ground"]},
magnezone:{num:462,species:"Magnezone",types:["Electric","Steel"],gender:"N",baseStats:{hp:70,atk:70,def:115,spa:130,spd:90,spe:60},abilities:{0:"Reckless",1:"Swift Swim"},heightm:1.2,weightkg:180,color:"Gray",prevo:"magneton",evoLevel:31,eggGroups:["Mineral"]},
lickilicky:{num:463,species:"Lickilicky",types:["Normal"],baseStats:{hp:110,atk:85,def:95,spa:80,spd:95,spe:50},abilities:{0:"Download",1:"Arena Trap"},heightm:1.7,weightkg:140,color:"Pink",prevo:"lickitung",evoLevel:2,evoMove:"Rollout",eggGroups:["Monster"]},
rhyperior:{num:464,species:"Rhyperior",types:["Ground","Rock"],baseStats:{hp:115,atk:140,def:130,spa:55,spd:55,spe:40},abilities:{0:"Scrappy",1:"Mummy"},heightm:2.4,weightkg:282.8,color:"Gray",prevo:"rhydon",evoLevel:42,eggGroups:["Monster","Ground"]},
tangrowth:{num:465,species:"Tangrowth",types:["Grass"],baseStats:{hp:100,atk:100,def:125,spa:110,spd:50,spe:50},abilities:{0:"Defiant",1:"Simple"},heightm:2,weightkg:128.6,color:"Blue",prevo:"tangela",evoLevel:2,evoMove:"AncientPower",eggGroups:["Plant"]},
electivire:{num:466,species:"Electivire",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:123,def:67,spa:95,spd:85,spe:95},abilities:{0:"Adaptability",1:"Toxic Boost"},heightm:1.8,weightkg:138.6,color:"Yellow",prevo:"electabuzz",evoLevel:30,eggGroups:["Humanshape"]},
magmortar:{num:467,species:"Magmortar",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:95,def:67,spa:125,spd:95,spe:83},abilities:{0:"Immunity",1:"Cloud Nine"},heightm:1.6,weightkg:68,color:"Red",prevo:"magmar",evoLevel:30,eggGroups:["Humanshape"]},
togekiss:{num:468,species:"Togekiss",types:["Normal","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:85,atk:50,def:95,spa:120,spd:115,spe:80},abilities:{0:"Intimidate",1:"Pickpocket"},heightm:1.5,weightkg:38,color:"White",prevo:"togetic",evoLevel:2,eggGroups:["Flying","Fairy"]},
yanmega:{num:469,species:"Yanmega",types:["Bug","Flying"],baseStats:{hp:86,atk:76,def:86,spa:116,spd:56,spe:95},abilities:{0:"Prankster",1:"Clear Body"},heightm:1.9,weightkg:51.5,color:"Green",prevo:"yanma",evoLevel:2,evoMove:"AncientPower",eggGroups:["Bug"]},
leafeon:{num:470,species:"Leafeon",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:110,def:130,spa:60,spd:65,spe:95},abilities:{0:"Water Absorb",1:"Cursed Body"},heightm:1,weightkg:25.5,color:"Green",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
glaceon:{num:471,species:"Glaceon",types:["Ice"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:60,def:110,spa:130,spd:95,spe:65},abilities:{0:"Color Change",1:"Trace"},heightm:0.8,weightkg:25.9,color:"Blue",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
gliscor:{num:472,species:"Gliscor",types:["Ground","Flying"],baseStats:{hp:75,atk:95,def:125,spa:45,spd:75,spe:95},abilities:{0:"Drought",1:"Clear Body"},heightm:2,weightkg:42.5,color:"Purple",prevo:"gligar",evoLevel:2,eggGroups:["Bug"]},
mamoswine:{num:473,species:"Mamoswine",types:["Ice","Ground"],baseStats:{hp:110,atk:130,def:80,spa:70,spd:60,spe:80},abilities:{0:"Liquid Ooze",1:"Tangled Feet"},heightm:2.5,weightkg:291,color:"Brown",prevo:"piloswine",evoLevel:34,evoMove:"AncientPower",eggGroups:["Ground"]},
porygonz:{num:474,species:"Porygon-Z",types:["Normal"],gender:"N",baseStats:{hp:85,atk:80,def:70,spa:135,spd:75,spe:90},abilities:{0:"Soundproof",1:"Compoundeyes"},heightm:0.9,weightkg:34,color:"Red",prevo:"porygon2",evoLevel:1,eggGroups:["Mineral"]},
gallade:{num:475,species:"Gallade",types:["Psychic","Fighting"],gender:"M",baseStats:{hp:68,atk:125,def:65,spa:65,spd:115,spe:80},abilities:{0:"Ice Body",1:"Chlorophyll"},heightm:1.6,weightkg:52,color:"White",prevo:"kirlia",evoLevel:20,eggGroups:["Indeterminate"]},
probopass:{num:476,species:"Probopass",types:["Rock","Steel"],baseStats:{hp:60,atk:55,def:145,spa:75,spd:150,spe:40},abilities:{0:"No Guard",1:"Heatproof"},heightm:1.4,weightkg:340,color:"Gray",prevo:"nosepass",evoLevel:2,eggGroups:["Mineral"]},
dusknoir:{num:477,species:"Dusknoir",types:["Ghost"],baseStats:{hp:45,atk:100,def:135,spa:65,spd:135,spe:45},abilities:{0:"Natural Cure",1:"Sand Force"},heightm:2.2,weightkg:106.6,color:"Black",prevo:"dusclops",evoLevel:37,eggGroups:["Indeterminate"]},
froslass:{num:478,species:"Froslass",types:["Ice","Ghost"],gender:"F",baseStats:{hp:70,atk:80,def:70,spa:80,spd:70,spe:110},abilities:{0:"Overcoat",1:"Heatproof"},heightm:1.3,weightkg:26.6,color:"White",prevo:"snorunt",evoLevel:1,eggGroups:["Fairy","Mineral"]},
rotom:{num:479,species:"Rotom",types:["Electric","Ghost"],gender:"N",baseStats:{hp:50,atk:50,def:77,spa:95,spd:77,spe:91},abilities:{0:"Steadfast",1:"Gluttony"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"],otherFormes:["rotomheat","rotomwash","rotomfrost","rotomfan","rotommow"]},
rotomheat:{num:479,species:"Rotom-Heat",baseSpecies:"Rotom",forme:"Heat",formeLetter:"H",types:["Electric","Fire"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Rain Dish",1:"Clear Body"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
rotomwash:{num:479,species:"Rotom-Wash",baseSpecies:"Rotom",forme:"Wash",formeLetter:"W",types:["Electric","Water"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Torrent",1:"Overcoat"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
rotomfrost:{num:479,species:"Rotom-Frost",baseSpecies:"Rotom",forme:"Frost",formeLetter:"F",types:["Electric","Ice"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Pressure",1:"Cloud Nine"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
rotomfan:{num:479,species:"Rotom-Fan",baseSpecies:"Rotom",forme:"Fan",formeLetter:"S",types:["Electric","Flying"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Sticky Hold",1:"Klutz"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
rotommow:{num:479,species:"Rotom-Mow",baseSpecies:"Rotom",forme:"Mow",formeLetter:"C",types:["Electric","Grass"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Oblivious",1:"Synchronize"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
uxie:{num:480,species:"Uxie",types:["Psychic"],gender:"N",baseStats:{hp:75,atk:75,def:130,spa:75,spd:130,spe:95},abilities:{0:"Limber",1:"Heatproof"},heightm:0.3,weightkg:0.3,color:"Yellow",eggGroups:["No Eggs"]},
mesprit:{num:481,species:"Mesprit",types:["Psychic"],gender:"N",baseStats:{hp:80,atk:105,def:105,spa:105,spd:105,spe:80},abilities:{0:"Clear Body",1:"Shadow Tag"},heightm:0.3,weightkg:0.3,color:"Pink",eggGroups:["No Eggs"]},
azelf:{num:482,species:"Azelf",types:["Psychic"],gender:"N",baseStats:{hp:75,atk:125,def:70,spa:125,spd:70,spe:115},abilities:{0:"Dry Skin",1:"Defiant"},heightm:0.3,weightkg:0.3,color:"Blue",eggGroups:["No Eggs"]},
dialga:{num:483,species:"Dialga",types:["Steel","Dragon"],gender:"N",baseStats:{hp:100,atk:120,def:120,spa:150,spd:100,spe:90},abilities:{0:"Rain Dish",1:"Pickpocket"},heightm:5.4,weightkg:683,color:"White",eggGroups:["No Eggs"]},
palkia:{num:484,species:"Palkia",types:["Water","Dragon"],gender:"N",baseStats:{hp:90,atk:120,def:100,spa:150,spd:120,spe:100},abilities:{0:"No Guard",1:"Contrary"},heightm:4.2,weightkg:336,color:"Purple",eggGroups:["No Eggs"]},
heatran:{num:485,species:"Heatran",types:["Fire","Steel"],baseStats:{hp:91,atk:90,def:106,spa:130,spd:106,spe:77},abilities:{0:"Technician",1:"Keen Eye"},heightm:1.7,weightkg:430,color:"Brown",eggGroups:["No Eggs"]},
regigigas:{num:486,species:"Regigigas",types:["Normal"],gender:"N",baseStats:{hp:110,atk:160,def:110,spa:80,spd:110,spe:100},abilities:{0:"Wonder Skin",1:"Contrary"},heightm:3.7,weightkg:420,color:"White",eggGroups:["No Eggs"]},
giratina:{num:487,species:"Giratina",baseForme:"Altered",types:["Ghost","Dragon"],gender:"N",baseStats:{hp:150,atk:100,def:120,spa:100,spd:120,spe:90},abilities:{0:"Rattled",1:"Motor Drive"},heightm:4.5,weightkg:750,color:"Black",eggGroups:["No Eggs"],otherFormes:["giratinaorigin"]},
giratinaorigin:{num:487,species:"Giratina-Origin",baseSpecies:"Giratina",forme:"Origin",formeLetter:"O",types:["Ghost","Dragon"],gender:"N",baseStats:{hp:150,atk:120,def:100,spa:120,spd:100,spe:90},abilities:{0:"Quick Feet",1:"Frisk"},heightm:6.9,weightkg:650,color:"Black",eggGroups:["No Eggs"]},
cresselia:{num:488,species:"Cresselia",types:["Psychic"],gender:"F",baseStats:{hp:120,atk:70,def:120,spa:75,spd:130,spe:85},abilities:{0:"Toxic Boost",1:"Scrappy"},heightm:1.5,weightkg:85.6,color:"Yellow",eggGroups:["No Eggs"]},
phione:{num:489,species:"Phione",types:["Water"],gender:"N",baseStats:{hp:80,atk:80,def:80,spa:80,spd:80,spe:80},abilities:{0:"Unburden",1:"Moxie"},heightm:0.4,weightkg:3.1,color:"Blue",eggGroups:["Water 1","Fairy"]},
manaphy:{num:490,species:"Manaphy",types:["Water"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Gluttony",1:"Synchronize"},heightm:0.3,weightkg:1.4,color:"Blue",eggGroups:["Water 1","Fairy"]},
darkrai:{num:491,species:"Darkrai",types:["Dark"],gender:"N",baseStats:{hp:70,atk:90,def:90,spa:135,spd:90,spe:125},abilities:{0:"Rattled",1:"Thick Fat"},heightm:1.5,weightkg:50.5,color:"Black",eggGroups:["No Eggs"]},
shaymin:{num:492,species:"Shaymin",baseForme:"Land",types:["Grass"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Magic Guard",1:"Compoundeyes"},heightm:0.2,weightkg:2.1,color:"Green",eggGroups:["No Eggs"],otherFormes:["shayminsky"]},
shayminsky:{num:492,species:"Shaymin-Sky",baseSpecies:"Shaymin",forme:"Sky",formeLetter:"S",types:["Grass","Flying"],gender:"N",baseStats:{hp:100,atk:103,def:75,spa:120,spd:75,spe:127},abilities:{0:"Quick Feet",1:"Rattled"},heightm:0.4,weightkg:5.2,color:"Green",eggGroups:["No Eggs"]},
arceus:{num:493,species:"Arceus",baseForme:"Normal",types:["Normal"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Tangled Feet",1:"Hyper Cutter"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["No Eggs"]},
victini:{num:494,species:"Victini",types:["Psychic","Fire"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Compoundeyes",1:"Aftermath"},heightm:0.4,weightkg:4,color:"Yellow",eggGroups:["No Eggs"]},
snivy:{num:495,species:"Snivy",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:45,def:55,spa:45,spd:55,spe:63},abilities:{0:"Gluttony",1:"Storm Drain"},heightm:0.6,weightkg:8.1,color:"Green",evos:["servine"],eggGroups:["Ground","Plant"]},
servine:{num:496,species:"Servine",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:60,def:75,spa:60,spd:75,spe:83},abilities:{0:"Sap Sipper",1:"Solar Power"},heightm:0.8,weightkg:16,color:"Green",prevo:"snivy",evos:["serperior"],evoLevel:17,eggGroups:["Ground","Plant"]},
serperior:{num:497,species:"Serperior",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:75,def:95,spa:75,spd:95,spe:113},abilities:{0:"Anger Point",1:"Forewarn"},heightm:3.3,weightkg:63,color:"Green",prevo:"servine",evoLevel:36,eggGroups:["Ground","Plant"]},
tepig:{num:498,species:"Tepig",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:63,def:45,spa:45,spd:45,spe:45},abilities:{0:"Damp",1:"Tinted Lens"},heightm:0.5,weightkg:9.9,color:"Red",evos:["pignite"],eggGroups:["Ground"]},
pignite:{num:499,species:"Pignite",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:90,atk:93,def:55,spa:70,spd:55,spe:55},abilities:{0:"Natural Cure",1:"Rattled"},heightm:1,weightkg:55.5,color:"Red",prevo:"tepig",evos:["emboar"],evoLevel:17,eggGroups:["Ground"]},
emboar:{num:500,species:"Emboar",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:110,atk:123,def:65,spa:100,spd:65,spe:65},abilities:{0:"Poison Heal",1:"Magnet Pull"},heightm:1.6,weightkg:150,color:"Red",prevo:"pignite",evoLevel:36,eggGroups:["Ground"]},
oshawott:{num:501,species:"Oshawott",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:55,def:45,spa:63,spd:45,spe:45},abilities:{0:"Marvel Scale",1:"Lightningrod"},heightm:0.5,weightkg:5.9,color:"Blue",evos:["dewott"],eggGroups:["Ground"]},
dewott:{num:502,species:"Dewott",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:75,def:60,spa:83,spd:60,spe:60},abilities:{0:"Storm Drain",1:"Aftermath"},heightm:0.8,weightkg:24.5,color:"Blue",prevo:"oshawott",evos:["samurott"],evoLevel:17,eggGroups:["Ground"]},
samurott:{num:503,species:"Samurott",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:100,def:85,spa:108,spd:70,spe:70},abilities:{0:"Weak Armor",1:"Klutz"},heightm:1.5,weightkg:94.6,color:"Blue",prevo:"dewott",evoLevel:36,eggGroups:["Ground"]},
patrat:{num:504,species:"Patrat",types:["Normal"],baseStats:{hp:45,atk:55,def:39,spa:35,spd:39,spe:42},abilities:{0:"Mummy",1:"Synchronize"},heightm:0.5,weightkg:11.6,color:"Brown",evos:["watchog"],eggGroups:["Ground"]},
watchog:{num:505,species:"Watchog",types:["Normal"],baseStats:{hp:60,atk:85,def:69,spa:60,spd:69,spe:77},abilities:{0:"Cloud Nine",1:"Swarm"},heightm:1.1,weightkg:27,color:"Brown",prevo:"patrat",evoLevel:20,eggGroups:["Ground"]},
lillipup:{num:506,species:"Lillipup",types:["Normal"],baseStats:{hp:45,atk:60,def:45,spa:25,spd:45,spe:55},abilities:{0:"Storm Drain",1:"Magic Bounce"},heightm:0.4,weightkg:4.1,color:"Brown",evos:["herdier"],eggGroups:["Ground"]},
herdier:{num:507,species:"Herdier",types:["Normal"],baseStats:{hp:65,atk:80,def:65,spa:35,spd:65,spe:60},abilities:{0:"Big Pecks",1:"Reckless"},heightm:0.9,weightkg:14.7,color:"Gray",prevo:"lillipup",evos:["stoutland"],evoLevel:16,eggGroups:["Ground"]},
stoutland:{num:508,species:"Stoutland",types:["Normal"],baseStats:{hp:85,atk:100,def:90,spa:45,spd:90,spe:80},abilities:{0:"Poison Touch",1:"Forewarn"},heightm:1.2,weightkg:61,color:"Gray",prevo:"herdier",evoLevel:32,eggGroups:["Ground"]},
purrloin:{num:509,species:"Purrloin",types:["Dark"],baseStats:{hp:41,atk:50,def:37,spa:50,spd:37,spe:66},abilities:{0:"Imposter",1:"Rain Dish"},heightm:0.4,weightkg:10.1,color:"Purple",evos:["liepard"],eggGroups:["Ground"]},
liepard:{num:510,species:"Liepard",types:["Dark"],baseStats:{hp:64,atk:88,def:50,spa:88,spd:50,spe:106},abilities:{0:"Ice Body",1:"Tangled Feet"},heightm:1.1,weightkg:37.5,color:"Purple",prevo:"purrloin",evoLevel:20,eggGroups:["Ground"]},
pansage:{num:511,species:"Pansage",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Steadfast",1:"Own Tempo"},heightm:0.6,weightkg:10.5,color:"Green",evos:["simisage"],eggGroups:["Ground"]},
simisage:{num:512,species:"Simisage",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Static",1:"Own Tempo"},heightm:1.1,weightkg:30.5,color:"Green",prevo:"pansage",evoLevel:1,eggGroups:["Ground"]},
pansear:{num:513,species:"Pansear",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Technician",1:"Drizzle"},heightm:0.6,weightkg:11,color:"Red",evos:["simisear"],eggGroups:["Ground"]},
simisear:{num:514,species:"Simisear",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Tinted Lens",1:"Sniper"},heightm:1,weightkg:28,color:"Red",prevo:"pansear",evoLevel:1,eggGroups:["Ground"]},
panpour:{num:515,species:"Panpour",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Swift Swim",1:"Poison Touch"},heightm:0.6,weightkg:13.5,color:"Blue",evos:["simipour"],eggGroups:["Ground"]},
simipour:{num:516,species:"Simipour",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Analytic",1:"Storm Drain"},heightm:1,weightkg:29,color:"Blue",prevo:"panpour",evoLevel:1,eggGroups:["Ground"]},
munna:{num:517,species:"Munna",types:["Psychic"],baseStats:{hp:76,atk:25,def:45,spa:67,spd:55,spe:24},abilities:{0:"Pure Power",1:"Volt Absorb"},heightm:0.6,weightkg:23.3,color:"Pink",evos:["musharna"],eggGroups:["Ground"]},
musharna:{num:518,species:"Musharna",types:["Psychic"],baseStats:{hp:116,atk:55,def:85,spa:107,spd:95,spe:29},abilities:{0:"Water Absorb",1:"Solar Power"},heightm:1.1,weightkg:60.5,color:"Pink",prevo:"munna",evoLevel:1,eggGroups:["Ground"]},
pidove:{num:519,species:"Pidove",types:["Normal","Flying"],baseStats:{hp:50,atk:55,def:50,spa:36,spd:30,spe:43},abilities:{0:"Solid Rock",1:"Clear Body"},heightm:0.3,weightkg:2.1,color:"Gray",evos:["tranquill"],eggGroups:["Flying"]},
tranquill:{num:520,species:"Tranquill",types:["Normal","Flying"],baseStats:{hp:62,atk:77,def:62,spa:50,spd:42,spe:65},abilities:{0:"Flame Body",1:"Hustle"},heightm:0.6,weightkg:15,color:"Gray",prevo:"pidove",evos:["unfezant"],evoLevel:21,eggGroups:["Flying"]},
unfezant:{num:521,species:"Unfezant",types:["Normal","Flying"],baseStats:{hp:80,atk:105,def:80,spa:65,spd:55,spe:93},abilities:{0:"Moxie",1:"Sand Veil"},heightm:1.2,weightkg:29,color:"Gray",prevo:"tranquill",evoLevel:32,eggGroups:["Flying"]},
blitzle:{num:522,species:"Blitzle",types:["Electric"],baseStats:{hp:45,atk:60,def:32,spa:50,spd:32,spe:76},abilities:{0:"Cursed Body",1:"Speed Boost"},heightm:0.8,weightkg:29.8,color:"Black",evos:["zebstrika"],eggGroups:["Ground"]},
zebstrika:{num:523,species:"Zebstrika",types:["Electric"],baseStats:{hp:75,atk:100,def:63,spa:80,spd:63,spe:116},abilities:{0:"Contrary",1:"Adaptability"},heightm:1.6,weightkg:79.5,color:"Black",prevo:"blitzle",evoLevel:27,eggGroups:["Ground"]},
roggenrola:{num:524,species:"Roggenrola",types:["Rock"],baseStats:{hp:55,atk:75,def:85,spa:25,spd:25,spe:15},abilities:{0:"Chlorophyll",1:"Natural Cure"},heightm:0.4,weightkg:18,color:"Blue",evos:["boldore"],eggGroups:["Mineral"]},
boldore:{num:525,species:"Boldore",types:["Rock"],baseStats:{hp:70,atk:105,def:105,spa:50,spd:40,spe:20},abilities:{0:"Keen Eye",1:"Flare Boost"},heightm:0.9,weightkg:102,color:"Blue",prevo:"roggenrola",evos:["gigalith"],evoLevel:25,eggGroups:["Mineral"]},
gigalith:{num:526,species:"Gigalith",types:["Rock"],baseStats:{hp:85,atk:135,def:130,spa:60,spd:70,spe:25},abilities:{0:"Compoundeyes",1:"Iron Barbs"},heightm:1.7,weightkg:260,color:"Blue",prevo:"boldore",evoLevel:25,eggGroups:["Mineral"]},
woobat:{num:527,species:"Woobat",types:["Psychic","Flying"],baseStats:{hp:55,atk:45,def:43,spa:55,spd:43,spe:72},abilities:{0:"Compoundeyes",1:"Poison Point"},heightm:0.4,weightkg:2.1,color:"Blue",evos:["swoobat"],eggGroups:["Flying","Ground"]},
swoobat:{num:528,species:"Swoobat",types:["Psychic","Flying"],baseStats:{hp:67,atk:57,def:55,spa:77,spd:55,spe:114},abilities:{0:"Rain Dish",1:"Sand Rush"},heightm:0.9,weightkg:10.5,color:"Blue",prevo:"woobat",evoLevel:2,eggGroups:["Flying","Ground"]},
drilbur:{num:529,species:"Drilbur",types:["Ground"],baseStats:{hp:60,atk:85,def:40,spa:30,spd:45,spe:68},abilities:{0:"Pickpocket",1:"Natural Cure"},heightm:0.3,weightkg:8.5,color:"Gray",evos:["excadrill"],eggGroups:["Ground"]},
excadrill:{num:530,species:"Excadrill",types:["Ground","Steel"],baseStats:{hp:110,atk:135,def:60,spa:50,spd:65,spe:88},abilities:{0:"Rain Dish",1:"Tinted Lens"},heightm:0.7,weightkg:40.4,color:"Gray",prevo:"drilbur",evoLevel:31,eggGroups:["Ground"]},
audino:{num:531,species:"Audino",types:["Normal"],baseStats:{hp:103,atk:60,def:86,spa:60,spd:86,spe:50},abilities:{0:"Magic Bounce",1:"Sand Veil"},heightm:1.1,weightkg:31,color:"Pink",eggGroups:["Fairy"]},
timburr:{num:532,species:"Timburr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:80,def:55,spa:25,spd:35,spe:35},abilities:{0:"Levitate",1:"Immunity"},heightm:0.6,weightkg:12.5,color:"Gray",evos:["gurdurr"],eggGroups:["Humanshape"]},
gurdurr:{num:533,species:"Gurdurr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:85,atk:105,def:85,spa:40,spd:50,spe:40},abilities:{0:"Pressure",1:"Storm Drain"},heightm:1.2,weightkg:40,color:"Gray",prevo:"timburr",evos:["conkeldurr"],evoLevel:25,eggGroups:["Humanshape"]},
conkeldurr:{num:534,species:"Conkeldurr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:105,atk:140,def:95,spa:55,spd:65,spe:45},abilities:{0:"Poison Heal",1:"Mold Breaker"},heightm:1.4,weightkg:87,color:"Brown",prevo:"gurdurr",evoLevel:25,eggGroups:["Humanshape"]},
tympole:{num:535,species:"Tympole",types:["Water"],baseStats:{hp:50,atk:50,def:40,spa:50,spd:40,spe:64},abilities:{0:"Liquid Ooze",1:"Sheer Force"},heightm:0.5,weightkg:4.5,color:"Blue",evos:["palpitoad"],eggGroups:["Water 1"]},
palpitoad:{num:536,species:"Palpitoad",types:["Water","Ground"],baseStats:{hp:75,atk:65,def:55,spa:65,spd:55,spe:69},abilities:{0:"Super Luck",1:"Tinted Lens"},heightm:0.8,weightkg:17,color:"Blue",prevo:"tympole",evos:["seismitoad"],evoLevel:25,eggGroups:["Water 1"]},
seismitoad:{num:537,species:"Seismitoad",types:["Water","Ground"],baseStats:{hp:105,atk:85,def:75,spa:85,spd:75,spe:74},abilities:{0:"Anger Point",1:"Liquid Ooze"},heightm:1.5,weightkg:62,color:"Blue",prevo:"palpitoad",evoLevel:36,eggGroups:["Water 1"]},
throh:{num:538,species:"Throh",types:["Fighting"],gender:"M",baseStats:{hp:120,atk:100,def:85,spa:30,spd:85,spe:45},abilities:{0:"Sap Sipper",1:"Analytic"},heightm:1.3,weightkg:55.5,color:"Red",eggGroups:["Humanshape"]},
sawk:{num:539,species:"Sawk",types:["Fighting"],gender:"M",baseStats:{hp:75,atk:125,def:75,spa:30,spd:75,spe:85},abilities:{0:"Stench",1:"Flash Fire"},heightm:1.4,weightkg:51,color:"Blue",eggGroups:["Humanshape"]},
sewaddle:{num:540,species:"Sewaddle",types:["Bug","Grass"],baseStats:{hp:45,atk:53,def:70,spa:40,spd:60,spe:42},abilities:{0:"Sticky Hold",1:"Unaware"},heightm:0.3,weightkg:2.5,color:"Yellow",evos:["swadloon"],eggGroups:["Bug"]},
swadloon:{num:541,species:"Swadloon",types:["Bug","Grass"],baseStats:{hp:55,atk:63,def:90,spa:50,spd:80,spe:42},abilities:{0:"Magnet Pull",1:"Magma Armor"},heightm:0.5,weightkg:7.3,color:"Green",prevo:"sewaddle",evos:["leavanny"],evoLevel:20,eggGroups:["Bug"]},
leavanny:{num:542,species:"Leavanny",types:["Bug","Grass"],baseStats:{hp:75,atk:103,def:80,spa:70,spd:70,spe:92},abilities:{0:"Wonder Skin",1:"Unburden"},heightm:1.2,weightkg:20.5,color:"Yellow",prevo:"swadloon",evoLevel:21,eggGroups:["Bug"]},
venipede:{num:543,species:"Venipede",types:["Bug","Poison"],baseStats:{hp:30,atk:45,def:59,spa:30,spd:39,spe:57},abilities:{0:"Battle Armor",1:"Sticky Hold"},heightm:0.4,weightkg:5.3,color:"Red",evos:["whirlipede"],eggGroups:["Bug"]},
whirlipede:{num:544,species:"Whirlipede",types:["Bug","Poison"],baseStats:{hp:40,atk:55,def:99,spa:40,spd:79,spe:47},abilities:{0:"Trace",1:"Rain Dish"},heightm:1.2,weightkg:58.5,color:"Gray",prevo:"venipede",evos:["scolipede"],evoLevel:22,eggGroups:["Bug"]},
scolipede:{num:545,species:"Scolipede",types:["Bug","Poison"],baseStats:{hp:60,atk:90,def:89,spa:55,spd:69,spe:112},abilities:{0:"Trace",1:"Technician"},heightm:2.5,weightkg:200.5,color:"Red",prevo:"whirlipede",evoLevel:30,eggGroups:["Bug"]},
cottonee:{num:546,species:"Cottonee",types:["Grass"],baseStats:{hp:40,atk:27,def:60,spa:37,spd:50,spe:66},abilities:{0:"Liquid Ooze",1:"Hyper Cutter"},heightm:0.3,weightkg:0.6,color:"Green",evos:["whimsicott"],eggGroups:["Fairy","Plant"]},
whimsicott:{num:547,species:"Whimsicott",types:["Grass"],baseStats:{hp:60,atk:67,def:85,spa:77,spd:75,spe:116},abilities:{0:"Mummy",1:"Snow Cloak"},heightm:0.7,weightkg:6.6,color:"Green",prevo:"cottonee",evoLevel:1,eggGroups:["Fairy","Plant"]},
petilil:{num:548,species:"Petilil",types:["Grass"],gender:"F",baseStats:{hp:45,atk:35,def:50,spa:70,spd:50,spe:30},abilities:{0:"Sturdy",1:"Weak Armor"},heightm:0.5,weightkg:6.6,color:"Green",evos:["lilligant"],eggGroups:["Plant"]},
lilligant:{num:549,species:"Lilligant",types:["Grass"],gender:"F",baseStats:{hp:70,atk:60,def:75,spa:110,spd:75,spe:90},abilities:{0:"Lightningrod",1:"Overgrow"},heightm:1.1,weightkg:16.3,color:"Green",prevo:"petilil",evoLevel:1,eggGroups:["Plant"]},
basculin:{num:550,species:"Basculin",baseForme:"Red-Striped",types:["Water"],baseStats:{hp:70,atk:92,def:65,spa:80,spd:55,spe:98},abilities:{0:"Contrary",1:"Volt Absorb"},heightm:1,weightkg:18,color:"Green",eggGroups:["Water 2"],otherFormes:["basculinbluestriped"]},
sandile:{num:551,species:"Sandile",types:["Ground","Dark"],baseStats:{hp:50,atk:72,def:35,spa:35,spd:35,spe:65},abilities:{0:"Suction Cups",1:"Weak Armor"},heightm:0.7,weightkg:15.2,color:"Brown",evos:["krokorok"],eggGroups:["Ground"]},
krokorok:{num:552,species:"Krokorok",types:["Ground","Dark"],baseStats:{hp:60,atk:82,def:45,spa:45,spd:45,spe:74},abilities:{0:"Water Absorb",1:"Infiltrator"},heightm:1,weightkg:33.4,color:"Brown",prevo:"sandile",evos:["krookodile"],evoLevel:29,eggGroups:["Ground"]},
krookodile:{num:553,species:"Krookodile",types:["Ground","Dark"],baseStats:{hp:95,atk:117,def:70,spa:65,spd:70,spe:92},abilities:{0:"Tangled Feet",1:"Magic Guard"},heightm:1.5,weightkg:96.3,color:"Red",prevo:"krokorok",evoLevel:40,eggGroups:["Ground"]},
darumaka:{num:554,species:"Darumaka",types:["Fire"],baseStats:{hp:70,atk:90,def:45,spa:15,spd:45,spe:50},abilities:{0:"Hyper Cutter",1:"Big Pecks"},heightm:0.6,weightkg:37.5,color:"Red",evos:["darmanitan"],eggGroups:["Ground"]},
darmanitan:{num:555,species:"Darmanitan",baseForme:"Standard",types:["Fire"],baseStats:{hp:105,atk:140,def:55,spa:30,spd:55,spe:95},abilities:{0:"Synchronize",1:"Poison Point"},heightm:1.3,weightkg:92.9,color:"Red",prevo:"darumaka",evoLevel:35,eggGroups:["Ground"]},
maractus:{num:556,species:"Maractus",types:["Grass"],baseStats:{hp:75,atk:86,def:67,spa:106,spd:67,spe:60},abilities:{0:"Solid Rock",1:"Hyper Cutter"},heightm:1,weightkg:28,color:"Green",eggGroups:["Plant"]},
dwebble:{num:557,species:"Dwebble",types:["Bug","Rock"],baseStats:{hp:50,atk:65,def:85,spa:35,spd:35,spe:55},abilities:{0:"Water Absorb",1:"Ice Body"},heightm:0.3,weightkg:14.5,color:"Red",evos:["crustle"],eggGroups:["Bug","Mineral"]},
crustle:{num:558,species:"Crustle",types:["Bug","Rock"],baseStats:{hp:70,atk:95,def:125,spa:65,spd:75,spe:45},abilities:{0:"Magic Bounce",1:"Super Luck"},heightm:1.4,weightkg:200,color:"Red",prevo:"dwebble",evoLevel:34,eggGroups:["Bug","Mineral"]},
scraggy:{num:559,species:"Scraggy",types:["Dark","Fighting"],baseStats:{hp:50,atk:75,def:70,spa:35,spd:70,spe:48},abilities:{0:"Solar Power",1:"Solid Rock"},heightm:0.6,weightkg:11.8,color:"Yellow",evos:["scrafty"],eggGroups:["Ground","Dragon"]},
scrafty:{num:560,species:"Scrafty",types:["Dark","Fighting"],baseStats:{hp:65,atk:90,def:115,spa:45,spd:115,spe:58},abilities:{0:"Sturdy",1:"Sand Rush"},heightm:1.1,weightkg:30,color:"Red",prevo:"scraggy",evoLevel:39,eggGroups:["Ground","Dragon"]},
sigilyph:{num:561,species:"Sigilyph",types:["Psychic","Flying"],baseStats:{hp:72,atk:58,def:80,spa:103,spd:80,spe:97},abilities:{0:"Swarm",1:"Tangled Feet"},heightm:1.4,weightkg:14,color:"Black",eggGroups:["Flying"]},
yamask:{num:562,species:"Yamask",types:["Ghost"],baseStats:{hp:38,atk:30,def:85,spa:55,spd:65,spe:30},abilities:{0:"Suction Cups",1:"Poison Heal"},heightm:0.5,weightkg:1.5,color:"Black",evos:["cofagrigus"],eggGroups:["Mineral","Indeterminate"]},
cofagrigus:{num:563,species:"Cofagrigus",types:["Ghost"],baseStats:{hp:58,atk:50,def:145,spa:95,spd:105,spe:30},abilities:{0:"Light Metal",1:"Cute Charm"},heightm:1.7,weightkg:76.5,color:"Yellow",prevo:"yamask",evoLevel:34,eggGroups:["Mineral","Indeterminate"]},
tirtouga:{num:564,species:"Tirtouga",types:["Water","Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:54,atk:78,def:103,spa:53,spd:45,spe:22},abilities:{0:"Immunity",1:"Magic Guard"},heightm:0.7,weightkg:16.5,color:"Blue",evos:["carracosta"],eggGroups:["Water 1","Water 3"]},
carracosta:{num:565,species:"Carracosta",types:["Water","Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:74,atk:108,def:133,spa:83,spd:65,spe:32},abilities:{0:"Toxic Boost",1:"Harvest"},heightm:1.2,weightkg:81,color:"Blue",prevo:"tirtouga",evoLevel:37,eggGroups:["Water 1","Water 3"]},
archen:{num:566,species:"Archen",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:112,def:45,spa:74,spd:45,spe:70},abilities:{0:"Multiscale",1:"Sniper"},heightm:0.5,weightkg:9.5,color:"Yellow",evos:["archeops"],eggGroups:["Flying","Water 3"]},
archeops:{num:567,species:"Archeops",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:140,def:65,spa:112,spd:65,spe:110},abilities:{0:"Natural Cure",1:"Blaze"},heightm:1.4,weightkg:32,color:"Yellow",prevo:"archen",evoLevel:37,eggGroups:["Flying","Water 3"]},
trubbish:{num:568,species:"Trubbish",types:["Poison"],baseStats:{hp:50,atk:50,def:62,spa:40,spd:62,spe:65},abilities:{0:"Rattled",1:"Snow Warning"},heightm:0.6,weightkg:31,color:"Green",evos:["garbodor"],eggGroups:["Mineral"]},
garbodor:{num:569,species:"Garbodor",types:["Poison"],baseStats:{hp:80,atk:95,def:82,spa:60,spd:82,spe:75},abilities:{0:"Clear Body",1:"Volt Absorb"},heightm:1.9,weightkg:107.3,color:"Green",prevo:"trubbish",evoLevel:36,eggGroups:["Mineral"]},
zorua:{num:570,species:"Zorua",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:65,def:40,spa:80,spd:40,spe:65},abilities:{0:"Toxic Boost",1:"Light Metal"},heightm:0.7,weightkg:12.5,color:"Gray",evos:["zoroark"],eggGroups:["Ground"]},
zoroark:{num:571,species:"Zoroark",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:105,def:60,spa:120,spd:60,spe:105},abilities:{0:"Early Bird",1:"Sand Veil"},heightm:1.6,weightkg:81.1,color:"Gray",prevo:"zorua",evoLevel:30,eggGroups:["Ground"]},
minccino:{num:572,species:"Minccino",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:55,atk:50,def:40,spa:40,spd:40,spe:75},abilities:{0:"Aftermath",1:"Klutz"},heightm:0.4,weightkg:5.8,color:"Gray",evos:["cinccino"],eggGroups:["Ground"]},
cinccino:{num:573,species:"Cinccino",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:75,atk:95,def:60,spa:65,spd:60,spe:115},abilities:{0:"Hyper Cutter",1:"Lightningrod"},heightm:0.5,weightkg:7.5,color:"Gray",prevo:"minccino",evoLevel:1,eggGroups:["Ground"]},
gothita:{num:574,species:"Gothita",types:["Psychic"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:45,atk:30,def:50,spa:55,spd:65,spe:45},abilities:{0:"Unaware",1:"Effect Spore"},heightm:0.4,weightkg:5.8,color:"Purple",evos:["gothorita"],eggGroups:["Humanshape"]},
gothorita:{num:575,species:"Gothorita",types:["Psychic"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:60,atk:45,def:70,spa:75,spd:85,spe:55},abilities:{0:"Cloud Nine",1:"Mold Breaker"},heightm:0.7,weightkg:18,color:"Purple",prevo:"gothita",evos:["gothitelle"],evoLevel:32,eggGroups:["Humanshape"]},
gothitelle:{num:576,species:"Gothitelle",types:["Psychic"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:55,def:95,spa:95,spd:110,spe:65},abilities:{0:"Overcoat",1:"Magic Bounce"},heightm:1.5,weightkg:44,color:"Purple",prevo:"gothorita",evoLevel:41,eggGroups:["Humanshape"]},
solosis:{num:577,species:"Solosis",types:["Psychic"],baseStats:{hp:45,atk:30,def:40,spa:105,spd:50,spe:20},abilities:{0:"Imposter",1:"Synchronize"},heightm:0.3,weightkg:1,color:"Green",evos:["duosion"],eggGroups:["Indeterminate"]},
duosion:{num:578,species:"Duosion",types:["Psychic"],baseStats:{hp:65,atk:40,def:50,spa:125,spd:60,spe:30},abilities:{0:"Analytic",1:"Magnet Pull"},heightm:0.6,weightkg:8,color:"Green",prevo:"solosis",evos:["reuniclus"],evoLevel:32,eggGroups:["Indeterminate"]},
reuniclus:{num:579,species:"Reuniclus",types:["Psychic"],baseStats:{hp:110,atk:65,def:75,spa:125,spd:85,spe:30},abilities:{0:"Natural Cure",1:"Analytic"},heightm:1,weightkg:20.1,color:"Green",prevo:"duosion",evoLevel:41,eggGroups:["Indeterminate"]},
ducklett:{num:580,species:"Ducklett",types:["Water","Flying"],baseStats:{hp:62,atk:44,def:50,spa:44,spd:50,spe:55},abilities:{0:"Magma Armor",1:"Victory Star"},heightm:0.5,weightkg:5.5,color:"Blue",evos:["swanna"],eggGroups:["Water 1","Flying"]},
swanna:{num:581,species:"Swanna",types:["Water","Flying"],baseStats:{hp:75,atk:87,def:63,spa:87,spd:63,spe:98},abilities:{0:"Shield Dust",1:"Early Bird"},heightm:1.3,weightkg:24.2,color:"White",prevo:"ducklett",evoLevel:35,eggGroups:["Water 1","Flying"]},
vanillite:{num:582,species:"Vanillite",types:["Ice"],baseStats:{hp:36,atk:50,def:50,spa:65,spd:60,spe:44},abilities:{0:"Arena Trap",1:"Magma Armor"},heightm:0.4,weightkg:5.7,color:"White",evos:["vanillish"],eggGroups:["Mineral"]},
vanillish:{num:583,species:"Vanillish",types:["Ice"],baseStats:{hp:51,atk:65,def:65,spa:80,spd:75,spe:59},abilities:{0:"Insomnia",1:"No Guard"},heightm:1.1,weightkg:41,color:"White",prevo:"vanillite",evos:["vanilluxe"],evoLevel:35,eggGroups:["Mineral"]},
vanilluxe:{num:584,species:"Vanilluxe",types:["Ice"],baseStats:{hp:71,atk:95,def:85,spa:110,spd:95,spe:79},abilities:{0:"Marvel Scale",1:"Hyper Cutter"},heightm:1.3,weightkg:57.5,color:"White",prevo:"vanillish",evoLevel:47,eggGroups:["Mineral"]},
deerling:{num:585,species:"Deerling",baseForme:"Spring",types:["Normal","Grass"],baseStats:{hp:60,atk:60,def:50,spa:40,spd:50,spe:75},abilities:{0:"Drizzle",1:"Water Veil"},heightm:0.6,weightkg:19.5,color:"Yellow",evos:["sawsbuck"],eggGroups:["Ground"],otherForms:["deerlingsummer","deerlingautumn","deerlingwinter"]},
sawsbuck:{num:586,species:"Sawsbuck",baseForme:"Spring",types:["Normal","Grass"],baseStats:{hp:80,atk:100,def:70,spa:60,spd:70,spe:95},abilities:{0:"Stench",1:"Speed Boost"},heightm:1.9,weightkg:92.5,color:"Brown",prevo:"deerling",evoLevel:34,eggGroups:["Ground"],otherForms:["sawsbucksummer","sawsbuckautumn","sawsbuckwinter"]},
emolga:{num:587,species:"Emolga",types:["Electric","Flying"],baseStats:{hp:55,atk:75,def:60,spa:75,spd:60,spe:103},abilities:{0:"Stall",1:"Sticky Hold"},heightm:0.4,weightkg:5,color:"White",eggGroups:["Ground"]},
karrablast:{num:588,species:"Karrablast",types:["Bug"],baseStats:{hp:50,atk:75,def:45,spa:40,spd:45,spe:60},abilities:{0:"Solid Rock",1:"Own Tempo"},heightm:0.5,weightkg:5.9,color:"Blue",evos:["escavalier"],eggGroups:["Bug"]},
escavalier:{num:589,species:"Escavalier",types:["Bug","Steel"],baseStats:{hp:70,atk:135,def:105,spa:60,spd:105,spe:20},abilities:{0:"Unnerve",1:"Compoundeyes"},heightm:1,weightkg:33,color:"Gray",prevo:"karrablast",evoLevel:1,eggGroups:["Bug"]},
foongus:{num:590,species:"Foongus",types:["Grass","Poison"],baseStats:{hp:69,atk:55,def:45,spa:55,spd:55,spe:15},abilities:{0:"Clear Body",1:"Imposter"},heightm:0.2,weightkg:1,color:"White",evos:["amoonguss"],eggGroups:["Plant"]},
amoonguss:{num:591,species:"Amoonguss",types:["Grass","Poison"],baseStats:{hp:114,atk:85,def:70,spa:85,spd:80,spe:30},abilities:{0:"Overcoat",1:"Gluttony"},heightm:0.6,weightkg:10.5,color:"White",prevo:"foongus",evoLevel:39,eggGroups:["Plant"]},
frillish:{num:592,species:"Frillish",types:["Water","Ghost"],baseStats:{hp:55,atk:40,def:50,spa:65,spd:85,spe:40},abilities:{0:"Levitate",1:"Poison Heal"},heightm:1.2,weightkg:33,color:"White",evos:["jellicent"],eggGroups:["Indeterminate"]},
jellicent:{num:593,species:"Jellicent",types:["Water","Ghost"],baseStats:{hp:100,atk:60,def:70,spa:85,spd:105,spe:60},abilities:{0:"Thick Fat",1:"Intimidate"},heightm:2.2,weightkg:135,color:"White",prevo:"frillish",evoLevel:40,eggGroups:["Indeterminate"]},
alomomola:{num:594,species:"Alomomola",types:["Water"],baseStats:{hp:165,atk:75,def:80,spa:40,spd:45,spe:65},abilities:{0:"Cloud Nine",1:"Serene Grace"},heightm:1.2,weightkg:31.6,color:"Pink",eggGroups:["Water 1","Water 2"]},
joltik:{num:595,species:"Joltik",types:["Bug","Electric"],baseStats:{hp:50,atk:47,def:50,spa:57,spd:50,spe:65},abilities:{0:"Super Luck",1:"Flash Fire"},heightm:0.1,weightkg:0.6,color:"Yellow",evos:["galvantula"],eggGroups:["Bug"]},
galvantula:{num:596,species:"Galvantula",types:["Bug","Electric"],baseStats:{hp:70,atk:77,def:60,spa:97,spd:60,spe:108},abilities:{0:"Pure Power",1:"Light Metal"},heightm:0.8,weightkg:14.3,color:"Yellow",prevo:"joltik",evoLevel:36,eggGroups:["Bug"]},
ferroseed:{num:597,species:"Ferroseed",types:["Grass","Steel"],baseStats:{hp:44,atk:50,def:91,spa:24,spd:86,spe:10},abilities:{0:"Shield Dust",1:"Overcoat"},heightm:0.6,weightkg:18.8,color:"Gray",evos:["ferrothorn"],eggGroups:["Plant","Mineral"]},
ferrothorn:{num:598,species:"Ferrothorn",types:["Grass","Steel"],baseStats:{hp:74,atk:94,def:131,spa:54,spd:116,spe:20},abilities:{0:"Illusion",1:"No Guard"},heightm:1,weightkg:110,color:"Gray",prevo:"ferroseed",evoLevel:40,eggGroups:["Plant","Mineral"]},
klink:{num:599,species:"Klink",types:["Steel"],gender:"N",baseStats:{hp:40,atk:55,def:70,spa:45,spd:60,spe:30},abilities:{0:"Stench",1:"Unaware"},heightm:0.3,weightkg:21,color:"Gray",evos:["klang"],eggGroups:["Mineral"]},
klang:{num:600,species:"Klang",types:["Steel"],gender:"N",baseStats:{hp:60,atk:80,def:95,spa:70,spd:85,spe:50},abilities:{0:"Blaze",1:"Sniper"},heightm:0.6,weightkg:51,color:"Gray",prevo:"klink",evos:["klinklang"],evoLevel:38,eggGroups:["Mineral"]},
klinklang:{num:601,species:"Klinklang",types:["Steel"],gender:"N",baseStats:{hp:60,atk:100,def:115,spa:70,spd:85,spe:90},abilities:{0:"Flame Body",1:"Scrappy"},heightm:0.6,weightkg:81,color:"Gray",prevo:"klang",evoLevel:49,eggGroups:["Mineral"]},
tynamo:{num:602,species:"Tynamo",types:["Electric"],baseStats:{hp:35,atk:55,def:40,spa:45,spd:40,spe:60},abilities:{0:"Color Change",1:"Prankster"},heightm:0.2,weightkg:0.3,color:"White",evos:["eelektrik"],eggGroups:["Indeterminate"]},
eelektrik:{num:603,species:"Eelektrik",types:["Electric"],baseStats:{hp:65,atk:85,def:70,spa:75,spd:70,spe:40},abilities:{0:"Moxie",1:"Anticipation"},heightm:1.2,weightkg:22,color:"Blue",prevo:"tynamo",evos:["eelektross"],evoLevel:39,eggGroups:["Indeterminate"]},
eelektross:{num:604,species:"Eelektross",types:["Electric"],baseStats:{hp:85,atk:115,def:80,spa:105,spd:80,spe:50},abilities:{0:"Liquid Ooze",1:"Rattled"},heightm:2.1,weightkg:80.5,color:"Blue",prevo:"eelektrik",evoLevel:39,eggGroups:["Indeterminate"]},
elgyem:{num:605,species:"Elgyem",types:["Psychic"],baseStats:{hp:55,atk:55,def:55,spa:85,spd:55,spe:30},abilities:{0:"Inner Focus",1:"Illusion"},heightm:0.5,weightkg:9,color:"Blue",evos:["beheeyem"],eggGroups:["Humanshape"]},
beheeyem:{num:606,species:"Beheeyem",types:["Psychic"],baseStats:{hp:75,atk:75,def:75,spa:125,spd:95,spe:40},abilities:{0:"Dry Skin",1:"Damp"},heightm:1,weightkg:34.5,color:"Brown",prevo:"elgyem",evoLevel:42,eggGroups:["Humanshape"]},
litwick:{num:607,species:"Litwick",types:["Ghost","Fire"],baseStats:{hp:50,atk:30,def:55,spa:65,spd:55,spe:20},abilities:{0:"Victory Star",1:"Snow Cloak"},heightm:0.3,weightkg:3.1,color:"White",evos:["lampent"],eggGroups:["Indeterminate"]},
lampent:{num:608,species:"Lampent",types:["Ghost","Fire"],baseStats:{hp:60,atk:40,def:60,spa:95,spd:60,spe:55},abilities:{0:"Snow Cloak",1:"Drought"},heightm:0.6,weightkg:13,color:"Black",prevo:"litwick",evos:["chandelure"],evoLevel:41,eggGroups:["Indeterminate"]},
chandelure:{num:609,species:"Chandelure",types:["Ghost","Fire"],baseStats:{hp:60,atk:55,def:90,spa:145,spd:90,spe:80},abilities:{0:"Keen Eye",1:"Magic Guard"},heightm:1,weightkg:34.3,color:"Black",prevo:"lampent",evoLevel:41,eggGroups:["Indeterminate"]},
axew:{num:610,species:"Axew",types:["Dragon"],baseStats:{hp:46,atk:87,def:60,spa:30,spd:40,spe:57},abilities:{0:"Sap Sipper",1:"Guts"},heightm:0.6,weightkg:18,color:"Green",evos:["fraxure"],eggGroups:["Monster","Dragon"]},
fraxure:{num:611,species:"Fraxure",types:["Dragon"],baseStats:{hp:66,atk:117,def:70,spa:40,spd:50,spe:67},abilities:{0:"Early Bird",1:"Light Metal"},heightm:1,weightkg:36,color:"Green",prevo:"axew",evos:["haxorus"],evoLevel:38,eggGroups:["Monster","Dragon"]},
haxorus:{num:612,species:"Haxorus",types:["Dragon"],baseStats:{hp:76,atk:147,def:90,spa:60,spd:70,spe:97},abilities:{0:"Motor Drive",1:"Sand Veil"},heightm:1.8,weightkg:105.5,color:"Yellow",prevo:"fraxure",evoLevel:48,eggGroups:["Monster","Dragon"]},
cubchoo:{num:613,species:"Cubchoo",types:["Ice"],baseStats:{hp:55,atk:70,def:40,spa:60,spd:40,spe:40},abilities:{0:"Unaware",1:"Sticky Hold"},heightm:0.5,weightkg:8.5,color:"White",evos:["beartic"],eggGroups:["Ground"]},
beartic:{num:614,species:"Beartic",types:["Ice"],baseStats:{hp:95,atk:110,def:80,spa:70,spd:80,spe:50},abilities:{0:"Gluttony",1:"Storm Drain"},heightm:2.6,weightkg:260,color:"White",prevo:"cubchoo",evoLevel:37,eggGroups:["Ground"]},
cryogonal:{num:615,species:"Cryogonal",types:["Ice"],gender:"N",baseStats:{hp:70,atk:50,def:30,spa:95,spd:135,spe:105},abilities:{0:"Sturdy",1:"Defiant"},heightm:1.1,weightkg:148,color:"Blue",eggGroups:["Mineral"]},
shelmet:{num:616,species:"Shelmet",types:["Bug"],baseStats:{hp:50,atk:40,def:85,spa:40,spd:65,spe:25},abilities:{0:"Light Metal",1:"Technician"},heightm:0.4,weightkg:7.7,color:"Red",evos:["accelgor"],eggGroups:["Bug"]},
accelgor:{num:617,species:"Accelgor",types:["Bug"],baseStats:{hp:80,atk:70,def:40,spa:100,spd:60,spe:145},abilities:{0:"Gluttony",1:"Snow Cloak"},heightm:0.8,weightkg:25.3,color:"Red",prevo:"shelmet",evoLevel:1,eggGroups:["Bug"]},
stunfisk:{num:618,species:"Stunfisk",types:["Ground","Electric"],baseStats:{hp:109,atk:66,def:84,spa:81,spd:99,spe:32},abilities:{0:"Pickpocket",1:"Battle Armor"},heightm:0.7,weightkg:11,color:"Brown",eggGroups:["Water 1","Indeterminate"]},
mienfoo:{num:619,species:"Mienfoo",types:["Fighting"],baseStats:{hp:45,atk:85,def:50,spa:55,spd:50,spe:65},abilities:{0:"Rattled",1:"Multiscale"},heightm:0.9,weightkg:20,color:"Yellow",evos:["mienshao"],eggGroups:["Ground","Humanshape"]},
mienshao:{num:620,species:"Mienshao",types:["Fighting"],baseStats:{hp:65,atk:125,def:60,spa:95,spd:60,spe:105},abilities:{0:"Harvest",1:"Cute Charm"},heightm:1.4,weightkg:35.5,color:"Purple",prevo:"mienfoo",evoLevel:50,eggGroups:["Ground","Humanshape"]},
druddigon:{num:621,species:"Druddigon",types:["Dragon"],baseStats:{hp:77,atk:120,def:90,spa:60,spd:90,spe:48},abilities:{0:"Sturdy",1:"Prankster"},heightm:1.6,weightkg:139,color:"Red",eggGroups:["Monster","Dragon"]},
golett:{num:622,species:"Golett",types:["Ground","Ghost"],gender:"N",baseStats:{hp:59,atk:74,def:50,spa:35,spd:50,spe:35},abilities:{0:"Snow Warning",1:"Magic Guard"},heightm:1,weightkg:92,color:"Green",evos:["golurk"],eggGroups:["Mineral"]},
golurk:{num:623,species:"Golurk",types:["Ground","Ghost"],gender:"N",baseStats:{hp:89,atk:124,def:80,spa:55,spd:80,spe:55},abilities:{0:"Aftermath",1:"Frisk"},heightm:2.8,weightkg:330,color:"Green",prevo:"golett",evoLevel:43,eggGroups:["Mineral"]},
pawniard:{num:624,species:"Pawniard",types:["Dark","Steel"],baseStats:{hp:45,atk:85,def:70,spa:40,spd:40,spe:60},abilities:{0:"Water Veil",1:"Liquid Ooze"},heightm:0.5,weightkg:10.2,color:"Red",evos:["bisharp"],eggGroups:["Humanshape"]},
bisharp:{num:625,species:"Bisharp",types:["Dark","Steel"],baseStats:{hp:65,atk:125,def:100,spa:60,spd:70,spe:70},abilities:{0:"Snow Cloak",1:"Forewarn"},heightm:1.6,weightkg:70,color:"Red",prevo:"pawniard",evoLevel:52,eggGroups:["Humanshape"]},
bouffalant:{num:626,species:"Bouffalant",types:["Normal"],baseStats:{hp:95,atk:110,def:95,spa:40,spd:95,spe:55},abilities:{0:"Static",1:"Dry Skin"},heightm:1.6,weightkg:94.6,color:"Brown",eggGroups:["Ground"]},
rufflet:{num:627,species:"Rufflet",types:["Normal","Flying"],gender:"M",baseStats:{hp:70,atk:83,def:50,spa:37,spd:50,spe:60},abilities:{0:"Pure Power",1:"Forewarn"},heightm:0.5,weightkg:10.5,color:"White",evos:["braviary"],eggGroups:["Flying"]},
braviary:{num:628,species:"Braviary",types:["Normal","Flying"],gender:"M",baseStats:{hp:100,atk:123,def:75,spa:57,spd:75,spe:80},abilities:{0:"Volt Absorb",1:"Sand Veil"},heightm:1.5,weightkg:41,color:"Red",prevo:"rufflet",evoLevel:54,eggGroups:["Flying"]},
vullaby:{num:629,species:"Vullaby",types:["Dark","Flying"],gender:"F",baseStats:{hp:70,atk:55,def:75,spa:45,spd:65,spe:60},abilities:{0:"Rock Head",1:"Sniper"},heightm:0.5,weightkg:9,color:"Brown",evos:["mandibuzz"],eggGroups:["Flying"]},
mandibuzz:{num:630,species:"Mandibuzz",types:["Dark","Flying"],gender:"F",baseStats:{hp:110,atk:65,def:105,spa:55,spd:95,spe:80},abilities:{0:"Mummy",1:"Iron Barbs"},heightm:1.2,weightkg:39.5,color:"Brown",prevo:"vullaby",evoLevel:54,eggGroups:["Flying"]},
heatmor:{num:631,species:"Heatmor",types:["Fire"],baseStats:{hp:85,atk:97,def:66,spa:105,spd:66,spe:65},abilities:{0:"Solid Rock",1:"Overcoat"},heightm:1.4,weightkg:58,color:"Red",eggGroups:["Ground"]},
durant:{num:632,species:"Durant",types:["Bug","Steel"],baseStats:{hp:58,atk:109,def:112,spa:48,spd:48,spe:109},abilities:{0:"Unnerve",1:"Sand Rush"},heightm:0.3,weightkg:33,color:"Gray",eggGroups:["Bug"]},
deino:{num:633,species:"Deino",types:["Dark","Dragon"],baseStats:{hp:52,atk:65,def:50,spa:45,spd:50,spe:38},abilities:{0:"Weak Armor",1:"Tinted Lens"},heightm:0.8,weightkg:17.3,color:"Blue",evos:["zweilous"],eggGroups:["Dragon"]},
zweilous:{num:634,species:"Zweilous",types:["Dark","Dragon"],baseStats:{hp:72,atk:85,def:70,spa:65,spd:70,spe:58},abilities:{0:"Justified",1:"Drizzle"},heightm:1.4,weightkg:50,color:"Blue",prevo:"deino",evos:["hydreigon"],evoLevel:50,eggGroups:["Dragon"]},
hydreigon:{num:635,species:"Hydreigon",types:["Dark","Dragon"],baseStats:{hp:92,atk:105,def:90,spa:125,spd:90,spe:98},abilities:{0:"Drought",1:"Hustle"},heightm:1.8,weightkg:160,color:"Blue",prevo:"zweilous",evoLevel:64,eggGroups:["Dragon"]},
larvesta:{num:636,species:"Larvesta",types:["Bug","Fire"],baseStats:{hp:55,atk:85,def:55,spa:50,spd:55,spe:60},abilities:{0:"Intimidate",1:"Sniper"},heightm:1.1,weightkg:28.8,color:"White",evos:["volcarona"],eggGroups:["Bug"]},
volcarona:{num:637,species:"Volcarona",types:["Bug","Fire"],baseStats:{hp:85,atk:60,def:65,spa:135,spd:105,spe:100},abilities:{0:"Wonder Guard",1:"Solar Power"},heightm:1.6,weightkg:46,color:"White",prevo:"larvesta",evoLevel:59,eggGroups:["Bug"]},
cobalion:{num:638,species:"Cobalion",types:["Steel","Fighting"],gender:"N",baseStats:{hp:91,atk:90,def:129,spa:90,spd:72,spe:108},abilities:{0:"Poison Point",1:"Magma Armor"},heightm:2.1,weightkg:250,color:"Blue",eggGroups:["No Eggs"]},
terrakion:{num:639,species:"Terrakion",types:["Rock","Fighting"],gender:"N",baseStats:{hp:91,atk:129,def:90,spa:72,spd:90,spe:108},abilities:{0:"Wonder Skin",1:"Shadow Tag"},heightm:1.9,weightkg:260,color:"Gray",eggGroups:["No Eggs"]},
virizion:{num:640,species:"Virizion",types:["Grass","Fighting"],gender:"N",baseStats:{hp:91,atk:90,def:72,spa:90,spd:129,spe:108},abilities:{0:"Moxie",1:"Analytic"},heightm:2,weightkg:200,color:"Green",eggGroups:["No Eggs"]},
tornadus:{num:641,species:"Tornadus",baseForme:"Incarnate",types:["Flying"],gender:"M",baseStats:{hp:79,atk:115,def:70,spa:125,spd:80,spe:111},abilities:{0:"Magma Armor",1:"Battle Armor"},heightm:1.5,weightkg:63,color:"Green",eggGroups:["No Eggs"],otherFormes:["tornadustherian"]},
tornadustherian:{num:641,species:"Tornadus-Therian",baseSpecies:"Tornadus",forme:"Therian",formeLetter:"T",types:["Flying"],gender:"M",baseStats:{hp:79,atk:100,def:80,spa:110,spd:90,spe:121},abilities:{0:"Iron Barbs",1:"Blaze"},heightm:1.4,weightkg:63,color:"Green",eggGroups:["No Eggs"]},
thundurus:{num:642,species:"Thundurus",baseForme:"Incarnate",types:["Electric","Flying"],gender:"M",baseStats:{hp:79,atk:115,def:70,spa:125,spd:80,spe:111},abilities:{0:"Clear Body",1:"Hustle"},heightm:1.5,weightkg:61,color:"Blue",eggGroups:["No Eggs"],otherFormes:["thundurustherian"]},
thundurustherian:{num:642,species:"Thundurus-Therian",baseSpecies:"Thundurus",forme:"Therian",formeLetter:"T",types:["Electric","Flying"],gender:"M",baseStats:{hp:79,atk:105,def:70,spa:145,spd:80,spe:101},abilities:{0:"Anger Point",1:"Insomnia"},heightm:3,weightkg:61,color:"Blue",eggGroups:["No Eggs"]},
reshiram:{num:643,species:"Reshiram",types:["Dragon","Fire"],gender:"N",baseStats:{hp:100,atk:120,def:100,spa:150,spd:120,spe:90},abilities:{0:"Infiltrator",1:"Tangled Feet"},heightm:3.2,weightkg:330,color:"White",eggGroups:["No Eggs"]},
zekrom:{num:644,species:"Zekrom",types:["Dragon","Electric"],gender:"N",baseStats:{hp:100,atk:150,def:120,spa:120,spd:100,spe:90},abilities:{0:"Weak Armor",1:"Limber"},heightm:2.9,weightkg:345,color:"Black",eggGroups:["No Eggs"]},
landorus:{num:645,species:"Landorus",baseForme:"Incarnate",types:["Ground","Flying"],gender:"M",baseStats:{hp:89,atk:125,def:90,spa:115,spd:80,spe:101},abilities:{0:"Soundproof",1:"Mummy"},heightm:1.5,weightkg:68,color:"Brown",eggGroups:["No Eggs"],otherFormes:["landorustherian"]},
landorustherian:{num:645,species:"Landorus-Therian",baseSpecies:"Landorus",forme:"Therian",formeLetter:"T",types:["Ground","Flying"],gender:"M",baseStats:{hp:89,atk:145,def:90,spa:105,spd:80,spe:91},abilities:{0:"Scrappy",1:"Bad Dreams"},heightm:1.3,weightkg:68,color:"Brown",eggGroups:["No Eggs"]},
kyurem:{num:646,species:"Kyurem",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:130,def:90,spa:130,spd:90,spe:95},abilities:{0:"Hydration",1:"Anger Point"},heightm:3,weightkg:325,color:"Gray",eggGroups:["No Eggs"],otherFormes:["kyuremblack","kyuremwhite"]},
kyuremblack:{num:646,species:"Kyurem-Black",baseSpecies:"Kyurem",forme:"Black",formeLetter:"B",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:170,def:100,spa:120,spd:90,spe:95},abilities:{0:"Weak Armor",1:"Shadow Tag"},heightm:3.3,weightkg:325,color:"Gray",eggGroups:["No Eggs"]},
kyuremwhite:{num:646,species:"Kyurem-White",baseSpecies:"Kyurem",forme:"White",formeLetter:"W",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:120,def:90,spa:170,spd:100,spe:95},abilities:{0:"No Guard",1:"Gluttony"},heightm:3.6,weightkg:325,color:"Gray",eggGroups:["No Eggs"]},
keldeo:{num:647,species:"Keldeo",baseForme:"Ordinary",types:["Water","Fighting"],gender:"N",baseStats:{hp:91,atk:72,def:90,spa:129,spd:90,spe:108},abilities:{0:"Shed Skin",1:"Speed Boost"},heightm:1.4,weightkg:48.5,color:"Yellow",eggGroups:["No Eggs"],otherFormes:["keldeoresolute"]},
meloetta:{num:648,species:"Meloetta",baseForme:"Aria",types:["Normal","Psychic"],gender:"N",baseStats:{hp:100,atk:77,def:77,spa:128,spd:128,spe:90},abilities:{0:"Multiscale",1:"Moxie"},heightm:0.6,weightkg:6.5,color:"White",eggGroups:["No Eggs"],otherFormes:["meloettapirouette"]},
meloettapirouette:{num:648,species:"Meloetta-Pirouette",baseSpecies:"Meloetta",forme:"Pirouette",formeLetter:"P",types:["Normal","Fighting"],gender:"N",baseStats:{hp:100,atk:128,def:90,spa:77,spd:77,spe:128},abilities:{0:"Multiscale",1:"Moxie"},heightm:0.6,weightkg:6.5,color:"White",eggGroups:["No Eggs"]},
genesect:{num:649,species:"Genesect",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"],otherFormes:["genesectdouse","genesectshock","genesectburn","genesectchill"]},
};
| mods/wonkymons/pokedex.js | exports.BattlePokedex = {
bulbasaur:{num:1,species:"Bulbasaur",types:["Grass","Poison"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:49,def:49,spa:65,spd:65,spe:45},abilities:{0:"Aftermath",1:"Adaptability"},heightm:0.7,weightkg:6.9,color:"Green",evos:["ivysaur"],eggGroups:["Monster","Plant"]},
ivysaur:{num:2,species:"Ivysaur",types:["Grass","Poison"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:62,def:63,spa:80,spd:80,spe:60},abilities:{0:"Regenerator",1:"Sturdy"},heightm:1,weightkg:13,color:"Green",prevo:"bulbasaur",evos:["venusaur"],evoLevel:16,eggGroups:["Monster","Plant"]},
venusaur:{num:3,species:"Venusaur",types:["Grass","Poison"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:82,def:83,spa:100,spd:100,spe:80},abilities:{0:"Heatproof",1:"Flare Boost"},heightm:2,weightkg:100,color:"Green",prevo:"ivysaur",evoLevel:32,eggGroups:["Monster","Plant"]},
charmander:{num:4,species:"Charmander",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:39,atk:52,def:43,spa:60,spd:50,spe:65},abilities:{0:"Infiltrator",1:"Cute Charm"},heightm:0.6,weightkg:8.5,color:"Red",evos:["charmeleon"],eggGroups:["Monster","Dragon"]},
charmeleon:{num:5,species:"Charmeleon",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:58,atk:64,def:58,spa:80,spd:65,spe:80},abilities:{0:"Technician",1:"Sand Force"},heightm:1.1,weightkg:19,color:"Red",prevo:"charmander",evos:["charizard"],evoLevel:16,eggGroups:["Monster","Dragon"]},
charizard:{num:6,species:"Charizard",types:["Fire","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:78,atk:84,def:78,spa:109,spd:85,spe:100},abilities:{0:"Sand Stream",1:"Regenerator"},heightm:1.7,weightkg:90.5,color:"Red",prevo:"charmeleon",evoLevel:36,eggGroups:["Monster","Dragon"]},
squirtle:{num:7,species:"Squirtle",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:44,atk:48,def:65,spa:50,spd:64,spe:43},abilities:{0:"Clear Body",1:"Lightningrod"},heightm:0.5,weightkg:9,color:"Blue",evos:["wartortle"],eggGroups:["Monster","Water 1"]},
wartortle:{num:8,species:"Wartortle",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:59,atk:63,def:80,spa:65,spd:80,spe:58},abilities:{0:"No Guard",1:"Poison Point"},heightm:1,weightkg:22.5,color:"Blue",prevo:"squirtle",evos:["blastoise"],evoLevel:16,eggGroups:["Monster","Water 1"]},
blastoise:{num:9,species:"Blastoise",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:79,atk:83,def:100,spa:85,spd:105,spe:78},abilities:{0:"Early Bird",1:"Overcoat"},heightm:1.6,weightkg:85.5,color:"Blue",prevo:"wartortle",evoLevel:36,eggGroups:["Monster","Water 1"]},
caterpie:{num:10,species:"Caterpie",types:["Bug"],baseStats:{hp:45,atk:30,def:35,spa:20,spd:20,spe:45},abilities:{0:"Iron Barbs",1:"Swift Swim"},heightm:0.3,weightkg:2.9,color:"Green",evos:["metapod"],eggGroups:["Bug"]},
metapod:{num:11,species:"Metapod",types:["Bug"],baseStats:{hp:50,atk:20,def:55,spa:25,spd:25,spe:30},abilities:{0:"Tinted Lens",1:"Shadow Tag"},heightm:0.7,weightkg:9.9,color:"Green",prevo:"caterpie",evos:["butterfree"],evoLevel:7,eggGroups:["Bug"]},
butterfree:{num:12,species:"Butterfree",types:["Bug","Flying"],baseStats:{hp:60,atk:45,def:50,spa:80,spd:80,spe:70},abilities:{0:"Sap Sipper",1:"Water Absorb"},heightm:1.1,weightkg:32,color:"White",prevo:"metapod",evoLevel:10,eggGroups:["Bug"]},
weedle:{num:13,species:"Weedle",types:["Bug","Poison"],baseStats:{hp:40,atk:35,def:30,spa:20,spd:20,spe:50},abilities:{0:"Damp",1:"Sheer Force"},heightm:0.3,weightkg:3.2,color:"Brown",evos:["kakuna"],eggGroups:["Bug"]},
kakuna:{num:14,species:"Kakuna",types:["Bug","Poison"],baseStats:{hp:45,atk:25,def:50,spa:25,spd:25,spe:35},abilities:{0:"Early Bird",1:"Light Metal"},heightm:0.6,weightkg:10,color:"Yellow",prevo:"weedle",evos:["beedrill"],evoLevel:7,eggGroups:["Bug"]},
beedrill:{num:15,species:"Beedrill",types:["Bug","Poison"],baseStats:{hp:65,atk:80,def:40,spa:45,spd:80,spe:75},abilities:{0:"Effect Spore",1:"Harvest"},heightm:1,weightkg:29.5,color:"Yellow",prevo:"kakuna",evoLevel:10,eggGroups:["Bug"]},
pidgey:{num:16,species:"Pidgey",types:["Normal","Flying"],baseStats:{hp:40,atk:45,def:40,spa:35,spd:35,spe:56},abilities:{0:"Bad Dreams",1:"Marvel Scale"},heightm:0.3,weightkg:1.8,color:"Brown",evos:["pidgeotto"],eggGroups:["Flying"]},
pidgeotto:{num:17,species:"Pidgeotto",types:["Normal","Flying"],baseStats:{hp:63,atk:60,def:55,spa:50,spd:50,spe:71},abilities:{0:"Soundproof",1:"Oblivious"},heightm:1.1,weightkg:30,color:"Brown",prevo:"pidgey",evos:["pidgeot"],evoLevel:18,eggGroups:["Flying"]},
pidgeot:{num:18,species:"Pidgeot",types:["Normal","Flying"],baseStats:{hp:83,atk:80,def:75,spa:70,spd:70,spe:91},abilities:{0:"Cute Charm",1:"Magma Armor"},heightm:1.5,weightkg:39.5,color:"Brown",prevo:"pidgeotto",evoLevel:36,eggGroups:["Flying"]},
rattata:{num:19,species:"Rattata",types:["Normal"],baseStats:{hp:30,atk:56,def:35,spa:25,spd:35,spe:72},abilities:{0:"Mummy",1:"Toxic Boost"},heightm:0.3,weightkg:3.5,color:"Purple",evos:["raticate"],eggGroups:["Ground"]},
raticate:{num:20,species:"Raticate",types:["Normal"],baseStats:{hp:55,atk:81,def:60,spa:50,spd:70,spe:97},abilities:{0:"Compoundeyes",1:"Illusion"},heightm:0.7,weightkg:18.5,color:"Brown",prevo:"rattata",evoLevel:20,eggGroups:["Ground"]},
spearow:{num:21,species:"Spearow",types:["Normal","Flying"],baseStats:{hp:40,atk:60,def:30,spa:31,spd:31,spe:70},abilities:{0:"Moxie",1:"Flame Body"},heightm:0.3,weightkg:2,color:"Brown",evos:["fearow"],eggGroups:["Flying"]},
fearow:{num:22,species:"Fearow",types:["Normal","Flying"],baseStats:{hp:65,atk:90,def:65,spa:61,spd:61,spe:100},abilities:{0:"Clear Body",1:"Trace"},heightm:1.2,weightkg:38,color:"Brown",prevo:"spearow",evoLevel:20,eggGroups:["Flying"]},
ekans:{num:23,species:"Ekans",types:["Poison"],baseStats:{hp:35,atk:60,def:44,spa:40,spd:54,spe:55},abilities:{0:"Defiant",1:"Shield Dust"},heightm:2,weightkg:6.9,color:"Purple",evos:["arbok"],eggGroups:["Ground","Dragon"]},
arbok:{num:24,species:"Arbok",types:["Poison"],baseStats:{hp:60,atk:85,def:69,spa:65,spd:79,spe:80},abilities:{0:"Thick Fat",1:"Quick Feet"},heightm:3.5,weightkg:65,color:"Purple",prevo:"ekans",evoLevel:22,eggGroups:["Ground","Dragon"]},
pichu:{num:172,species:"Pichu",types:["Electric"],baseStats:{hp:20,atk:40,def:15,spa:35,spd:35,spe:60},abilities:{0:"Soundproof",1:"Analytic"},heightm:0.3,weightkg:2,color:"Yellow",evos:["pikachu"],eggGroups:["No Eggs"],otherFormes:["pichuspikyeared"]},
pichuspikyeared:{num:172,species:"Pichu-Spiky-eared",baseSpecies:"Pichu",forme:"Spiky-eared",formeLetter:"S",types:["Electric"],baseStats:{hp:20,atk:40,def:15,spa:35,spd:35,spe:60},abilities:{0:"Soundproof",1:"Analytic"},heightm:0.3,weightkg:2,color:"Yellow",evos:["pikachu"],eggGroups:["No Eggs"]},
raichu:{num:26,species:"Raichu",types:["Electric"],baseStats:{hp:60,atk:90,def:55,spa:90,spd:80,spe:100},abilities:{0:"Magic Bounce",1:"Battle Armor"},heightm:0.8,weightkg:30,color:"Yellow",prevo:"pikachu",evoLevel:1,eggGroups:["Ground","Fairy"]},
pikachu:{num:25,species:"Pikachu",types:["Electric"],baseStats:{hp:35,atk:55,def:30,spa:50,spd:40,spe:90},abilities:{0:"Infiltrator",1:"Sturdy"},heightm:0.4,weightkg:6,color:"Yellow",prevo:"pichu",evos:["raichu"],evoLevel:1,eggGroups:["Ground","Fairy"]},
sandshrew:{num:27,species:"Sandshrew",types:["Ground"],baseStats:{hp:50,atk:75,def:85,spa:20,spd:30,spe:40},abilities:{0:"Magma Armor",1:"Magic Guard"},heightm:0.6,weightkg:12,color:"Yellow",evos:["sandslash"],eggGroups:["Ground"]},
sandslash:{num:28,species:"Sandslash",types:["Ground"],baseStats:{hp:75,atk:100,def:110,spa:45,spd:55,spe:65},abilities:{0:"Infiltrator",1:"Sheer Force"},heightm:1,weightkg:29.5,color:"Yellow",prevo:"sandshrew",evoLevel:22,eggGroups:["Ground"]},
nidoranf:{num:29,species:"NidoranF",types:["Poison"],gender:"F",baseStats:{hp:55,atk:47,def:52,spa:40,spd:40,spe:41},abilities:{0:"Poison Touch",1:"Bad Dreams"},heightm:0.4,weightkg:7,color:"Blue",evos:["nidorina"],eggGroups:["Monster","Ground"]},
nidorina:{num:30,species:"Nidorina",types:["Poison"],gender:"F",baseStats:{hp:70,atk:62,def:67,spa:55,spd:55,spe:56},abilities:{0:"Rock Head",1:"Chlorophyll"},heightm:0.8,weightkg:20,color:"Blue",prevo:"nidoranf",evos:["nidoqueen"],evoLevel:16,eggGroups:["No Eggs"]},
nidoqueen:{num:31,species:"Nidoqueen",types:["Poison","Ground"],gender:"F",baseStats:{hp:90,atk:82,def:87,spa:75,spd:85,spe:76},abilities:{0:"Pressure",1:"Clear Body"},heightm:1.3,weightkg:60,color:"Blue",prevo:"nidorina",evoLevel:1,eggGroups:["No Eggs"]},
nidoranm:{num:32,species:"NidoranM",types:["Poison"],gender:"M",baseStats:{hp:46,atk:57,def:40,spa:40,spd:40,spe:50},abilities:{0:"Limber",1:"Big Pecks"},heightm:0.5,weightkg:9,color:"Purple",evos:["nidorino"],eggGroups:["Monster","Ground"]},
nidorino:{num:33,species:"Nidorino",types:["Poison"],gender:"M",baseStats:{hp:61,atk:72,def:57,spa:55,spd:55,spe:65},abilities:{0:"Marvel Scale",1:"Drought"},heightm:0.9,weightkg:19.5,color:"Purple",prevo:"nidoranm",evos:["nidoking"],evoLevel:16,eggGroups:["Monster","Ground"]},
nidoking:{num:34,species:"Nidoking",types:["Poison","Ground"],gender:"M",baseStats:{hp:81,atk:92,def:77,spa:85,spd:75,spe:85},abilities:{0:"Shield Dust",1:"Hyper Cutter"},heightm:1.4,weightkg:62,color:"Purple",prevo:"nidorino",evoLevel:1,eggGroups:["Monster","Ground"]},
cleffa:{num:173,species:"Cleffa",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:25,def:28,spa:45,spd:55,spe:15},abilities:{0:"Gluttony",1:"Sticky Hold"},heightm:0.3,weightkg:3,color:"Pink",evos:["clefairy"],eggGroups:["No Eggs"]},
clefairy:{num:35,species:"Clefairy",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:45,def:48,spa:60,spd:65,spe:35},abilities:{0:"Pickpocket",1:"Prankster"},heightm:0.6,weightkg:7.5,color:"Pink",prevo:"cleffa",evos:["clefable"],evoLevel:1,eggGroups:["Fairy"]},
clefable:{num:36,species:"Clefable",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:95,atk:70,def:73,spa:85,spd:90,spe:60},abilities:{0:"Infiltrator",1:"Suction Cups"},heightm:1.3,weightkg:40,color:"Pink",prevo:"clefairy",evoLevel:1,eggGroups:["Fairy"]},
vulpix:{num:37,species:"Vulpix",types:["Fire"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:38,atk:41,def:40,spa:50,spd:65,spe:65},abilities:{0:"Toxic Boost",1:"Soundproof"},heightm:0.6,weightkg:9.9,color:"Brown",evos:["ninetales"],eggGroups:["Ground"]},
ninetales:{num:38,species:"Ninetales",types:["Fire"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:73,atk:76,def:75,spa:81,spd:100,spe:100},abilities:{0:"Sand Veil",1:"Hyper Cutter"},heightm:1.1,weightkg:19.9,color:"Yellow",prevo:"vulpix",evoLevel:1,eggGroups:["Ground"]},
igglybuff:{num:174,species:"Igglybuff",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:90,atk:30,def:15,spa:40,spd:20,spe:15},abilities:{0:"Gluttony",1:"Overgrow"},heightm:0.3,weightkg:1,color:"Pink",evos:["jigglypuff"],eggGroups:["No Eggs"]},
jigglypuff:{num:39,species:"Jigglypuff",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:115,atk:45,def:20,spa:45,spd:25,spe:20},abilities:{0:"Gluttony",1:"Color Change"},heightm:0.5,weightkg:5.5,color:"Pink",prevo:"igglybuff",evos:["wigglytuff"],evoLevel:1,eggGroups:["Fairy"]},
wigglytuff:{num:40,species:"Wigglytuff",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:140,atk:70,def:45,spa:75,spd:50,spe:45},abilities:{0:"Tinted Lens",1:"Multiscale"},heightm:1,weightkg:12,color:"Pink",prevo:"jigglypuff",evoLevel:1,eggGroups:["Fairy"]},
zubat:{num:41,species:"Zubat",types:["Poison","Flying"],baseStats:{hp:40,atk:45,def:35,spa:30,spd:40,spe:55},abilities:{0:"Prankster",1:"Snow Cloak"},heightm:0.8,weightkg:7.5,color:"Purple",evos:["golbat"],eggGroups:["Flying"]},
golbat:{num:42,species:"Golbat",types:["Poison","Flying"],baseStats:{hp:75,atk:80,def:70,spa:65,spd:75,spe:90},abilities:{0:"Simple",1:"Rock Head"},heightm:1.6,weightkg:55,color:"Purple",prevo:"zubat",evos:["crobat"],evoLevel:22,eggGroups:["Flying"]},
crobat:{num:169,species:"Crobat",types:["Poison","Flying"],baseStats:{hp:85,atk:90,def:80,spa:70,spd:80,spe:130},abilities:{0:"Solid Rock",1:"Trace"},heightm:1.8,weightkg:75,color:"Purple",prevo:"golbat",evoLevel:1,eggGroups:["Flying"]},
oddish:{num:43,species:"Oddish",types:["Grass","Poison"],baseStats:{hp:45,atk:50,def:55,spa:75,spd:65,spe:30},abilities:{0:"Tinted Lens",1:"Cute Charm"},heightm:0.5,weightkg:5.4,color:"Blue",evos:["gloom"],eggGroups:["Plant"]},
gloom:{num:44,species:"Gloom",types:["Grass","Poison"],baseStats:{hp:60,atk:65,def:70,spa:85,spd:75,spe:40},abilities:{0:"Drought",1:"Volt Absorb"},heightm:0.8,weightkg:8.6,color:"Blue",prevo:"oddish",evos:["vileplume","bellossom"],evoLevel:21,eggGroups:["Plant"]},
vileplume:{num:45,species:"Vileplume",types:["Grass","Poison"],baseStats:{hp:75,atk:80,def:85,spa:100,spd:90,spe:50},abilities:{0:"Thick Fat",1:"Steadfast"},heightm:1.2,weightkg:18.6,color:"Red",prevo:"gloom",evoLevel:1,eggGroups:["Plant"]},
bellossom:{num:182,species:"Bellossom",types:["Grass"],baseStats:{hp:75,atk:80,def:85,spa:90,spd:100,spe:50},abilities:{0:"Oblivious",1:"Clear Body"},heightm:0.4,weightkg:5.8,color:"Green",prevo:"gloom",evoLevel:1,eggGroups:["Plant"]},
paras:{num:46,species:"Paras",types:["Bug","Grass"],baseStats:{hp:35,atk:70,def:55,spa:45,spd:55,spe:25},abilities:{0:"Stall",1:"Lightningrod"},heightm:0.3,weightkg:5.4,color:"Red",evos:["parasect"],eggGroups:["Bug","Plant"]},
parasect:{num:47,species:"Parasect",types:["Bug","Grass"],baseStats:{hp:60,atk:95,def:80,spa:60,spd:80,spe:30},abilities:{0:"Motor Drive",1:"Quick Feet"},heightm:1,weightkg:29.5,color:"Red",prevo:"paras",evoLevel:24,eggGroups:["Bug","Plant"]},
venonat:{num:48,species:"Venonat",types:["Bug","Poison"],baseStats:{hp:60,atk:55,def:50,spa:40,spd:55,spe:45},abilities:{0:"Heatproof",1:"Quick Feet"},heightm:1,weightkg:30,color:"Purple",evos:["venomoth"],eggGroups:["Bug"]},
venomoth:{num:49,species:"Venomoth",types:["Bug","Poison"],baseStats:{hp:70,atk:65,def:60,spa:90,spd:75,spe:90},abilities:{0:"Thick Fat",1:"Imposter"},heightm:1.5,weightkg:12.5,color:"Purple",prevo:"venonat",evoLevel:31,eggGroups:["Bug"]},
diglett:{num:50,species:"Diglett",types:["Ground"],baseStats:{hp:10,atk:55,def:25,spa:35,spd:45,spe:95},abilities:{0:"Marvel Scale",1:"Stall"},heightm:0.2,weightkg:0.8,color:"Brown",evos:["dugtrio"],eggGroups:["Ground"]},
dugtrio:{num:51,species:"Dugtrio",types:["Ground"],baseStats:{hp:35,atk:80,def:50,spa:50,spd:70,spe:120},abilities:{0:"Poison Heal",1:"Color Change"},heightm:0.7,weightkg:33.3,color:"Brown",prevo:"diglett",evoLevel:26,eggGroups:["Ground"]},
meowth:{num:52,species:"Meowth",types:["Normal"],baseStats:{hp:40,atk:45,def:35,spa:40,spd:40,spe:90},abilities:{0:"Poison Point",1:"Serene Grace"},heightm:0.4,weightkg:4.2,color:"Yellow",evos:["persian"],eggGroups:["Ground"]},
persian:{num:53,species:"Persian",types:["Normal"],baseStats:{hp:65,atk:70,def:60,spa:65,spd:65,spe:115},abilities:{0:"Poison Point",1:"Snow Cloak"},heightm:1,weightkg:32,color:"Yellow",prevo:"meowth",evoLevel:28,eggGroups:["Ground"]},
psyduck:{num:54,species:"Psyduck",types:["Water"],baseStats:{hp:50,atk:52,def:48,spa:65,spd:50,spe:55},abilities:{0:"Trace",1:"Suction Cups"},heightm:0.8,weightkg:19.6,color:"Yellow",evos:["golduck"],eggGroups:["Water 1","Ground"]},
golduck:{num:55,species:"Golduck",types:["Water"],baseStats:{hp:80,atk:82,def:78,spa:95,spd:80,spe:85},abilities:{0:"Drizzle",1:"Immunity"},heightm:1.7,weightkg:76.6,color:"Blue",prevo:"psyduck",evoLevel:33,eggGroups:["Water 1","Ground"]},
mankey:{num:56,species:"Mankey",types:["Fighting"],baseStats:{hp:40,atk:80,def:35,spa:35,spd:45,spe:70},abilities:{0:"Sand Veil",1:"Arena Trap"},heightm:0.5,weightkg:28,color:"Brown",evos:["primeape"],eggGroups:["Ground"]},
primeape:{num:57,species:"Primeape",types:["Fighting"],baseStats:{hp:65,atk:105,def:60,spa:60,spd:70,spe:95},abilities:{0:"Poison Heal",1:"Soundproof"},heightm:1,weightkg:32,color:"Brown",prevo:"mankey",evoLevel:28,eggGroups:["Ground"]},
growlithe:{num:58,species:"Growlithe",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:55,atk:70,def:45,spa:70,spd:50,spe:60},abilities:{0:"Hustle",1:"Shed Skin"},heightm:0.7,weightkg:19,color:"Brown",evos:["arcanine"],eggGroups:["Ground"]},
arcanine:{num:59,species:"Arcanine",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:90,atk:110,def:80,spa:100,spd:80,spe:95},abilities:{0:"Cute Charm",1:"Illusion"},heightm:1.9,weightkg:155,color:"Brown",prevo:"growlithe",evoLevel:1,eggGroups:["Ground"]},
poliwag:{num:60,species:"Poliwag",types:["Water"],baseStats:{hp:40,atk:50,def:40,spa:40,spd:40,spe:90},abilities:{0:"Oblivious",1:"Thick Fat"},heightm:0.6,weightkg:12.4,color:"Blue",evos:["poliwhirl"],eggGroups:["Water 1"]},
poliwhirl:{num:61,species:"Poliwhirl",types:["Water"],baseStats:{hp:65,atk:65,def:65,spa:50,spd:50,spe:90},abilities:{0:"Solid Rock",1:"Magic Guard"},heightm:1,weightkg:20,color:"Blue",prevo:"poliwag",evos:["poliwrath","politoed"],evoLevel:25,eggGroups:["Water 1"]},
poliwrath:{num:62,species:"Poliwrath",types:["Water","Fighting"],baseStats:{hp:90,atk:85,def:95,spa:70,spd:90,spe:70},abilities:{0:"Poison Heal",1:"Magma Armor"},heightm:1.3,weightkg:54,color:"Blue",prevo:"poliwhirl",evoLevel:1,eggGroups:["Water 1"]},
politoed:{num:186,species:"Politoed",types:["Water"],baseStats:{hp:90,atk:75,def:75,spa:90,spd:100,spe:70},abilities:{0:"Klutz",1:"Magic Bounce"},heightm:1.1,weightkg:33.9,color:"Green",prevo:"poliwhirl",evoLevel:1,eggGroups:["Water 1"]},
abra:{num:63,species:"Abra",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:25,atk:20,def:15,spa:105,spd:55,spe:90},abilities:{0:"Sand Stream",1:"Anticipation"},heightm:0.9,weightkg:19.5,color:"Brown",evos:["kadabra"],eggGroups:["Humanshape"]},
kadabra:{num:64,species:"Kadabra",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:40,atk:35,def:30,spa:120,spd:70,spe:105},abilities:{0:"Leaf Guard",1:"Hustle"},heightm:1.3,weightkg:56.5,color:"Brown",prevo:"abra",evos:["alakazam"],evoLevel:16,eggGroups:["Humanshape"]},
alakazam:{num:65,species:"Alakazam",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:55,atk:50,def:45,spa:135,spd:85,spe:120},abilities:{0:"Multiscale",1:"Snow Cloak"},heightm:1.5,weightkg:48,color:"Brown",prevo:"kadabra",evoLevel:1,eggGroups:["Humanshape"]},
machop:{num:66,species:"Machop",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:70,atk:80,def:50,spa:35,spd:35,spe:35},abilities:{0:"Frisk",1:"Unburden"},heightm:0.8,weightkg:19.5,color:"Gray",evos:["machoke"],eggGroups:["Humanshape"]},
machoke:{num:67,species:"Machoke",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:80,atk:100,def:70,spa:50,spd:60,spe:45},abilities:{0:"Rain Dish",1:"Infiltrator"},heightm:1.5,weightkg:70.5,color:"Gray",prevo:"machop",evos:["machamp"],evoLevel:28,eggGroups:["Humanshape"]},
machamp:{num:68,species:"Machamp",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:90,atk:130,def:80,spa:65,spd:85,spe:55},abilities:{0:"Iron Barbs",1:"Tangled Feet"},heightm:1.6,weightkg:130,color:"Gray",prevo:"machoke",evoLevel:1,eggGroups:["Humanshape"]},
bellsprout:{num:69,species:"Bellsprout",types:["Grass","Poison"],baseStats:{hp:50,atk:75,def:35,spa:70,spd:30,spe:40},abilities:{0:"Sand Rush",1:"Unnerve"},heightm:0.7,weightkg:4,color:"Green",evos:["weepinbell"],eggGroups:["Plant"]},
weepinbell:{num:70,species:"Weepinbell",types:["Grass","Poison"],baseStats:{hp:65,atk:90,def:50,spa:85,spd:45,spe:55},abilities:{0:"Rattled",1:"Snow Warning"},heightm:1,weightkg:6.4,color:"Green",prevo:"bellsprout",evos:["victreebel"],evoLevel:21,eggGroups:["Plant"]},
victreebel:{num:71,species:"Victreebel",types:["Grass","Poison"],baseStats:{hp:80,atk:105,def:65,spa:100,spd:60,spe:70},abilities:{0:"Magic Bounce",1:"Storm Drain"},heightm:1.7,weightkg:15.5,color:"Green",prevo:"weepinbell",evoLevel:1,eggGroups:["Plant"]},
tentacool:{num:72,species:"Tentacool",types:["Water","Poison"],baseStats:{hp:40,atk:40,def:35,spa:50,spd:100,spe:70},abilities:{0:"Leaf Guard",1:"Storm Drain"},heightm:0.9,weightkg:45.5,color:"Blue",evos:["tentacruel"],eggGroups:["Water 3"]},
tentacruel:{num:73,species:"Tentacruel",types:["Water","Poison"],baseStats:{hp:80,atk:70,def:65,spa:80,spd:120,spe:100},abilities:{0:"Ice Body",1:"No Guard"},heightm:1.6,weightkg:55,color:"Blue",prevo:"tentacool",evoLevel:30,eggGroups:["Water 3"]},
geodude:{num:74,species:"Geodude",types:["Rock","Ground"],baseStats:{hp:40,atk:80,def:100,spa:30,spd:30,spe:20},abilities:{0:"Pure Power",1:"Leaf Guard"},heightm:0.4,weightkg:20,color:"Brown",evos:["graveler"],eggGroups:["Mineral"]},
graveler:{num:75,species:"Graveler",types:["Rock","Ground"],baseStats:{hp:55,atk:95,def:115,spa:45,spd:45,spe:35},abilities:{0:"Steadfast",1:"Water Veil"},heightm:1,weightkg:105,color:"Brown",prevo:"geodude",evos:["golem"],evoLevel:25,eggGroups:["Mineral"]},
golem:{num:76,species:"Golem",types:["Rock","Ground"],baseStats:{hp:80,atk:110,def:130,spa:55,spd:65,spe:45},abilities:{0:"Unburden",1:"Magic Bounce"},heightm:1.4,weightkg:300,color:"Brown",prevo:"graveler",evoLevel:1,eggGroups:["Mineral"]},
ponyta:{num:77,species:"Ponyta",types:["Fire"],baseStats:{hp:50,atk:85,def:55,spa:65,spd:65,spe:90},abilities:{0:"Moxie",1:"Synchronize"},heightm:1,weightkg:30,color:"Yellow",evos:["rapidash"],eggGroups:["Ground"]},
rapidash:{num:78,species:"Rapidash",types:["Fire"],baseStats:{hp:65,atk:100,def:70,spa:80,spd:80,spe:105},abilities:{0:"Intimidate",1:"Hyper Cutter"},heightm:1.7,weightkg:95,color:"Yellow",prevo:"ponyta",evoLevel:40,eggGroups:["Ground"]},
slowpoke:{num:79,species:"Slowpoke",types:["Water","Psychic"],baseStats:{hp:90,atk:65,def:65,spa:40,spd:40,spe:15},abilities:{0:"Prankster",1:"Pickpocket"},heightm:1.2,weightkg:36,color:"Pink",evos:["slowbro","slowking"],eggGroups:["Monster","Water 1"]},
slowbro:{num:80,species:"Slowbro",types:["Water","Psychic"],baseStats:{hp:95,atk:75,def:110,spa:100,spd:80,spe:30},abilities:{0:"Water Veil",1:"Unnerve"},heightm:1.6,weightkg:78.5,color:"Pink",prevo:"slowpoke",evoLevel:37,eggGroups:["Monster","Water 1"]},
slowking:{num:199,species:"Slowking",types:["Water","Psychic"],baseStats:{hp:95,atk:75,def:80,spa:100,spd:110,spe:30},abilities:{0:"Harvest",1:"Torrent"},heightm:2,weightkg:79.5,color:"Pink",prevo:"slowpoke",evoLevel:1,eggGroups:["Monster","Water 1"]},
magnemite:{num:81,species:"Magnemite",types:["Electric","Steel"],gender:"N",baseStats:{hp:25,atk:35,def:70,spa:95,spd:55,spe:45},abilities:{0:"Liquid Ooze",1:"Insomnia"},heightm:0.3,weightkg:6,color:"Gray",evos:["magneton"],eggGroups:["Mineral"]},
magneton:{num:82,species:"Magneton",types:["Electric","Steel"],gender:"N",baseStats:{hp:50,atk:60,def:95,spa:120,spd:70,spe:70},abilities:{0:"Solid Rock",1:"Sand Force"},heightm:1,weightkg:60,color:"Gray",prevo:"magnemite",evos:["magnezone"],evoLevel:30,eggGroups:["Mineral"]},
magnezone:{num:462,species:"Magnezone",types:["Electric","Steel"],gender:"N",baseStats:{hp:70,atk:70,def:115,spa:130,spd:90,spe:60},abilities:{0:"Reckless",1:"Swift Swim"},heightm:1.2,weightkg:180,color:"Gray",prevo:"magneton",evoLevel:1,eggGroups:["Mineral"]},
farfetchd:{num:83,species:"Farfetch'd",types:["Normal","Flying"],baseStats:{hp:52,atk:65,def:55,spa:58,spd:62,spe:60},abilities:{0:"Marvel Scale",1:"Snow Cloak"},heightm:0.8,weightkg:15,color:"Brown",eggGroups:["Flying","Ground"]},
doduo:{num:84,species:"Doduo",types:["Normal","Flying"],baseStats:{hp:35,atk:85,def:45,spa:35,spd:35,spe:75},abilities:{0:"Flash Fire",1:"Arena Trap"},heightm:1.4,weightkg:39.2,color:"Brown",evos:["dodrio"],eggGroups:["Flying"]},
dodrio:{num:85,species:"Dodrio",types:["Normal","Flying"],baseStats:{hp:60,atk:110,def:70,spa:60,spd:60,spe:100},abilities:{0:"Wonder Guard",1:"Sticky Hold"},heightm:1.8,weightkg:85.2,color:"Brown",prevo:"doduo",evoLevel:31,eggGroups:["Flying"]},
seel:{num:86,species:"Seel",types:["Water"],baseStats:{hp:65,atk:45,def:55,spa:45,spd:70,spe:45},abilities:{0:"Insomnia",1:"Flame Body"},heightm:1.1,weightkg:90,color:"White",evos:["dewgong"],eggGroups:["Water 1","Ground"]},
dewgong:{num:87,species:"Dewgong",types:["Water","Ice"],baseStats:{hp:90,atk:70,def:80,spa:70,spd:95,spe:70},abilities:{0:"Frisk",1:"Sand Veil"},heightm:1.7,weightkg:120,color:"White",prevo:"seel",evoLevel:34,eggGroups:["Water 1","Ground"]},
grimer:{num:88,species:"Grimer",types:["Poison"],baseStats:{hp:80,atk:80,def:50,spa:40,spd:50,spe:25},abilities:{0:"Drizzle",1:"Magic Bounce"},heightm:0.9,weightkg:30,color:"Purple",evos:["muk"],eggGroups:["Indeterminate"]},
muk:{num:89,species:"Muk",types:["Poison"],baseStats:{hp:105,atk:105,def:75,spa:65,spd:100,spe:50},abilities:{0:"Infiltrator",1:"Levitate"},heightm:1.2,weightkg:30,color:"Purple",prevo:"grimer",evoLevel:38,eggGroups:["Indeterminate"]},
shellder:{num:90,species:"Shellder",types:["Water"],baseStats:{hp:30,atk:65,def:100,spa:45,spd:25,spe:40},abilities:{0:"Iron Barbs",1:"Drizzle"},heightm:0.3,weightkg:4,color:"Purple",evos:["cloyster"],eggGroups:["Water 3"]},
cloyster:{num:91,species:"Cloyster",types:["Water","Ice"],baseStats:{hp:50,atk:95,def:180,spa:85,spd:45,spe:70},abilities:{0:"Inner Focus",1:"Wonder Skin"},heightm:1.5,weightkg:132.5,color:"Purple",prevo:"shellder",evoLevel:1,eggGroups:["Water 3"]},
gastly:{num:92,species:"Gastly",types:["Ghost","Poison"],baseStats:{hp:30,atk:35,def:30,spa:100,spd:35,spe:80},abilities:{0:"Sand Veil",1:"Chlorophyll"},heightm:1.3,weightkg:0.1,color:"Purple",evos:["haunter"],eggGroups:["Indeterminate"]},
haunter:{num:93,species:"Haunter",types:["Ghost","Poison"],baseStats:{hp:45,atk:50,def:45,spa:115,spd:55,spe:95},abilities:{0:"Technician",1:"Aftermath"},heightm:1.6,weightkg:0.1,color:"Purple",prevo:"gastly",evos:["gengar"],evoLevel:25,eggGroups:["Indeterminate"]},
gengar:{num:94,species:"Gengar",types:["Ghost","Poison"],baseStats:{hp:60,atk:65,def:60,spa:130,spd:75,spe:110},abilities:{0:"Swift Swim",1:"Heavy Metal"},heightm:1.5,weightkg:40.5,color:"Purple",prevo:"haunter",evoLevel:1,eggGroups:["Indeterminate"]},
onix:{num:95,species:"Onix",types:["Rock","Ground"],baseStats:{hp:35,atk:45,def:160,spa:30,spd:45,spe:70},abilities:{0:"Sand Veil",1:"Cute Charm"},heightm:8.8,weightkg:210,color:"Gray",evos:["steelix"],eggGroups:["Mineral"]},
steelix:{num:208,species:"Steelix",types:["Steel","Ground"],baseStats:{hp:75,atk:85,def:200,spa:55,spd:65,spe:30},abilities:{0:"Multiscale",1:"Anticipation"},heightm:9.2,weightkg:400,color:"Gray",prevo:"onix",evoLevel:1,eggGroups:["Mineral"]},
drowzee:{num:96,species:"Drowzee",types:["Psychic"],baseStats:{hp:60,atk:48,def:45,spa:43,spd:90,spe:42},abilities:{0:"Tangled Feet",1:"Sniper"},heightm:1,weightkg:32.4,color:"Yellow",evos:["hypno"],eggGroups:["Humanshape"]},
hypno:{num:97,species:"Hypno",types:["Psychic"],baseStats:{hp:85,atk:73,def:70,spa:73,spd:115,spe:67},abilities:{0:"Solar Power",1:"Technician"},heightm:1.6,weightkg:75.6,color:"Yellow",prevo:"drowzee",evoLevel:26,eggGroups:["Humanshape"]},
krabby:{num:98,species:"Krabby",types:["Water"],baseStats:{hp:30,atk:105,def:90,spa:25,spd:25,spe:50},abilities:{0:"Iron Barbs",1:"Tangled Feet"},heightm:0.4,weightkg:6.5,color:"Red",evos:["kingler"],eggGroups:["Water 3"]},
kingler:{num:99,species:"Kingler",types:["Water"],baseStats:{hp:55,atk:130,def:115,spa:50,spd:50,spe:75},abilities:{0:"Sturdy",1:"Color Change"},heightm:1.3,weightkg:60,color:"Red",prevo:"krabby",evoLevel:28,eggGroups:["Water 3"]},
voltorb:{num:100,species:"Voltorb",types:["Electric"],gender:"N",baseStats:{hp:40,atk:30,def:50,spa:55,spd:55,spe:100},abilities:{0:"Big Pecks",1:"Early Bird"},heightm:0.5,weightkg:10.4,color:"Red",evos:["electrode"],eggGroups:["Mineral"]},
electrode:{num:101,species:"Electrode",types:["Electric"],gender:"N",baseStats:{hp:60,atk:50,def:70,spa:80,spd:80,spe:140},abilities:{0:"Shadow Tag",1:"Levitate"},heightm:1.2,weightkg:66.6,color:"Red",prevo:"voltorb",evoLevel:30,eggGroups:["Mineral"]},
exeggcute:{num:102,species:"Exeggcute",types:["Grass","Psychic"],baseStats:{hp:60,atk:40,def:80,spa:60,spd:45,spe:40},abilities:{0:"Cute Charm",1:"Forewarn"},heightm:0.4,weightkg:2.5,color:"Pink",evos:["exeggutor"],eggGroups:["Plant"]},
exeggutor:{num:103,species:"Exeggutor",types:["Grass","Psychic"],baseStats:{hp:95,atk:95,def:85,spa:125,spd:65,spe:55},abilities:{0:"Rain Dish",1:"Mold Breaker"},heightm:2,weightkg:120,color:"Yellow",prevo:"exeggcute",evoLevel:1,eggGroups:["Plant"]},
cubone:{num:104,species:"Cubone",types:["Ground"],baseStats:{hp:50,atk:50,def:95,spa:40,spd:50,spe:35},abilities:{0:"Marvel Scale",1:"Blaze"},heightm:0.4,weightkg:6.5,color:"Brown",evos:["marowak"],eggGroups:["Monster"]},
marowak:{num:105,species:"Marowak",types:["Ground"],baseStats:{hp:60,atk:80,def:110,spa:50,spd:80,spe:45},abilities:{0:"Scrappy",1:"Magic Bounce"},heightm:1,weightkg:45,color:"Brown",prevo:"cubone",evoLevel:28,eggGroups:["Monster"]},
tyrogue:{num:236,species:"Tyrogue",types:["Fighting"],gender:"M",baseStats:{hp:35,atk:35,def:35,spa:35,spd:35,spe:35},abilities:{0:"Flare Boost",1:"Imposter"},heightm:0.7,weightkg:21,color:"Purple",evos:["hitmonlee","hitmonchan","hitmontop"],eggGroups:["No Eggs"]},
hitmonlee:{num:106,species:"Hitmonlee",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:120,def:53,spa:35,spd:110,spe:87},abilities:{0:"Clear Body",1:"Rain Dish"},heightm:1.5,weightkg:49.8,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Humanshape"]},
hitmonchan:{num:107,species:"Hitmonchan",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:105,def:79,spa:35,spd:110,spe:76},abilities:{0:"Weak Armor",1:"Download"},heightm:1.4,weightkg:50.2,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Humanshape"]},
hitmontop:{num:237,species:"Hitmontop",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:95,def:95,spa:35,spd:110,spe:70},abilities:{0:"Klutz",1:"Aftermath"},heightm:1.4,weightkg:48,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Humanshape"]},
lickitung:{num:108,species:"Lickitung",types:["Normal"],baseStats:{hp:90,atk:55,def:75,spa:60,spd:75,spe:30},abilities:{0:"Sticky Hold",1:"Victory Star"},heightm:1.2,weightkg:65.5,color:"Pink",evos:["lickilicky"],eggGroups:["Monster"]},
lickilicky:{num:463,species:"Lickilicky",types:["Normal"],baseStats:{hp:110,atk:85,def:95,spa:80,spd:95,spe:50},abilities:{0:"Download",1:"Arena Trap"},heightm:1.7,weightkg:140,color:"Pink",prevo:"lickitung",evoLevel:1,evoMove:"Rollout",eggGroups:["Monster"]},
koffing:{num:109,species:"Koffing",types:["Poison"],baseStats:{hp:40,atk:65,def:95,spa:60,spd:45,spe:35},abilities:{0:"Rivalry",1:"Dry Skin"},heightm:0.6,weightkg:1,color:"Purple",evos:["weezing"],eggGroups:["Indeterminate"]},
weezing:{num:110,species:"Weezing",types:["Poison"],baseStats:{hp:65,atk:90,def:120,spa:85,spd:70,spe:60},abilities:{0:"Bad Dreams",1:"Super Luck"},heightm:1.2,weightkg:9.5,color:"Purple",prevo:"koffing",evoLevel:35,eggGroups:["Indeterminate"]},
rhyhorn:{num:111,species:"Rhyhorn",types:["Ground","Rock"],baseStats:{hp:80,atk:85,def:95,spa:30,spd:30,spe:25},abilities:{0:"Cloud Nine",1:"Magnet Pull"},heightm:1,weightkg:115,color:"Gray",evos:["rhydon"],eggGroups:["Monster","Ground"]},
rhydon:{num:112,species:"Rhydon",types:["Ground","Rock"],baseStats:{hp:105,atk:130,def:120,spa:45,spd:45,spe:40},abilities:{0:"Pickpocket",1:"Poison Point"},heightm:1.9,weightkg:120,color:"Gray",prevo:"rhyhorn",evos:["rhyperior"],evoLevel:42,eggGroups:["Monster","Ground"]},
rhyperior:{num:464,species:"Rhyperior",types:["Ground","Rock"],baseStats:{hp:115,atk:140,def:130,spa:55,spd:55,spe:40},abilities:{0:"Scrappy",1:"Mummy"},heightm:2.4,weightkg:282.8,color:"Gray",prevo:"rhydon",evoLevel:1,eggGroups:["Monster","Ground"]},
happiny:{num:440,species:"Happiny",types:["Normal"],gender:"F",baseStats:{hp:100,atk:5,def:5,spa:15,spd:65,spe:30},abilities:{0:"Stench",1:"Unnerve"},heightm:0.6,weightkg:24.4,color:"Pink",evos:["chansey"],eggGroups:["No Eggs"]},
chansey:{num:113,species:"Chansey",types:["Normal"],gender:"F",baseStats:{hp:250,atk:5,def:5,spa:35,spd:105,spe:50},abilities:{0:"Liquid Ooze",1:"Static"},heightm:1.1,weightkg:34.6,color:"Pink",prevo:"happiny",evos:["blissey"],evoLevel:1,eggGroups:["Fairy"]},
blissey:{num:242,species:"Blissey",types:["Normal"],gender:"F",baseStats:{hp:255,atk:10,def:10,spa:75,spd:135,spe:55},abilities:{0:"Shed Skin",1:"Early Bird"},heightm:1.5,weightkg:46.8,color:"Pink",prevo:"chansey",evoLevel:1,eggGroups:["Fairy"]},
tangela:{num:114,species:"Tangela",types:["Grass"],baseStats:{hp:65,atk:55,def:115,spa:100,spd:40,spe:60},abilities:{0:"Insomnia",1:"Battle Armor"},heightm:1,weightkg:35,color:"Blue",evos:["tangrowth"],eggGroups:["Plant"]},
tangrowth:{num:465,species:"Tangrowth",types:["Grass"],baseStats:{hp:100,atk:100,def:125,spa:110,spd:50,spe:50},abilities:{0:"Defiant",1:"Simple"},heightm:2,weightkg:128.6,color:"Blue",prevo:"tangela",evoLevel:1,evoMove:"AncientPower",eggGroups:["Plant"]},
kangaskhan:{num:115,species:"Kangaskhan",types:["Normal"],gender:"F",baseStats:{hp:105,atk:95,def:80,spa:40,spd:80,spe:90},abilities:{0:"Light Metal",1:"Bad Dreams"},heightm:2.2,weightkg:80,color:"Brown",eggGroups:["Monster"]},
horsea:{num:116,species:"Horsea",types:["Water"],baseStats:{hp:30,atk:40,def:70,spa:70,spd:25,spe:60},abilities:{0:"Big Pecks",1:"Sandstream"},heightm:0.4,weightkg:8,color:"Blue",evos:["seadra"],eggGroups:["Water 1","Dragon"]},
seadra:{num:117,species:"Seadra",types:["Water"],baseStats:{hp:55,atk:65,def:95,spa:95,spd:45,spe:85},abilities:{0:"Snow Warning",1:"Rivalry"},heightm:1.2,weightkg:25,color:"Blue",prevo:"horsea",evos:["kingdra"],evoLevel:32,eggGroups:["Water 1","Dragon"]},
kingdra:{num:230,species:"Kingdra",types:["Water","Dragon"],baseStats:{hp:75,atk:95,def:95,spa:95,spd:95,spe:85},abilities:{0:"Cloud Nine",1:"Pickpocket"},heightm:1.8,weightkg:152,color:"Blue",prevo:"seadra",evoLevel:1,eggGroups:["Water 1","Dragon"]},
goldeen:{num:118,species:"Goldeen",types:["Water"],baseStats:{hp:45,atk:67,def:60,spa:35,spd:50,spe:63},abilities:{0:"Magic Bounce",1:"Overcoat"},heightm:0.6,weightkg:15,color:"Red",evos:["seaking"],eggGroups:["Water 2"]},
seaking:{num:119,species:"Seaking",types:["Water"],baseStats:{hp:80,atk:92,def:65,spa:65,spd:80,spe:68},abilities:{0:"Analytic",1:"Natural Cure"},heightm:1.3,weightkg:39,color:"Red",prevo:"goldeen",evoLevel:33,eggGroups:["Water 2"]},
staryu:{num:120,species:"Staryu",types:["Water"],gender:"N",baseStats:{hp:30,atk:45,def:55,spa:70,spd:55,spe:85},abilities:{0:"Limber",1:"Battle Armor"},heightm:0.8,weightkg:34.5,color:"Brown",evos:["starmie"],eggGroups:["Water 3"]},
starmie:{num:121,species:"Starmie",types:["Water","Psychic"],gender:"N",baseStats:{hp:60,atk:75,def:85,spa:100,spd:85,spe:115},abilities:{0:"Overcoat",1:"Stench"},heightm:1.1,weightkg:80,color:"Purple",prevo:"staryu",evoLevel:1,eggGroups:["Water 3"]},
mimejr:{num:439,species:"Mime Jr.",types:["Psychic"],baseStats:{hp:20,atk:25,def:45,spa:70,spd:90,spe:60},abilities:{0:"Flame Body",1:"Victory Star"},heightm:0.6,weightkg:13,color:"Pink",evos:["mrmime"],eggGroups:["No Eggs"]},
mrmime:{num:122,species:"Mr. Mime",types:["Psychic"],baseStats:{hp:40,atk:45,def:65,spa:100,spd:120,spe:90},abilities:{0:"Reckless",1:"Pressure"},heightm:1.3,weightkg:54.5,color:"Pink",prevo:"mimejr",evoLevel:1,evoMove:"Mimic",eggGroups:["Humanshape"]},
scyther:{num:123,species:"Scyther",types:["Bug","Flying"],baseStats:{hp:70,atk:110,def:80,spa:55,spd:80,spe:105},abilities:{0:"Synchronize",1:"Unburden"},heightm:1.5,weightkg:56,color:"Green",evos:["scizor"],eggGroups:["Bug"]},
scizor:{num:212,species:"Scizor",types:["Bug","Steel"],baseStats:{hp:70,atk:130,def:100,spa:55,spd:80,spe:65},abilities:{0:"Iron Barbs",1:"Magma Armor"},heightm:1.8,weightkg:118,color:"Red",prevo:"scyther",evoLevel:1,eggGroups:["Bug"]},
smoochum:{num:238,species:"Smoochum",types:["Ice","Psychic"],gender:"F",baseStats:{hp:45,atk:30,def:15,spa:85,spd:65,spe:65},abilities:{0:"Rock Head",1:"Oblivious"},heightm:0.4,weightkg:6,color:"Pink",evos:["jynx"],eggGroups:["No Eggs"]},
jynx:{num:124,species:"Jynx",types:["Ice","Psychic"],gender:"F",baseStats:{hp:65,atk:50,def:35,spa:115,spd:95,spe:95},abilities:{0:"Reckless",1:"Harvest"},heightm:1.4,weightkg:40.6,color:"Red",prevo:"smoochum",evoLevel:30,eggGroups:["Humanshape"]},
elekid:{num:239,species:"Elekid",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:45,atk:63,def:37,spa:65,spd:55,spe:95},abilities:{0:"Wonder Guard",1:"Unaware"},heightm:0.6,weightkg:23.5,color:"Yellow",evos:["electabuzz"],eggGroups:["No Eggs"]},
electabuzz:{num:125,species:"Electabuzz",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:65,atk:83,def:57,spa:95,spd:85,spe:105},abilities:{0:"Adaptability",1:"Poison Heal"},heightm:1.1,weightkg:30,color:"Yellow",prevo:"elekid",evos:["electivire"],evoLevel:30,eggGroups:["Humanshape"]},
electivire:{num:466,species:"Electivire",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:123,def:67,spa:95,spd:85,spe:95},abilities:{0:"Adaptability",1:"Toxic Boost"},heightm:1.8,weightkg:138.6,color:"Yellow",prevo:"electabuzz",evoLevel:1,eggGroups:["Humanshape"]},
magby:{num:240,species:"Magby",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:45,atk:75,def:37,spa:70,spd:55,spe:83},abilities:{0:"Static",1:"Adaptability"},heightm:0.7,weightkg:21.4,color:"Red",evos:["magmar"],eggGroups:["No Eggs"]},
magmar:{num:126,species:"Magmar",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:65,atk:95,def:57,spa:100,spd:85,spe:93},abilities:{0:"Marvel Scale",1:"Cloud Nine"},heightm:1.3,weightkg:44.5,color:"Red",prevo:"magby",evos:["magmortar"],evoLevel:30,eggGroups:["Humanshape"]},
magmortar:{num:467,species:"Magmortar",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:95,def:67,spa:125,spd:95,spe:83},abilities:{0:"Immunity",1:"Cloud Nine"},heightm:1.6,weightkg:68,color:"Red",prevo:"magmar",evoLevel:1,eggGroups:["Humanshape"]},
pinsir:{num:127,species:"Pinsir",types:["Bug"],baseStats:{hp:65,atk:125,def:100,spa:55,spd:70,spe:85},abilities:{0:"Super Luck",1:"Flame Body"},heightm:1.5,weightkg:55,color:"Brown",eggGroups:["Bug"]},
tauros:{num:128,species:"Tauros",types:["Normal"],gender:"M",baseStats:{hp:75,atk:100,def:95,spa:40,spd:70,spe:110},abilities:{0:"Keen Eye",1:"Cloud Nine"},heightm:1.4,weightkg:88.4,color:"Brown",eggGroups:["Ground"]},
magikarp:{num:129,species:"Magikarp",types:["Water"],baseStats:{hp:20,atk:10,def:55,spa:15,spd:20,spe:80},abilities:{0:"Big Pecks",1:"Weak Armor"},heightm:0.9,weightkg:10,color:"Red",evos:["gyarados"],eggGroups:["Water 2","Dragon"]},
gyarados:{num:130,species:"Gyarados",types:["Water","Flying"],baseStats:{hp:95,atk:125,def:79,spa:60,spd:100,spe:81},abilities:{0:"Iron Barbs",1:"Solid Rock"},heightm:6.5,weightkg:235,color:"Blue",prevo:"magikarp",evoLevel:20,eggGroups:["Water 2","Dragon"]},
lapras:{num:131,species:"Lapras",types:["Water","Ice"],baseStats:{hp:130,atk:85,def:80,spa:85,spd:95,spe:60},abilities:{0:"Tangled Feet",1:"Drought"},heightm:2.5,weightkg:220,color:"Blue",eggGroups:["Monster","Water 1"]},
ditto:{num:132,species:"Ditto",types:["Normal"],gender:"N",baseStats:{hp:48,atk:48,def:48,spa:48,spd:48,spe:48},abilities:{0:"Hydration",1:"Forewarn"},heightm:0.3,weightkg:4,color:"Purple",eggGroups:["Ditto"]},
eevee:{num:133,species:"Eevee",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:55,def:50,spa:45,spd:65,spe:55},abilities:{0:"Pure Power",1:"Poison Heal"},heightm:0.3,weightkg:6.5,color:"Brown",evos:["vaporeon","jolteon","flareon","espeon","umbreon","leafeon","glaceon"],eggGroups:["Ground"]},
vaporeon:{num:134,species:"Vaporeon",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:130,atk:65,def:60,spa:110,spd:95,spe:65},abilities:{0:"Stench",1:"Leaf Guard"},heightm:1,weightkg:29,color:"Blue",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
jolteon:{num:135,species:"Jolteon",types:["Electric"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:65,def:60,spa:110,spd:95,spe:130},abilities:{0:"Magnet Pull",1:"Synchronize"},heightm:0.8,weightkg:24.5,color:"Yellow",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
flareon:{num:136,species:"Flareon",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:130,def:60,spa:95,spd:110,spe:65},abilities:{0:"Ice Body",1:"Imposter"},heightm:0.9,weightkg:25,color:"Red",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
espeon:{num:196,species:"Espeon",types:["Psychic"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:65,def:60,spa:130,spd:95,spe:110},abilities:{0:"Technician",1:"Sand Veil"},heightm:0.9,weightkg:26.5,color:"Purple",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
umbreon:{num:197,species:"Umbreon",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:65,def:110,spa:60,spd:130,spe:65},abilities:{0:"Immunity",1:"Sniper"},heightm:1,weightkg:27,color:"Black",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
leafeon:{num:470,species:"Leafeon",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:110,def:130,spa:60,spd:65,spe:95},abilities:{0:"Water Absorb",1:"Cursed Body"},heightm:1,weightkg:25.5,color:"Green",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
glaceon:{num:471,species:"Glaceon",types:["Ice"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:60,def:110,spa:130,spd:95,spe:65},abilities:{0:"Color Change",1:"Trace"},heightm:0.8,weightkg:25.9,color:"Blue",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
porygon:{num:137,species:"Porygon",types:["Normal"],gender:"N",baseStats:{hp:65,atk:60,def:70,spa:85,spd:75,spe:40},abilities:{0:"Thick Fat",1:"Aftermath"},heightm:0.8,weightkg:36.5,color:"Pink",evos:["porygon2"],eggGroups:["Mineral"]},
porygon2:{num:233,species:"Porygon2",types:["Normal"],gender:"N",baseStats:{hp:85,atk:80,def:90,spa:105,spd:95,spe:60},abilities:{0:"Battle Armor",1:"Drought"},heightm:0.6,weightkg:32.5,color:"Red",prevo:"porygon",evos:["porygonz"],evoLevel:1,eggGroups:["Mineral"]},
porygonz:{num:474,species:"Porygon-Z",types:["Normal"],gender:"N",baseStats:{hp:85,atk:80,def:70,spa:135,spd:75,spe:90},abilities:{0:"Soundproof",1:"Compoundeyes"},heightm:0.9,weightkg:34,color:"Red",prevo:"porygon2",evoLevel:1,eggGroups:["Mineral"]},
omanyte:{num:138,species:"Omanyte",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:35,atk:40,def:100,spa:90,spd:55,spe:35},abilities:{0:"Wonder Guard",1:"Aftermath"},heightm:0.4,weightkg:7.5,color:"Blue",evos:["omastar"],eggGroups:["Water 1","Water 3"]},
omastar:{num:139,species:"Omastar",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:60,def:125,spa:115,spd:70,spe:55},abilities:{0:"Light Metal",1:"Klutz"},heightm:1,weightkg:35,color:"Blue",prevo:"omanyte",evoLevel:40,eggGroups:["Water 1","Water 3"]},
kabuto:{num:140,species:"Kabuto",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:80,def:90,spa:55,spd:45,spe:55},abilities:{0:"Own Tempo",1:"Frisk"},heightm:0.5,weightkg:11.5,color:"Brown",evos:["kabutops"],eggGroups:["Water 1","Water 3"]},
kabutops:{num:141,species:"Kabutops",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:115,def:105,spa:65,spd:70,spe:80},abilities:{0:"Justified",1:"Aftermath"},heightm:1.3,weightkg:40.5,color:"Brown",prevo:"kabuto",evoLevel:40,eggGroups:["Water 1","Water 3"]},
aerodactyl:{num:142,species:"Aerodactyl",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:105,def:65,spa:60,spd:75,spe:130},abilities:{0:"Magma Armor",1:"Early Bird"},heightm:1.8,weightkg:59,color:"Purple",eggGroups:["Flying"]},
munchlax:{num:446,species:"Munchlax",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:135,atk:85,def:40,spa:40,spd:85,spe:5},abilities:{0:"Marvel Scale",1:"Drought"},heightm:0.6,weightkg:105,color:"Black",evos:["snorlax"],eggGroups:["No Eggs"]},
snorlax:{num:143,species:"Snorlax",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:160,atk:110,def:65,spa:65,spd:110,spe:30},abilities:{0:"Snow Warning",1:"Overcoat"},heightm:2.1,weightkg:460,color:"Black",prevo:"munchlax",evoLevel:1,eggGroups:["Monster"]},
articuno:{num:144,species:"Articuno",types:["Ice","Flying"],gender:"N",baseStats:{hp:90,atk:85,def:100,spa:95,spd:125,spe:85},abilities:{0:"Chlorophyll",1:"Stall"},heightm:1.7,weightkg:55.4,color:"Blue",eggGroups:["No Eggs"]},
zapdos:{num:145,species:"Zapdos",types:["Electric","Flying"],gender:"N",baseStats:{hp:90,atk:90,def:85,spa:125,spd:90,spe:100},abilities:{0:"Sniper",1:"Regenerator"},heightm:1.6,weightkg:52.6,color:"Yellow",eggGroups:["No Eggs"]},
moltres:{num:146,species:"Moltres",types:["Fire","Flying"],gender:"N",baseStats:{hp:90,atk:100,def:90,spa:125,spd:85,spe:90},abilities:{0:"Cursed Body",1:"Hyper Cutter"},heightm:2,weightkg:60,color:"Yellow",eggGroups:["No Eggs"]},
dratini:{num:147,species:"Dratini",types:["Dragon"],baseStats:{hp:41,atk:64,def:45,spa:50,spd:50,spe:50},abilities:{0:"Snow Cloak",1:"Big Pecks"},heightm:1.8,weightkg:3.3,color:"Blue",evos:["dragonair"],eggGroups:["Water 1","Dragon"]},
dragonair:{num:148,species:"Dragonair",types:["Dragon"],baseStats:{hp:61,atk:84,def:65,spa:70,spd:70,spe:70},abilities:{0:"Serene Grace",1:"Blaze"},heightm:4,weightkg:16.5,color:"Blue",prevo:"dratini",evos:["dragonite"],evoLevel:30,eggGroups:["Water 1","Dragon"]},
dragonite:{num:149,species:"Dragonite",types:["Dragon","Flying"],baseStats:{hp:91,atk:134,def:95,spa:100,spd:100,spe:80},abilities:{0:"Sand Stream",1:"Drizzle"},heightm:2.2,weightkg:210,color:"Brown",prevo:"dragonair",evoLevel:55,eggGroups:["Water 1","Dragon"]},
mewtwo:{num:150,species:"Mewtwo",types:["Psychic"],gender:"N",baseStats:{hp:106,atk:110,def:90,spa:154,spd:90,spe:130},abilities:{0:"Drizzle",1:"Prankster"},heightm:2,weightkg:122,color:"Purple",eggGroups:["No Eggs"]},
mew:{num:151,species:"Mew",types:["Psychic"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Liquid Ooze",1:"Victory Star"},heightm:0.4,weightkg:4,color:"Pink",eggGroups:["No Eggs"]},
chikorita:{num:152,species:"Chikorita",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:49,def:65,spa:49,spd:65,spe:45},abilities:{0:"Heatproof",1:"Levitate"},heightm:0.9,weightkg:6.4,color:"Green",evos:["bayleef"],eggGroups:["Monster","Plant"]},
bayleef:{num:153,species:"Bayleef",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:62,def:80,spa:63,spd:80,spe:60},abilities:{0:"Rattled",1:"Immunity"},heightm:1.2,weightkg:15.8,color:"Green",prevo:"chikorita",evos:["meganium"],evoLevel:16,eggGroups:["Monster","Plant"]},
meganium:{num:154,species:"Meganium",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:82,def:100,spa:83,spd:100,spe:80},abilities:{0:"Poison Heal",1:"Overcoat"},heightm:1.8,weightkg:100.5,color:"Green",prevo:"bayleef",evoLevel:32,eggGroups:["Monster","Plant"]},
cyndaquil:{num:155,species:"Cyndaquil",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:39,atk:52,def:43,spa:60,spd:50,spe:65},abilities:{0:"Levitate",1:"Serene Grace"},heightm:0.5,weightkg:7.9,color:"Yellow",evos:["quilava"],eggGroups:["Ground"]},
quilava:{num:156,species:"Quilava",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:58,atk:64,def:58,spa:80,spd:65,spe:80},abilities:{0:"Natural Cure",1:"Weak Armor"},heightm:0.9,weightkg:19,color:"Yellow",prevo:"cyndaquil",evos:["typhlosion"],evoLevel:14,eggGroups:["Ground"]},
typhlosion:{num:157,species:"Typhlosion",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:78,atk:84,def:78,spa:109,spd:85,spe:100},abilities:{0:"Swift Swim",1:"Poison Heal"},heightm:1.7,weightkg:79.5,color:"Yellow",prevo:"quilava",evoLevel:36,eggGroups:["Ground"]},
totodile:{num:158,species:"Totodile",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:65,def:64,spa:44,spd:48,spe:43},abilities:{0:"Technician",1:"Compoundeyes"},heightm:0.6,weightkg:9.5,color:"Blue",evos:["croconaw"],eggGroups:["Monster","Water 1"]},
croconaw:{num:159,species:"Croconaw",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:80,def:80,spa:59,spd:63,spe:58},abilities:{0:"Dry Skin",1:"Regenerator"},heightm:1.1,weightkg:25,color:"Blue",prevo:"totodile",evos:["feraligatr"],evoLevel:18,eggGroups:["Monster","Water 1"]},
feraligatr:{num:160,species:"Feraligatr",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:85,atk:105,def:100,spa:79,spd:83,spe:78},abilities:{0:"Gluttony",1:"Stench"},heightm:2.3,weightkg:88.8,color:"Blue",prevo:"croconaw",evoLevel:30,eggGroups:["Monster","Water 1"]},
sentret:{num:161,species:"Sentret",types:["Normal"],baseStats:{hp:35,atk:46,def:34,spa:35,spd:45,spe:20},abilities:{0:"Sand Rush",1:"Cute Charm"},heightm:0.8,weightkg:6,color:"Brown",evos:["furret"],eggGroups:["Ground"]},
furret:{num:162,species:"Furret",types:["Normal"],baseStats:{hp:85,atk:76,def:64,spa:45,spd:55,spe:90},abilities:{0:"Soundproof",1:"Sturdy"},heightm:1.8,weightkg:32.5,color:"Brown",prevo:"sentret",evoLevel:15,eggGroups:["Ground"]},
hoothoot:{num:163,species:"Hoothoot",types:["Normal","Flying"],baseStats:{hp:60,atk:30,def:30,spa:36,spd:56,spe:50},abilities:{0:"Soundproof",1:"Gluttony"},heightm:0.7,weightkg:21.2,color:"Brown",evos:["noctowl"],eggGroups:["Flying"]},
noctowl:{num:164,species:"Noctowl",types:["Normal","Flying"],baseStats:{hp:100,atk:50,def:50,spa:76,spd:96,spe:70},abilities:{0:"Sap Sipper",1:"Anger Point"},heightm:1.6,weightkg:40.8,color:"Brown",prevo:"hoothoot",evoLevel:20,eggGroups:["Flying"]},
ledyba:{num:165,species:"Ledyba",types:["Bug","Flying"],baseStats:{hp:40,atk:20,def:30,spa:40,spd:80,spe:55},abilities:{0:"Toxic Boost",1:"Cursed Body"},heightm:1,weightkg:10.8,color:"Red",evos:["ledian"],eggGroups:["Bug"]},
ledian:{num:166,species:"Ledian",types:["Bug","Flying"],baseStats:{hp:55,atk:35,def:50,spa:55,spd:110,spe:85},abilities:{0:"Static",1:"Clear Body"},heightm:1.4,weightkg:35.6,color:"Red",prevo:"ledyba",evoLevel:18,eggGroups:["Bug"]},
spinarak:{num:167,species:"Spinarak",types:["Bug","Poison"],baseStats:{hp:40,atk:60,def:40,spa:40,spd:40,spe:30},abilities:{0:"Mold Breaker",1:"Reckless"},heightm:0.5,weightkg:8.5,color:"Green",evos:["ariados"],eggGroups:["Bug"]},
ariados:{num:168,species:"Ariados",types:["Bug","Poison"],baseStats:{hp:70,atk:90,def:70,spa:60,spd:60,spe:40},abilities:{0:"Snow Warning",1:"Super Luck"},heightm:1.1,weightkg:33.5,color:"Red",prevo:"spinarak",evoLevel:22,eggGroups:["Bug"]},
chinchou:{num:170,species:"Chinchou",types:["Water","Electric"],baseStats:{hp:75,atk:38,def:38,spa:56,spd:56,spe:67},abilities:{0:"Technician",1:"Sand Veil"},heightm:0.5,weightkg:12,color:"Blue",evos:["lanturn"],eggGroups:["Water 2"]},
lanturn:{num:171,species:"Lanturn",types:["Water","Electric"],baseStats:{hp:125,atk:58,def:58,spa:76,spd:76,spe:67},abilities:{0:"Trace",1:"Clear Body"},heightm:1.2,weightkg:22.5,color:"Blue",prevo:"chinchou",evoLevel:27,eggGroups:["Water 2"]},
togepi:{num:175,species:"Togepi",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:35,atk:20,def:65,spa:40,spd:65,spe:20},abilities:{0:"Insomnia",1:"Anger Point"},heightm:0.3,weightkg:1.5,color:"White",evos:["togetic"],eggGroups:["No Eggs"]},
togetic:{num:176,species:"Togetic",types:["Normal","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:40,def:85,spa:80,spd:105,spe:40},abilities:{0:"Damp",1:"Mummy"},heightm:0.6,weightkg:3.2,color:"White",prevo:"togepi",evos:["togekiss"],evoLevel:1,eggGroups:["Flying","Fairy"]},
togekiss:{num:468,species:"Togekiss",types:["Normal","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:85,atk:50,def:95,spa:120,spd:115,spe:80},abilities:{0:"Intimidate",1:"Pickpocket"},heightm:1.5,weightkg:38,color:"White",prevo:"togetic",evoLevel:1,eggGroups:["Flying","Fairy"]},
natu:{num:177,species:"Natu",types:["Psychic","Flying"],baseStats:{hp:40,atk:50,def:45,spa:70,spd:45,spe:70},abilities:{0:"Water Absorb",1:"Mummy"},heightm:0.2,weightkg:2,color:"Green",evos:["xatu"],eggGroups:["Flying"]},
xatu:{num:178,species:"Xatu",types:["Psychic","Flying"],baseStats:{hp:65,atk:75,def:70,spa:95,spd:70,spe:95},abilities:{0:"Shed Skin",1:"Sand Veil"},heightm:1.5,weightkg:15,color:"Green",prevo:"natu",evoLevel:25,eggGroups:["Flying"]},
mareep:{num:179,species:"Mareep",types:["Electric"],baseStats:{hp:55,atk:40,def:40,spa:65,spd:45,spe:35},abilities:{0:"Steadfast",1:"Compoundeyes"},heightm:0.6,weightkg:7.8,color:"White",evos:["flaaffy"],eggGroups:["Monster","Ground"]},
flaaffy:{num:180,species:"Flaaffy",types:["Electric"],baseStats:{hp:70,atk:55,def:55,spa:80,spd:60,spe:45},abilities:{0:"Sand Veil",1:"Volt Absorb"},heightm:0.8,weightkg:13.3,color:"Pink",prevo:"mareep",evos:["ampharos"],evoLevel:15,eggGroups:["Monster","Ground"]},
ampharos:{num:181,species:"Ampharos",types:["Electric"],baseStats:{hp:90,atk:75,def:75,spa:115,spd:90,spe:55},abilities:{0:"Rivalry",1:"Snow Cloak"},heightm:1.4,weightkg:61.5,color:"Yellow",prevo:"flaaffy",evoLevel:30,eggGroups:["Monster","Ground"]},
azurill:{num:298,species:"Azurill",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:20,def:40,spa:20,spd:40,spe:20},abilities:{0:"Flame Body",1:"Early Bird"},heightm:0.2,weightkg:2,color:"Blue",evos:["marill"],eggGroups:["No Eggs"]},
marill:{num:183,species:"Marill",types:["Water"],baseStats:{hp:70,atk:20,def:50,spa:20,spd:50,spe:40},abilities:{0:"Adaptability",1:"Chlorophyll"},heightm:0.4,weightkg:8.5,color:"Blue",prevo:"azurill",evos:["azumarill"],evoLevel:1,eggGroups:["Water 1","Fairy"]},
azumarill:{num:184,species:"Azumarill",types:["Water"],baseStats:{hp:100,atk:50,def:80,spa:50,spd:80,spe:50},abilities:{0:"Pickpocket",1:"Technician"},heightm:0.8,weightkg:28.5,color:"Blue",prevo:"marill",evoLevel:18,eggGroups:["Water 1","Fairy"]},
bonsly:{num:438,species:"Bonsly",types:["Rock"],baseStats:{hp:50,atk:80,def:95,spa:10,spd:45,spe:10},abilities:{0:"Tangled Feet",1:"Soundproof"},heightm:0.5,weightkg:15,color:"Brown",evos:["sudowoodo"],eggGroups:["No Eggs"]},
sudowoodo:{num:185,species:"Sudowoodo",types:["Rock"],baseStats:{hp:70,atk:100,def:115,spa:30,spd:65,spe:30},abilities:{0:"Victory Star",1:"Own Tempo"},heightm:1.2,weightkg:38,color:"Brown",prevo:"bonsly",evoLevel:1,evoMove:"Mimic",eggGroups:["Mineral"]},
hoppip:{num:187,species:"Hoppip",types:["Grass","Flying"],baseStats:{hp:35,atk:35,def:40,spa:35,spd:55,spe:50},abilities:{0:"Suction Cups",1:"Drought"},heightm:0.4,weightkg:0.5,color:"Pink",evos:["skiploom"],eggGroups:["Fairy","Plant"]},
skiploom:{num:188,species:"Skiploom",types:["Grass","Flying"],baseStats:{hp:55,atk:45,def:50,spa:45,spd:65,spe:80},abilities:{0:"Steadfast",1:"Prankster"},heightm:0.6,weightkg:1,color:"Green",prevo:"hoppip",evos:["jumpluff"],evoLevel:18,eggGroups:["Fairy","Plant"]},
jumpluff:{num:189,species:"Jumpluff",types:["Grass","Flying"],baseStats:{hp:75,atk:55,def:70,spa:55,spd:85,spe:110},abilities:{0:"Magic Bounce",1:"Imposter"},heightm:0.8,weightkg:3,color:"Blue",prevo:"skiploom",evoLevel:27,eggGroups:["Fairy","Plant"]},
aipom:{num:190,species:"Aipom",types:["Normal"],baseStats:{hp:55,atk:70,def:55,spa:40,spd:55,spe:85},abilities:{0:"Forewarn",1:"Light Metal"},heightm:0.8,weightkg:11.5,color:"Purple",evos:["ambipom"],eggGroups:["Ground"]},
ambipom:{num:424,species:"Ambipom",types:["Normal"],baseStats:{hp:75,atk:100,def:66,spa:60,spd:66,spe:115},abilities:{0:"Unaware",1:"Drizzle"},heightm:1.2,weightkg:20.3,color:"Purple",prevo:"aipom",evoLevel:1,evoMove:"Double Hit",eggGroups:["Ground"]},
sunkern:{num:191,species:"Sunkern",types:["Grass"],baseStats:{hp:30,atk:30,def:30,spa:30,spd:30,spe:30},abilities:{0:"Damp",1:"Serene Grace"},heightm:0.3,weightkg:1.8,color:"Yellow",evos:["sunflora"],eggGroups:["Plant"]},
sunflora:{num:192,species:"Sunflora",types:["Grass"],baseStats:{hp:75,atk:75,def:55,spa:105,spd:85,spe:30},abilities:{0:"Simple",1:"Drizzle"},heightm:0.8,weightkg:8.5,color:"Yellow",prevo:"sunkern",evoLevel:1,eggGroups:["Plant"]},
yanma:{num:193,species:"Yanma",types:["Bug","Flying"],baseStats:{hp:65,atk:65,def:45,spa:75,spd:45,spe:95},abilities:{0:"Flash Fire",1:"Effect Spore"},heightm:1.2,weightkg:38,color:"Red",evos:["yanmega"],eggGroups:["Bug"]},
yanmega:{num:469,species:"Yanmega",types:["Bug","Flying"],baseStats:{hp:86,atk:76,def:86,spa:116,spd:56,spe:95},abilities:{0:"Prankster",1:"Clear Body"},heightm:1.9,weightkg:51.5,color:"Green",prevo:"yanma",evoLevel:1,evoMove:"AncientPower",eggGroups:["Bug"]},
wooper:{num:194,species:"Wooper",types:["Water","Ground"],baseStats:{hp:55,atk:45,def:45,spa:25,spd:25,spe:15},abilities:{0:"Rain Dish",1:"Weak Armor"},heightm:0.4,weightkg:8.5,color:"Blue",evos:["quagsire"],eggGroups:["Water 1","Ground"]},
quagsire:{num:195,species:"Quagsire",types:["Water","Ground"],baseStats:{hp:95,atk:85,def:85,spa:65,spd:65,spe:35},abilities:{0:"Anticipation",1:"Arena Trap"},heightm:1.4,weightkg:75,color:"Blue",prevo:"wooper",evoLevel:20,eggGroups:["Water 1","Ground"]},
murkrow:{num:198,species:"Murkrow",types:["Dark","Flying"],baseStats:{hp:60,atk:85,def:42,spa:85,spd:42,spe:91},abilities:{0:"Cute Charm",1:"Quick Feet"},heightm:0.5,weightkg:2.1,color:"Black",evos:["honchkrow"],eggGroups:["Flying"]},
honchkrow:{num:430,species:"Honchkrow",types:["Dark","Flying"],baseStats:{hp:100,atk:125,def:52,spa:105,spd:52,spe:71},abilities:{0:"Poison Heal",1:"Harvest"},heightm:0.9,weightkg:27.3,color:"Black",prevo:"murkrow",evoLevel:1,eggGroups:["Flying"]},
misdreavus:{num:200,species:"Misdreavus",types:["Ghost"],baseStats:{hp:60,atk:60,def:60,spa:85,spd:85,spe:85},abilities:{0:"Shed Skin",1:"Inner Focus"},heightm:0.7,weightkg:1,color:"Gray",evos:["mismagius"],eggGroups:["Indeterminate"]},
mismagius:{num:429,species:"Mismagius",types:["Ghost"],baseStats:{hp:60,atk:60,def:60,spa:105,spd:105,spe:105},abilities:{0:"Sticky Hold",1:"Defiant"},heightm:0.9,weightkg:4.4,color:"Purple",prevo:"misdreavus",evoLevel:1,eggGroups:["Indeterminate"]},
unown:{num:201,species:"Unown",baseForme:"A",types:["Psychic"],gender:"N",baseStats:{hp:48,atk:72,def:48,spa:72,spd:48,spe:48},abilities:{0:"Solid Rock",1:"Rain Dish"},heightm:0.5,weightkg:5,color:"Black",eggGroups:["No Eggs"],otherForms:["unownb","unownc","unownd","unowne","unownf","unowng","unownh","unowni","unownj","unownk","unownl","unownm","unownn","unowno","unownp","unownq","unownr","unowns","unownt","unownu","unownv","unownw","unownx","unowny","unownz","unownem","unownqm"]},
wynaut:{num:360,species:"Wynaut",types:["Psychic"],baseStats:{hp:95,atk:23,def:48,spa:23,spd:48,spe:23},abilities:{0:"Mold Breaker",1:"Mummy"},heightm:0.6,weightkg:14,color:"Blue",evos:["wobbuffet"],eggGroups:["No Eggs"]},
wobbuffet:{num:202,species:"Wobbuffet",types:["Psychic"],baseStats:{hp:190,atk:33,def:58,spa:33,spd:58,spe:33},abilities:{0:"Own Tempo",1:"Suction Cups"},heightm:1.3,weightkg:28.5,color:"Blue",prevo:"wynaut",evoLevel:15,eggGroups:["Indeterminate"]},
girafarig:{num:203,species:"Girafarig",types:["Normal","Psychic"],baseStats:{hp:70,atk:80,def:65,spa:90,spd:65,spe:85},abilities:{0:"Color Change",1:"Big Pecks"},heightm:1.5,weightkg:41.5,color:"Yellow",eggGroups:["Ground"]},
pineco:{num:204,species:"Pineco",types:["Bug"],baseStats:{hp:50,atk:65,def:90,spa:35,spd:35,spe:15},abilities:{0:"Damp",1:"Iron Barbs"},heightm:0.6,weightkg:7.2,color:"Gray",evos:["forretress"],eggGroups:["Bug"]},
forretress:{num:205,species:"Forretress",types:["Bug","Steel"],baseStats:{hp:75,atk:90,def:140,spa:60,spd:60,spe:40},abilities:{0:"Imposter",1:"Gluttony"},heightm:1.2,weightkg:125.8,color:"Purple",prevo:"pineco",evoLevel:31,eggGroups:["Bug"]},
dunsparce:{num:206,species:"Dunsparce",types:["Normal"],baseStats:{hp:100,atk:70,def:70,spa:65,spd:65,spe:45},abilities:{0:"Tangled Feet",1:"Speed Boost"},heightm:1.5,weightkg:14,color:"Yellow",eggGroups:["Ground"]},
gligar:{num:207,species:"Gligar",types:["Ground","Flying"],baseStats:{hp:65,atk:75,def:105,spa:35,spd:65,spe:85},abilities:{0:"Flare Boost",1:"Suction Cups"},heightm:1.1,weightkg:64.8,color:"Purple",evos:["gliscor"],eggGroups:["Bug"]},
gliscor:{num:472,species:"Gliscor",types:["Ground","Flying"],baseStats:{hp:75,atk:95,def:125,spa:45,spd:75,spe:95},abilities:{0:"Drought",1:"Clear Body"},heightm:2,weightkg:42.5,color:"Purple",prevo:"gligar",evoLevel:1,eggGroups:["Bug"]},
snubbull:{num:209,species:"Snubbull",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:60,atk:80,def:50,spa:40,spd:40,spe:30},abilities:{0:"Compoundeyes",1:"Hydration"},heightm:0.6,weightkg:7.8,color:"Pink",evos:["granbull"],eggGroups:["Ground","Fairy"]},
granbull:{num:210,species:"Granbull",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:90,atk:120,def:75,spa:60,spd:60,spe:45},abilities:{0:"Poison Heal",1:"Static"},heightm:1.4,weightkg:48.7,color:"Purple",prevo:"snubbull",evoLevel:23,eggGroups:["Ground","Fairy"]},
qwilfish:{num:211,species:"Qwilfish",types:["Water","Poison"],baseStats:{hp:65,atk:95,def:75,spa:55,spd:55,spe:85},abilities:{0:"Storm Drain",1:"Simple"},heightm:0.5,weightkg:3.9,color:"Gray",eggGroups:["Water 2"]},
shuckle:{num:213,species:"Shuckle",types:["Bug","Rock"],baseStats:{hp:20,atk:10,def:230,spa:10,spd:230,spe:5},abilities:{0:"Drought",1:"Compoundeyes"},heightm:0.6,weightkg:20.5,color:"Yellow",eggGroups:["Bug"]},
heracross:{num:214,species:"Heracross",types:["Bug","Fighting"],baseStats:{hp:80,atk:125,def:75,spa:40,spd:95,spe:85},abilities:{0:"Heavy Metal",1:"Contrary"},heightm:1.5,weightkg:54,color:"Blue",eggGroups:["Bug"]},
sneasel:{num:215,species:"Sneasel",types:["Dark","Ice"],baseStats:{hp:55,atk:95,def:55,spa:35,spd:75,spe:115},abilities:{0:"Sap Sipper",1:"Compoundeyes"},heightm:0.9,weightkg:28,color:"Black",evos:["weavile"],eggGroups:["Ground"]},
weavile:{num:461,species:"Weavile",types:["Dark","Ice"],baseStats:{hp:70,atk:120,def:65,spa:45,spd:85,spe:125},abilities:{0:"Solid Rock",1:"Chlorophyll"},heightm:1.1,weightkg:34,color:"Black",prevo:"sneasel",evoLevel:1,eggGroups:["Ground"]},
teddiursa:{num:216,species:"Teddiursa",types:["Normal"],baseStats:{hp:60,atk:80,def:50,spa:50,spd:50,spe:40},abilities:{0:"Analytic",1:"Color Change"},heightm:0.6,weightkg:8.8,color:"Brown",evos:["ursaring"],eggGroups:["Ground"]},
ursaring:{num:217,species:"Ursaring",types:["Normal"],baseStats:{hp:90,atk:130,def:75,spa:75,spd:75,spe:55},abilities:{0:"Soundproof",1:"Synchronize"},heightm:1.8,weightkg:125.8,color:"Brown",prevo:"teddiursa",evoLevel:30,eggGroups:["Ground"]},
slugma:{num:218,species:"Slugma",types:["Fire"],baseStats:{hp:40,atk:40,def:40,spa:70,spd:40,spe:20},abilities:{0:"Shield Dust",1:"Intimidate"},heightm:0.7,weightkg:35,color:"Red",evos:["magcargo"],eggGroups:["Indeterminate"]},
magcargo:{num:219,species:"Magcargo",types:["Fire","Rock"],baseStats:{hp:50,atk:50,def:120,spa:80,spd:80,spe:30},abilities:{0:"Clear Body",1:"Tinted Lens"},heightm:0.8,weightkg:55,color:"Red",prevo:"slugma",evoLevel:38,eggGroups:["Indeterminate"]},
swinub:{num:220,species:"Swinub",types:["Ice","Ground"],baseStats:{hp:50,atk:50,def:40,spa:30,spd:30,spe:50},abilities:{0:"Cursed Body",1:"Technician"},heightm:0.4,weightkg:6.5,color:"Brown",evos:["piloswine"],eggGroups:["Ground"]},
piloswine:{num:221,species:"Piloswine",types:["Ice","Ground"],baseStats:{hp:100,atk:100,def:80,spa:60,spd:60,spe:50},abilities:{0:"Simple",1:"Rivalry"},heightm:1.1,weightkg:55.8,color:"Brown",prevo:"swinub",evos:["mamoswine"],evoLevel:33,eggGroups:["Ground"]},
mamoswine:{num:473,species:"Mamoswine",types:["Ice","Ground"],baseStats:{hp:110,atk:130,def:80,spa:70,spd:60,spe:80},abilities:{0:"Liquid Ooze",1:"Tangled Feet"},heightm:2.5,weightkg:291,color:"Brown",prevo:"piloswine",evoLevel:1,evoMove:"AncientPower",eggGroups:["Ground"]},
corsola:{num:222,species:"Corsola",types:["Water","Rock"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:55,atk:55,def:85,spa:65,spd:85,spe:35},abilities:{0:"Color Change",1:"Tinted Lens"},heightm:0.6,weightkg:5,color:"Pink",eggGroups:["Water 1","Water 3"]},
remoraid:{num:223,species:"Remoraid",types:["Water"],baseStats:{hp:35,atk:65,def:35,spa:65,spd:35,spe:65},abilities:{0:"Effect Spore",1:"Water Absorb"},heightm:0.6,weightkg:12,color:"Gray",evos:["octillery"],eggGroups:["Water 1","Water 2"]},
octillery:{num:224,species:"Octillery",types:["Water"],baseStats:{hp:75,atk:105,def:75,spa:105,spd:75,spe:45},abilities:{0:"Tangled Feet",1:"Cloud Nine"},heightm:0.9,weightkg:28.5,color:"Red",prevo:"remoraid",evoLevel:25,eggGroups:["Water 1","Water 2"]},
delibird:{num:225,species:"Delibird",types:["Ice","Flying"],baseStats:{hp:45,atk:55,def:45,spa:65,spd:45,spe:75},abilities:{0:"Reckless",1:"Keen Eye"},heightm:0.9,weightkg:16,color:"Red",eggGroups:["Water 1","Ground"]},
mantyke:{num:458,species:"Mantyke",types:["Water","Flying"],baseStats:{hp:45,atk:20,def:50,spa:60,spd:120,spe:50},abilities:{0:"Arena Trap",1:"Battle Armor"},heightm:1,weightkg:65,color:"Blue",evos:["mantine"],eggGroups:["No Eggs"]},
mantine:{num:226,species:"Mantine",types:["Water","Flying"],baseStats:{hp:65,atk:40,def:70,spa:80,spd:140,spe:70},abilities:{0:"Chlorophyll",1:"Flare Boost"},heightm:2.1,weightkg:220,color:"Purple",prevo:"mantyke",evoLevel:1,eggGroups:["Water 1"]},
skarmory:{num:227,species:"Skarmory",types:["Steel","Flying"],baseStats:{hp:65,atk:80,def:140,spa:40,spd:70,spe:70},abilities:{0:"Rivalry",1:"Rock Head"},heightm:1.7,weightkg:50.5,color:"Gray",eggGroups:["Flying"]},
houndour:{num:228,species:"Houndour",types:["Dark","Fire"],baseStats:{hp:45,atk:60,def:30,spa:80,spd:50,spe:65},abilities:{0:"Victory Star",1:"Unburden"},heightm:0.6,weightkg:10.8,color:"Black",evos:["houndoom"],eggGroups:["Ground"]},
houndoom:{num:229,species:"Houndoom",types:["Dark","Fire"],baseStats:{hp:75,atk:90,def:50,spa:110,spd:80,spe:95},abilities:{0:"Shed Skin",1:"Sand Force"},heightm:1.4,weightkg:35,color:"Black",prevo:"houndour",evoLevel:24,eggGroups:["Ground"]},
phanpy:{num:231,species:"Phanpy",types:["Ground"],baseStats:{hp:90,atk:60,def:60,spa:40,spd:40,spe:40},abilities:{0:"Flash Fire",1:"Levitate"},heightm:0.5,weightkg:33.5,color:"Blue",evos:["donphan"],eggGroups:["Ground"]},
donphan:{num:232,species:"Donphan",types:["Ground"],baseStats:{hp:90,atk:120,def:120,spa:60,spd:60,spe:50},abilities:{0:"Hyper Cutter",1:"Damp"},heightm:1.1,weightkg:120,color:"Gray",prevo:"phanpy",evoLevel:25,eggGroups:["Ground"]},
stantler:{num:234,species:"Stantler",types:["Normal"],baseStats:{hp:73,atk:95,def:62,spa:85,spd:65,spe:85},abilities:{0:"Swarm",1:"Lightningrod"},heightm:1.4,weightkg:71.2,color:"Brown",eggGroups:["Ground"]},
smeargle:{num:235,species:"Smeargle",types:["Normal"],baseStats:{hp:55,atk:20,def:35,spa:20,spd:45,spe:75},abilities:{0:"Gluttony",1:"Super Luck"},heightm:1.2,weightkg:58,color:"White",eggGroups:["Ground"]},
miltank:{num:241,species:"Miltank",types:["Normal"],gender:"F",baseStats:{hp:95,atk:80,def:105,spa:40,spd:70,spe:100},abilities:{0:"Defiant",1:"Normalize"},heightm:1.2,weightkg:75.5,color:"Pink",eggGroups:["Ground"]},
raikou:{num:243,species:"Raikou",types:["Electric"],gender:"N",baseStats:{hp:90,atk:85,def:75,spa:115,spd:100,spe:115},abilities:{0:"Lightningrod",1:"Iron Barbs"},heightm:1.9,weightkg:178,color:"Yellow",eggGroups:["No Eggs"]},
entei:{num:244,species:"Entei",types:["Fire"],gender:"N",baseStats:{hp:115,atk:115,def:85,spa:90,spd:75,spe:100},abilities:{0:"Thick Fat",1:"Dry Skin"},heightm:2.1,weightkg:198,color:"Brown",eggGroups:["No Eggs"]},
suicune:{num:245,species:"Suicune",types:["Water"],gender:"N",baseStats:{hp:100,atk:75,def:115,spa:90,spd:115,spe:85},abilities:{0:"Forewarn",1:"Poison Heal"},heightm:2,weightkg:187,color:"Blue",eggGroups:["No Eggs"]},
larvitar:{num:246,species:"Larvitar",types:["Rock","Ground"],baseStats:{hp:50,atk:64,def:50,spa:45,spd:50,spe:41},abilities:{0:"Synchronize",1:"Rock Head"},heightm:0.6,weightkg:72,color:"Green",evos:["pupitar"],eggGroups:["Monster"]},
pupitar:{num:247,species:"Pupitar",types:["Rock","Ground"],baseStats:{hp:70,atk:84,def:70,spa:65,spd:70,spe:51},abilities:{0:"Mummy",1:"Sheer Force"},heightm:1.2,weightkg:152,color:"Gray",prevo:"larvitar",evos:["tyranitar"],evoLevel:30,eggGroups:["Monster"]},
tyranitar:{num:248,species:"Tyranitar",types:["Rock","Dark"],baseStats:{hp:100,atk:134,def:110,spa:95,spd:100,spe:61},abilities:{0:"Anticipation",1:"Rain Dish"},heightm:2,weightkg:202,color:"Green",prevo:"pupitar",evoLevel:55,eggGroups:["Monster"]},
lugia:{num:249,species:"Lugia",types:["Psychic","Flying"],gender:"N",baseStats:{hp:106,atk:90,def:130,spa:90,spd:154,spe:110},abilities:{0:"Sap Sipper",1:"Limber"},heightm:5.2,weightkg:216,color:"White",eggGroups:["No Eggs"]},
hooh:{num:250,species:"Ho-Oh",types:["Fire","Flying"],gender:"N",baseStats:{hp:106,atk:130,def:90,spa:110,spd:154,spe:90},abilities:{0:"Poison Heal",1:"Magnet Pull"},heightm:3.8,weightkg:199,color:"Red",eggGroups:["No Eggs"]},
celebi:{num:251,species:"Celebi",types:["Psychic","Grass"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Soundproof",1:"Simple"},heightm:0.6,weightkg:5,color:"Green",eggGroups:["No Eggs"]},
treecko:{num:252,species:"Treecko",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:45,def:35,spa:65,spd:55,spe:70},abilities:{0:"Overcoat",1:"Thick Fat"},heightm:0.5,weightkg:5,color:"Green",evos:["grovyle"],eggGroups:["Monster","Dragon"]},
grovyle:{num:253,species:"Grovyle",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:65,def:45,spa:85,spd:65,spe:95},abilities:{0:"Rock Head",1:"Clear Body"},heightm:0.9,weightkg:21.6,color:"Green",prevo:"treecko",evos:["sceptile"],evoLevel:16,eggGroups:["Monster","Dragon"]},
sceptile:{num:254,species:"Sceptile",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:85,def:65,spa:105,spd:85,spe:120},abilities:{0:"Tinted Lens",1:"Justified"},heightm:1.7,weightkg:52.2,color:"Green",prevo:"grovyle",evoLevel:36,eggGroups:["Monster","Dragon"]},
torchic:{num:255,species:"Torchic",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:60,def:40,spa:70,spd:50,spe:45},abilities:{0:"Victory Star",1:"Infiltrator"},heightm:0.4,weightkg:2.5,color:"Red",evos:["combusken"],eggGroups:["Ground"]},
combusken:{num:256,species:"Combusken",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:85,def:60,spa:85,spd:60,spe:55},abilities:{0:"Limber",1:"Super Luck"},heightm:0.9,weightkg:19.5,color:"Red",prevo:"torchic",evos:["blaziken"],evoLevel:16,eggGroups:["Ground"]},
blaziken:{num:257,species:"Blaziken",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:120,def:70,spa:110,spd:70,spe:80},abilities:{0:"Justified",1:"Light Metal"},heightm:1.9,weightkg:52,color:"Red",prevo:"combusken",evoLevel:36,eggGroups:["Ground"]},
mudkip:{num:258,species:"Mudkip",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:70,def:50,spa:50,spd:50,spe:40},abilities:{0:"Contrary",1:"Cursed Body"},heightm:0.4,weightkg:7.6,color:"Blue",evos:["marshtomp"],eggGroups:["Monster","Water 1"]},
marshtomp:{num:259,species:"Marshtomp",types:["Water","Ground"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:85,def:70,spa:60,spd:70,spe:50},abilities:{0:"Frisk",1:"Magma Armor"},heightm:0.7,weightkg:28,color:"Blue",prevo:"mudkip",evos:["swampert"],evoLevel:16,eggGroups:["Monster","Water 1"]},
swampert:{num:260,species:"Swampert",types:["Water","Ground"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:100,atk:110,def:90,spa:85,spd:90,spe:60},abilities:{0:"Sturdy",1:"Chlorophyll"},heightm:1.5,weightkg:81.9,color:"Blue",prevo:"marshtomp",evoLevel:36,eggGroups:["Monster","Water 1"]},
poochyena:{num:261,species:"Poochyena",types:["Dark"],baseStats:{hp:35,atk:55,def:35,spa:30,spd:30,spe:35},abilities:{0:"Adaptability",1:"Early Bird"},heightm:0.5,weightkg:13.6,color:"Gray",evos:["mightyena"],eggGroups:["Ground"]},
mightyena:{num:262,species:"Mightyena",types:["Dark"],baseStats:{hp:70,atk:90,def:70,spa:60,spd:60,spe:70},abilities:{0:"Unaware",1:"Hydration"},heightm:1,weightkg:37,color:"Gray",prevo:"poochyena",evoLevel:18,eggGroups:["Ground"]},
zigzagoon:{num:263,species:"Zigzagoon",types:["Normal"],baseStats:{hp:38,atk:30,def:41,spa:30,spd:41,spe:60},abilities:{0:"Volt Absorb",1:"Static"},heightm:0.4,weightkg:17.5,color:"Brown",evos:["linoone"],eggGroups:["Ground"]},
linoone:{num:264,species:"Linoone",types:["Normal"],baseStats:{hp:78,atk:70,def:61,spa:50,spd:61,spe:100},abilities:{0:"Reckless",1:"Water Veil"},heightm:0.5,weightkg:32.5,color:"White",prevo:"zigzagoon",evoLevel:20,eggGroups:["Ground"]},
wurmple:{num:265,species:"Wurmple",types:["Bug"],baseStats:{hp:45,atk:45,def:35,spa:20,spd:30,spe:20},abilities:{0:"Poison Touch",1:"Shadow Tag"},heightm:0.3,weightkg:3.6,color:"Red",evos:["silcoon","cascoon"],eggGroups:["Bug"]},
silcoon:{num:266,species:"Silcoon",types:["Bug"],baseStats:{hp:50,atk:35,def:55,spa:25,spd:25,spe:15},abilities:{0:"Contrary",1:"Unaware"},heightm:0.6,weightkg:10,color:"White",prevo:"wurmple",evos:["beautifly"],evoLevel:7,eggGroups:["Bug"]},
beautifly:{num:267,species:"Beautifly",types:["Bug","Flying"],baseStats:{hp:60,atk:70,def:50,spa:90,spd:50,spe:65},abilities:{0:"Stall",1:"Illusion"},heightm:1,weightkg:28.4,color:"Yellow",prevo:"silcoon",evoLevel:10,eggGroups:["Bug"]},
cascoon:{num:268,species:"Cascoon",types:["Bug"],baseStats:{hp:50,atk:35,def:55,spa:25,spd:25,spe:15},abilities:{0:"Dry Skin",1:"Prankster"},heightm:0.7,weightkg:11.5,color:"Purple",prevo:"wurmple",evos:["dustox"],evoLevel:7,eggGroups:["Bug"]},
dustox:{num:269,species:"Dustox",types:["Bug","Poison"],baseStats:{hp:60,atk:50,def:70,spa:50,spd:90,spe:65},abilities:{0:"Justified",1:"Victory Star"},heightm:1.2,weightkg:31.6,color:"Green",prevo:"cascoon",evoLevel:10,eggGroups:["Bug"]},
lotad:{num:270,species:"Lotad",types:["Water","Grass"],baseStats:{hp:40,atk:30,def:30,spa:40,spd:50,spe:30},abilities:{0:"Technician",1:"Magma Armor"},heightm:0.5,weightkg:2.6,color:"Green",evos:["lombre"],eggGroups:["Water 1","Plant"]},
lombre:{num:271,species:"Lombre",types:["Water","Grass"],baseStats:{hp:60,atk:50,def:50,spa:60,spd:70,spe:50},abilities:{0:"Magic Bounce",1:"Effect Spore"},heightm:1.2,weightkg:32.5,color:"Green",prevo:"lotad",evos:["ludicolo"],evoLevel:14,eggGroups:["Water 1","Plant"]},
ludicolo:{num:272,species:"Ludicolo",types:["Water","Grass"],baseStats:{hp:80,atk:70,def:70,spa:90,spd:100,spe:70},abilities:{0:"Forewarn",1:"Damp"},heightm:1.5,weightkg:55,color:"Green",prevo:"lombre",evoLevel:1,eggGroups:["Water 1","Plant"]},
seedot:{num:273,species:"Seedot",types:["Grass"],baseStats:{hp:40,atk:40,def:50,spa:30,spd:30,spe:30},abilities:{0:"Sturdy",1:"Forewarn"},heightm:0.5,weightkg:4,color:"Brown",evos:["nuzleaf"],eggGroups:["Ground","Plant"]},
nuzleaf:{num:274,species:"Nuzleaf",types:["Grass","Dark"],baseStats:{hp:70,atk:70,def:40,spa:60,spd:40,spe:60},abilities:{0:"Flash Fire",1:"Flame Body"},heightm:1,weightkg:28,color:"Brown",prevo:"seedot",evos:["shiftry"],evoLevel:14,eggGroups:["Ground","Plant"]},
shiftry:{num:275,species:"Shiftry",types:["Grass","Dark"],baseStats:{hp:90,atk:100,def:60,spa:90,spd:60,spe:80},abilities:{0:"Moxie",1:"Sand Veil"},heightm:1.3,weightkg:59.6,color:"Brown",prevo:"nuzleaf",evoLevel:1,eggGroups:["Ground","Plant"]},
taillow:{num:276,species:"Taillow",types:["Normal","Flying"],baseStats:{hp:40,atk:55,def:30,spa:30,spd:30,spe:85},abilities:{0:"Sturdy",1:"Serene Grace"},heightm:0.3,weightkg:2.3,color:"Blue",evos:["swellow"],eggGroups:["Flying"]},
swellow:{num:277,species:"Swellow",types:["Normal","Flying"],baseStats:{hp:60,atk:85,def:60,spa:50,spd:50,spe:125},abilities:{0:"Klutz",1:"Poison Touch"},heightm:0.7,weightkg:19.8,color:"Blue",prevo:"taillow",evoLevel:22,eggGroups:["Flying"]},
wingull:{num:278,species:"Wingull",types:["Water","Flying"],baseStats:{hp:40,atk:30,def:30,spa:55,spd:30,spe:85},abilities:{0:"Defiant",1:"Synchronize"},heightm:0.6,weightkg:9.5,color:"White",evos:["pelipper"],eggGroups:["Water 1","Flying"]},
pelipper:{num:279,species:"Pelipper",types:["Water","Flying"],baseStats:{hp:60,atk:50,def:100,spa:85,spd:70,spe:65},abilities:{0:"Own Tempo",1:"Heatproof"},heightm:1.2,weightkg:28,color:"Yellow",prevo:"wingull",evoLevel:25,eggGroups:["Water 1","Flying"]},
ralts:{num:280,species:"Ralts",types:["Psychic"],baseStats:{hp:28,atk:25,def:25,spa:45,spd:35,spe:40},abilities:{0:"Sand Force",1:"Heatproof"},heightm:0.4,weightkg:6.6,color:"White",evos:["kirlia"],eggGroups:["Indeterminate"]},
kirlia:{num:281,species:"Kirlia",types:["Psychic"],baseStats:{hp:38,atk:35,def:35,spa:65,spd:55,spe:50},abilities:{0:"Static",1:"Hustle"},heightm:0.8,weightkg:20.2,color:"White",prevo:"ralts",evos:["gardevoir","gallade"],evoLevel:20,eggGroups:["Indeterminate"]},
gardevoir:{num:282,species:"Gardevoir",types:["Psychic"],baseStats:{hp:68,atk:65,def:65,spa:125,spd:115,spe:80},abilities:{0:"Battle Armor",1:"Tinted Lens"},heightm:1.6,weightkg:48.4,color:"White",prevo:"kirlia",evoLevel:30,eggGroups:["Indeterminate"]},
gallade:{num:475,species:"Gallade",types:["Psychic","Fighting"],gender:"M",baseStats:{hp:68,atk:125,def:65,spa:65,spd:115,spe:80},abilities:{0:"Ice Body",1:"Chlorophyll"},heightm:1.6,weightkg:52,color:"White",prevo:"kirlia",evoLevel:1,eggGroups:["Indeterminate"]},
surskit:{num:283,species:"Surskit",types:["Bug","Water"],baseStats:{hp:40,atk:30,def:32,spa:50,spd:52,spe:65},abilities:{0:"Thick Fat",1:"Soundproof"},heightm:0.5,weightkg:1.7,color:"Blue",evos:["masquerain"],eggGroups:["Water 1","Bug"]},
masquerain:{num:284,species:"Masquerain",types:["Bug","Flying"],baseStats:{hp:70,atk:60,def:62,spa:80,spd:82,spe:60},abilities:{0:"Frisk",1:"Magic Bounce"},heightm:0.8,weightkg:3.6,color:"Blue",prevo:"surskit",evoLevel:22,eggGroups:["Water 1","Bug"]},
shroomish:{num:285,species:"Shroomish",types:["Grass"],baseStats:{hp:60,atk:40,def:60,spa:40,spd:60,spe:35},abilities:{0:"Heatproof",1:"Oblivious"},heightm:0.4,weightkg:4.5,color:"Brown",evos:["breloom"],eggGroups:["Fairy","Plant"]},
breloom:{num:286,species:"Breloom",types:["Grass","Fighting"],baseStats:{hp:60,atk:130,def:80,spa:60,spd:60,spe:70},abilities:{0:"Simple",1:"Damp"},heightm:1.2,weightkg:39.2,color:"Green",prevo:"shroomish",evoLevel:23,eggGroups:["Fairy","Plant"]},
slakoth:{num:287,species:"Slakoth",types:["Normal"],baseStats:{hp:60,atk:60,def:60,spa:35,spd:35,spe:30},abilities:{0:"Compoundeyes",1:"Tinted Lens"},heightm:0.8,weightkg:24,color:"Brown",evos:["vigoroth"],eggGroups:["Ground"]},
vigoroth:{num:288,species:"Vigoroth",types:["Normal"],baseStats:{hp:80,atk:80,def:80,spa:55,spd:55,spe:90},abilities:{0:"Rock Head",1:"Weak Armor"},heightm:1.4,weightkg:46.5,color:"White",prevo:"slakoth",evos:["slaking"],evoLevel:18,eggGroups:["Ground"]},
slaking:{num:289,species:"Slaking",types:["Normal"],baseStats:{hp:150,atk:160,def:100,spa:95,spd:65,spe:100},abilities:{0:"Compoundeyes",1:"Levitate"},heightm:2,weightkg:130.5,color:"Brown",prevo:"vigoroth",evoLevel:36,eggGroups:["Ground"]},
nincada:{num:290,species:"Nincada",types:["Bug","Ground"],baseStats:{hp:31,atk:45,def:90,spa:30,spd:30,spe:40},abilities:{0:"Overcoat",1:"Magic Bounce"},heightm:0.5,weightkg:5.5,color:"Gray",evos:["ninjask","shedinja"],eggGroups:["Bug"]},
ninjask:{num:291,species:"Ninjask",types:["Bug","Flying"],baseStats:{hp:61,atk:90,def:45,spa:50,spd:50,spe:160},abilities:{0:"Frisk",1:"Magic Guard"},heightm:0.8,weightkg:12,color:"Yellow",prevo:"nincada",evoLevel:20,eggGroups:["Bug"]},
shedinja:{num:292,species:"Shedinja",types:["Bug","Ghost"],gender:"N",baseStats:{hp:1,atk:90,def:45,spa:30,spd:30,spe:40},abilities:{0:"Skill Link",1:"Leaf Guard"},heightm:0.8,weightkg:1.2,color:"Brown",prevo:"nincada",evoLevel:1,eggGroups:["Mineral"]},
whismur:{num:293,species:"Whismur",types:["Normal"],baseStats:{hp:64,atk:51,def:23,spa:51,spd:23,spe:28},abilities:{0:"Color Change",1:"Contrary"},heightm:0.6,weightkg:16.3,color:"Pink",evos:["loudred"],eggGroups:["Monster","Ground"]},
loudred:{num:294,species:"Loudred",types:["Normal"],baseStats:{hp:84,atk:71,def:43,spa:71,spd:43,spe:48},abilities:{0:"Heatproof",1:"Sand Veil"},heightm:1,weightkg:40.5,color:"Blue",prevo:"whismur",evos:["exploud"],evoLevel:20,eggGroups:["Monster","Ground"]},
exploud:{num:295,species:"Exploud",types:["Normal"],baseStats:{hp:104,atk:91,def:63,spa:91,spd:63,spe:68},abilities:{0:"Clear Body",1:"Infiltrator"},heightm:1.5,weightkg:84,color:"Blue",prevo:"loudred",evoLevel:40,eggGroups:["Monster","Ground"]},
makuhita:{num:296,species:"Makuhita",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:72,atk:60,def:30,spa:20,spd:30,spe:25},abilities:{0:"Poison Heal",1:"Poison Point"},heightm:1,weightkg:86.4,color:"Yellow",evos:["hariyama"],eggGroups:["Humanshape"]},
hariyama:{num:297,species:"Hariyama",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:144,atk:120,def:60,spa:40,spd:60,spe:50},abilities:{0:"Harvest",1:"Battle Armor"},heightm:2.3,weightkg:253.8,color:"Brown",prevo:"makuhita",evoLevel:24,eggGroups:["Humanshape"]},
nosepass:{num:299,species:"Nosepass",types:["Rock"],baseStats:{hp:30,atk:45,def:135,spa:45,spd:90,spe:30},abilities:{0:"Motor Drive",1:"Big Pecks"},heightm:1,weightkg:97,color:"Gray",evos:["probopass"],eggGroups:["Mineral"]},
probopass:{num:476,species:"Probopass",types:["Rock","Steel"],baseStats:{hp:60,atk:55,def:145,spa:75,spd:150,spe:40},abilities:{0:"No Guard",1:"Heatproof"},heightm:1.4,weightkg:340,color:"Gray",prevo:"nosepass",evoLevel:1,eggGroups:["Mineral"]},
skitty:{num:300,species:"Skitty",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:45,def:45,spa:35,spd:35,spe:50},abilities:{0:"Synchronize",1:"Weak Armor"},heightm:0.6,weightkg:11,color:"Pink",evos:["delcatty"],eggGroups:["Ground","Fairy"]},
delcatty:{num:301,species:"Delcatty",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:65,def:65,spa:55,spd:55,spe:70},abilities:{0:"Magnet Pull",1:"Poison Heal"},heightm:1.1,weightkg:32.6,color:"Purple",prevo:"skitty",evoLevel:1,eggGroups:["Ground","Fairy"]},
sableye:{num:302,species:"Sableye",types:["Dark","Ghost"],baseStats:{hp:50,atk:75,def:75,spa:65,spd:65,spe:50},abilities:{0:"Soundproof",1:"Magic Bounce"},heightm:0.5,weightkg:11,color:"Purple",eggGroups:["Humanshape"]},
mawile:{num:303,species:"Mawile",types:["Steel"],baseStats:{hp:50,atk:85,def:85,spa:55,spd:55,spe:50},abilities:{0:"Solar Power",1:"Guts"},heightm:0.6,weightkg:11.5,color:"Black",eggGroups:["Ground","Fairy"]},
aron:{num:304,species:"Aron",types:["Steel","Rock"],baseStats:{hp:50,atk:70,def:100,spa:40,spd:40,spe:30},abilities:{0:"Harvest",1:"Aftermath"},heightm:0.4,weightkg:60,color:"Gray",evos:["lairon"],eggGroups:["Monster"]},
lairon:{num:305,species:"Lairon",types:["Steel","Rock"],baseStats:{hp:60,atk:90,def:140,spa:50,spd:50,spe:40},abilities:{0:"Iron Barbs",1:"Storm Drain"},heightm:0.9,weightkg:120,color:"Gray",prevo:"aron",evos:["aggron"],evoLevel:32,eggGroups:["Monster"]},
aggron:{num:306,species:"Aggron",types:["Steel","Rock"],baseStats:{hp:70,atk:110,def:180,spa:60,spd:60,spe:50},abilities:{0:"Bad Dreams",1:"Simple"},heightm:2.1,weightkg:360,color:"Gray",prevo:"lairon",evoLevel:42,eggGroups:["Monster"]},
meditite:{num:307,species:"Meditite",types:["Fighting","Psychic"],baseStats:{hp:30,atk:40,def:55,spa:40,spd:55,spe:60},abilities:{0:"Download",1:"Damp"},heightm:0.6,weightkg:11.2,color:"Blue",evos:["medicham"],eggGroups:["Humanshape"]},
medicham:{num:308,species:"Medicham",types:["Fighting","Psychic"],baseStats:{hp:60,atk:60,def:75,spa:60,spd:75,spe:80},abilities:{0:"Pickpocket",1:"Battle Armor"},heightm:1.3,weightkg:31.5,color:"Red",prevo:"meditite",evoLevel:37,eggGroups:["Humanshape"]},
electrike:{num:309,species:"Electrike",types:["Electric"],baseStats:{hp:40,atk:45,def:40,spa:65,spd:40,spe:65},abilities:{0:"Shield Dust",1:"Battle Armor"},heightm:0.6,weightkg:15.2,color:"Green",evos:["manectric"],eggGroups:["Ground"]},
manectric:{num:310,species:"Manectric",types:["Electric"],baseStats:{hp:70,atk:75,def:60,spa:105,spd:60,spe:105},abilities:{0:"Suction Cups",1:"Poison Touch"},heightm:1.5,weightkg:40.2,color:"Yellow",prevo:"electrike",evoLevel:26,eggGroups:["Ground"]},
plusle:{num:311,species:"Plusle",types:["Electric"],baseStats:{hp:60,atk:50,def:40,spa:85,spd:75,spe:95},abilities:{0:"Anger Point",1:"Cursed Body"},heightm:0.4,weightkg:4.2,color:"Yellow",eggGroups:["Fairy"]},
minun:{num:312,species:"Minun",types:["Electric"],baseStats:{hp:60,atk:40,def:50,spa:75,spd:85,spe:95},abilities:{0:"Unnerve",1:"Battle Armor"},heightm:0.4,weightkg:4.2,color:"Yellow",eggGroups:["Fairy"]},
volbeat:{num:313,species:"Volbeat",types:["Bug"],gender:"M",baseStats:{hp:65,atk:73,def:55,spa:47,spd:75,spe:85},abilities:{0:"Rain Dish",1:"Cursed Body"},heightm:0.7,weightkg:17.7,color:"Gray",eggGroups:["Bug","Humanshape"]},
illumise:{num:314,species:"Illumise",types:["Bug"],gender:"F",baseStats:{hp:65,atk:47,def:55,spa:73,spd:75,spe:85},abilities:{0:"Victory Star",1:"Leaf Guard"},heightm:0.6,weightkg:17.7,color:"Purple",eggGroups:["Bug","Humanshape"]},
budew:{num:406,species:"Budew",types:["Grass","Poison"],baseStats:{hp:40,atk:30,def:35,spa:50,spd:70,spe:55},abilities:{0:"Sheer Force",1:"Victory Star"},heightm:0.2,weightkg:1.2,color:"Green",evos:["roselia"],eggGroups:["No Eggs"]},
roselia:{num:315,species:"Roselia",types:["Grass","Poison"],baseStats:{hp:50,atk:60,def:45,spa:100,spd:80,spe:65},abilities:{0:"Adaptability",1:"Stall"},heightm:0.3,weightkg:2,color:"Green",prevo:"budew",evos:["roserade"],evoLevel:1,eggGroups:["Fairy","Plant"]},
roserade:{num:407,species:"Roserade",types:["Grass","Poison"],baseStats:{hp:60,atk:70,def:55,spa:125,spd:105,spe:90},abilities:{0:"Victory Star",1:"Gluttony"},heightm:0.9,weightkg:14.5,color:"Green",prevo:"roselia",evoLevel:1,eggGroups:["Fairy","Plant"]},
gulpin:{num:316,species:"Gulpin",types:["Poison"],baseStats:{hp:70,atk:43,def:53,spa:43,spd:53,spe:40},abilities:{0:"Imposter",1:"Flash Fire"},heightm:0.4,weightkg:10.3,color:"Green",evos:["swalot"],eggGroups:["Indeterminate"]},
swalot:{num:317,species:"Swalot",types:["Poison"],baseStats:{hp:100,atk:73,def:83,spa:73,spd:83,spe:55},abilities:{0:"Iron Barbs",1:"Unnerve"},heightm:1.7,weightkg:80,color:"Purple",prevo:"gulpin",evoLevel:26,eggGroups:["Indeterminate"]},
carvanha:{num:318,species:"Carvanha",types:["Water","Dark"],baseStats:{hp:45,atk:90,def:20,spa:65,spd:20,spe:65},abilities:{0:"Magma Armor",1:"Quick Feet"},heightm:0.8,weightkg:20.8,color:"Red",evos:["sharpedo"],eggGroups:["Water 2"]},
sharpedo:{num:319,species:"Sharpedo",types:["Water","Dark"],baseStats:{hp:70,atk:120,def:40,spa:95,spd:40,spe:95},abilities:{0:"Immunity",1:"Anticipation"},heightm:1.8,weightkg:88.8,color:"Blue",prevo:"carvanha",evoLevel:30,eggGroups:["Water 2"]},
wailmer:{num:320,species:"Wailmer",types:["Water"],baseStats:{hp:130,atk:70,def:35,spa:70,spd:35,spe:60},abilities:{0:"Trace",1:"Tangled Feet"},heightm:2,weightkg:130,color:"Blue",evos:["wailord"],eggGroups:["Ground","Water 2"]},
wailord:{num:321,species:"Wailord",types:["Water"],baseStats:{hp:170,atk:90,def:45,spa:90,spd:45,spe:60},abilities:{0:"Quick Feet",1:"Contrary"},heightm:14.5,weightkg:398,color:"Blue",prevo:"wailmer",evoLevel:40,eggGroups:["Ground","Water 2"]},
numel:{num:322,species:"Numel",types:["Fire","Ground"],baseStats:{hp:60,atk:60,def:40,spa:65,spd:45,spe:35},abilities:{0:"Cloud Nine",1:"Toxic Boost"},heightm:0.7,weightkg:24,color:"Yellow",evos:["camerupt"],eggGroups:["Ground"]},
camerupt:{num:323,species:"Camerupt",types:["Fire","Ground"],baseStats:{hp:70,atk:100,def:70,spa:105,spd:75,spe:40},abilities:{0:"Wonder Guard",1:"Big Pecks"},heightm:1.9,weightkg:220,color:"Red",prevo:"numel",evoLevel:33,eggGroups:["Ground"]},
torkoal:{num:324,species:"Torkoal",types:["Fire"],baseStats:{hp:70,atk:85,def:140,spa:85,spd:70,spe:20},abilities:{0:"Illusion",1:"Sand Force"},heightm:0.5,weightkg:80.4,color:"Brown",eggGroups:["Ground"]},
spoink:{num:325,species:"Spoink",types:["Psychic"],baseStats:{hp:60,atk:25,def:35,spa:70,spd:80,spe:60},abilities:{0:"Cute Charm",1:"Magma Armor"},heightm:0.7,weightkg:30.6,color:"Black",evos:["grumpig"],eggGroups:["Ground"]},
grumpig:{num:326,species:"Grumpig",types:["Psychic"],baseStats:{hp:80,atk:45,def:65,spa:90,spd:110,spe:80},abilities:{0:"Justified",1:"Cursed Body"},heightm:0.9,weightkg:71.5,color:"Purple",prevo:"spoink",evoLevel:32,eggGroups:["Ground"]},
spinda:{num:327,species:"Spinda",types:["Normal"],baseStats:{hp:60,atk:60,def:60,spa:60,spd:60,spe:60},abilities:{0:"Sand Veil",1:"Guts"},heightm:1.1,weightkg:5,color:"Brown",eggGroups:["Ground","Humanshape"]},
trapinch:{num:328,species:"Trapinch",types:["Ground"],baseStats:{hp:45,atk:100,def:45,spa:45,spd:45,spe:10},abilities:{0:"Battle Armor",1:"Serene Grace"},heightm:0.7,weightkg:15,color:"Brown",evos:["vibrava"],eggGroups:["Bug"]},
vibrava:{num:329,species:"Vibrava",types:["Ground","Dragon"],baseStats:{hp:50,atk:70,def:50,spa:50,spd:50,spe:70},abilities:{0:"Damp",1:"Light Metal"},heightm:1.1,weightkg:15.3,color:"Green",prevo:"trapinch",evos:["flygon"],evoLevel:35,eggGroups:["Bug"]},
flygon:{num:330,species:"Flygon",types:["Ground","Dragon"],baseStats:{hp:80,atk:100,def:80,spa:80,spd:80,spe:100},abilities:{0:"Color Change",1:"Solar Power"},heightm:2,weightkg:82,color:"Green",prevo:"vibrava",evoLevel:45,eggGroups:["Bug"]},
cacnea:{num:331,species:"Cacnea",types:["Grass"],baseStats:{hp:50,atk:85,def:40,spa:85,spd:40,spe:35},abilities:{0:"Analytic",1:"Cute Charm"},heightm:0.4,weightkg:51.3,color:"Green",evos:["cacturne"],eggGroups:["Plant","Humanshape"]},
cacturne:{num:332,species:"Cacturne",types:["Grass","Dark"],baseStats:{hp:70,atk:115,def:60,spa:115,spd:60,spe:55},abilities:{0:"Dry Skin",1:"Adaptability"},heightm:1.3,weightkg:77.4,color:"Green",prevo:"cacnea",evoLevel:32,eggGroups:["Plant","Humanshape"]},
swablu:{num:333,species:"Swablu",types:["Normal","Flying"],baseStats:{hp:45,atk:40,def:60,spa:40,spd:75,spe:50},abilities:{0:"Suction Cups",1:"Simple"},heightm:0.4,weightkg:1.2,color:"Blue",evos:["altaria"],eggGroups:["Flying","Dragon"]},
altaria:{num:334,species:"Altaria",types:["Dragon","Flying"],baseStats:{hp:75,atk:70,def:90,spa:70,spd:105,spe:80},abilities:{0:"Leaf Guard",1:"Color Change"},heightm:1.1,weightkg:20.6,color:"Blue",prevo:"swablu",evoLevel:35,eggGroups:["Flying","Dragon"]},
zangoose:{num:335,species:"Zangoose",types:["Normal"],baseStats:{hp:73,atk:115,def:60,spa:60,spd:60,spe:90},abilities:{0:"Infiltrator",1:"Shed Skin"},heightm:1.3,weightkg:40.3,color:"White",eggGroups:["Ground"]},
seviper:{num:336,species:"Seviper",types:["Poison"],baseStats:{hp:73,atk:100,def:60,spa:100,spd:60,spe:65},abilities:{0:"Serene Grace",1:"Sand Rush"},heightm:2.7,weightkg:52.5,color:"Black",eggGroups:["Ground","Dragon"]},
lunatone:{num:337,species:"Lunatone",types:["Rock","Psychic"],gender:"N",baseStats:{hp:70,atk:55,def:65,spa:95,spd:85,spe:70},abilities:{0:"Illusion",1:"Analytic"},heightm:1,weightkg:168,color:"Yellow",eggGroups:["Mineral"]},
solrock:{num:338,species:"Solrock",types:["Rock","Psychic"],gender:"N",baseStats:{hp:70,atk:95,def:85,spa:55,spd:65,spe:70},abilities:{0:"Pressure",1:"Moxie"},heightm:1.2,weightkg:154,color:"Red",eggGroups:["Mineral"]},
barboach:{num:339,species:"Barboach",types:["Water","Ground"],baseStats:{hp:50,atk:48,def:43,spa:46,spd:41,spe:60},abilities:{0:"Intimidate",1:"Rain Dish"},heightm:0.4,weightkg:1.9,color:"Gray",evos:["whiscash"],eggGroups:["Water 2"]},
whiscash:{num:340,species:"Whiscash",types:["Water","Ground"],baseStats:{hp:110,atk:78,def:73,spa:76,spd:71,spe:60},abilities:{0:"Damp",1:"Battle Armor"},heightm:0.9,weightkg:23.6,color:"Blue",prevo:"barboach",evoLevel:30,eggGroups:["Water 2"]},
corphish:{num:341,species:"Corphish",types:["Water"],baseStats:{hp:43,atk:80,def:65,spa:50,spd:35,spe:35},abilities:{0:"Anger Point",1:"Anticipation"},heightm:0.6,weightkg:11.5,color:"Red",evos:["crawdaunt"],eggGroups:["Water 1","Water 3"]},
crawdaunt:{num:342,species:"Crawdaunt",types:["Water","Dark"],baseStats:{hp:63,atk:120,def:85,spa:90,spd:55,spe:55},abilities:{0:"Speed Boost",1:"Oblivious"},heightm:1.1,weightkg:32.8,color:"Red",prevo:"corphish",evoLevel:30,eggGroups:["Water 1","Water 3"]},
baltoy:{num:343,species:"Baltoy",types:["Ground","Psychic"],gender:"N",baseStats:{hp:40,atk:40,def:55,spa:40,spd:70,spe:55},abilities:{0:"Clear Body",1:"Early Bird"},heightm:0.5,weightkg:21.5,color:"Brown",evos:["claydol"],eggGroups:["Mineral"]},
claydol:{num:344,species:"Claydol",types:["Ground","Psychic"],gender:"N",baseStats:{hp:60,atk:70,def:105,spa:70,spd:120,spe:75},abilities:{0:"Rattled",1:"Klutz"},heightm:1.5,weightkg:108,color:"Black",prevo:"baltoy",evoLevel:36,eggGroups:["Mineral"]},
lileep:{num:345,species:"Lileep",types:["Rock","Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:66,atk:41,def:77,spa:61,spd:87,spe:23},abilities:{0:"Skill Link",1:"Rain Dish"},heightm:1,weightkg:23.8,color:"Purple",evos:["cradily"],eggGroups:["Water 3"]},
cradily:{num:346,species:"Cradily",types:["Rock","Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:86,atk:81,def:97,spa:81,spd:107,spe:43},abilities:{0:"Analytic",1:"Serene Grace"},heightm:1.5,weightkg:60.4,color:"Green",prevo:"lileep",evoLevel:40,eggGroups:["Water 3"]},
anorith:{num:347,species:"Anorith",types:["Rock","Bug"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:95,def:50,spa:40,spd:50,spe:75},abilities:{0:"Suction Cups",1:"Reckless"},heightm:0.7,weightkg:12.5,color:"Gray",evos:["armaldo"],eggGroups:["Water 3"]},
armaldo:{num:348,species:"Armaldo",types:["Rock","Bug"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:125,def:100,spa:70,spd:80,spe:45},abilities:{0:"Magma Armor",1:"Stall"},heightm:1.5,weightkg:68.2,color:"Gray",prevo:"anorith",evoLevel:40,eggGroups:["Water 3"]},
feebas:{num:349,species:"Feebas",types:["Water"],baseStats:{hp:20,atk:15,def:20,spa:10,spd:55,spe:80},abilities:{0:"Clear Body",1:"Iron Barbs"},heightm:0.6,weightkg:7.4,color:"Brown",evos:["milotic"],eggGroups:["Water 1","Dragon"]},
milotic:{num:350,species:"Milotic",types:["Water"],baseStats:{hp:95,atk:60,def:79,spa:100,spd:125,spe:81},abilities:{0:"Big Pecks",1:"Snow Warning"},heightm:6.2,weightkg:162,color:"Pink",prevo:"feebas",evoLevel:1,eggGroups:["Water 1","Dragon"]},
castform:{num:351,species:"Castform",types:["Normal"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Wonder Guard",1:"Sap Sipper"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Indeterminate"],otherFormes:["castformsunny","castformrainy","castformsnowy"]},
castformsunny:{num:351,species:"Castform-Sunny",baseSpecies:"Castform",forme:"Sunny",formeLetter:"S",types:["Fire"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Wonder Guard",1:"Sap Sipper"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Indeterminate"]},
castformrainy:{num:351,species:"Castform-Rainy",baseSpecies:"Castform",forme:"Rainy",formeLetter:"R",types:["Water"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Wonder Guard",1:"Sap Sipper"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Indeterminate"]},
castformsnowy:{num:351,species:"Castform-Snowy",baseSpecies:"Castform",forme:"Snowy",formeLetter:"S",types:["Ice"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Wonder Guard",1:"Sap Sipper"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Indeterminate"]},
kecleon:{num:352,species:"Kecleon",types:["Normal"],baseStats:{hp:60,atk:90,def:70,spa:60,spd:120,spe:40},abilities:{0:"Inner Focus",1:"Dry Skin"},heightm:1,weightkg:22,color:"Green",eggGroups:["Ground"]},
shuppet:{num:353,species:"Shuppet",types:["Ghost"],baseStats:{hp:44,atk:75,def:35,spa:63,spd:33,spe:45},abilities:{0:"Chlorophyll",1:"Defiant"},heightm:0.6,weightkg:2.3,color:"Black",evos:["banette"],eggGroups:["Indeterminate"]},
banette:{num:354,species:"Banette",types:["Ghost"],baseStats:{hp:64,atk:115,def:65,spa:83,spd:63,spe:65},abilities:{0:"Clear Body",1:"Volt Absorb"},heightm:1.1,weightkg:12.5,color:"Black",prevo:"shuppet",evoLevel:37,eggGroups:["Indeterminate"]},
duskull:{num:355,species:"Duskull",types:["Ghost"],baseStats:{hp:20,atk:40,def:90,spa:30,spd:90,spe:25},abilities:{0:"Natural Cure",1:"Swift Swim"},heightm:0.8,weightkg:15,color:"Black",evos:["dusclops"],eggGroups:["Indeterminate"]},
dusclops:{num:356,species:"Dusclops",types:["Ghost"],baseStats:{hp:40,atk:70,def:130,spa:60,spd:130,spe:25},abilities:{0:"Oblivious",1:"Wonder Skin"},heightm:1.6,weightkg:30.6,color:"Black",prevo:"duskull",evos:["dusknoir"],evoLevel:37,eggGroups:["Indeterminate"]},
dusknoir:{num:477,species:"Dusknoir",types:["Ghost"],baseStats:{hp:45,atk:100,def:135,spa:65,spd:135,spe:45},abilities:{0:"Natural Cure",1:"Sand Force"},heightm:2.2,weightkg:106.6,color:"Black",prevo:"dusclops",evoLevel:1,eggGroups:["Indeterminate"]},
tropius:{num:357,species:"Tropius",types:["Grass","Flying"],baseStats:{hp:99,atk:68,def:83,spa:72,spd:87,spe:51},abilities:{0:"Cursed Body",1:"Immunity"},heightm:2,weightkg:100,color:"Green",eggGroups:["Monster","Plant"]},
chingling:{num:433,species:"Chingling",types:["Psychic"],baseStats:{hp:45,atk:30,def:50,spa:65,spd:50,spe:45},abilities:{0:"Magnet Pull",1:"Flare Boost"},heightm:0.2,weightkg:0.6,color:"Yellow",evos:["chimecho"],eggGroups:["No Eggs"]},
chimecho:{num:358,species:"Chimecho",types:["Psychic"],baseStats:{hp:65,atk:50,def:70,spa:95,spd:80,spe:65},abilities:{0:"Swift Swim",1:"Rock Head"},heightm:0.6,weightkg:1,color:"Blue",prevo:"chingling",evoLevel:1,eggGroups:["Indeterminate"]},
absol:{num:359,species:"Absol",types:["Dark"],baseStats:{hp:65,atk:130,def:60,spa:75,spd:60,spe:75},abilities:{0:"Volt Absorb",1:"Sticky Hold"},heightm:1.2,weightkg:47,color:"White",eggGroups:["Ground"]},
snorunt:{num:361,species:"Snorunt",types:["Ice"],baseStats:{hp:50,atk:50,def:50,spa:50,spd:50,spe:50},abilities:{0:"No Guard",1:"Insomnia"},heightm:0.7,weightkg:16.8,color:"Gray",evos:["glalie","froslass"],eggGroups:["Fairy","Mineral"]},
glalie:{num:362,species:"Glalie",types:["Ice"],baseStats:{hp:80,atk:80,def:80,spa:80,spd:80,spe:80},abilities:{0:"Overcoat",1:"Clear Body"},heightm:1.5,weightkg:256.5,color:"Gray",prevo:"snorunt",evoLevel:42,eggGroups:["Fairy","Mineral"]},
froslass:{num:478,species:"Froslass",types:["Ice","Ghost"],gender:"F",baseStats:{hp:70,atk:80,def:70,spa:80,spd:70,spe:110},abilities:{0:"Overcoat",1:"Heatproof"},heightm:1.3,weightkg:26.6,color:"White",prevo:"snorunt",evoLevel:1,eggGroups:["Fairy","Mineral"]},
spheal:{num:363,species:"Spheal",types:["Ice","Water"],baseStats:{hp:70,atk:40,def:50,spa:55,spd:50,spe:25},abilities:{0:"Multiscale",1:"Static"},heightm:0.8,weightkg:39.5,color:"Blue",evos:["sealeo"],eggGroups:["Water 1","Ground"]},
sealeo:{num:364,species:"Sealeo",types:["Ice","Water"],baseStats:{hp:90,atk:60,def:70,spa:75,spd:70,spe:45},abilities:{0:"Pressure",1:"Drought"},heightm:1.1,weightkg:87.6,color:"Blue",prevo:"spheal",evos:["walrein"],evoLevel:32,eggGroups:["Water 1","Ground"]},
walrein:{num:365,species:"Walrein",types:["Ice","Water"],baseStats:{hp:110,atk:80,def:90,spa:95,spd:90,spe:65},abilities:{0:"Sap Sipper",1:"Mold Breaker"},heightm:1.4,weightkg:150.6,color:"Blue",prevo:"sealeo",evoLevel:44,eggGroups:["Water 1","Ground"]},
clamperl:{num:366,species:"Clamperl",types:["Water"],baseStats:{hp:35,atk:64,def:85,spa:74,spd:55,spe:32},abilities:{0:"Heavy Metal",1:"Sand Rush"},heightm:0.4,weightkg:52.5,color:"Blue",evos:["huntail","gorebyss"],eggGroups:["Water 1"]},
huntail:{num:367,species:"Huntail",types:["Water"],baseStats:{hp:55,atk:104,def:105,spa:94,spd:75,spe:52},abilities:{0:"Anger Point",1:"Multiscale"},heightm:1.7,weightkg:27,color:"Blue",prevo:"clamperl",evoLevel:1,eggGroups:["Water 1"]},
gorebyss:{num:368,species:"Gorebyss",types:["Water"],baseStats:{hp:55,atk:84,def:105,spa:114,spd:75,spe:52},abilities:{0:"Cloud Nine",1:"Rivalry"},heightm:1.8,weightkg:22.6,color:"Pink",prevo:"clamperl",evoLevel:1,eggGroups:["Water 1"]},
relicanth:{num:369,species:"Relicanth",types:["Water","Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:100,atk:90,def:130,spa:45,spd:65,spe:55},abilities:{0:"Flare Boost",1:"Anticipation"},heightm:1,weightkg:23.4,color:"Gray",eggGroups:["Water 1","Water 2"]},
luvdisc:{num:370,species:"Luvdisc",types:["Water"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:43,atk:30,def:55,spa:40,spd:65,spe:97},abilities:{0:"Unaware",1:"Adaptability"},heightm:0.6,weightkg:8.7,color:"Pink",eggGroups:["Water 2"]},
bagon:{num:371,species:"Bagon",types:["Dragon"],baseStats:{hp:45,atk:75,def:60,spa:40,spd:30,spe:50},abilities:{0:"Simple",1:"Blaze"},heightm:0.6,weightkg:42.1,color:"Blue",evos:["shelgon"],eggGroups:["Dragon"]},
shelgon:{num:372,species:"Shelgon",types:["Dragon"],baseStats:{hp:65,atk:95,def:100,spa:60,spd:50,spe:50},abilities:{0:"Pressure",1:"Magic Guard"},heightm:1.1,weightkg:110.5,color:"White",prevo:"bagon",evos:["salamence"],evoLevel:30,eggGroups:["Dragon"]},
salamence:{num:373,species:"Salamence",types:["Dragon","Flying"],baseStats:{hp:95,atk:135,def:80,spa:110,spd:80,spe:100},abilities:{0:"Forewarn",1:"Poison Point"},heightm:1.5,weightkg:102.6,color:"Blue",prevo:"shelgon",evoLevel:50,eggGroups:["Dragon"]},
beldum:{num:374,species:"Beldum",types:["Steel","Psychic"],gender:"N",baseStats:{hp:40,atk:55,def:80,spa:35,spd:60,spe:30},abilities:{0:"Snow Warning",1:"Justified"},heightm:0.6,weightkg:95.2,color:"Blue",evos:["metang"],eggGroups:["Mineral"]},
metang:{num:375,species:"Metang",types:["Steel","Psychic"],gender:"N",baseStats:{hp:60,atk:75,def:100,spa:55,spd:80,spe:50},abilities:{0:"Flare Boost",1:"Steadfast"},heightm:1.2,weightkg:202.5,color:"Blue",prevo:"beldum",evos:["metagross"],evoLevel:20,eggGroups:["Mineral"]},
metagross:{num:376,species:"Metagross",types:["Steel","Psychic"],gender:"N",baseStats:{hp:80,atk:135,def:130,spa:95,spd:90,spe:70},abilities:{0:"Tangled Feet",1:"Battle Armor"},heightm:1.6,weightkg:550,color:"Blue",prevo:"metang",evoLevel:45,eggGroups:["Mineral"]},
regirock:{num:377,species:"Regirock",types:["Rock"],gender:"N",baseStats:{hp:80,atk:100,def:200,spa:50,spd:100,spe:50},abilities:{0:"Water Absorb",1:"Dry Skin"},heightm:1.7,weightkg:230,color:"Brown",eggGroups:["No Eggs"]},
regice:{num:378,species:"Regice",types:["Ice"],gender:"N",baseStats:{hp:80,atk:50,def:100,spa:100,spd:200,spe:50},abilities:{0:"Poison Heal",1:"Drought"},heightm:1.8,weightkg:175,color:"Blue",eggGroups:["No Eggs"]},
registeel:{num:379,species:"Registeel",types:["Steel"],gender:"N",baseStats:{hp:80,atk:75,def:150,spa:75,spd:150,spe:50},abilities:{0:"Harvest",1:"Pickpocket"},heightm:1.9,weightkg:205,color:"Gray",eggGroups:["No Eggs"]},
latias:{num:380,species:"Latias",types:["Dragon","Psychic"],gender:"F",baseStats:{hp:80,atk:80,def:90,spa:110,spd:130,spe:110},abilities:{0:"Pickpocket",1:"Limber"},heightm:1.4,weightkg:40,color:"Red",eggGroups:["No Eggs"]},
latios:{num:381,species:"Latios",types:["Dragon","Psychic"],gender:"M",baseStats:{hp:80,atk:90,def:80,spa:130,spd:110,spe:110},abilities:{0:"Harvest",1:"Heavy Metal"},heightm:2,weightkg:60,color:"Blue",eggGroups:["No Eggs"]},
kyogre:{num:382,species:"Kyogre",types:["Water"],gender:"N",baseStats:{hp:100,atk:100,def:90,spa:150,spd:140,spe:90},abilities:{0:"Pickpocket",1:"Sand Veil"},heightm:4.5,weightkg:352,color:"Blue",eggGroups:["No Eggs"]},
groudon:{num:383,species:"Groudon",types:["Ground"],gender:"N",baseStats:{hp:100,atk:150,def:140,spa:100,spd:90,spe:90},abilities:{0:"Simple",1:"Rain Dish"},heightm:3.5,weightkg:950,color:"Red",eggGroups:["No Eggs"]},
rayquaza:{num:384,species:"Rayquaza",types:["Dragon","Flying"],gender:"N",baseStats:{hp:105,atk:150,def:90,spa:150,spd:90,spe:95},abilities:{0:"Rain Dish",1:"Dry Skin"},heightm:7,weightkg:206.5,color:"Green",eggGroups:["No Eggs"]},
jirachi:{num:385,species:"Jirachi",types:["Steel","Psychic"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Snow Cloak",1:"Solar Power"},heightm:0.3,weightkg:1.1,color:"Yellow",eggGroups:["No Eggs"]},
deoxys:{num:386,species:"Deoxys",baseForme:"Normal",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:150,def:50,spa:150,spd:50,spe:150},abilities:{0:"Early Bird",1:"Flare Boost"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["No Eggs"],otherFormes:["deoxysattack","deoxysdefense","deoxysspeed"]},
deoxysattack:{num:386,species:"Deoxys-Attack",baseSpecies:"Deoxys",forme:"Attack",formeLetter:"A",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:180,def:20,spa:180,spd:20,spe:150},abilities:{0:"Cloud Nine",1:"Unaware"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["No Eggs"]},
deoxysdefense:{num:386,species:"Deoxys-Defense",baseSpecies:"Deoxys",forme:"Defense",formeLetter:"D",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:70,def:160,spa:70,spd:160,spe:90},abilities:{0:"Sand Force",1:"Quick Feet"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["No Eggs"]},
deoxysspeed:{num:386,species:"Deoxys-Speed",baseSpecies:"Deoxys",forme:"Speed",formeLetter:"S",types:["Psychic"],gender:"N",baseStats:{hp:50,atk:95,def:90,spa:95,spd:90,spe:180},abilities:{0:"Unburden",1:"Reckless"},heightm:1.7,weightkg:60.8,color:"Red",eggGroups:["No Eggs"]},
turtwig:{num:387,species:"Turtwig",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:68,def:64,spa:45,spd:55,spe:31},abilities:{0:"Swift Swim",1:"Marvel Scale"},heightm:0.4,weightkg:10.2,color:"Green",evos:["grotle"],eggGroups:["Monster","Plant"]},
grotle:{num:388,species:"Grotle",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:89,def:85,spa:55,spd:65,spe:36},abilities:{0:"Pressure",1:"Stall"},heightm:1.1,weightkg:97,color:"Green",prevo:"turtwig",evos:["torterra"],evoLevel:18,eggGroups:["Monster","Plant"]},
torterra:{num:389,species:"Torterra",types:["Grass","Ground"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:109,def:105,spa:75,spd:85,spe:56},abilities:{0:"Pickpocket",1:"Sand Rush"},heightm:2.2,weightkg:310,color:"Green",prevo:"grotle",evoLevel:32,eggGroups:["Monster","Plant"]},
chimchar:{num:390,species:"Chimchar",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:44,atk:58,def:44,spa:58,spd:44,spe:61},abilities:{0:"Drought",1:"Solid Rock"},heightm:0.5,weightkg:6.2,color:"Brown",evos:["monferno"],eggGroups:["Ground","Humanshape"]},
monferno:{num:391,species:"Monferno",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:64,atk:78,def:52,spa:78,spd:52,spe:81},abilities:{0:"Stall",1:"Unnerve"},heightm:0.9,weightkg:22,color:"Brown",prevo:"chimchar",evos:["infernape"],evoLevel:14,eggGroups:["Ground","Humanshape"]},
infernape:{num:392,species:"Infernape",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:76,atk:104,def:71,spa:104,spd:71,spe:108},abilities:{0:"Super Luck",1:"Intimidate"},heightm:1.2,weightkg:55,color:"Brown",prevo:"monferno",evoLevel:36,eggGroups:["Ground","Humanshape"]},
piplup:{num:393,species:"Piplup",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:53,atk:51,def:53,spa:61,spd:56,spe:40},abilities:{0:"Quick Feet",1:"Heatproof"},heightm:0.4,weightkg:5.2,color:"Blue",evos:["prinplup"],eggGroups:["Water 1","Ground"]},
prinplup:{num:394,species:"Prinplup",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:64,atk:66,def:68,spa:81,spd:76,spe:50},abilities:{0:"Technician",1:"Overgrow"},heightm:0.8,weightkg:23,color:"Blue",prevo:"piplup",evos:["empoleon"],evoLevel:16,eggGroups:["Water 1","Ground"]},
empoleon:{num:395,species:"Empoleon",types:["Water","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:84,atk:86,def:88,spa:111,spd:101,spe:60},abilities:{0:"Rain Dish",1:"Skill Link"},heightm:1.7,weightkg:84.5,color:"Blue",prevo:"prinplup",evoLevel:36,eggGroups:["Water 1","Ground"]},
starly:{num:396,species:"Starly",types:["Normal","Flying"],baseStats:{hp:40,atk:55,def:30,spa:30,spd:30,spe:60},abilities:{0:"Liquid Ooze",1:"Defiant"},heightm:0.3,weightkg:2,color:"Brown",evos:["staravia"],eggGroups:["Flying"]},
staravia:{num:397,species:"Staravia",types:["Normal","Flying"],baseStats:{hp:55,atk:75,def:50,spa:40,spd:40,spe:80},abilities:{0:"Iron Barbs",1:"Multiscale"},heightm:0.6,weightkg:15.5,color:"Brown",prevo:"starly",evos:["staraptor"],evoLevel:14,eggGroups:["Flying"]},
staraptor:{num:398,species:"Staraptor",types:["Normal","Flying"],baseStats:{hp:85,atk:120,def:70,spa:50,spd:50,spe:100},abilities:{0:"Flare Boost",1:"Flash Fire"},heightm:1.2,weightkg:24.9,color:"Brown",prevo:"staravia",evoLevel:34,eggGroups:["Flying"]},
bidoof:{num:399,species:"Bidoof",types:["Normal"],baseStats:{hp:59,atk:45,def:40,spa:35,spd:40,spe:31},abilities:{0:"Pure Power",1:"Ice Body"},heightm:0.5,weightkg:20,color:"Brown",evos:["bibarel"],eggGroups:["Water 1","Ground"]},
bibarel:{num:400,species:"Bibarel",types:["Normal","Water"],baseStats:{hp:79,atk:85,def:60,spa:55,spd:60,spe:71},abilities:{0:"Super Luck",1:"Snow Warning"},heightm:1,weightkg:31.5,color:"Brown",prevo:"bidoof",evoLevel:15,eggGroups:["Water 1","Ground"]},
kricketot:{num:401,species:"Kricketot",types:["Bug"],baseStats:{hp:37,atk:25,def:41,spa:25,spd:41,spe:25},abilities:{0:"Sturdy",1:"Quick Feet"},heightm:0.3,weightkg:2.2,color:"Red",evos:["kricketune"],eggGroups:["Bug"]},
kricketune:{num:402,species:"Kricketune",types:["Bug"],baseStats:{hp:77,atk:85,def:51,spa:55,spd:51,spe:65},abilities:{0:"Steadfast",1:"Clear Body"},heightm:1,weightkg:25.5,color:"Red",prevo:"kricketot",evoLevel:10,eggGroups:["Bug"]},
shinx:{num:403,species:"Shinx",types:["Electric"],baseStats:{hp:45,atk:65,def:34,spa:40,spd:34,spe:45},abilities:{0:"Pickpocket",1:"Sheer Force"},heightm:0.5,weightkg:9.5,color:"Blue",evos:["luxio"],eggGroups:["Ground"]},
luxio:{num:404,species:"Luxio",types:["Electric"],baseStats:{hp:60,atk:85,def:49,spa:60,spd:49,spe:60},abilities:{0:"Motor Drive",1:"Solar Power"},heightm:0.9,weightkg:30.5,color:"Blue",prevo:"shinx",evos:["luxray"],evoLevel:15,eggGroups:["Ground"]},
luxray:{num:405,species:"Luxray",types:["Electric"],baseStats:{hp:80,atk:120,def:79,spa:95,spd:79,spe:70},abilities:{0:"Weak Armor",1:"Insomnia"},heightm:1.4,weightkg:42,color:"Blue",prevo:"luxio",evoLevel:30,eggGroups:["Ground"]},
cranidos:{num:408,species:"Cranidos",types:["Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:67,atk:125,def:40,spa:30,spd:30,spe:58},abilities:{0:"Quick Feet",1:"Color Change"},heightm:0.9,weightkg:31.5,color:"Blue",evos:["rampardos"],eggGroups:["Monster"]},
rampardos:{num:409,species:"Rampardos",types:["Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:97,atk:165,def:60,spa:65,spd:50,spe:58},abilities:{0:"Victory Star",1:"Sniper"},heightm:1.6,weightkg:102.5,color:"Blue",prevo:"cranidos",evoLevel:30,eggGroups:["Monster"]},
shieldon:{num:410,species:"Shieldon",types:["Rock","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:42,def:118,spa:42,spd:88,spe:30},abilities:{0:"Normalize",1:"Sap Sipper"},heightm:0.5,weightkg:57,color:"Gray",evos:["bastiodon"],eggGroups:["Monster"]},
bastiodon:{num:411,species:"Bastiodon",types:["Rock","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:52,def:168,spa:47,spd:138,spe:30},abilities:{0:"Battle Armor",1:"Damp"},heightm:1.3,weightkg:149.5,color:"Gray",prevo:"shieldon",evoLevel:30,eggGroups:["Monster"]},
burmy:{num:412,species:"Burmy",baseForme:"Plant",types:["Bug"],baseStats:{hp:40,atk:29,def:45,spa:29,spd:45,spe:36},abilities:{0:"Light Metal",1:"Inner Focus"},heightm:0.2,weightkg:3.4,color:"Gray",evos:["wormadam","wormadamsandy","wormadamtrash","mothim"],eggGroups:["Bug"],otherForms:["burmysandy","burmytrash"]},
wormadam:{num:413,species:"Wormadam",baseForme:"Plant",types:["Bug","Grass"],gender:"F",baseStats:{hp:60,atk:59,def:85,spa:79,spd:105,spe:36},abilities:{0:"Sand Veil",1:"Sniper"},heightm:0.5,weightkg:6.5,color:"Gray",prevo:"burmy",evoLevel:20,eggGroups:["Bug"],otherFormes:["wormadamsandy","wormadamtrash"]},
wormadamsandy:{num:413,species:"Wormadam-Sandy",baseSpecies:"Wormadam",forme:"Sandy",formeLetter:"G",types:["Bug","Ground"],gender:"F",baseStats:{hp:60,atk:79,def:105,spa:59,spd:85,spe:36},abilities:{0:"Hustle",1:"Sand Force"},heightm:0.5,weightkg:6.5,color:"Gray",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]},
wormadamtrash:{num:413,species:"Wormadam-Trash",baseSpecies:"Wormadam",forme:"Trash",formeLetter:"S",types:["Bug","Steel"],gender:"F",baseStats:{hp:60,atk:69,def:95,spa:69,spd:95,spe:36},abilities:{0:"Limber",1:"Motor Drive"},heightm:0.5,weightkg:6.5,color:"Gray",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]},
mothim:{num:414,species:"Mothim",types:["Bug","Flying"],gender:"M",baseStats:{hp:70,atk:94,def:50,spa:94,spd:50,spe:66},abilities:{0:"Defiant",1:"Unburden"},heightm:0.9,weightkg:23.3,color:"Yellow",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]},
combee:{num:415,species:"Combee",types:["Bug","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:30,def:42,spa:30,spd:42,spe:70},abilities:{0:"Lightningrod",1:"Normalize"},heightm:0.3,weightkg:5.5,color:"Yellow",evos:["vespiquen"],eggGroups:["Bug"]},
vespiquen:{num:416,species:"Vespiquen",types:["Bug","Flying"],gender:"F",baseStats:{hp:70,atk:80,def:102,spa:80,spd:102,spe:40},abilities:{0:"Simpe",1:"Tangled Feet"},heightm:1.2,weightkg:38.5,color:"Yellow",prevo:"combee",evoLevel:21,eggGroups:["Bug"]},
pachirisu:{num:417,species:"Pachirisu",types:["Electric"],baseStats:{hp:60,atk:45,def:70,spa:45,spd:90,spe:95},abilities:{0:"Super Luck",1:"Heavy Metal"},heightm:0.4,weightkg:3.9,color:"White",eggGroups:["Ground","Fairy"]},
buizel:{num:418,species:"Buizel",types:["Water"],baseStats:{hp:55,atk:65,def:35,spa:60,spd:30,spe:85},abilities:{0:"Storm Drain",1:"Pressure"},heightm:0.7,weightkg:29.5,color:"Brown",evos:["floatzel"],eggGroups:["Water 1","Ground"]},
floatzel:{num:419,species:"Floatzel",types:["Water"],baseStats:{hp:85,atk:105,def:55,spa:85,spd:50,spe:115},abilities:{0:"Imposter",1:"Mold Breaker"},heightm:1.1,weightkg:33.5,color:"Brown",prevo:"buizel",evoLevel:26,eggGroups:["Water 1","Ground"]},
cherubi:{num:420,species:"Cherubi",types:["Grass"],baseStats:{hp:45,atk:35,def:45,spa:62,spd:53,spe:35},abilities:{0:"Flash Fire",1:"Guts"},heightm:0.4,weightkg:3.3,color:"Pink",evos:["cherrim"],eggGroups:["Fairy","Plant"]},
cherrim:{num:421,species:"Cherrim",baseForme:"Overcast",types:["Grass"],baseStats:{hp:70,atk:60,def:70,spa:87,spd:78,spe:85},abilities:{0:"Leaf Guard",1:"Battle Armor"},heightm:0.5,weightkg:9.3,color:"Pink",prevo:"cherubi",evoLevel:25,eggGroups:["Fairy","Plant"],otherFormes:["cherrimsunshine"]},
cherrimsunshine:{num:421,species:"Cherrim-Sunshine",baseSpecies:"Cherrim",forme:"Sunshine",formeLetter:"S",types:["Grass"],baseStats:{hp:70,atk:60,def:70,spa:87,spd:78,spe:85},abilities:{0:"Leaf Guard",1:"Battle Armor"},heightm:0.5,weightkg:9.3,color:"Pink",prevo:"cherubi",evoLevel:25,eggGroups:["Fairy","Plant"]},
shellos:{num:422,species:"Shellos",baseForme:"West",types:["Water"],baseStats:{hp:76,atk:48,def:48,spa:57,spd:62,spe:34},abilities:{0:"Own Tempo",1:"Swift Swim"},heightm:0.3,weightkg:6.3,color:"Purple",evos:["gastrodon"],eggGroups:["Water 1","Indeterminate"],otherForms:["shelloseast"]},
gastrodon:{num:423,species:"Gastrodon",baseForme:"West",types:["Water","Ground"],baseStats:{hp:111,atk:83,def:68,spa:92,spd:82,spe:39},abilities:{0:"Hustle",1:"Rivalry"},heightm:0.9,weightkg:29.9,color:"Purple",prevo:"shellos",evoLevel:30,eggGroups:["Water 1","Indeterminate"],otherForms:["gastrodoneast"]},
drifloon:{num:425,species:"Drifloon",types:["Ghost","Flying"],baseStats:{hp:90,atk:50,def:34,spa:60,spd:44,spe:70},abilities:{0:"Drought",1:"Adaptability"},heightm:0.4,weightkg:1.2,color:"Purple",evos:["drifblim"],eggGroups:["Indeterminate"]},
drifblim:{num:426,species:"Drifblim",types:["Ghost","Flying"],baseStats:{hp:150,atk:80,def:44,spa:90,spd:54,spe:80},abilities:{0:"Bad Dreams",1:"Cute Charm"},heightm:1.2,weightkg:15,color:"Purple",prevo:"drifloon",evoLevel:28,eggGroups:["Indeterminate"]},
buneary:{num:427,species:"Buneary",types:["Normal"],baseStats:{hp:55,atk:66,def:44,spa:44,spd:56,spe:85},abilities:{0:"Rattled",1:"Early Bird"},heightm:0.4,weightkg:5.5,color:"Brown",evos:["lopunny"],eggGroups:["Ground","Humanshape"]},
lopunny:{num:428,species:"Lopunny",types:["Normal"],baseStats:{hp:65,atk:76,def:84,spa:54,spd:96,spe:105},abilities:{0:"Snow Warning",1:"Justified"},heightm:1.2,weightkg:33.3,color:"Brown",prevo:"buneary",evoLevel:1,eggGroups:["Ground","Humanshape"]},
glameow:{num:431,species:"Glameow",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:49,atk:55,def:42,spa:42,spd:37,spe:85},abilities:{0:"Toxic Boost",1:"Light Metal"},heightm:0.5,weightkg:3.9,color:"Gray",evos:["purugly"],eggGroups:["Ground"]},
purugly:{num:432,species:"Purugly",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:71,atk:82,def:64,spa:64,spd:59,spe:112},abilities:{0:"Shadow Tag",1:"Sturdy"},heightm:1,weightkg:43.8,color:"Gray",prevo:"glameow",evoLevel:38,eggGroups:["Ground"]},
stunky:{num:434,species:"Stunky",types:["Poison","Dark"],baseStats:{hp:63,atk:63,def:47,spa:41,spd:41,spe:74},abilities:{0:"Super Luck",1:"Download"},heightm:0.4,weightkg:19.2,color:"Purple",evos:["skuntank"],eggGroups:["Ground"]},
skuntank:{num:435,species:"Skuntank",types:["Poison","Dark"],baseStats:{hp:103,atk:93,def:67,spa:71,spd:61,spe:84},abilities:{0:"Wonder Skin",1:"Leaf Guard"},heightm:1,weightkg:38,color:"Purple",prevo:"stunky",evoLevel:34,eggGroups:["Ground"]},
bronzor:{num:436,species:"Bronzor",types:["Steel","Psychic"],gender:"N",baseStats:{hp:57,atk:24,def:86,spa:24,spd:86,spe:23},abilities:{0:"Mummy",1:"Hustle"},heightm:0.5,weightkg:60.5,color:"Green",evos:["bronzong"],eggGroups:["Mineral"]},
bronzong:{num:437,species:"Bronzong",types:["Steel","Psychic"],gender:"N",baseStats:{hp:67,atk:89,def:116,spa:79,spd:116,spe:33},abilities:{0:"Defiant",1:"No Guard"},heightm:1.3,weightkg:187,color:"Green",prevo:"bronzor",evoLevel:33,eggGroups:["Mineral"]},
chatot:{num:441,species:"Chatot",types:["Normal","Flying"],baseStats:{hp:76,atk:65,def:45,spa:92,spd:42,spe:91},abilities:{0:"Wonder Skin",1:"Sap Sipper"},heightm:0.5,weightkg:1.9,color:"Black",eggGroups:["Flying"]},
spiritomb:{num:442,species:"Spiritomb",types:["Ghost","Dark"],baseStats:{hp:50,atk:92,def:108,spa:92,spd:108,spe:35},abilities:{0:"Effect Spore",1:"Cute Charm"},heightm:1,weightkg:108,color:"Purple",eggGroups:["Indeterminate"]},
gible:{num:443,species:"Gible",types:["Dragon","Ground"],baseStats:{hp:58,atk:70,def:45,spa:40,spd:45,spe:42},abilities:{0:"Drizzle",1:"Magma Armor"},heightm:0.7,weightkg:20.5,color:"Blue",evos:["gabite"],eggGroups:["Monster","Dragon"]},
gabite:{num:444,species:"Gabite",types:["Dragon","Ground"],baseStats:{hp:68,atk:90,def:65,spa:50,spd:55,spe:82},abilities:{0:"Wonder Guard",1:"Bad Dreams"},heightm:1.4,weightkg:56,color:"Blue",prevo:"gible",evos:["garchomp"],evoLevel:24,eggGroups:["Monster","Dragon"]},
garchomp:{num:445,species:"Garchomp",types:["Dragon","Ground"],baseStats:{hp:108,atk:130,def:95,spa:80,spd:85,spe:102},abilities:{0:"Sticky Hold",1:"Normalize"},heightm:1.9,weightkg:95,color:"Blue",prevo:"gabite",evoLevel:48,eggGroups:["Monster","Dragon"]},
riolu:{num:447,species:"Riolu",types:["Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:70,def:40,spa:35,spd:40,spe:60},abilities:{0:"Analytic",1:"Tangled Feet"},heightm:0.7,weightkg:20.2,color:"Blue",evos:["lucario"],eggGroups:["No Eggs"]},
lucario:{num:448,species:"Lucario",types:["Fighting","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:110,def:70,spa:115,spd:70,spe:90},abilities:{0:"Magnet Pull",1:"Poison Touch"},heightm:1.2,weightkg:54,color:"Blue",prevo:"riolu",evoLevel:1,eggGroups:["Ground","Humanshape"]},
hippopotas:{num:449,species:"Hippopotas",types:["Ground"],baseStats:{hp:68,atk:72,def:78,spa:38,spd:42,spe:32},abilities:{0:"Klutz",1:"Clear Body"},heightm:0.8,weightkg:49.5,color:"Brown",evos:["hippowdon"],eggGroups:["Ground"]},
hippowdon:{num:450,species:"Hippowdon",types:["Ground"],baseStats:{hp:108,atk:112,def:118,spa:68,spd:72,spe:47},abilities:{0:"Swift Swim",1:"Gluttony"},heightm:2,weightkg:300,color:"Brown",prevo:"hippopotas",evoLevel:34,eggGroups:["Ground"]},
skorupi:{num:451,species:"Skorupi",types:["Poison","Bug"],baseStats:{hp:40,atk:50,def:90,spa:30,spd:55,spe:65},abilities:{0:"Cursed Body",1:"Pickpocket"},heightm:0.8,weightkg:12,color:"Purple",evos:["drapion"],eggGroups:["Bug","Water 3"]},
drapion:{num:452,species:"Drapion",types:["Poison","Dark"],baseStats:{hp:70,atk:90,def:110,spa:60,spd:75,spe:95},abilities:{0:"Sheer Force",1:"Suction Cups"},heightm:1.3,weightkg:61.5,color:"Purple",prevo:"skorupi",evoLevel:40,eggGroups:["Bug","Water 3"]},
croagunk:{num:453,species:"Croagunk",types:["Poison","Fighting"],baseStats:{hp:48,atk:61,def:40,spa:61,spd:40,spe:50},abilities:{0:"Oblivious",1:"Sap Sipper"},heightm:0.7,weightkg:23,color:"Blue",evos:["toxicroak"],eggGroups:["Humanshape"]},
toxicroak:{num:454,species:"Toxicroak",types:["Poison","Fighting"],baseStats:{hp:83,atk:106,def:65,spa:86,spd:65,spe:85},abilities:{0:"Iron Fist",1:"Anger Point"},heightm:1.3,weightkg:44.4,color:"Blue",prevo:"croagunk",evoLevel:37,eggGroups:["Humanshape"]},
carnivine:{num:455,species:"Carnivine",types:["Grass"],baseStats:{hp:74,atk:100,def:72,spa:90,spd:72,spe:46},abilities:{0:"Bad Dreams",1:"Defiant"},heightm:1.4,weightkg:27,color:"Green",eggGroups:["Plant"]},
finneon:{num:456,species:"Finneon",types:["Water"],baseStats:{hp:49,atk:49,def:56,spa:49,spd:61,spe:66},abilities:{0:"Leaf Guard",1:"Mummy"},heightm:0.4,weightkg:7,color:"Blue",evos:["lumineon"],eggGroups:["Water 2"]},
lumineon:{num:457,species:"Lumineon",types:["Water"],baseStats:{hp:69,atk:69,def:76,spa:69,spd:86,spe:91},abilities:{0:"Pickpocket",1:"Big Pecks"},heightm:1.2,weightkg:24,color:"Blue",prevo:"finneon",evoLevel:31,eggGroups:["Water 2"]},
snover:{num:459,species:"Snover",types:["Grass","Ice"],baseStats:{hp:60,atk:62,def:50,spa:62,spd:60,spe:40},abilities:{0:"Storm Drain",1:"Inner Focus"},heightm:1,weightkg:50.5,color:"White",evos:["abomasnow"],eggGroups:["Monster","Plant"]},
abomasnow:{num:460,species:"Abomasnow",types:["Grass","Ice"],baseStats:{hp:90,atk:92,def:75,spa:92,spd:85,spe:60},abilities:{0:"Clear Body",1:"Own Tempo"},heightm:2.2,weightkg:135.5,color:"White",prevo:"snover",evoLevel:40,eggGroups:["Monster","Plant"]},
rotom:{num:479,species:"Rotom",types:["Electric","Ghost"],gender:"N",baseStats:{hp:50,atk:50,def:77,spa:95,spd:77,spe:91},abilities:{0:"Steadfast",1:"Gluttony"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"],otherFormes:["rotomheat","rotomwash","rotomfrost","rotomfan","rotommow"]},
rotomheat:{num:479,species:"Rotom-Heat",baseSpecies:"Rotom",forme:"Heat",formeLetter:"H",types:["Electric","Fire"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Rain Dish",1:"Clear Body"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
rotomwash:{num:479,species:"Rotom-Wash",baseSpecies:"Rotom",forme:"Wash",formeLetter:"W",types:["Electric","Water"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Torrent",1:"Overcoat"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
rotomfrost:{num:479,species:"Rotom-Frost",baseSpecies:"Rotom",forme:"Frost",formeLetter:"F",types:["Electric","Ice"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Pressure",1:"Cloud Nine"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
rotomfan:{num:479,species:"Rotom-Fan",baseSpecies:"Rotom",forme:"Fan",formeLetter:"S",types:["Electric","Flying"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Sticky Hold",1:"Klutz"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
rotommow:{num:479,species:"Rotom-Mow",baseSpecies:"Rotom",forme:"Mow",formeLetter:"C",types:["Electric","Grass"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Oblivious",1:"Synchronize"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
uxie:{num:480,species:"Uxie",types:["Psychic"],gender:"N",baseStats:{hp:75,atk:75,def:130,spa:75,spd:130,spe:95},abilities:{0:"Limber",1:"Heatproof"},heightm:0.3,weightkg:0.3,color:"Yellow",eggGroups:["No Eggs"]},
mesprit:{num:481,species:"Mesprit",types:["Psychic"],gender:"N",baseStats:{hp:80,atk:105,def:105,spa:105,spd:105,spe:80},abilities:{0:"Clear Body",1:"Shadow Tag"},heightm:0.3,weightkg:0.3,color:"Pink",eggGroups:["No Eggs"]},
azelf:{num:482,species:"Azelf",types:["Psychic"],gender:"N",baseStats:{hp:75,atk:125,def:70,spa:125,spd:70,spe:115},abilities:{0:"Dry Skin",1:"Defiant"},heightm:0.3,weightkg:0.3,color:"Blue",eggGroups:["No Eggs"]},
dialga:{num:483,species:"Dialga",types:["Steel","Dragon"],gender:"N",baseStats:{hp:100,atk:120,def:120,spa:150,spd:100,spe:90},abilities:{0:"Rain Dish",1:"Pickpocket"},heightm:5.4,weightkg:683,color:"White",eggGroups:["No Eggs"]},
palkia:{num:484,species:"Palkia",types:["Water","Dragon"],gender:"N",baseStats:{hp:90,atk:120,def:100,spa:150,spd:120,spe:100},abilities:{0:"No Guard",1:"Contrary"},heightm:4.2,weightkg:336,color:"Purple",eggGroups:["No Eggs"]},
heatran:{num:485,species:"Heatran",types:["Fire","Steel"],baseStats:{hp:91,atk:90,def:106,spa:130,spd:106,spe:77},abilities:{0:"Technician",1:"Keen Eye"},heightm:1.7,weightkg:430,color:"Brown",eggGroups:["No Eggs"]},
regigigas:{num:486,species:"Regigigas",types:["Normal"],gender:"N",baseStats:{hp:110,atk:160,def:110,spa:80,spd:110,spe:100},abilities:{0:"Wonder Skin",1:"Contrary"},heightm:3.7,weightkg:420,color:"White",eggGroups:["No Eggs"]},
giratina:{num:487,species:"Giratina",baseForme:"Altered",types:["Ghost","Dragon"],gender:"N",baseStats:{hp:150,atk:100,def:120,spa:100,spd:120,spe:90},abilities:{0:"Rattled",1:"Motor Drive"},heightm:4.5,weightkg:750,color:"Black",eggGroups:["No Eggs"],otherFormes:["giratinaorigin"]},
giratinaorigin:{num:487,species:"Giratina-Origin",baseSpecies:"Giratina",forme:"Origin",formeLetter:"O",types:["Ghost","Dragon"],gender:"N",baseStats:{hp:150,atk:120,def:100,spa:120,spd:100,spe:90},abilities:{0:"Quick Feet",1:"Frisk"},heightm:6.9,weightkg:650,color:"Black",eggGroups:["No Eggs"]},
cresselia:{num:488,species:"Cresselia",types:["Psychic"],gender:"F",baseStats:{hp:120,atk:70,def:120,spa:75,spd:130,spe:85},abilities:{0:"Toxic Boost",1:"Scrappy"},heightm:1.5,weightkg:85.6,color:"Yellow",eggGroups:["No Eggs"]},
phione:{num:489,species:"Phione",types:["Water"],gender:"N",baseStats:{hp:80,atk:80,def:80,spa:80,spd:80,spe:80},abilities:{0:"Unburden",1:"Moxie"},heightm:0.4,weightkg:3.1,color:"Blue",eggGroups:["Water 1","Fairy"]},
manaphy:{num:490,species:"Manaphy",types:["Water"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Gluttony",1:"Synchronize"},heightm:0.3,weightkg:1.4,color:"Blue",eggGroups:["Water 1","Fairy"]},
darkrai:{num:491,species:"Darkrai",types:["Dark"],gender:"N",baseStats:{hp:70,atk:90,def:90,spa:135,spd:90,spe:125},abilities:{0:"Rattled",1:"Thick Fat"},heightm:1.5,weightkg:50.5,color:"Black",eggGroups:["No Eggs"]},
shaymin:{num:492,species:"Shaymin",baseForme:"Land",types:["Grass"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Magic Guard",1:"Compoundeyes"},heightm:0.2,weightkg:2.1,color:"Green",eggGroups:["No Eggs"],otherFormes:["shayminsky"]},
shayminsky:{num:492,species:"Shaymin-Sky",baseSpecies:"Shaymin",forme:"Sky",formeLetter:"S",types:["Grass","Flying"],gender:"N",baseStats:{hp:100,atk:103,def:75,spa:120,spd:75,spe:127},abilities:{0:"Quick Feet",1:"Rattled"},heightm:0.4,weightkg:5.2,color:"Green",eggGroups:["No Eggs"]},
arceus:{num:493,species:"Arceus",baseForme:"Normal",types:["Normal"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Tangled Feet",1:"Hyper Cutter"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["No Eggs"]},
victini:{num:494,species:"Victini",types:["Psychic","Fire"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Compoundeyes",1:"Aftermath"},heightm:0.4,weightkg:4,color:"Yellow",eggGroups:["No Eggs"]},
snivy:{num:495,species:"Snivy",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:45,def:55,spa:45,spd:55,spe:63},abilities:{0:"Gluttony",1:"Storm Drain"},heightm:0.6,weightkg:8.1,color:"Green",evos:["servine"],eggGroups:["Ground","Plant"]},
servine:{num:496,species:"Servine",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:60,def:75,spa:60,spd:75,spe:83},abilities:{0:"Sap Sipper",1:"Solar Power"},heightm:0.8,weightkg:16,color:"Green",prevo:"snivy",evos:["serperior"],evoLevel:17,eggGroups:["Ground","Plant"]},
serperior:{num:497,species:"Serperior",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:75,def:95,spa:75,spd:95,spe:113},abilities:{0:"Anger Point",1:"Forewarn"},heightm:3.3,weightkg:63,color:"Green",prevo:"servine",evoLevel:36,eggGroups:["Ground","Plant"]},
tepig:{num:498,species:"Tepig",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:63,def:45,spa:45,spd:45,spe:45},abilities:{0:"Damp",1:"Tinted Lens"},heightm:0.5,weightkg:9.9,color:"Red",evos:["pignite"],eggGroups:["Ground"]},
pignite:{num:499,species:"Pignite",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:90,atk:93,def:55,spa:70,spd:55,spe:55},abilities:{0:"Natural Cure",1:"Rattled"},heightm:1,weightkg:55.5,color:"Red",prevo:"tepig",evos:["emboar"],evoLevel:17,eggGroups:["Ground"]},
emboar:{num:500,species:"Emboar",types:["Fire","Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:110,atk:123,def:65,spa:100,spd:65,spe:65},abilities:{0:"Poison Heal",1:"Magnet Pull"},heightm:1.6,weightkg:150,color:"Red",prevo:"pignite",evoLevel:36,eggGroups:["Ground"]},
oshawott:{num:501,species:"Oshawott",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:55,def:45,spa:63,spd:45,spe:45},abilities:{0:"Marvel Scale",1:"Lightningrod"},heightm:0.5,weightkg:5.9,color:"Blue",evos:["dewott"],eggGroups:["Ground"]},
dewott:{num:502,species:"Dewott",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:75,def:60,spa:83,spd:60,spe:60},abilities:{0:"Storm Drain",1:"Aftermath"},heightm:0.8,weightkg:24.5,color:"Blue",prevo:"oshawott",evos:["samurott"],evoLevel:17,eggGroups:["Ground"]},
samurott:{num:503,species:"Samurott",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:100,def:85,spa:108,spd:70,spe:70},abilities:{0:"Weak Armor",1:"Klutz"},heightm:1.5,weightkg:94.6,color:"Blue",prevo:"dewott",evoLevel:36,eggGroups:["Ground"]},
patrat:{num:504,species:"Patrat",types:["Normal"],baseStats:{hp:45,atk:55,def:39,spa:35,spd:39,spe:42},abilities:{0:"Mummy",1:"Synchronize"},heightm:0.5,weightkg:11.6,color:"Brown",evos:["watchog"],eggGroups:["Ground"]},
watchog:{num:505,species:"Watchog",types:["Normal"],baseStats:{hp:60,atk:85,def:69,spa:60,spd:69,spe:77},abilities:{0:"Cloud Nine",1:"Swarm"},heightm:1.1,weightkg:27,color:"Brown",prevo:"patrat",evoLevel:20,eggGroups:["Ground"]},
lillipup:{num:506,species:"Lillipup",types:["Normal"],baseStats:{hp:45,atk:60,def:45,spa:25,spd:45,spe:55},abilities:{0:"Storm Drain",1:"Magic Bounce"},heightm:0.4,weightkg:4.1,color:"Brown",evos:["herdier"],eggGroups:["Ground"]},
herdier:{num:507,species:"Herdier",types:["Normal"],baseStats:{hp:65,atk:80,def:65,spa:35,spd:65,spe:60},abilities:{0:"Big Pecks",1:"Reckless"},heightm:0.9,weightkg:14.7,color:"Gray",prevo:"lillipup",evos:["stoutland"],evoLevel:16,eggGroups:["Ground"]},
stoutland:{num:508,species:"Stoutland",types:["Normal"],baseStats:{hp:85,atk:100,def:90,spa:45,spd:90,spe:80},abilities:{0:"Poison Touch",1:"Forewarn"},heightm:1.2,weightkg:61,color:"Gray",prevo:"herdier",evoLevel:32,eggGroups:["Ground"]},
purrloin:{num:509,species:"Purrloin",types:["Dark"],baseStats:{hp:41,atk:50,def:37,spa:50,spd:37,spe:66},abilities:{0:"Imposter",1:"Rain Dish"},heightm:0.4,weightkg:10.1,color:"Purple",evos:["liepard"],eggGroups:["Ground"]},
liepard:{num:510,species:"Liepard",types:["Dark"],baseStats:{hp:64,atk:88,def:50,spa:88,spd:50,spe:106},abilities:{0:"Ice Body",1:"Tangled Feet"},heightm:1.1,weightkg:37.5,color:"Purple",prevo:"purrloin",evoLevel:20,eggGroups:["Ground"]},
pansage:{num:511,species:"Pansage",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Steadfast",1:"Own Tempo"},heightm:0.6,weightkg:10.5,color:"Green",evos:["simisage"],eggGroups:["Ground"]},
simisage:{num:512,species:"Simisage",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Static",1:"Own Tempo"},heightm:1.1,weightkg:30.5,color:"Green",prevo:"pansage",evoLevel:1,eggGroups:["Ground"]},
pansear:{num:513,species:"Pansear",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Technician",1:"Drizzle"},heightm:0.6,weightkg:11,color:"Red",evos:["simisear"],eggGroups:["Ground"]},
simisear:{num:514,species:"Simisear",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Tinted Lens",1:"Sniper"},heightm:1,weightkg:28,color:"Red",prevo:"pansear",evoLevel:1,eggGroups:["Ground"]},
panpour:{num:515,species:"Panpour",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Swift Swim",1:"Poison Touch"},heightm:0.6,weightkg:13.5,color:"Blue",evos:["simipour"],eggGroups:["Ground"]},
simipour:{num:516,species:"Simipour",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Analytic",1:"Storm Drain"},heightm:1,weightkg:29,color:"Blue",prevo:"panpour",evoLevel:1,eggGroups:["Ground"]},
munna:{num:517,species:"Munna",types:["Psychic"],baseStats:{hp:76,atk:25,def:45,spa:67,spd:55,spe:24},abilities:{0:"Pure Power",1:"Volt Absorb"},heightm:0.6,weightkg:23.3,color:"Pink",evos:["musharna"],eggGroups:["Ground"]},
musharna:{num:518,species:"Musharna",types:["Psychic"],baseStats:{hp:116,atk:55,def:85,spa:107,spd:95,spe:29},abilities:{0:"Water Absorb",1:"Solar Power"},heightm:1.1,weightkg:60.5,color:"Pink",prevo:"munna",evoLevel:1,eggGroups:["Ground"]},
pidove:{num:519,species:"Pidove",types:["Normal","Flying"],baseStats:{hp:50,atk:55,def:50,spa:36,spd:30,spe:43},abilities:{0:"Solid Rock",1:"Clear Body"},heightm:0.3,weightkg:2.1,color:"Gray",evos:["tranquill"],eggGroups:["Flying"]},
tranquill:{num:520,species:"Tranquill",types:["Normal","Flying"],baseStats:{hp:62,atk:77,def:62,spa:50,spd:42,spe:65},abilities:{0:"Flame Body",1:"Hustle"},heightm:0.6,weightkg:15,color:"Gray",prevo:"pidove",evos:["unfezant"],evoLevel:21,eggGroups:["Flying"]},
unfezant:{num:521,species:"Unfezant",types:["Normal","Flying"],baseStats:{hp:80,atk:105,def:80,spa:65,spd:55,spe:93},abilities:{0:"Moxie",1:"Sand Veil"},heightm:1.2,weightkg:29,color:"Gray",prevo:"tranquill",evoLevel:32,eggGroups:["Flying"]},
blitzle:{num:522,species:"Blitzle",types:["Electric"],baseStats:{hp:45,atk:60,def:32,spa:50,spd:32,spe:76},abilities:{0:"Cursed Body",1:"Speed Boost"},heightm:0.8,weightkg:29.8,color:"Black",evos:["zebstrika"],eggGroups:["Ground"]},
zebstrika:{num:523,species:"Zebstrika",types:["Electric"],baseStats:{hp:75,atk:100,def:63,spa:80,spd:63,spe:116},abilities:{0:"Contrary",1:"Adaptability"},heightm:1.6,weightkg:79.5,color:"Black",prevo:"blitzle",evoLevel:27,eggGroups:["Ground"]},
roggenrola:{num:524,species:"Roggenrola",types:["Rock"],baseStats:{hp:55,atk:75,def:85,spa:25,spd:25,spe:15},abilities:{0:"Chlorophyll",1:"Natural Cure"},heightm:0.4,weightkg:18,color:"Blue",evos:["boldore"],eggGroups:["Mineral"]},
boldore:{num:525,species:"Boldore",types:["Rock"],baseStats:{hp:70,atk:105,def:105,spa:50,spd:40,spe:20},abilities:{0:"Keen Eye",1:"Flare Boost"},heightm:0.9,weightkg:102,color:"Blue",prevo:"roggenrola",evos:["gigalith"],evoLevel:25,eggGroups:["Mineral"]},
gigalith:{num:526,species:"Gigalith",types:["Rock"],baseStats:{hp:85,atk:135,def:130,spa:60,spd:70,spe:25},abilities:{0:"Compoundeyes",1:"Iron Barbs"},heightm:1.7,weightkg:260,color:"Blue",prevo:"boldore",evoLevel:1,eggGroups:["Mineral"]},
woobat:{num:527,species:"Woobat",types:["Psychic","Flying"],baseStats:{hp:55,atk:45,def:43,spa:55,spd:43,spe:72},abilities:{0:"Compoundeyes",1:"Poison Point"},heightm:0.4,weightkg:2.1,color:"Blue",evos:["swoobat"],eggGroups:["Flying","Ground"]},
swoobat:{num:528,species:"Swoobat",types:["Psychic","Flying"],baseStats:{hp:67,atk:57,def:55,spa:77,spd:55,spe:114},abilities:{0:"Rain Dish",1:"Sand Rush"},heightm:0.9,weightkg:10.5,color:"Blue",prevo:"woobat",evoLevel:1,eggGroups:["Flying","Ground"]},
drilbur:{num:529,species:"Drilbur",types:["Ground"],baseStats:{hp:60,atk:85,def:40,spa:30,spd:45,spe:68},abilities:{0:"Pickpocket",1:"Natural Cure"},heightm:0.3,weightkg:8.5,color:"Gray",evos:["excadrill"],eggGroups:["Ground"]},
excadrill:{num:530,species:"Excadrill",types:["Ground","Steel"],baseStats:{hp:110,atk:135,def:60,spa:50,spd:65,spe:88},abilities:{0:"Rain Dish",1:"Tinted Lens"},heightm:0.7,weightkg:40.4,color:"Gray",prevo:"drilbur",evoLevel:31,eggGroups:["Ground"]},
audino:{num:531,species:"Audino",types:["Normal"],baseStats:{hp:103,atk:60,def:86,spa:60,spd:86,spe:50},abilities:{0:"Magic Bounce",1:"Sand Veil"},heightm:1.1,weightkg:31,color:"Pink",eggGroups:["Fairy"]},
timburr:{num:532,species:"Timburr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:80,def:55,spa:25,spd:35,spe:35},abilities:{0:"Levitate",1:"Immunity"},heightm:0.6,weightkg:12.5,color:"Gray",evos:["gurdurr"],eggGroups:["Humanshape"]},
gurdurr:{num:533,species:"Gurdurr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:85,atk:105,def:85,spa:40,spd:50,spe:40},abilities:{0:"Pressure",1:"Storm Drain"},heightm:1.2,weightkg:40,color:"Gray",prevo:"timburr",evos:["conkeldurr"],evoLevel:25,eggGroups:["Humanshape"]},
conkeldurr:{num:534,species:"Conkeldurr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:105,atk:140,def:95,spa:55,spd:65,spe:45},abilities:{0:"Poison Heal",1:"Mold Breaker"},heightm:1.4,weightkg:87,color:"Brown",prevo:"gurdurr",evoLevel:1,eggGroups:["Humanshape"]},
tympole:{num:535,species:"Tympole",types:["Water"],baseStats:{hp:50,atk:50,def:40,spa:50,spd:40,spe:64},abilities:{0:"Liquid Ooze",1:"Sheer Force"},heightm:0.5,weightkg:4.5,color:"Blue",evos:["palpitoad"],eggGroups:["Water 1"]},
palpitoad:{num:536,species:"Palpitoad",types:["Water","Ground"],baseStats:{hp:75,atk:65,def:55,spa:65,spd:55,spe:69},abilities:{0:"Super Luck",1:"Tinted Lens"},heightm:0.8,weightkg:17,color:"Blue",prevo:"tympole",evos:["seismitoad"],evoLevel:25,eggGroups:["Water 1"]},
seismitoad:{num:537,species:"Seismitoad",types:["Water","Ground"],baseStats:{hp:105,atk:85,def:75,spa:85,spd:75,spe:74},abilities:{0:"Anger Point",1:"Liquid Ooze"},heightm:1.5,weightkg:62,color:"Blue",prevo:"palpitoad",evoLevel:36,eggGroups:["Water 1"]},
throh:{num:538,species:"Throh",types:["Fighting"],gender:"M",baseStats:{hp:120,atk:100,def:85,spa:30,spd:85,spe:45},abilities:{0:"Sap Sipper",1:"Analytic"},heightm:1.3,weightkg:55.5,color:"Red",eggGroups:["Humanshape"]},
sawk:{num:539,species:"Sawk",types:["Fighting"],gender:"M",baseStats:{hp:75,atk:125,def:75,spa:30,spd:75,spe:85},abilities:{0:"Stench",1:"Flash Fire"},heightm:1.4,weightkg:51,color:"Blue",eggGroups:["Humanshape"]},
sewaddle:{num:540,species:"Sewaddle",types:["Bug","Grass"],baseStats:{hp:45,atk:53,def:70,spa:40,spd:60,spe:42},abilities:{0:"Stikcy Hold",1:"Unaware"},heightm:0.3,weightkg:2.5,color:"Yellow",evos:["swadloon"],eggGroups:["Bug"]},
swadloon:{num:541,species:"Swadloon",types:["Bug","Grass"],baseStats:{hp:55,atk:63,def:90,spa:50,spd:80,spe:42},abilities:{0:"Magnet Pull",1:"Magma Armor"},heightm:0.5,weightkg:7.3,color:"Green",prevo:"sewaddle",evos:["leavanny"],evoLevel:20,eggGroups:["Bug"]},
leavanny:{num:542,species:"Leavanny",types:["Bug","Grass"],baseStats:{hp:75,atk:103,def:80,spa:70,spd:70,spe:92},abilities:{0:"Wonder Skin",1:"Unburden"},heightm:1.2,weightkg:20.5,color:"Yellow",prevo:"swadloon",evoLevel:1,eggGroups:["Bug"]},
venipede:{num:543,species:"Venipede",types:["Bug","Poison"],baseStats:{hp:30,atk:45,def:59,spa:30,spd:39,spe:57},abilities:{0:"Battle Armor",1:"Sticky Hold"},heightm:0.4,weightkg:5.3,color:"Red",evos:["whirlipede"],eggGroups:["Bug"]},
whirlipede:{num:544,species:"Whirlipede",types:["Bug","Poison"],baseStats:{hp:40,atk:55,def:99,spa:40,spd:79,spe:47},abilities:{0:"Trace",1:"Rain Dish"},heightm:1.2,weightkg:58.5,color:"Gray",prevo:"venipede",evos:["scolipede"],evoLevel:22,eggGroups:["Bug"]},
scolipede:{num:545,species:"Scolipede",types:["Bug","Poison"],baseStats:{hp:60,atk:90,def:89,spa:55,spd:69,spe:112},abilities:{0:"Trace",1:"Technician"},heightm:2.5,weightkg:200.5,color:"Red",prevo:"whirlipede",evoLevel:30,eggGroups:["Bug"]},
cottonee:{num:546,species:"Cottonee",types:["Grass"],baseStats:{hp:40,atk:27,def:60,spa:37,spd:50,spe:66},abilities:{0:"Liquid Ooze",1:"Hyper Cutter"},heightm:0.3,weightkg:0.6,color:"Green",evos:["whimsicott"],eggGroups:["Fairy","Plant"]},
whimsicott:{num:547,species:"Whimsicott",types:["Grass"],baseStats:{hp:60,atk:67,def:85,spa:77,spd:75,spe:116},abilities:{0:"Mummy",1:"Snow Cloak"},heightm:0.7,weightkg:6.6,color:"Green",prevo:"cottonee",evoLevel:1,eggGroups:["Fairy","Plant"]},
petilil:{num:548,species:"Petilil",types:["Grass"],gender:"F",baseStats:{hp:45,atk:35,def:50,spa:70,spd:50,spe:30},abilities:{0:"Sturdy",1:"Weak Armor"},heightm:0.5,weightkg:6.6,color:"Green",evos:["lilligant"],eggGroups:["Plant"]},
lilligant:{num:549,species:"Lilligant",types:["Grass"],gender:"F",baseStats:{hp:70,atk:60,def:75,spa:110,spd:75,spe:90},abilities:{0:"Lightningrod",1:"Overgrow"},heightm:1.1,weightkg:16.3,color:"Green",prevo:"petilil",evoLevel:1,eggGroups:["Plant"]},
basculin:{num:550,species:"Basculin",baseForme:"Red-Striped",types:["Water"],baseStats:{hp:70,atk:92,def:65,spa:80,spd:55,spe:98},abilities:{0:"Contrary",1:"Volt Absorb"},heightm:1,weightkg:18,color:"Green",eggGroups:["Water 2"],otherFormes:["basculinbluestriped"]},
basculinbluestriped:{num:550,species:"Basculin-Blue-Striped",baseSpecies:"Basculin",forme:"Blue-Striped",formeLetter:"B",types:["Water"],baseStats:{hp:70,atk:92,def:65,spa:80,spd:55,spe:98},abilities:{0:"Contrary",1:"Volt Absorb"},heightm:1,weightkg:18,color:"Green",eggGroups:["Water 2"]},
sandile:{num:551,species:"Sandile",types:["Ground","Dark"],baseStats:{hp:50,atk:72,def:35,spa:35,spd:35,spe:65},abilities:{0:"Suction Cups",1:"Weak Armor"},heightm:0.7,weightkg:15.2,color:"Brown",evos:["krokorok"],eggGroups:["Ground"]},
krokorok:{num:552,species:"Krokorok",types:["Ground","Dark"],baseStats:{hp:60,atk:82,def:45,spa:45,spd:45,spe:74},abilities:{0:"Water Absorb",1:"Infiltrator"},heightm:1,weightkg:33.4,color:"Brown",prevo:"sandile",evos:["krookodile"],evoLevel:29,eggGroups:["Ground"]},
krookodile:{num:553,species:"Krookodile",types:["Ground","Dark"],baseStats:{hp:95,atk:117,def:70,spa:65,spd:70,spe:92},abilities:{0:"Tangled Feet",1:"Magic Guard"},heightm:1.5,weightkg:96.3,color:"Red",prevo:"krokorok",evoLevel:40,eggGroups:["Ground"]},
darumaka:{num:554,species:"Darumaka",types:["Fire"],baseStats:{hp:70,atk:90,def:45,spa:15,spd:45,spe:50},abilities:{0:"Hyper Cutter",1:"Big Pecks"},heightm:0.6,weightkg:37.5,color:"Red",evos:["darmanitan"],eggGroups:["Ground"]},
darmanitan:{num:555,species:"Darmanitan",baseForme:"Standard",types:["Fire"],baseStats:{hp:105,atk:140,def:55,spa:30,spd:55,spe:95},abilities:{0:"Synchronize",1:"Poison Point"},heightm:1.3,weightkg:92.9,color:"Red",prevo:"darumaka",evoLevel:35,eggGroups:["Ground"]},
maractus:{num:556,species:"Maractus",types:["Grass"],baseStats:{hp:75,atk:86,def:67,spa:106,spd:67,spe:60},abilities:{0:"Solid Rock",1:"Hyper Cutter"},heightm:1,weightkg:28,color:"Green",eggGroups:["Plant"]},
dwebble:{num:557,species:"Dwebble",types:["Bug","Rock"],baseStats:{hp:50,atk:65,def:85,spa:35,spd:35,spe:55},abilities:{0:"Water Absorb",1:"Ice Body"},heightm:0.3,weightkg:14.5,color:"Red",evos:["crustle"],eggGroups:["Bug","Mineral"]},
crustle:{num:558,species:"Crustle",types:["Bug","Rock"],baseStats:{hp:70,atk:95,def:125,spa:65,spd:75,spe:45},abilities:{0:"Magic Bounce",1:"Super Luck"},heightm:1.4,weightkg:200,color:"Red",prevo:"dwebble",evoLevel:34,eggGroups:["Bug","Mineral"]},
scraggy:{num:559,species:"Scraggy",types:["Dark","Fighting"],baseStats:{hp:50,atk:75,def:70,spa:35,spd:70,spe:48},abilities:{0:"Solar Power",1:"Solid Rock"},heightm:0.6,weightkg:11.8,color:"Yellow",evos:["scrafty"],eggGroups:["Ground","Dragon"]},
scrafty:{num:560,species:"Scrafty",types:["Dark","Fighting"],baseStats:{hp:65,atk:90,def:115,spa:45,spd:115,spe:58},abilities:{0:"Sturdy",1:"Sand Rush"},heightm:1.1,weightkg:30,color:"Red",prevo:"scraggy",evoLevel:39,eggGroups:["Ground","Dragon"]},
sigilyph:{num:561,species:"Sigilyph",types:["Psychic","Flying"],baseStats:{hp:72,atk:58,def:80,spa:103,spd:80,spe:97},abilities:{0:"Swarm",1:"Tangled Feet"},heightm:1.4,weightkg:14,color:"Black",eggGroups:["Flying"]},
yamask:{num:562,species:"Yamask",types:["Ghost"],baseStats:{hp:38,atk:30,def:85,spa:55,spd:65,spe:30},abilities:{0:"Suction Cups",1:"Poison Heal"},heightm:0.5,weightkg:1.5,color:"Black",evos:["cofagrigus"],eggGroups:["Mineral","Indeterminate"]},
cofagrigus:{num:563,species:"Cofagrigus",types:["Ghost"],baseStats:{hp:58,atk:50,def:145,spa:95,spd:105,spe:30},abilities:{0:"Light Metal",1:"Cute Charm"},heightm:1.7,weightkg:76.5,color:"Yellow",prevo:"yamask",evoLevel:34,eggGroups:["Mineral","Indeterminate"]},
tirtouga:{num:564,species:"Tirtouga",types:["Water","Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:54,atk:78,def:103,spa:53,spd:45,spe:22},abilities:{0:"Immunity",1:"Magic Guard"},heightm:0.7,weightkg:16.5,color:"Blue",evos:["carracosta"],eggGroups:["Water 1","Water 3"]},
carracosta:{num:565,species:"Carracosta",types:["Water","Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:74,atk:108,def:133,spa:83,spd:65,spe:32},abilities:{0:"Toxic Boost",1:"Harvest"},heightm:1.2,weightkg:81,color:"Blue",prevo:"tirtouga",evoLevel:37,eggGroups:["Water 1","Water 3"]},
archen:{num:566,species:"Archen",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:112,def:45,spa:74,spd:45,spe:70},abilities:{0:"Multiscale",1:"Sniper"},heightm:0.5,weightkg:9.5,color:"Yellow",evos:["archeops"],eggGroups:["Flying","Water 3"]},
archeops:{num:567,species:"Archeops",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:140,def:65,spa:112,spd:65,spe:110},abilities:{0:"Natural Cure",1:"Blaze"},heightm:1.4,weightkg:32,color:"Yellow",prevo:"archen",evoLevel:37,eggGroups:["Flying","Water 3"]},
trubbish:{num:568,species:"Trubbish",types:["Poison"],baseStats:{hp:50,atk:50,def:62,spa:40,spd:62,spe:65},abilities:{0:"Rattled",1:"Snow Warning"},heightm:0.6,weightkg:31,color:"Green",evos:["garbodor"],eggGroups:["Mineral"]},
garbodor:{num:569,species:"Garbodor",types:["Poison"],baseStats:{hp:80,atk:95,def:82,spa:60,spd:82,spe:75},abilities:{0:"Clear Body",1:"Volt Absorb"},heightm:1.9,weightkg:107.3,color:"Green",prevo:"trubbish",evoLevel:36,eggGroups:["Mineral"]},
zorua:{num:570,species:"Zorua",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:65,def:40,spa:80,spd:40,spe:65},abilities:{0:"Toxic Boost",1:"Light Metal"},heightm:0.7,weightkg:12.5,color:"Gray",evos:["zoroark"],eggGroups:["Ground"]},
zoroark:{num:571,species:"Zoroark",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:105,def:60,spa:120,spd:60,spe:105},abilities:{0:"Early Bird",1:"Sand Veil"},heightm:1.6,weightkg:81.1,color:"Gray",prevo:"zorua",evoLevel:30,eggGroups:["Ground"]},
minccino:{num:572,species:"Minccino",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:55,atk:50,def:40,spa:40,spd:40,spe:75},abilities:{0:"Aftermath",1:"Klutz"},heightm:0.4,weightkg:5.8,color:"Gray",evos:["cinccino"],eggGroups:["Ground"]},
cinccino:{num:573,species:"Cinccino",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:75,atk:95,def:60,spa:65,spd:60,spe:115},abilities:{0:"Hyper Cutter",1:"Lightningrod"},heightm:0.5,weightkg:7.5,color:"Gray",prevo:"minccino",evoLevel:1,eggGroups:["Ground"]},
gothita:{num:574,species:"Gothita",types:["Psychic"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:45,atk:30,def:50,spa:55,spd:65,spe:45},abilities:{0:"Unaware",1:"Effect Spore"},heightm:0.4,weightkg:5.8,color:"Purple",evos:["gothorita"],eggGroups:["Humanshape"]},
gothorita:{num:575,species:"Gothorita",types:["Psychic"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:60,atk:45,def:70,spa:75,spd:85,spe:55},abilities:{0:"Cloud Nine",1:"Mold Breaker"},heightm:0.7,weightkg:18,color:"Purple",prevo:"gothita",evos:["gothitelle"],evoLevel:32,eggGroups:["Humanshape"]},
gothitelle:{num:576,species:"Gothitelle",types:["Psychic"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:55,def:95,spa:95,spd:110,spe:65},abilities:{0:"Overcoat",1:"Magic Bounce"},heightm:1.5,weightkg:44,color:"Purple",prevo:"gothorita",evoLevel:41,eggGroups:["Humanshape"]},
solosis:{num:577,species:"Solosis",types:["Psychic"],baseStats:{hp:45,atk:30,def:40,spa:105,spd:50,spe:20},abilities:{0:"Imposter",1:"Synchronize"},heightm:0.3,weightkg:1,color:"Green",evos:["duosion"],eggGroups:["Indeterminate"]},
duosion:{num:578,species:"Duosion",types:["Psychic"],baseStats:{hp:65,atk:40,def:50,spa:125,spd:60,spe:30},abilities:{0:"Analytic",1:"Magnet Pull"},heightm:0.6,weightkg:8,color:"Green",prevo:"solosis",evos:["reuniclus"],evoLevel:32,eggGroups:["Indeterminate"]},
reuniclus:{num:579,species:"Reuniclus",types:["Psychic"],baseStats:{hp:110,atk:65,def:75,spa:125,spd:85,spe:30},abilities:{0:"Natural Cure",1:"Analytic"},heightm:1,weightkg:20.1,color:"Green",prevo:"duosion",evoLevel:41,eggGroups:["Indeterminate"]},
ducklett:{num:580,species:"Ducklett",types:["Water","Flying"],baseStats:{hp:62,atk:44,def:50,spa:44,spd:50,spe:55},abilities:{0:"Magma Armor",1:"Victory Star"},heightm:0.5,weightkg:5.5,color:"Blue",evos:["swanna"],eggGroups:["Water 1","Flying"]},
swanna:{num:581,species:"Swanna",types:["Water","Flying"],baseStats:{hp:75,atk:87,def:63,spa:87,spd:63,spe:98},abilities:{0:"Shield Dust",1:"Early Bird"},heightm:1.3,weightkg:24.2,color:"White",prevo:"ducklett",evoLevel:35,eggGroups:["Water 1","Flying"]},
vanillite:{num:582,species:"Vanillite",types:["Ice"],baseStats:{hp:36,atk:50,def:50,spa:65,spd:60,spe:44},abilities:{0:"Arena Trap",1:"Magma Armor"},heightm:0.4,weightkg:5.7,color:"White",evos:["vanillish"],eggGroups:["Mineral"]},
vanillish:{num:583,species:"Vanillish",types:["Ice"],baseStats:{hp:51,atk:65,def:65,spa:80,spd:75,spe:59},abilities:{0:"Insomnia",1:"No Guard"},heightm:1.1,weightkg:41,color:"White",prevo:"vanillite",evos:["vanilluxe"],evoLevel:35,eggGroups:["Mineral"]},
vanilluxe:{num:584,species:"Vanilluxe",types:["Ice"],baseStats:{hp:71,atk:95,def:85,spa:110,spd:95,spe:79},abilities:{0:"Marvel Scale",1:"Hyper Cutter"},heightm:1.3,weightkg:57.5,color:"White",prevo:"vanillish",evoLevel:47,eggGroups:["Mineral"]},
deerling:{num:585,species:"Deerling",baseForme:"Spring",types:["Normal","Grass"],baseStats:{hp:60,atk:60,def:50,spa:40,spd:50,spe:75},abilities:{0:"Drizzle",1:"Water Veil"},heightm:0.6,weightkg:19.5,color:"Yellow",evos:["sawsbuck"],eggGroups:["Ground"],otherForms:["deerlingsummer","deerlingautumn","deerlingwinter"]},
sawsbuck:{num:586,species:"Sawsbuck",baseForme:"Spring",types:["Normal","Grass"],baseStats:{hp:80,atk:100,def:70,spa:60,spd:70,spe:95},abilities:{0:"Stench",1:"Speed Boost"},heightm:1.9,weightkg:92.5,color:"Brown",prevo:"deerling",evoLevel:34,eggGroups:["Ground"],otherForms:["sawsbucksummer","sawsbuckautumn","sawsbuckwinter"]},
emolga:{num:587,species:"Emolga",types:["Electric","Flying"],baseStats:{hp:55,atk:75,def:60,spa:75,spd:60,spe:103},abilities:{0:"Stall",1:"Sticky Hold"},heightm:0.4,weightkg:5,color:"White",eggGroups:["Ground"]},
karrablast:{num:588,species:"Karrablast",types:["Bug"],baseStats:{hp:50,atk:75,def:45,spa:40,spd:45,spe:60},abilities:{0:"Solid Rock",1:"Own Tempo"},heightm:0.5,weightkg:5.9,color:"Blue",evos:["escavalier"],eggGroups:["Bug"]},
escavalier:{num:589,species:"Escavalier",types:["Bug","Steel"],baseStats:{hp:70,atk:135,def:105,spa:60,spd:105,spe:20},abilities:{0:"Unnerve",1:"Compoundeyes"},heightm:1,weightkg:33,color:"Gray",prevo:"karrablast",evoLevel:1,eggGroups:["Bug"]},
foongus:{num:590,species:"Foongus",types:["Grass","Poison"],baseStats:{hp:69,atk:55,def:45,spa:55,spd:55,spe:15},abilities:{0:"Clear Body",1:"Imposter"},heightm:0.2,weightkg:1,color:"White",evos:["amoonguss"],eggGroups:["Plant"]},
amoonguss:{num:591,species:"Amoonguss",types:["Grass","Poison"],baseStats:{hp:114,atk:85,def:70,spa:85,spd:80,spe:30},abilities:{0:"Overcoat",1:"Gluttony"},heightm:0.6,weightkg:10.5,color:"White",prevo:"foongus",evoLevel:39,eggGroups:["Plant"]},
frillish:{num:592,species:"Frillish",types:["Water","Ghost"],baseStats:{hp:55,atk:40,def:50,spa:65,spd:85,spe:40},abilities:{0:"Levitate",1:"Poison Heal"},heightm:1.2,weightkg:33,color:"White",evos:["jellicent"],eggGroups:["Indeterminate"]},
jellicent:{num:593,species:"Jellicent",types:["Water","Ghost"],baseStats:{hp:100,atk:60,def:70,spa:85,spd:105,spe:60},abilities:{0:"Thick Fat",1:"Intimidate"},heightm:2.2,weightkg:135,color:"White",prevo:"frillish",evoLevel:40,eggGroups:["Indeterminate"]},
alomomola:{num:594,species:"Alomomola",types:["Water"],baseStats:{hp:165,atk:75,def:80,spa:40,spd:45,spe:65},abilities:{0:"Cloud Nine",1:"Serene Grace"},heightm:1.2,weightkg:31.6,color:"Pink",eggGroups:["Water 1","Water 2"]},
joltik:{num:595,species:"Joltik",types:["Bug","Electric"],baseStats:{hp:50,atk:47,def:50,spa:57,spd:50,spe:65},abilities:{0:"Super Luck",1:"Flash Fire"},heightm:0.1,weightkg:0.6,color:"Yellow",evos:["galvantula"],eggGroups:["Bug"]},
galvantula:{num:596,species:"Galvantula",types:["Bug","Electric"],baseStats:{hp:70,atk:77,def:60,spa:97,spd:60,spe:108},abilities:{0:"Pure Power",1:"Light Metal"},heightm:0.8,weightkg:14.3,color:"Yellow",prevo:"joltik",evoLevel:36,eggGroups:["Bug"]},
ferroseed:{num:597,species:"Ferroseed",types:["Grass","Steel"],baseStats:{hp:44,atk:50,def:91,spa:24,spd:86,spe:10},abilities:{0:"Shield Dust",1:"Overcoat"},heightm:0.6,weightkg:18.8,color:"Gray",evos:["ferrothorn"],eggGroups:["Plant","Mineral"]},
ferrothorn:{num:598,species:"Ferrothorn",types:["Grass","Steel"],baseStats:{hp:74,atk:94,def:131,spa:54,spd:116,spe:20},abilities:{0:"Illusion",1:"No Guard"},heightm:1,weightkg:110,color:"Gray",prevo:"ferroseed",evoLevel:40,eggGroups:["Plant","Mineral"]},
klink:{num:599,species:"Klink",types:["Steel"],gender:"N",baseStats:{hp:40,atk:55,def:70,spa:45,spd:60,spe:30},abilities:{0:"Stench",1:"Unaware"},heightm:0.3,weightkg:21,color:"Gray",evos:["klang"],eggGroups:["Mineral"]},
klang:{num:600,species:"Klang",types:["Steel"],gender:"N",baseStats:{hp:60,atk:80,def:95,spa:70,spd:85,spe:50},abilities:{0:"Blaze",1:"Sniper"},heightm:0.6,weightkg:51,color:"Gray",prevo:"klink",evos:["klinklang"],evoLevel:38,eggGroups:["Mineral"]},
klinklang:{num:601,species:"Klinklang",types:["Steel"],gender:"N",baseStats:{hp:60,atk:100,def:115,spa:70,spd:85,spe:90},abilities:{0:"Flame Body",1:"Scrappy"},heightm:0.6,weightkg:81,color:"Gray",prevo:"klang",evoLevel:49,eggGroups:["Mineral"]},
tynamo:{num:602,species:"Tynamo",types:["Electric"],baseStats:{hp:35,atk:55,def:40,spa:45,spd:40,spe:60},abilities:{0:"Color Change",1:"Prankster"},heightm:0.2,weightkg:0.3,color:"White",evos:["eelektrik"],eggGroups:["Indeterminate"]},
eelektrik:{num:603,species:"Eelektrik",types:["Electric"],baseStats:{hp:65,atk:85,def:70,spa:75,spd:70,spe:40},abilities:{0:"Moxie",1:"Anticipation"},heightm:1.2,weightkg:22,color:"Blue",prevo:"tynamo",evos:["eelektross"],evoLevel:39,eggGroups:["Indeterminate"]},
eelektross:{num:604,species:"Eelektross",types:["Electric"],baseStats:{hp:85,atk:115,def:80,spa:105,spd:80,spe:50},abilities:{0:"Liqiud Ooze",1:"Rattled"},heightm:2.1,weightkg:80.5,color:"Blue",prevo:"eelektrik",evoLevel:1,eggGroups:["Indeterminate"]},
elgyem:{num:605,species:"Elgyem",types:["Psychic"],baseStats:{hp:55,atk:55,def:55,spa:85,spd:55,spe:30},abilities:{0:"Inner Focus",1:"Illusion"},heightm:0.5,weightkg:9,color:"Blue",evos:["beheeyem"],eggGroups:["Humanshape"]},
beheeyem:{num:606,species:"Beheeyem",types:["Psychic"],baseStats:{hp:75,atk:75,def:75,spa:125,spd:95,spe:40},abilities:{0:"Dry Skin",1:"Damp"},heightm:1,weightkg:34.5,color:"Brown",prevo:"elgyem",evoLevel:42,eggGroups:["Humanshape"]},
litwick:{num:607,species:"Litwick",types:["Ghost","Fire"],baseStats:{hp:50,atk:30,def:55,spa:65,spd:55,spe:20},abilities:{0:"Victory Star",1:"Snow Cloak"},heightm:0.3,weightkg:3.1,color:"White",evos:["lampent"],eggGroups:["Indeterminate"]},
lampent:{num:608,species:"Lampent",types:["Ghost","Fire"],baseStats:{hp:60,atk:40,def:60,spa:95,spd:60,spe:55},abilities:{0:"Snow Cloak",1:"Drought"},heightm:0.6,weightkg:13,color:"Black",prevo:"litwick",evos:["chandelure"],evoLevel:41,eggGroups:["Indeterminate"]},
chandelure:{num:609,species:"Chandelure",types:["Ghost","Fire"],baseStats:{hp:60,atk:55,def:90,spa:145,spd:90,spe:80},abilities:{0:"Keen Eye",1:"Magic Guard"},heightm:1,weightkg:34.3,color:"Black",prevo:"lampent",evoLevel:1,eggGroups:["Indeterminate"]},
axew:{num:610,species:"Axew",types:["Dragon"],baseStats:{hp:46,atk:87,def:60,spa:30,spd:40,spe:57},abilities:{0:"Sap Sipper",1:"Guts"},heightm:0.6,weightkg:18,color:"Green",evos:["fraxure"],eggGroups:["Monster","Dragon"]},
fraxure:{num:611,species:"Fraxure",types:["Dragon"],baseStats:{hp:66,atk:117,def:70,spa:40,spd:50,spe:67},abilities:{0:"Early Bird",1:"Light Metal"},heightm:1,weightkg:36,color:"Green",prevo:"axew",evos:["haxorus"],evoLevel:38,eggGroups:["Monster","Dragon"]},
haxorus:{num:612,species:"Haxorus",types:["Dragon"],baseStats:{hp:76,atk:147,def:90,spa:60,spd:70,spe:97},abilities:{0:"Motor Drive",1:"Sand Veil"},heightm:1.8,weightkg:105.5,color:"Yellow",prevo:"fraxure",evoLevel:48,eggGroups:["Monster","Dragon"]},
cubchoo:{num:613,species:"Cubchoo",types:["Ice"],baseStats:{hp:55,atk:70,def:40,spa:60,spd:40,spe:40},abilities:{0:"Unaware",1:"Sticky Hold"},heightm:0.5,weightkg:8.5,color:"White",evos:["beartic"],eggGroups:["Ground"]},
beartic:{num:614,species:"Beartic",types:["Ice"],baseStats:{hp:95,atk:110,def:80,spa:70,spd:80,spe:50},abilities:{0:"Gluttony",1:"Storm Drain"},heightm:2.6,weightkg:260,color:"White",prevo:"cubchoo",evoLevel:37,eggGroups:["Ground"]},
cryogonal:{num:615,species:"Cryogonal",types:["Ice"],gender:"N",baseStats:{hp:70,atk:50,def:30,spa:95,spd:135,spe:105},abilities:{0:"Sturdy",1:"Defiant"},heightm:1.1,weightkg:148,color:"Blue",eggGroups:["Mineral"]},
shelmet:{num:616,species:"Shelmet",types:["Bug"],baseStats:{hp:50,atk:40,def:85,spa:40,spd:65,spe:25},abilities:{0:"Light Metal",1:"Technician"},heightm:0.4,weightkg:7.7,color:"Red",evos:["accelgor"],eggGroups:["Bug"]},
accelgor:{num:617,species:"Accelgor",types:["Bug"],baseStats:{hp:80,atk:70,def:40,spa:100,spd:60,spe:145},abilities:{0:"Gluttony",1:"Snow Cloak"},heightm:0.8,weightkg:25.3,color:"Red",prevo:"shelmet",evoLevel:1,eggGroups:["Bug"]},
stunfisk:{num:618,species:"Stunfisk",types:["Ground","Electric"],baseStats:{hp:109,atk:66,def:84,spa:81,spd:99,spe:32},abilities:{0:"Pickpocket",1:"Battle Armor"},heightm:0.7,weightkg:11,color:"Brown",eggGroups:["Water 1","Indeterminate"]},
mienfoo:{num:619,species:"Mienfoo",types:["Fighting"],baseStats:{hp:45,atk:85,def:50,spa:55,spd:50,spe:65},abilities:{0:"Rattled",1:"Multiscale"},heightm:0.9,weightkg:20,color:"Yellow",evos:["mienshao"],eggGroups:["Ground","Humanshape"]},
mienshao:{num:620,species:"Mienshao",types:["Fighting"],baseStats:{hp:65,atk:125,def:60,spa:95,spd:60,spe:105},abilities:{0:"Harvest",1:"Cute Charm"},heightm:1.4,weightkg:35.5,color:"Purple",prevo:"mienfoo",evoLevel:50,eggGroups:["Ground","Humanshape"]},
druddigon:{num:621,species:"Druddigon",types:["Dragon"],baseStats:{hp:77,atk:120,def:90,spa:60,spd:90,spe:48},abilities:{0:"Sturdy",1:"Prankster"},heightm:1.6,weightkg:139,color:"Red",eggGroups:["Monster","Dragon"]},
golett:{num:622,species:"Golett",types:["Ground","Ghost"],gender:"N",baseStats:{hp:59,atk:74,def:50,spa:35,spd:50,spe:35},abilities:{0:"Snow Warning",1:"Magic Guard"},heightm:1,weightkg:92,color:"Green",evos:["golurk"],eggGroups:["Mineral"]},
golurk:{num:623,species:"Golurk",types:["Ground","Ghost"],gender:"N",baseStats:{hp:89,atk:124,def:80,spa:55,spd:80,spe:55},abilities:{0:"Aftermath",1:"Frisk"},heightm:2.8,weightkg:330,color:"Green",prevo:"golett",evoLevel:43,eggGroups:["Mineral"]},
pawniard:{num:624,species:"Pawniard",types:["Dark","Steel"],baseStats:{hp:45,atk:85,def:70,spa:40,spd:40,spe:60},abilities:{0:"Water Veil",1:"Liquid Ooze"},heightm:0.5,weightkg:10.2,color:"Red",evos:["bisharp"],eggGroups:["Humanshape"]},
bisharp:{num:625,species:"Bisharp",types:["Dark","Steel"],baseStats:{hp:65,atk:125,def:100,spa:60,spd:70,spe:70},abilities:{0:"Snow Cloak",1:"Forewarn"},heightm:1.6,weightkg:70,color:"Red",prevo:"pawniard",evoLevel:52,eggGroups:["Humanshape"]},
bouffalant:{num:626,species:"Bouffalant",types:["Normal"],baseStats:{hp:95,atk:110,def:95,spa:40,spd:95,spe:55},abilities:{0:"Static",1:"Dry Skin"},heightm:1.6,weightkg:94.6,color:"Brown",eggGroups:["Ground"]},
rufflet:{num:627,species:"Rufflet",types:["Normal","Flying"],gender:"M",baseStats:{hp:70,atk:83,def:50,spa:37,spd:50,spe:60},abilities:{0:"Pure Power",1:"Forewarn"},heightm:0.5,weightkg:10.5,color:"White",evos:["braviary"],eggGroups:["Flying"]},
braviary:{num:628,species:"Braviary",types:["Normal","Flying"],gender:"M",baseStats:{hp:100,atk:123,def:75,spa:57,spd:75,spe:80},abilities:{0:"Volt Absorb",1:"Sand Veil"},heightm:1.5,weightkg:41,color:"Red",prevo:"rufflet",evoLevel:54,eggGroups:["Flying"]},
vullaby:{num:629,species:"Vullaby",types:["Dark","Flying"],gender:"F",baseStats:{hp:70,atk:55,def:75,spa:45,spd:65,spe:60},abilities:{0:"Rock Head",1:"Sniper"},heightm:0.5,weightkg:9,color:"Brown",evos:["mandibuzz"],eggGroups:["Flying"]},
mandibuzz:{num:630,species:"Mandibuzz",types:["Dark","Flying"],gender:"F",baseStats:{hp:110,atk:65,def:105,spa:55,spd:95,spe:80},abilities:{0:"Mummy",1:"Iron Barbs"},heightm:1.2,weightkg:39.5,color:"Brown",prevo:"vullaby",evoLevel:54,eggGroups:["Flying"]},
heatmor:{num:631,species:"Heatmor",types:["Fire"],baseStats:{hp:85,atk:97,def:66,spa:105,spd:66,spe:65},abilities:{0:"Solid Rock",1:"Overcoat"},heightm:1.4,weightkg:58,color:"Red",eggGroups:["Ground"]},
durant:{num:632,species:"Durant",types:["Bug","Steel"],baseStats:{hp:58,atk:109,def:112,spa:48,spd:48,spe:109},abilities:{0:"Unnerve",1:"Sand Rush"},heightm:0.3,weightkg:33,color:"Gray",eggGroups:["Bug"]},
deino:{num:633,species:"Deino",types:["Dark","Dragon"],baseStats:{hp:52,atk:65,def:50,spa:45,spd:50,spe:38},abilities:{0:"Weak Armor",1:"Tinted Lens"},heightm:0.8,weightkg:17.3,color:"Blue",evos:["zweilous"],eggGroups:["Dragon"]},
zweilous:{num:634,species:"Zweilous",types:["Dark","Dragon"],baseStats:{hp:72,atk:85,def:70,spa:65,spd:70,spe:58},abilities:{0:"Justified",1:"Drizzle"},heightm:1.4,weightkg:50,color:"Blue",prevo:"deino",evos:["hydreigon"],evoLevel:50,eggGroups:["Dragon"]},
hydreigon:{num:635,species:"Hydreigon",types:["Dark","Dragon"],baseStats:{hp:92,atk:105,def:90,spa:125,spd:90,spe:98},abilities:{0:"Drought",1:"Hustle"},heightm:1.8,weightkg:160,color:"Blue",prevo:"zweilous",evoLevel:64,eggGroups:["Dragon"]},
larvesta:{num:636,species:"Larvesta",types:["Bug","Fire"],baseStats:{hp:55,atk:85,def:55,spa:50,spd:55,spe:60},abilities:{0:"Intimidate",1:"Sniper"},heightm:1.1,weightkg:28.8,color:"White",evos:["volcarona"],eggGroups:["Bug"]},
volcarona:{num:637,species:"Volcarona",types:["Bug","Fire"],baseStats:{hp:85,atk:60,def:65,spa:135,spd:105,spe:100},abilities:{0:"Wonder Guard",1:"Solar Power"},heightm:1.6,weightkg:46,color:"White",prevo:"larvesta",evoLevel:59,eggGroups:["Bug"]},
cobalion:{num:638,species:"Cobalion",types:["Steel","Fighting"],gender:"N",baseStats:{hp:91,atk:90,def:129,spa:90,spd:72,spe:108},abilities:{0:"Poison Point",1:"Magma Armor"},heightm:2.1,weightkg:250,color:"Blue",eggGroups:["No Eggs"]},
terrakion:{num:639,species:"Terrakion",types:["Rock","Fighting"],gender:"N",baseStats:{hp:91,atk:129,def:90,spa:72,spd:90,spe:108},abilities:{0:"Wonder Skin",1:"Shadow Tag"},heightm:1.9,weightkg:260,color:"Gray",eggGroups:["No Eggs"]},
virizion:{num:640,species:"Virizion",types:["Grass","Fighting"],gender:"N",baseStats:{hp:91,atk:90,def:72,spa:90,spd:129,spe:108},abilities:{0:"Moxie",1:"Analytic"},heightm:2,weightkg:200,color:"Green",eggGroups:["No Eggs"]},
tornadus:{num:641,species:"Tornadus",baseForme:"Incarnate",types:["Flying"],gender:"M",baseStats:{hp:79,atk:115,def:70,spa:125,spd:80,spe:111},abilities:{0:"Magma Armor",1:"Battle Armor"},heightm:1.5,weightkg:63,color:"Green",eggGroups:["No Eggs"],otherFormes:["tornadustherian"]},
tornadustherian:{num:641,species:"Tornadus-Therian",baseSpecies:"Tornadus",forme:"Therian",formeLetter:"T",types:["Flying"],gender:"M",baseStats:{hp:79,atk:100,def:80,spa:110,spd:90,spe:121},abilities:{0:"Iron Barbs",1:"Blaze"},heightm:1.4,weightkg:63,color:"Green",eggGroups:["No Eggs"]},
thundurus:{num:642,species:"Thundurus",baseForme:"Incarnate",types:["Electric","Flying"],gender:"M",baseStats:{hp:79,atk:115,def:70,spa:125,spd:80,spe:111},abilities:{0:"Clear Body",1:"Hustle"},heightm:1.5,weightkg:61,color:"Blue",eggGroups:["No Eggs"],otherFormes:["thundurustherian"]},
thundurustherian:{num:642,species:"Thundurus-Therian",baseSpecies:"Thundurus",forme:"Therian",formeLetter:"T",types:["Electric","Flying"],gender:"M",baseStats:{hp:79,atk:105,def:70,spa:145,spd:80,spe:101},abilities:{0:"Anger Point",1:"Insomnia"},heightm:3,weightkg:61,color:"Blue",eggGroups:["No Eggs"]},
reshiram:{num:643,species:"Reshiram",types:["Dragon","Fire"],gender:"N",baseStats:{hp:100,atk:120,def:100,spa:150,spd:120,spe:90},abilities:{0:"Infiltrator",1:"Tangled Feet"},heightm:3.2,weightkg:330,color:"White",eggGroups:["No Eggs"]},
zekrom:{num:644,species:"Zekrom",types:["Dragon","Electric"],gender:"N",baseStats:{hp:100,atk:150,def:120,spa:120,spd:100,spe:90},abilities:{0:"Weak Armor",1:"Limber"},heightm:2.9,weightkg:345,color:"Black",eggGroups:["No Eggs"]},
landorus:{num:645,species:"Landorus",baseForme:"Incarnate",types:["Ground","Flying"],gender:"M",baseStats:{hp:89,atk:125,def:90,spa:115,spd:80,spe:101},abilities:{0:"Soundproof",1:"Mummy"},heightm:1.5,weightkg:68,color:"Brown",eggGroups:["No Eggs"],otherFormes:["landorustherian"]},
landorustherian:{num:645,species:"Landorus-Therian",baseSpecies:"Landorus",forme:"Therian",formeLetter:"T",types:["Ground","Flying"],gender:"M",baseStats:{hp:89,atk:145,def:90,spa:105,spd:80,spe:91},abilities:{0:"Scrappy",1:"Bad Dreams"},heightm:1.3,weightkg:68,color:"Brown",eggGroups:["No Eggs"]},
kyurem:{num:646,species:"Kyurem",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:130,def:90,spa:130,spd:90,spe:95},abilities:{0:"Hydration",1:"Anger Point"},heightm:3,weightkg:325,color:"Gray",eggGroups:["No Eggs"],otherFormes:["kyuremblack","kyuremwhite"]},
kyuremblack:{num:646,species:"Kyurem-Black",baseSpecies:"Kyurem",forme:"Black",formeLetter:"B",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:170,def:100,spa:120,spd:90,spe:95},abilities:{0:"Weak Armor",1:"Shadow Tag"},heightm:3.3,weightkg:325,color:"Gray",eggGroups:["No Eggs"]},
kyuremwhite:{num:646,species:"Kyurem-White",baseSpecies:"Kyurem",forme:"White",formeLetter:"W",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:120,def:90,spa:170,spd:100,spe:95},abilities:{0:"No Guard",1:"Gluttony"},heightm:3.6,weightkg:325,color:"Gray",eggGroups:["No Eggs"]},
keldeo:{num:647,species:"Keldeo",baseForme:"Ordinary",types:["Water","Fighting"],gender:"N",baseStats:{hp:91,atk:72,def:90,spa:129,spd:90,spe:108},abilities:{0:"Shed Skin",1:"Speed Boost"},heightm:1.4,weightkg:48.5,color:"Yellow",eggGroups:["No Eggs"],otherFormes:["keldeoresolute"]},
keldeoresolute:{num:647,species:"Keldeo-Resolute",baseSpecies:"Keldeo",forme:"Resolute",formeLetter:"R",types:["Water","Fighting"],gender:"N",baseStats:{hp:91,atk:72,def:90,spa:129,spd:90,spe:108},abilities:{0:"Shed Skin",1:"Speed Boost"},heightm:1.4,weightkg:48.5,color:"Yellow",eggGroups:["No Eggs"]},
meloetta:{num:648,species:"Meloetta",baseForme:"Aria",types:["Normal","Psychic"],gender:"N",baseStats:{hp:100,atk:77,def:77,spa:128,spd:128,spe:90},abilities:{0:"Multiscale",1:"Moxie"},heightm:0.6,weightkg:6.5,color:"White",eggGroups:["No Eggs"],otherFormes:["meloettapirouette"]},
meloettapirouette:{num:648,species:"Meloetta-Pirouette",baseSpecies:"Meloetta",forme:"Pirouette",formeLetter:"P",types:["Normal","Fighting"],gender:"N",baseStats:{hp:100,atk:128,def:90,spa:77,spd:77,spe:128},abilities:{0:"Multiscale",1:"Moxie"},heightm:0.6,weightkg:6.5,color:"White",eggGroups:["No Eggs"]},
genesect:{num:649,species:"Genesect",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"],otherFormes:["genesectdouse","genesectshock","genesectburn","genesectchill"]},
genesectdouse:{num:649,species:"Genesect-Douse",baseSpecies:"Genesect",forme:"Douse",formeLetter:"D",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"]},
genesectshock:{num:649,species:"Genesect-Shock",baseSpecies:"Genesect",forme:"Shock",formeLetter:"S",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"]},
genesectburn:{num:649,species:"Genesect-Burn",baseSpecies:"Genesect",forme:"Burn",formeLetter:"B",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities: {0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"]},
genesectchill:{num:649,species:"Genesect-Chill",baseSpecies:"Genesect",forme:"Chill",formeLetter:"C",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities: {0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"]}
}; | Update Wonkymons | mods/wonkymons/pokedex.js | Update Wonkymons | <ide><path>ods/wonkymons/pokedex.js
<ide> fearow:{num:22,species:"Fearow",types:["Normal","Flying"],baseStats:{hp:65,atk:90,def:65,spa:61,spd:61,spe:100},abilities:{0:"Clear Body",1:"Trace"},heightm:1.2,weightkg:38,color:"Brown",prevo:"spearow",evoLevel:20,eggGroups:["Flying"]},
<ide> ekans:{num:23,species:"Ekans",types:["Poison"],baseStats:{hp:35,atk:60,def:44,spa:40,spd:54,spe:55},abilities:{0:"Defiant",1:"Shield Dust"},heightm:2,weightkg:6.9,color:"Purple",evos:["arbok"],eggGroups:["Ground","Dragon"]},
<ide> arbok:{num:24,species:"Arbok",types:["Poison"],baseStats:{hp:60,atk:85,def:69,spa:65,spd:79,spe:80},abilities:{0:"Thick Fat",1:"Quick Feet"},heightm:3.5,weightkg:65,color:"Purple",prevo:"ekans",evoLevel:22,eggGroups:["Ground","Dragon"]},
<del>pichu:{num:172,species:"Pichu",types:["Electric"],baseStats:{hp:20,atk:40,def:15,spa:35,spd:35,spe:60},abilities:{0:"Soundproof",1:"Analytic"},heightm:0.3,weightkg:2,color:"Yellow",evos:["pikachu"],eggGroups:["No Eggs"],otherFormes:["pichuspikyeared"]},
<del>pichuspikyeared:{num:172,species:"Pichu-Spiky-eared",baseSpecies:"Pichu",forme:"Spiky-eared",formeLetter:"S",types:["Electric"],baseStats:{hp:20,atk:40,def:15,spa:35,spd:35,spe:60},abilities:{0:"Soundproof",1:"Analytic"},heightm:0.3,weightkg:2,color:"Yellow",evos:["pikachu"],eggGroups:["No Eggs"]},
<add>pikachu:{num:25,species:"Pikachu",types:["Electric"],baseStats:{hp:35,atk:55,def:30,spa:50,spd:40,spe:90},abilities:{0:"Infiltrator",1:"Sturdy"},heightm:0.4,weightkg:6,color:"Yellow",prevo:"pichu",evos:["raichu"],evoLevel:1,eggGroups:["Ground","Fairy"]},
<ide> raichu:{num:26,species:"Raichu",types:["Electric"],baseStats:{hp:60,atk:90,def:55,spa:90,spd:80,spe:100},abilities:{0:"Magic Bounce",1:"Battle Armor"},heightm:0.8,weightkg:30,color:"Yellow",prevo:"pikachu",evoLevel:1,eggGroups:["Ground","Fairy"]},
<del>pikachu:{num:25,species:"Pikachu",types:["Electric"],baseStats:{hp:35,atk:55,def:30,spa:50,spd:40,spe:90},abilities:{0:"Infiltrator",1:"Sturdy"},heightm:0.4,weightkg:6,color:"Yellow",prevo:"pichu",evos:["raichu"],evoLevel:1,eggGroups:["Ground","Fairy"]},
<ide> sandshrew:{num:27,species:"Sandshrew",types:["Ground"],baseStats:{hp:50,atk:75,def:85,spa:20,spd:30,spe:40},abilities:{0:"Magma Armor",1:"Magic Guard"},heightm:0.6,weightkg:12,color:"Yellow",evos:["sandslash"],eggGroups:["Ground"]},
<ide> sandslash:{num:28,species:"Sandslash",types:["Ground"],baseStats:{hp:75,atk:100,def:110,spa:45,spd:55,spe:65},abilities:{0:"Infiltrator",1:"Sheer Force"},heightm:1,weightkg:29.5,color:"Yellow",prevo:"sandshrew",evoLevel:22,eggGroups:["Ground"]},
<ide> nidoranf:{num:29,species:"NidoranF",types:["Poison"],gender:"F",baseStats:{hp:55,atk:47,def:52,spa:40,spd:40,spe:41},abilities:{0:"Poison Touch",1:"Bad Dreams"},heightm:0.4,weightkg:7,color:"Blue",evos:["nidorina"],eggGroups:["Monster","Ground"]},
<ide> nidorina:{num:30,species:"Nidorina",types:["Poison"],gender:"F",baseStats:{hp:70,atk:62,def:67,spa:55,spd:55,spe:56},abilities:{0:"Rock Head",1:"Chlorophyll"},heightm:0.8,weightkg:20,color:"Blue",prevo:"nidoranf",evos:["nidoqueen"],evoLevel:16,eggGroups:["No Eggs"]},
<del>nidoqueen:{num:31,species:"Nidoqueen",types:["Poison","Ground"],gender:"F",baseStats:{hp:90,atk:82,def:87,spa:75,spd:85,spe:76},abilities:{0:"Pressure",1:"Clear Body"},heightm:1.3,weightkg:60,color:"Blue",prevo:"nidorina",evoLevel:1,eggGroups:["No Eggs"]},
<add>nidoqueen:{num:31,species:"Nidoqueen",types:["Poison","Ground"],gender:"F",baseStats:{hp:90,atk:82,def:87,spa:75,spd:85,spe:76},abilities:{0:"Pressure",1:"Clear Body"},heightm:1.3,weightkg:60,color:"Blue",prevo:"nidorina",evoLevel:16,eggGroups:["No Eggs"]},
<ide> nidoranm:{num:32,species:"NidoranM",types:["Poison"],gender:"M",baseStats:{hp:46,atk:57,def:40,spa:40,spd:40,spe:50},abilities:{0:"Limber",1:"Big Pecks"},heightm:0.5,weightkg:9,color:"Purple",evos:["nidorino"],eggGroups:["Monster","Ground"]},
<ide> nidorino:{num:33,species:"Nidorino",types:["Poison"],gender:"M",baseStats:{hp:61,atk:72,def:57,spa:55,spd:55,spe:65},abilities:{0:"Marvel Scale",1:"Drought"},heightm:0.9,weightkg:19.5,color:"Purple",prevo:"nidoranm",evos:["nidoking"],evoLevel:16,eggGroups:["Monster","Ground"]},
<del>nidoking:{num:34,species:"Nidoking",types:["Poison","Ground"],gender:"M",baseStats:{hp:81,atk:92,def:77,spa:85,spd:75,spe:85},abilities:{0:"Shield Dust",1:"Hyper Cutter"},heightm:1.4,weightkg:62,color:"Purple",prevo:"nidorino",evoLevel:1,eggGroups:["Monster","Ground"]},
<del>cleffa:{num:173,species:"Cleffa",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:25,def:28,spa:45,spd:55,spe:15},abilities:{0:"Gluttony",1:"Sticky Hold"},heightm:0.3,weightkg:3,color:"Pink",evos:["clefairy"],eggGroups:["No Eggs"]},
<add>nidoking:{num:34,species:"Nidoking",types:["Poison","Ground"],gender:"M",baseStats:{hp:81,atk:92,def:77,spa:85,spd:75,spe:85},abilities:{0:"Shield Dust",1:"Hyper Cutter"},heightm:1.4,weightkg:62,color:"Purple",prevo:"nidorino",evoLevel:16,eggGroups:["Monster","Ground"]},
<ide> clefairy:{num:35,species:"Clefairy",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:45,def:48,spa:60,spd:65,spe:35},abilities:{0:"Pickpocket",1:"Prankster"},heightm:0.6,weightkg:7.5,color:"Pink",prevo:"cleffa",evos:["clefable"],evoLevel:1,eggGroups:["Fairy"]},
<ide> clefable:{num:36,species:"Clefable",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:95,atk:70,def:73,spa:85,spd:90,spe:60},abilities:{0:"Infiltrator",1:"Suction Cups"},heightm:1.3,weightkg:40,color:"Pink",prevo:"clefairy",evoLevel:1,eggGroups:["Fairy"]},
<ide> vulpix:{num:37,species:"Vulpix",types:["Fire"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:38,atk:41,def:40,spa:50,spd:65,spe:65},abilities:{0:"Toxic Boost",1:"Soundproof"},heightm:0.6,weightkg:9.9,color:"Brown",evos:["ninetales"],eggGroups:["Ground"]},
<ide> ninetales:{num:38,species:"Ninetales",types:["Fire"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:73,atk:76,def:75,spa:81,spd:100,spe:100},abilities:{0:"Sand Veil",1:"Hyper Cutter"},heightm:1.1,weightkg:19.9,color:"Yellow",prevo:"vulpix",evoLevel:1,eggGroups:["Ground"]},
<del>igglybuff:{num:174,species:"Igglybuff",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:90,atk:30,def:15,spa:40,spd:20,spe:15},abilities:{0:"Gluttony",1:"Overgrow"},heightm:0.3,weightkg:1,color:"Pink",evos:["jigglypuff"],eggGroups:["No Eggs"]},
<ide> jigglypuff:{num:39,species:"Jigglypuff",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:115,atk:45,def:20,spa:45,spd:25,spe:20},abilities:{0:"Gluttony",1:"Color Change"},heightm:0.5,weightkg:5.5,color:"Pink",prevo:"igglybuff",evos:["wigglytuff"],evoLevel:1,eggGroups:["Fairy"]},
<ide> wigglytuff:{num:40,species:"Wigglytuff",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:140,atk:70,def:45,spa:75,spd:50,spe:45},abilities:{0:"Tinted Lens",1:"Multiscale"},heightm:1,weightkg:12,color:"Pink",prevo:"jigglypuff",evoLevel:1,eggGroups:["Fairy"]},
<ide> zubat:{num:41,species:"Zubat",types:["Poison","Flying"],baseStats:{hp:40,atk:45,def:35,spa:30,spd:40,spe:55},abilities:{0:"Prankster",1:"Snow Cloak"},heightm:0.8,weightkg:7.5,color:"Purple",evos:["golbat"],eggGroups:["Flying"]},
<ide> golbat:{num:42,species:"Golbat",types:["Poison","Flying"],baseStats:{hp:75,atk:80,def:70,spa:65,spd:75,spe:90},abilities:{0:"Simple",1:"Rock Head"},heightm:1.6,weightkg:55,color:"Purple",prevo:"zubat",evos:["crobat"],evoLevel:22,eggGroups:["Flying"]},
<del>crobat:{num:169,species:"Crobat",types:["Poison","Flying"],baseStats:{hp:85,atk:90,def:80,spa:70,spd:80,spe:130},abilities:{0:"Solid Rock",1:"Trace"},heightm:1.8,weightkg:75,color:"Purple",prevo:"golbat",evoLevel:1,eggGroups:["Flying"]},
<ide> oddish:{num:43,species:"Oddish",types:["Grass","Poison"],baseStats:{hp:45,atk:50,def:55,spa:75,spd:65,spe:30},abilities:{0:"Tinted Lens",1:"Cute Charm"},heightm:0.5,weightkg:5.4,color:"Blue",evos:["gloom"],eggGroups:["Plant"]},
<ide> gloom:{num:44,species:"Gloom",types:["Grass","Poison"],baseStats:{hp:60,atk:65,def:70,spa:85,spd:75,spe:40},abilities:{0:"Drought",1:"Volt Absorb"},heightm:0.8,weightkg:8.6,color:"Blue",prevo:"oddish",evos:["vileplume","bellossom"],evoLevel:21,eggGroups:["Plant"]},
<del>vileplume:{num:45,species:"Vileplume",types:["Grass","Poison"],baseStats:{hp:75,atk:80,def:85,spa:100,spd:90,spe:50},abilities:{0:"Thick Fat",1:"Steadfast"},heightm:1.2,weightkg:18.6,color:"Red",prevo:"gloom",evoLevel:1,eggGroups:["Plant"]},
<del>bellossom:{num:182,species:"Bellossom",types:["Grass"],baseStats:{hp:75,atk:80,def:85,spa:90,spd:100,spe:50},abilities:{0:"Oblivious",1:"Clear Body"},heightm:0.4,weightkg:5.8,color:"Green",prevo:"gloom",evoLevel:1,eggGroups:["Plant"]},
<add>vileplume:{num:45,species:"Vileplume",types:["Grass","Poison"],baseStats:{hp:75,atk:80,def:85,spa:100,spd:90,spe:50},abilities:{0:"Thick Fat",1:"Steadfast"},heightm:1.2,weightkg:18.6,color:"Red",prevo:"gloom",evoLevel:21,eggGroups:["Plant"]},
<ide> paras:{num:46,species:"Paras",types:["Bug","Grass"],baseStats:{hp:35,atk:70,def:55,spa:45,spd:55,spe:25},abilities:{0:"Stall",1:"Lightningrod"},heightm:0.3,weightkg:5.4,color:"Red",evos:["parasect"],eggGroups:["Bug","Plant"]},
<ide> parasect:{num:47,species:"Parasect",types:["Bug","Grass"],baseStats:{hp:60,atk:95,def:80,spa:60,spd:80,spe:30},abilities:{0:"Motor Drive",1:"Quick Feet"},heightm:1,weightkg:29.5,color:"Red",prevo:"paras",evoLevel:24,eggGroups:["Bug","Plant"]},
<ide> venonat:{num:48,species:"Venonat",types:["Bug","Poison"],baseStats:{hp:60,atk:55,def:50,spa:40,spd:55,spe:45},abilities:{0:"Heatproof",1:"Quick Feet"},heightm:1,weightkg:30,color:"Purple",evos:["venomoth"],eggGroups:["Bug"]},
<ide> arcanine:{num:59,species:"Arcanine",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:90,atk:110,def:80,spa:100,spd:80,spe:95},abilities:{0:"Cute Charm",1:"Illusion"},heightm:1.9,weightkg:155,color:"Brown",prevo:"growlithe",evoLevel:1,eggGroups:["Ground"]},
<ide> poliwag:{num:60,species:"Poliwag",types:["Water"],baseStats:{hp:40,atk:50,def:40,spa:40,spd:40,spe:90},abilities:{0:"Oblivious",1:"Thick Fat"},heightm:0.6,weightkg:12.4,color:"Blue",evos:["poliwhirl"],eggGroups:["Water 1"]},
<ide> poliwhirl:{num:61,species:"Poliwhirl",types:["Water"],baseStats:{hp:65,atk:65,def:65,spa:50,spd:50,spe:90},abilities:{0:"Solid Rock",1:"Magic Guard"},heightm:1,weightkg:20,color:"Blue",prevo:"poliwag",evos:["poliwrath","politoed"],evoLevel:25,eggGroups:["Water 1"]},
<del>poliwrath:{num:62,species:"Poliwrath",types:["Water","Fighting"],baseStats:{hp:90,atk:85,def:95,spa:70,spd:90,spe:70},abilities:{0:"Poison Heal",1:"Magma Armor"},heightm:1.3,weightkg:54,color:"Blue",prevo:"poliwhirl",evoLevel:1,eggGroups:["Water 1"]},
<del>politoed:{num:186,species:"Politoed",types:["Water"],baseStats:{hp:90,atk:75,def:75,spa:90,spd:100,spe:70},abilities:{0:"Klutz",1:"Magic Bounce"},heightm:1.1,weightkg:33.9,color:"Green",prevo:"poliwhirl",evoLevel:1,eggGroups:["Water 1"]},
<add>poliwrath:{num:62,species:"Poliwrath",types:["Water","Fighting"],baseStats:{hp:90,atk:85,def:95,spa:70,spd:90,spe:70},abilities:{0:"Poison Heal",1:"Magma Armor"},heightm:1.3,weightkg:54,color:"Blue",prevo:"poliwhirl",evoLevel:25,eggGroups:["Water 1"]},
<ide> abra:{num:63,species:"Abra",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:25,atk:20,def:15,spa:105,spd:55,spe:90},abilities:{0:"Sand Stream",1:"Anticipation"},heightm:0.9,weightkg:19.5,color:"Brown",evos:["kadabra"],eggGroups:["Humanshape"]},
<ide> kadabra:{num:64,species:"Kadabra",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:40,atk:35,def:30,spa:120,spd:70,spe:105},abilities:{0:"Leaf Guard",1:"Hustle"},heightm:1.3,weightkg:56.5,color:"Brown",prevo:"abra",evos:["alakazam"],evoLevel:16,eggGroups:["Humanshape"]},
<del>alakazam:{num:65,species:"Alakazam",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:55,atk:50,def:45,spa:135,spd:85,spe:120},abilities:{0:"Multiscale",1:"Snow Cloak"},heightm:1.5,weightkg:48,color:"Brown",prevo:"kadabra",evoLevel:1,eggGroups:["Humanshape"]},
<add>alakazam:{num:65,species:"Alakazam",types:["Psychic"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:55,atk:50,def:45,spa:135,spd:85,spe:120},abilities:{0:"Multiscale",1:"Snow Cloak"},heightm:1.5,weightkg:48,color:"Brown",prevo:"kadabra",evoLevel:16,eggGroups:["Humanshape"]},
<ide> machop:{num:66,species:"Machop",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:70,atk:80,def:50,spa:35,spd:35,spe:35},abilities:{0:"Frisk",1:"Unburden"},heightm:0.8,weightkg:19.5,color:"Gray",evos:["machoke"],eggGroups:["Humanshape"]},
<ide> machoke:{num:67,species:"Machoke",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:80,atk:100,def:70,spa:50,spd:60,spe:45},abilities:{0:"Rain Dish",1:"Infiltrator"},heightm:1.5,weightkg:70.5,color:"Gray",prevo:"machop",evos:["machamp"],evoLevel:28,eggGroups:["Humanshape"]},
<del>machamp:{num:68,species:"Machamp",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:90,atk:130,def:80,spa:65,spd:85,spe:55},abilities:{0:"Iron Barbs",1:"Tangled Feet"},heightm:1.6,weightkg:130,color:"Gray",prevo:"machoke",evoLevel:1,eggGroups:["Humanshape"]},
<add>machamp:{num:68,species:"Machamp",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:90,atk:130,def:80,spa:65,spd:85,spe:55},abilities:{0:"Iron Barbs",1:"Tangled Feet"},heightm:1.6,weightkg:130,color:"Gray",prevo:"machoke",evoLevel:28,eggGroups:["Humanshape"]},
<ide> bellsprout:{num:69,species:"Bellsprout",types:["Grass","Poison"],baseStats:{hp:50,atk:75,def:35,spa:70,spd:30,spe:40},abilities:{0:"Sand Rush",1:"Unnerve"},heightm:0.7,weightkg:4,color:"Green",evos:["weepinbell"],eggGroups:["Plant"]},
<ide> weepinbell:{num:70,species:"Weepinbell",types:["Grass","Poison"],baseStats:{hp:65,atk:90,def:50,spa:85,spd:45,spe:55},abilities:{0:"Rattled",1:"Snow Warning"},heightm:1,weightkg:6.4,color:"Green",prevo:"bellsprout",evos:["victreebel"],evoLevel:21,eggGroups:["Plant"]},
<del>victreebel:{num:71,species:"Victreebel",types:["Grass","Poison"],baseStats:{hp:80,atk:105,def:65,spa:100,spd:60,spe:70},abilities:{0:"Magic Bounce",1:"Storm Drain"},heightm:1.7,weightkg:15.5,color:"Green",prevo:"weepinbell",evoLevel:1,eggGroups:["Plant"]},
<add>victreebel:{num:71,species:"Victreebel",types:["Grass","Poison"],baseStats:{hp:80,atk:105,def:65,spa:100,spd:60,spe:70},abilities:{0:"Magic Bounce",1:"Storm Drain"},heightm:1.7,weightkg:15.5,color:"Green",prevo:"weepinbell",evoLevel:21,eggGroups:["Plant"]},
<ide> tentacool:{num:72,species:"Tentacool",types:["Water","Poison"],baseStats:{hp:40,atk:40,def:35,spa:50,spd:100,spe:70},abilities:{0:"Leaf Guard",1:"Storm Drain"},heightm:0.9,weightkg:45.5,color:"Blue",evos:["tentacruel"],eggGroups:["Water 3"]},
<ide> tentacruel:{num:73,species:"Tentacruel",types:["Water","Poison"],baseStats:{hp:80,atk:70,def:65,spa:80,spd:120,spe:100},abilities:{0:"Ice Body",1:"No Guard"},heightm:1.6,weightkg:55,color:"Blue",prevo:"tentacool",evoLevel:30,eggGroups:["Water 3"]},
<ide> geodude:{num:74,species:"Geodude",types:["Rock","Ground"],baseStats:{hp:40,atk:80,def:100,spa:30,spd:30,spe:20},abilities:{0:"Pure Power",1:"Leaf Guard"},heightm:0.4,weightkg:20,color:"Brown",evos:["graveler"],eggGroups:["Mineral"]},
<ide> graveler:{num:75,species:"Graveler",types:["Rock","Ground"],baseStats:{hp:55,atk:95,def:115,spa:45,spd:45,spe:35},abilities:{0:"Steadfast",1:"Water Veil"},heightm:1,weightkg:105,color:"Brown",prevo:"geodude",evos:["golem"],evoLevel:25,eggGroups:["Mineral"]},
<del>golem:{num:76,species:"Golem",types:["Rock","Ground"],baseStats:{hp:80,atk:110,def:130,spa:55,spd:65,spe:45},abilities:{0:"Unburden",1:"Magic Bounce"},heightm:1.4,weightkg:300,color:"Brown",prevo:"graveler",evoLevel:1,eggGroups:["Mineral"]},
<add>golem:{num:76,species:"Golem",types:["Rock","Ground"],baseStats:{hp:80,atk:110,def:130,spa:55,spd:65,spe:45},abilities:{0:"Unburden",1:"Magic Bounce"},heightm:1.4,weightkg:300,color:"Brown",prevo:"graveler",evoLevel:25,eggGroups:["Mineral"]},
<ide> ponyta:{num:77,species:"Ponyta",types:["Fire"],baseStats:{hp:50,atk:85,def:55,spa:65,spd:65,spe:90},abilities:{0:"Moxie",1:"Synchronize"},heightm:1,weightkg:30,color:"Yellow",evos:["rapidash"],eggGroups:["Ground"]},
<ide> rapidash:{num:78,species:"Rapidash",types:["Fire"],baseStats:{hp:65,atk:100,def:70,spa:80,spd:80,spe:105},abilities:{0:"Intimidate",1:"Hyper Cutter"},heightm:1.7,weightkg:95,color:"Yellow",prevo:"ponyta",evoLevel:40,eggGroups:["Ground"]},
<ide> slowpoke:{num:79,species:"Slowpoke",types:["Water","Psychic"],baseStats:{hp:90,atk:65,def:65,spa:40,spd:40,spe:15},abilities:{0:"Prankster",1:"Pickpocket"},heightm:1.2,weightkg:36,color:"Pink",evos:["slowbro","slowking"],eggGroups:["Monster","Water 1"]},
<ide> slowbro:{num:80,species:"Slowbro",types:["Water","Psychic"],baseStats:{hp:95,atk:75,def:110,spa:100,spd:80,spe:30},abilities:{0:"Water Veil",1:"Unnerve"},heightm:1.6,weightkg:78.5,color:"Pink",prevo:"slowpoke",evoLevel:37,eggGroups:["Monster","Water 1"]},
<del>slowking:{num:199,species:"Slowking",types:["Water","Psychic"],baseStats:{hp:95,atk:75,def:80,spa:100,spd:110,spe:30},abilities:{0:"Harvest",1:"Torrent"},heightm:2,weightkg:79.5,color:"Pink",prevo:"slowpoke",evoLevel:1,eggGroups:["Monster","Water 1"]},
<ide> magnemite:{num:81,species:"Magnemite",types:["Electric","Steel"],gender:"N",baseStats:{hp:25,atk:35,def:70,spa:95,spd:55,spe:45},abilities:{0:"Liquid Ooze",1:"Insomnia"},heightm:0.3,weightkg:6,color:"Gray",evos:["magneton"],eggGroups:["Mineral"]},
<ide> magneton:{num:82,species:"Magneton",types:["Electric","Steel"],gender:"N",baseStats:{hp:50,atk:60,def:95,spa:120,spd:70,spe:70},abilities:{0:"Solid Rock",1:"Sand Force"},heightm:1,weightkg:60,color:"Gray",prevo:"magnemite",evos:["magnezone"],evoLevel:30,eggGroups:["Mineral"]},
<del>magnezone:{num:462,species:"Magnezone",types:["Electric","Steel"],gender:"N",baseStats:{hp:70,atk:70,def:115,spa:130,spd:90,spe:60},abilities:{0:"Reckless",1:"Swift Swim"},heightm:1.2,weightkg:180,color:"Gray",prevo:"magneton",evoLevel:1,eggGroups:["Mineral"]},
<ide> farfetchd:{num:83,species:"Farfetch'd",types:["Normal","Flying"],baseStats:{hp:52,atk:65,def:55,spa:58,spd:62,spe:60},abilities:{0:"Marvel Scale",1:"Snow Cloak"},heightm:0.8,weightkg:15,color:"Brown",eggGroups:["Flying","Ground"]},
<ide> doduo:{num:84,species:"Doduo",types:["Normal","Flying"],baseStats:{hp:35,atk:85,def:45,spa:35,spd:35,spe:75},abilities:{0:"Flash Fire",1:"Arena Trap"},heightm:1.4,weightkg:39.2,color:"Brown",evos:["dodrio"],eggGroups:["Flying"]},
<ide> dodrio:{num:85,species:"Dodrio",types:["Normal","Flying"],baseStats:{hp:60,atk:110,def:70,spa:60,spd:60,spe:100},abilities:{0:"Wonder Guard",1:"Sticky Hold"},heightm:1.8,weightkg:85.2,color:"Brown",prevo:"doduo",evoLevel:31,eggGroups:["Flying"]},
<ide> cloyster:{num:91,species:"Cloyster",types:["Water","Ice"],baseStats:{hp:50,atk:95,def:180,spa:85,spd:45,spe:70},abilities:{0:"Inner Focus",1:"Wonder Skin"},heightm:1.5,weightkg:132.5,color:"Purple",prevo:"shellder",evoLevel:1,eggGroups:["Water 3"]},
<ide> gastly:{num:92,species:"Gastly",types:["Ghost","Poison"],baseStats:{hp:30,atk:35,def:30,spa:100,spd:35,spe:80},abilities:{0:"Sand Veil",1:"Chlorophyll"},heightm:1.3,weightkg:0.1,color:"Purple",evos:["haunter"],eggGroups:["Indeterminate"]},
<ide> haunter:{num:93,species:"Haunter",types:["Ghost","Poison"],baseStats:{hp:45,atk:50,def:45,spa:115,spd:55,spe:95},abilities:{0:"Technician",1:"Aftermath"},heightm:1.6,weightkg:0.1,color:"Purple",prevo:"gastly",evos:["gengar"],evoLevel:25,eggGroups:["Indeterminate"]},
<del>gengar:{num:94,species:"Gengar",types:["Ghost","Poison"],baseStats:{hp:60,atk:65,def:60,spa:130,spd:75,spe:110},abilities:{0:"Swift Swim",1:"Heavy Metal"},heightm:1.5,weightkg:40.5,color:"Purple",prevo:"haunter",evoLevel:1,eggGroups:["Indeterminate"]},
<add>gengar:{num:94,species:"Gengar",types:["Ghost","Poison"],baseStats:{hp:60,atk:65,def:60,spa:130,spd:75,spe:110},abilities:{0:"Swift Swim",1:"Heavy Metal"},heightm:1.5,weightkg:40.5,color:"Purple",prevo:"haunter",evoLevel:25,eggGroups:["Indeterminate"]},
<ide> onix:{num:95,species:"Onix",types:["Rock","Ground"],baseStats:{hp:35,atk:45,def:160,spa:30,spd:45,spe:70},abilities:{0:"Sand Veil",1:"Cute Charm"},heightm:8.8,weightkg:210,color:"Gray",evos:["steelix"],eggGroups:["Mineral"]},
<del>steelix:{num:208,species:"Steelix",types:["Steel","Ground"],baseStats:{hp:75,atk:85,def:200,spa:55,spd:65,spe:30},abilities:{0:"Multiscale",1:"Anticipation"},heightm:9.2,weightkg:400,color:"Gray",prevo:"onix",evoLevel:1,eggGroups:["Mineral"]},
<ide> drowzee:{num:96,species:"Drowzee",types:["Psychic"],baseStats:{hp:60,atk:48,def:45,spa:43,spd:90,spe:42},abilities:{0:"Tangled Feet",1:"Sniper"},heightm:1,weightkg:32.4,color:"Yellow",evos:["hypno"],eggGroups:["Humanshape"]},
<ide> hypno:{num:97,species:"Hypno",types:["Psychic"],baseStats:{hp:85,atk:73,def:70,spa:73,spd:115,spe:67},abilities:{0:"Solar Power",1:"Technician"},heightm:1.6,weightkg:75.6,color:"Yellow",prevo:"drowzee",evoLevel:26,eggGroups:["Humanshape"]},
<ide> krabby:{num:98,species:"Krabby",types:["Water"],baseStats:{hp:30,atk:105,def:90,spa:25,spd:25,spe:50},abilities:{0:"Iron Barbs",1:"Tangled Feet"},heightm:0.4,weightkg:6.5,color:"Red",evos:["kingler"],eggGroups:["Water 3"]},
<ide> exeggutor:{num:103,species:"Exeggutor",types:["Grass","Psychic"],baseStats:{hp:95,atk:95,def:85,spa:125,spd:65,spe:55},abilities:{0:"Rain Dish",1:"Mold Breaker"},heightm:2,weightkg:120,color:"Yellow",prevo:"exeggcute",evoLevel:1,eggGroups:["Plant"]},
<ide> cubone:{num:104,species:"Cubone",types:["Ground"],baseStats:{hp:50,atk:50,def:95,spa:40,spd:50,spe:35},abilities:{0:"Marvel Scale",1:"Blaze"},heightm:0.4,weightkg:6.5,color:"Brown",evos:["marowak"],eggGroups:["Monster"]},
<ide> marowak:{num:105,species:"Marowak",types:["Ground"],baseStats:{hp:60,atk:80,def:110,spa:50,spd:80,spe:45},abilities:{0:"Scrappy",1:"Magic Bounce"},heightm:1,weightkg:45,color:"Brown",prevo:"cubone",evoLevel:28,eggGroups:["Monster"]},
<del>tyrogue:{num:236,species:"Tyrogue",types:["Fighting"],gender:"M",baseStats:{hp:35,atk:35,def:35,spa:35,spd:35,spe:35},abilities:{0:"Flare Boost",1:"Imposter"},heightm:0.7,weightkg:21,color:"Purple",evos:["hitmonlee","hitmonchan","hitmontop"],eggGroups:["No Eggs"]},
<ide> hitmonlee:{num:106,species:"Hitmonlee",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:120,def:53,spa:35,spd:110,spe:87},abilities:{0:"Clear Body",1:"Rain Dish"},heightm:1.5,weightkg:49.8,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Humanshape"]},
<ide> hitmonchan:{num:107,species:"Hitmonchan",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:105,def:79,spa:35,spd:110,spe:76},abilities:{0:"Weak Armor",1:"Download"},heightm:1.4,weightkg:50.2,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Humanshape"]},
<del>hitmontop:{num:237,species:"Hitmontop",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:95,def:95,spa:35,spd:110,spe:70},abilities:{0:"Klutz",1:"Aftermath"},heightm:1.4,weightkg:48,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Humanshape"]},
<ide> lickitung:{num:108,species:"Lickitung",types:["Normal"],baseStats:{hp:90,atk:55,def:75,spa:60,spd:75,spe:30},abilities:{0:"Sticky Hold",1:"Victory Star"},heightm:1.2,weightkg:65.5,color:"Pink",evos:["lickilicky"],eggGroups:["Monster"]},
<del>lickilicky:{num:463,species:"Lickilicky",types:["Normal"],baseStats:{hp:110,atk:85,def:95,spa:80,spd:95,spe:50},abilities:{0:"Download",1:"Arena Trap"},heightm:1.7,weightkg:140,color:"Pink",prevo:"lickitung",evoLevel:1,evoMove:"Rollout",eggGroups:["Monster"]},
<ide> koffing:{num:109,species:"Koffing",types:["Poison"],baseStats:{hp:40,atk:65,def:95,spa:60,spd:45,spe:35},abilities:{0:"Rivalry",1:"Dry Skin"},heightm:0.6,weightkg:1,color:"Purple",evos:["weezing"],eggGroups:["Indeterminate"]},
<ide> weezing:{num:110,species:"Weezing",types:["Poison"],baseStats:{hp:65,atk:90,def:120,spa:85,spd:70,spe:60},abilities:{0:"Bad Dreams",1:"Super Luck"},heightm:1.2,weightkg:9.5,color:"Purple",prevo:"koffing",evoLevel:35,eggGroups:["Indeterminate"]},
<ide> rhyhorn:{num:111,species:"Rhyhorn",types:["Ground","Rock"],baseStats:{hp:80,atk:85,def:95,spa:30,spd:30,spe:25},abilities:{0:"Cloud Nine",1:"Magnet Pull"},heightm:1,weightkg:115,color:"Gray",evos:["rhydon"],eggGroups:["Monster","Ground"]},
<ide> rhydon:{num:112,species:"Rhydon",types:["Ground","Rock"],baseStats:{hp:105,atk:130,def:120,spa:45,spd:45,spe:40},abilities:{0:"Pickpocket",1:"Poison Point"},heightm:1.9,weightkg:120,color:"Gray",prevo:"rhyhorn",evos:["rhyperior"],evoLevel:42,eggGroups:["Monster","Ground"]},
<del>rhyperior:{num:464,species:"Rhyperior",types:["Ground","Rock"],baseStats:{hp:115,atk:140,def:130,spa:55,spd:55,spe:40},abilities:{0:"Scrappy",1:"Mummy"},heightm:2.4,weightkg:282.8,color:"Gray",prevo:"rhydon",evoLevel:1,eggGroups:["Monster","Ground"]},
<del>happiny:{num:440,species:"Happiny",types:["Normal"],gender:"F",baseStats:{hp:100,atk:5,def:5,spa:15,spd:65,spe:30},abilities:{0:"Stench",1:"Unnerve"},heightm:0.6,weightkg:24.4,color:"Pink",evos:["chansey"],eggGroups:["No Eggs"]},
<ide> chansey:{num:113,species:"Chansey",types:["Normal"],gender:"F",baseStats:{hp:250,atk:5,def:5,spa:35,spd:105,spe:50},abilities:{0:"Liquid Ooze",1:"Static"},heightm:1.1,weightkg:34.6,color:"Pink",prevo:"happiny",evos:["blissey"],evoLevel:1,eggGroups:["Fairy"]},
<del>blissey:{num:242,species:"Blissey",types:["Normal"],gender:"F",baseStats:{hp:255,atk:10,def:10,spa:75,spd:135,spe:55},abilities:{0:"Shed Skin",1:"Early Bird"},heightm:1.5,weightkg:46.8,color:"Pink",prevo:"chansey",evoLevel:1,eggGroups:["Fairy"]},
<ide> tangela:{num:114,species:"Tangela",types:["Grass"],baseStats:{hp:65,atk:55,def:115,spa:100,spd:40,spe:60},abilities:{0:"Insomnia",1:"Battle Armor"},heightm:1,weightkg:35,color:"Blue",evos:["tangrowth"],eggGroups:["Plant"]},
<del>tangrowth:{num:465,species:"Tangrowth",types:["Grass"],baseStats:{hp:100,atk:100,def:125,spa:110,spd:50,spe:50},abilities:{0:"Defiant",1:"Simple"},heightm:2,weightkg:128.6,color:"Blue",prevo:"tangela",evoLevel:1,evoMove:"AncientPower",eggGroups:["Plant"]},
<ide> kangaskhan:{num:115,species:"Kangaskhan",types:["Normal"],gender:"F",baseStats:{hp:105,atk:95,def:80,spa:40,spd:80,spe:90},abilities:{0:"Light Metal",1:"Bad Dreams"},heightm:2.2,weightkg:80,color:"Brown",eggGroups:["Monster"]},
<del>horsea:{num:116,species:"Horsea",types:["Water"],baseStats:{hp:30,atk:40,def:70,spa:70,spd:25,spe:60},abilities:{0:"Big Pecks",1:"Sandstream"},heightm:0.4,weightkg:8,color:"Blue",evos:["seadra"],eggGroups:["Water 1","Dragon"]},
<add>horsea:{num:116,species:"Horsea",types:["Water"],baseStats:{hp:30,atk:40,def:70,spa:70,spd:25,spe:60},abilities:{0:"Big Pecks",1:"Sand Stream"},heightm:0.4,weightkg:8,color:"Blue",evos:["seadra"],eggGroups:["Water 1","Dragon"]},
<ide> seadra:{num:117,species:"Seadra",types:["Water"],baseStats:{hp:55,atk:65,def:95,spa:95,spd:45,spe:85},abilities:{0:"Snow Warning",1:"Rivalry"},heightm:1.2,weightkg:25,color:"Blue",prevo:"horsea",evos:["kingdra"],evoLevel:32,eggGroups:["Water 1","Dragon"]},
<del>kingdra:{num:230,species:"Kingdra",types:["Water","Dragon"],baseStats:{hp:75,atk:95,def:95,spa:95,spd:95,spe:85},abilities:{0:"Cloud Nine",1:"Pickpocket"},heightm:1.8,weightkg:152,color:"Blue",prevo:"seadra",evoLevel:1,eggGroups:["Water 1","Dragon"]},
<ide> goldeen:{num:118,species:"Goldeen",types:["Water"],baseStats:{hp:45,atk:67,def:60,spa:35,spd:50,spe:63},abilities:{0:"Magic Bounce",1:"Overcoat"},heightm:0.6,weightkg:15,color:"Red",evos:["seaking"],eggGroups:["Water 2"]},
<ide> seaking:{num:119,species:"Seaking",types:["Water"],baseStats:{hp:80,atk:92,def:65,spa:65,spd:80,spe:68},abilities:{0:"Analytic",1:"Natural Cure"},heightm:1.3,weightkg:39,color:"Red",prevo:"goldeen",evoLevel:33,eggGroups:["Water 2"]},
<ide> staryu:{num:120,species:"Staryu",types:["Water"],gender:"N",baseStats:{hp:30,atk:45,def:55,spa:70,spd:55,spe:85},abilities:{0:"Limber",1:"Battle Armor"},heightm:0.8,weightkg:34.5,color:"Brown",evos:["starmie"],eggGroups:["Water 3"]},
<ide> starmie:{num:121,species:"Starmie",types:["Water","Psychic"],gender:"N",baseStats:{hp:60,atk:75,def:85,spa:100,spd:85,spe:115},abilities:{0:"Overcoat",1:"Stench"},heightm:1.1,weightkg:80,color:"Purple",prevo:"staryu",evoLevel:1,eggGroups:["Water 3"]},
<del>mimejr:{num:439,species:"Mime Jr.",types:["Psychic"],baseStats:{hp:20,atk:25,def:45,spa:70,spd:90,spe:60},abilities:{0:"Flame Body",1:"Victory Star"},heightm:0.6,weightkg:13,color:"Pink",evos:["mrmime"],eggGroups:["No Eggs"]},
<ide> mrmime:{num:122,species:"Mr. Mime",types:["Psychic"],baseStats:{hp:40,atk:45,def:65,spa:100,spd:120,spe:90},abilities:{0:"Reckless",1:"Pressure"},heightm:1.3,weightkg:54.5,color:"Pink",prevo:"mimejr",evoLevel:1,evoMove:"Mimic",eggGroups:["Humanshape"]},
<ide> scyther:{num:123,species:"Scyther",types:["Bug","Flying"],baseStats:{hp:70,atk:110,def:80,spa:55,spd:80,spe:105},abilities:{0:"Synchronize",1:"Unburden"},heightm:1.5,weightkg:56,color:"Green",evos:["scizor"],eggGroups:["Bug"]},
<del>scizor:{num:212,species:"Scizor",types:["Bug","Steel"],baseStats:{hp:70,atk:130,def:100,spa:55,spd:80,spe:65},abilities:{0:"Iron Barbs",1:"Magma Armor"},heightm:1.8,weightkg:118,color:"Red",prevo:"scyther",evoLevel:1,eggGroups:["Bug"]},
<del>smoochum:{num:238,species:"Smoochum",types:["Ice","Psychic"],gender:"F",baseStats:{hp:45,atk:30,def:15,spa:85,spd:65,spe:65},abilities:{0:"Rock Head",1:"Oblivious"},heightm:0.4,weightkg:6,color:"Pink",evos:["jynx"],eggGroups:["No Eggs"]},
<ide> jynx:{num:124,species:"Jynx",types:["Ice","Psychic"],gender:"F",baseStats:{hp:65,atk:50,def:35,spa:115,spd:95,spe:95},abilities:{0:"Reckless",1:"Harvest"},heightm:1.4,weightkg:40.6,color:"Red",prevo:"smoochum",evoLevel:30,eggGroups:["Humanshape"]},
<del>elekid:{num:239,species:"Elekid",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:45,atk:63,def:37,spa:65,spd:55,spe:95},abilities:{0:"Wonder Guard",1:"Unaware"},heightm:0.6,weightkg:23.5,color:"Yellow",evos:["electabuzz"],eggGroups:["No Eggs"]},
<ide> electabuzz:{num:125,species:"Electabuzz",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:65,atk:83,def:57,spa:95,spd:85,spe:105},abilities:{0:"Adaptability",1:"Poison Heal"},heightm:1.1,weightkg:30,color:"Yellow",prevo:"elekid",evos:["electivire"],evoLevel:30,eggGroups:["Humanshape"]},
<del>electivire:{num:466,species:"Electivire",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:123,def:67,spa:95,spd:85,spe:95},abilities:{0:"Adaptability",1:"Toxic Boost"},heightm:1.8,weightkg:138.6,color:"Yellow",prevo:"electabuzz",evoLevel:1,eggGroups:["Humanshape"]},
<del>magby:{num:240,species:"Magby",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:45,atk:75,def:37,spa:70,spd:55,spe:83},abilities:{0:"Static",1:"Adaptability"},heightm:0.7,weightkg:21.4,color:"Red",evos:["magmar"],eggGroups:["No Eggs"]},
<ide> magmar:{num:126,species:"Magmar",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:65,atk:95,def:57,spa:100,spd:85,spe:93},abilities:{0:"Marvel Scale",1:"Cloud Nine"},heightm:1.3,weightkg:44.5,color:"Red",prevo:"magby",evos:["magmortar"],evoLevel:30,eggGroups:["Humanshape"]},
<del>magmortar:{num:467,species:"Magmortar",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:95,def:67,spa:125,spd:95,spe:83},abilities:{0:"Immunity",1:"Cloud Nine"},heightm:1.6,weightkg:68,color:"Red",prevo:"magmar",evoLevel:1,eggGroups:["Humanshape"]},
<ide> pinsir:{num:127,species:"Pinsir",types:["Bug"],baseStats:{hp:65,atk:125,def:100,spa:55,spd:70,spe:85},abilities:{0:"Super Luck",1:"Flame Body"},heightm:1.5,weightkg:55,color:"Brown",eggGroups:["Bug"]},
<ide> tauros:{num:128,species:"Tauros",types:["Normal"],gender:"M",baseStats:{hp:75,atk:100,def:95,spa:40,spd:70,spe:110},abilities:{0:"Keen Eye",1:"Cloud Nine"},heightm:1.4,weightkg:88.4,color:"Brown",eggGroups:["Ground"]},
<ide> magikarp:{num:129,species:"Magikarp",types:["Water"],baseStats:{hp:20,atk:10,def:55,spa:15,spd:20,spe:80},abilities:{0:"Big Pecks",1:"Weak Armor"},heightm:0.9,weightkg:10,color:"Red",evos:["gyarados"],eggGroups:["Water 2","Dragon"]},
<ide> eevee:{num:133,species:"Eevee",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:55,def:50,spa:45,spd:65,spe:55},abilities:{0:"Pure Power",1:"Poison Heal"},heightm:0.3,weightkg:6.5,color:"Brown",evos:["vaporeon","jolteon","flareon","espeon","umbreon","leafeon","glaceon"],eggGroups:["Ground"]},
<ide> vaporeon:{num:134,species:"Vaporeon",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:130,atk:65,def:60,spa:110,spd:95,spe:65},abilities:{0:"Stench",1:"Leaf Guard"},heightm:1,weightkg:29,color:"Blue",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<ide> jolteon:{num:135,species:"Jolteon",types:["Electric"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:65,def:60,spa:110,spd:95,spe:130},abilities:{0:"Magnet Pull",1:"Synchronize"},heightm:0.8,weightkg:24.5,color:"Yellow",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<del>flareon:{num:136,species:"Flareon",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:130,def:60,spa:95,spd:110,spe:65},abilities:{0:"Ice Body",1:"Imposter"},heightm:0.9,weightkg:25,color:"Red",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<del>espeon:{num:196,species:"Espeon",types:["Psychic"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:65,def:60,spa:130,spd:95,spe:110},abilities:{0:"Technician",1:"Sand Veil"},heightm:0.9,weightkg:26.5,color:"Purple",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<del>umbreon:{num:197,species:"Umbreon",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:65,def:110,spa:60,spd:130,spe:65},abilities:{0:"Immunity",1:"Sniper"},heightm:1,weightkg:27,color:"Black",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<del>leafeon:{num:470,species:"Leafeon",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:110,def:130,spa:60,spd:65,spe:95},abilities:{0:"Water Absorb",1:"Cursed Body"},heightm:1,weightkg:25.5,color:"Green",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<del>glaceon:{num:471,species:"Glaceon",types:["Ice"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:60,def:110,spa:130,spd:95,spe:65},abilities:{0:"Color Change",1:"Trace"},heightm:0.8,weightkg:25.9,color:"Blue",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<add>flareon:{num:136,species:"Flareon",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:130,def:60,spa:95,spd:110,spe:65},abilities:{0:"Ice Body",1:"Imposter"},heightm:0.9,weightkg:25,color:"Red",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<ide> porygon:{num:137,species:"Porygon",types:["Normal"],gender:"N",baseStats:{hp:65,atk:60,def:70,spa:85,spd:75,spe:40},abilities:{0:"Thick Fat",1:"Aftermath"},heightm:0.8,weightkg:36.5,color:"Pink",evos:["porygon2"],eggGroups:["Mineral"]},
<del>porygon2:{num:233,species:"Porygon2",types:["Normal"],gender:"N",baseStats:{hp:85,atk:80,def:90,spa:105,spd:95,spe:60},abilities:{0:"Battle Armor",1:"Drought"},heightm:0.6,weightkg:32.5,color:"Red",prevo:"porygon",evos:["porygonz"],evoLevel:1,eggGroups:["Mineral"]},
<del>porygonz:{num:474,species:"Porygon-Z",types:["Normal"],gender:"N",baseStats:{hp:85,atk:80,def:70,spa:135,spd:75,spe:90},abilities:{0:"Soundproof",1:"Compoundeyes"},heightm:0.9,weightkg:34,color:"Red",prevo:"porygon2",evoLevel:1,eggGroups:["Mineral"]},
<ide> omanyte:{num:138,species:"Omanyte",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:35,atk:40,def:100,spa:90,spd:55,spe:35},abilities:{0:"Wonder Guard",1:"Aftermath"},heightm:0.4,weightkg:7.5,color:"Blue",evos:["omastar"],eggGroups:["Water 1","Water 3"]},
<ide> omastar:{num:139,species:"Omastar",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:60,def:125,spa:115,spd:70,spe:55},abilities:{0:"Light Metal",1:"Klutz"},heightm:1,weightkg:35,color:"Blue",prevo:"omanyte",evoLevel:40,eggGroups:["Water 1","Water 3"]},
<ide> kabuto:{num:140,species:"Kabuto",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:80,def:90,spa:55,spd:45,spe:55},abilities:{0:"Own Tempo",1:"Frisk"},heightm:0.5,weightkg:11.5,color:"Brown",evos:["kabutops"],eggGroups:["Water 1","Water 3"]},
<ide> kabutops:{num:141,species:"Kabutops",types:["Rock","Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:115,def:105,spa:65,spd:70,spe:80},abilities:{0:"Justified",1:"Aftermath"},heightm:1.3,weightkg:40.5,color:"Brown",prevo:"kabuto",evoLevel:40,eggGroups:["Water 1","Water 3"]},
<ide> aerodactyl:{num:142,species:"Aerodactyl",types:["Rock","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:80,atk:105,def:65,spa:60,spd:75,spe:130},abilities:{0:"Magma Armor",1:"Early Bird"},heightm:1.8,weightkg:59,color:"Purple",eggGroups:["Flying"]},
<del>munchlax:{num:446,species:"Munchlax",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:135,atk:85,def:40,spa:40,spd:85,spe:5},abilities:{0:"Marvel Scale",1:"Drought"},heightm:0.6,weightkg:105,color:"Black",evos:["snorlax"],eggGroups:["No Eggs"]},
<ide> snorlax:{num:143,species:"Snorlax",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:160,atk:110,def:65,spa:65,spd:110,spe:30},abilities:{0:"Snow Warning",1:"Overcoat"},heightm:2.1,weightkg:460,color:"Black",prevo:"munchlax",evoLevel:1,eggGroups:["Monster"]},
<ide> articuno:{num:144,species:"Articuno",types:["Ice","Flying"],gender:"N",baseStats:{hp:90,atk:85,def:100,spa:95,spd:125,spe:85},abilities:{0:"Chlorophyll",1:"Stall"},heightm:1.7,weightkg:55.4,color:"Blue",eggGroups:["No Eggs"]},
<ide> zapdos:{num:145,species:"Zapdos",types:["Electric","Flying"],gender:"N",baseStats:{hp:90,atk:90,def:85,spa:125,spd:90,spe:100},abilities:{0:"Sniper",1:"Regenerator"},heightm:1.6,weightkg:52.6,color:"Yellow",eggGroups:["No Eggs"]},
<ide> ledian:{num:166,species:"Ledian",types:["Bug","Flying"],baseStats:{hp:55,atk:35,def:50,spa:55,spd:110,spe:85},abilities:{0:"Static",1:"Clear Body"},heightm:1.4,weightkg:35.6,color:"Red",prevo:"ledyba",evoLevel:18,eggGroups:["Bug"]},
<ide> spinarak:{num:167,species:"Spinarak",types:["Bug","Poison"],baseStats:{hp:40,atk:60,def:40,spa:40,spd:40,spe:30},abilities:{0:"Mold Breaker",1:"Reckless"},heightm:0.5,weightkg:8.5,color:"Green",evos:["ariados"],eggGroups:["Bug"]},
<ide> ariados:{num:168,species:"Ariados",types:["Bug","Poison"],baseStats:{hp:70,atk:90,def:70,spa:60,spd:60,spe:40},abilities:{0:"Snow Warning",1:"Super Luck"},heightm:1.1,weightkg:33.5,color:"Red",prevo:"spinarak",evoLevel:22,eggGroups:["Bug"]},
<del>chinchou:{num:170,species:"Chinchou",types:["Water","Electric"],baseStats:{hp:75,atk:38,def:38,spa:56,spd:56,spe:67},abilities:{0:"Technician",1:"Sand Veil"},heightm:0.5,weightkg:12,color:"Blue",evos:["lanturn"],eggGroups:["Water 2"]},
<add>crobat:{num:169,species:"Crobat",types:["Poison","Flying"],baseStats:{hp:85,atk:90,def:80,spa:70,spd:80,spe:130},abilities:{0:"Solid Rock",1:"Trace"},heightm:1.8,weightkg:75,color:"Purple",prevo:"golbat",evoLevel:23,eggGroups:["Flying"]},
<add>chinchou:{num:170,species:"Chinchou",types:["Water","Electric"],baseStats:{hp:75,atk:38,def:38,spa:56,spd:56,spe:67},abilities:{0:"Technician",1:"Sand Veil"},heightm:0.5,weightkg:12,color:"Blue",evos:["lanturn"],eggGroups:["Water 2"]},
<ide> lanturn:{num:171,species:"Lanturn",types:["Water","Electric"],baseStats:{hp:125,atk:58,def:58,spa:76,spd:76,spe:67},abilities:{0:"Trace",1:"Clear Body"},heightm:1.2,weightkg:22.5,color:"Blue",prevo:"chinchou",evoLevel:27,eggGroups:["Water 2"]},
<add>pichu:{num:172,species:"Pichu",types:["Electric"],baseStats:{hp:20,atk:40,def:15,spa:35,spd:35,spe:60},abilities:{0:"Soundproof",1:"Analytic"},heightm:0.3,weightkg:2,color:"Yellow",evos:["pikachu"],eggGroups:["No Eggs"]},
<add>cleffa:{num:173,species:"Cleffa",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:25,def:28,spa:45,spd:55,spe:15},abilities:{0:"Gluttony",1:"Sticky Hold"},heightm:0.3,weightkg:3,color:"Pink",evos:["clefairy"],eggGroups:["No Eggs"]},
<add>igglybuff:{num:174,species:"Igglybuff",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:90,atk:30,def:15,spa:40,spd:20,spe:15},abilities:{0:"Gluttony",1:"Overgrow"},heightm:0.3,weightkg:1,color:"Pink",evos:["jigglypuff"],eggGroups:["No Eggs"]},
<ide> togepi:{num:175,species:"Togepi",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:35,atk:20,def:65,spa:40,spd:65,spe:20},abilities:{0:"Insomnia",1:"Anger Point"},heightm:0.3,weightkg:1.5,color:"White",evos:["togetic"],eggGroups:["No Eggs"]},
<del>togetic:{num:176,species:"Togetic",types:["Normal","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:40,def:85,spa:80,spd:105,spe:40},abilities:{0:"Damp",1:"Mummy"},heightm:0.6,weightkg:3.2,color:"White",prevo:"togepi",evos:["togekiss"],evoLevel:1,eggGroups:["Flying","Fairy"]},
<del>togekiss:{num:468,species:"Togekiss",types:["Normal","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:85,atk:50,def:95,spa:120,spd:115,spe:80},abilities:{0:"Intimidate",1:"Pickpocket"},heightm:1.5,weightkg:38,color:"White",prevo:"togetic",evoLevel:1,eggGroups:["Flying","Fairy"]},
<add>togetic:{num:176,species:"Togetic",types:["Normal","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:55,atk:40,def:85,spa:80,spd:105,spe:40},abilities:{0:"Damp",1:"Mummy"},heightm:0.6,weightkg:3.2,color:"White",prevo:"togepi",evos:["togekiss"],evoLevel:2,eggGroups:["Flying","Fairy"]},
<ide> natu:{num:177,species:"Natu",types:["Psychic","Flying"],baseStats:{hp:40,atk:50,def:45,spa:70,spd:45,spe:70},abilities:{0:"Water Absorb",1:"Mummy"},heightm:0.2,weightkg:2,color:"Green",evos:["xatu"],eggGroups:["Flying"]},
<del>xatu:{num:178,species:"Xatu",types:["Psychic","Flying"],baseStats:{hp:65,atk:75,def:70,spa:95,spd:70,spe:95},abilities:{0:"Shed Skin",1:"Sand Veil"},heightm:1.5,weightkg:15,color:"Green",prevo:"natu",evoLevel:25,eggGroups:["Flying"]},
<add>xatu:{num:178,species:"Xatu",types:["Psychic","Flying"],baseStats:{hp:65,atk:75,def:70,spa:95,spd:70,spe:95},abilities:{0:"Shed Skin",1:"Sand Veil"},heightm:1.5,weightkg:15,color:"Green",prevo:"natu",evoLevel:25,eggGroups:["Flying"]},
<ide> mareep:{num:179,species:"Mareep",types:["Electric"],baseStats:{hp:55,atk:40,def:40,spa:65,spd:45,spe:35},abilities:{0:"Steadfast",1:"Compoundeyes"},heightm:0.6,weightkg:7.8,color:"White",evos:["flaaffy"],eggGroups:["Monster","Ground"]},
<ide> flaaffy:{num:180,species:"Flaaffy",types:["Electric"],baseStats:{hp:70,atk:55,def:55,spa:80,spd:60,spe:45},abilities:{0:"Sand Veil",1:"Volt Absorb"},heightm:0.8,weightkg:13.3,color:"Pink",prevo:"mareep",evos:["ampharos"],evoLevel:15,eggGroups:["Monster","Ground"]},
<ide> ampharos:{num:181,species:"Ampharos",types:["Electric"],baseStats:{hp:90,atk:75,def:75,spa:115,spd:90,spe:55},abilities:{0:"Rivalry",1:"Snow Cloak"},heightm:1.4,weightkg:61.5,color:"Yellow",prevo:"flaaffy",evoLevel:30,eggGroups:["Monster","Ground"]},
<del>azurill:{num:298,species:"Azurill",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:20,def:40,spa:20,spd:40,spe:20},abilities:{0:"Flame Body",1:"Early Bird"},heightm:0.2,weightkg:2,color:"Blue",evos:["marill"],eggGroups:["No Eggs"]},
<add>bellossom:{num:182,species:"Bellossom",types:["Grass"],baseStats:{hp:75,atk:80,def:85,spa:90,spd:100,spe:50},abilities:{0:"Oblivious",1:"Clear Body"},heightm:0.4,weightkg:5.8,color:"Green",prevo:"gloom",evoLevel:21,eggGroups:["Plant"]},
<ide> marill:{num:183,species:"Marill",types:["Water"],baseStats:{hp:70,atk:20,def:50,spa:20,spd:50,spe:40},abilities:{0:"Adaptability",1:"Chlorophyll"},heightm:0.4,weightkg:8.5,color:"Blue",prevo:"azurill",evos:["azumarill"],evoLevel:1,eggGroups:["Water 1","Fairy"]},
<ide> azumarill:{num:184,species:"Azumarill",types:["Water"],baseStats:{hp:100,atk:50,def:80,spa:50,spd:80,spe:50},abilities:{0:"Pickpocket",1:"Technician"},heightm:0.8,weightkg:28.5,color:"Blue",prevo:"marill",evoLevel:18,eggGroups:["Water 1","Fairy"]},
<del>bonsly:{num:438,species:"Bonsly",types:["Rock"],baseStats:{hp:50,atk:80,def:95,spa:10,spd:45,spe:10},abilities:{0:"Tangled Feet",1:"Soundproof"},heightm:0.5,weightkg:15,color:"Brown",evos:["sudowoodo"],eggGroups:["No Eggs"]},
<ide> sudowoodo:{num:185,species:"Sudowoodo",types:["Rock"],baseStats:{hp:70,atk:100,def:115,spa:30,spd:65,spe:30},abilities:{0:"Victory Star",1:"Own Tempo"},heightm:1.2,weightkg:38,color:"Brown",prevo:"bonsly",evoLevel:1,evoMove:"Mimic",eggGroups:["Mineral"]},
<add>politoed:{num:186,species:"Politoed",types:["Water"],baseStats:{hp:90,atk:75,def:75,spa:90,spd:100,spe:70},abilities:{0:"Klutz",1:"Magic Bounce"},heightm:1.1,weightkg:33.9,color:"Green",prevo:"poliwhirl",evoLevel:25,eggGroups:["Water 1"]},
<ide> hoppip:{num:187,species:"Hoppip",types:["Grass","Flying"],baseStats:{hp:35,atk:35,def:40,spa:35,spd:55,spe:50},abilities:{0:"Suction Cups",1:"Drought"},heightm:0.4,weightkg:0.5,color:"Pink",evos:["skiploom"],eggGroups:["Fairy","Plant"]},
<ide> skiploom:{num:188,species:"Skiploom",types:["Grass","Flying"],baseStats:{hp:55,atk:45,def:50,spa:45,spd:65,spe:80},abilities:{0:"Steadfast",1:"Prankster"},heightm:0.6,weightkg:1,color:"Green",prevo:"hoppip",evos:["jumpluff"],evoLevel:18,eggGroups:["Fairy","Plant"]},
<ide> jumpluff:{num:189,species:"Jumpluff",types:["Grass","Flying"],baseStats:{hp:75,atk:55,def:70,spa:55,spd:85,spe:110},abilities:{0:"Magic Bounce",1:"Imposter"},heightm:0.8,weightkg:3,color:"Blue",prevo:"skiploom",evoLevel:27,eggGroups:["Fairy","Plant"]},
<ide> aipom:{num:190,species:"Aipom",types:["Normal"],baseStats:{hp:55,atk:70,def:55,spa:40,spd:55,spe:85},abilities:{0:"Forewarn",1:"Light Metal"},heightm:0.8,weightkg:11.5,color:"Purple",evos:["ambipom"],eggGroups:["Ground"]},
<del>ambipom:{num:424,species:"Ambipom",types:["Normal"],baseStats:{hp:75,atk:100,def:66,spa:60,spd:66,spe:115},abilities:{0:"Unaware",1:"Drizzle"},heightm:1.2,weightkg:20.3,color:"Purple",prevo:"aipom",evoLevel:1,evoMove:"Double Hit",eggGroups:["Ground"]},
<ide> sunkern:{num:191,species:"Sunkern",types:["Grass"],baseStats:{hp:30,atk:30,def:30,spa:30,spd:30,spe:30},abilities:{0:"Damp",1:"Serene Grace"},heightm:0.3,weightkg:1.8,color:"Yellow",evos:["sunflora"],eggGroups:["Plant"]},
<del>sunflora:{num:192,species:"Sunflora",types:["Grass"],baseStats:{hp:75,atk:75,def:55,spa:105,spd:85,spe:30},abilities:{0:"Simple",1:"Drizzle"},heightm:0.8,weightkg:8.5,color:"Yellow",prevo:"sunkern",evoLevel:1,eggGroups:["Plant"]},
<add>sunflora:{num:192,species:"Sunflora",types:["Grass"],baseStats:{hp:75,atk:75,def:55,spa:105,spd:85,spe:30},abilities:{0:"Simple",1:"Drizzle"},heightm:0.8,weightkg:8.5,color:"Yellow",prevo:"sunkern",evoLevel:1,eggGroups:["Plant"]},
<ide> yanma:{num:193,species:"Yanma",types:["Bug","Flying"],baseStats:{hp:65,atk:65,def:45,spa:75,spd:45,spe:95},abilities:{0:"Flash Fire",1:"Effect Spore"},heightm:1.2,weightkg:38,color:"Red",evos:["yanmega"],eggGroups:["Bug"]},
<del>yanmega:{num:469,species:"Yanmega",types:["Bug","Flying"],baseStats:{hp:86,atk:76,def:86,spa:116,spd:56,spe:95},abilities:{0:"Prankster",1:"Clear Body"},heightm:1.9,weightkg:51.5,color:"Green",prevo:"yanma",evoLevel:1,evoMove:"AncientPower",eggGroups:["Bug"]},
<ide> wooper:{num:194,species:"Wooper",types:["Water","Ground"],baseStats:{hp:55,atk:45,def:45,spa:25,spd:25,spe:15},abilities:{0:"Rain Dish",1:"Weak Armor"},heightm:0.4,weightkg:8.5,color:"Blue",evos:["quagsire"],eggGroups:["Water 1","Ground"]},
<ide> quagsire:{num:195,species:"Quagsire",types:["Water","Ground"],baseStats:{hp:95,atk:85,def:85,spa:65,spd:65,spe:35},abilities:{0:"Anticipation",1:"Arena Trap"},heightm:1.4,weightkg:75,color:"Blue",prevo:"wooper",evoLevel:20,eggGroups:["Water 1","Ground"]},
<add>espeon:{num:196,species:"Espeon",types:["Psychic"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:65,def:60,spa:130,spd:95,spe:110},abilities:{0:"Technician",1:"Sand Veil"},heightm:0.9,weightkg:26.5,color:"Purple",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<add>umbreon:{num:197,species:"Umbreon",types:["Dark"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:95,atk:65,def:110,spa:60,spd:130,spe:65},abilities:{0:"Immunity",1:"Sniper"},heightm:1,weightkg:27,color:"Black",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<ide> murkrow:{num:198,species:"Murkrow",types:["Dark","Flying"],baseStats:{hp:60,atk:85,def:42,spa:85,spd:42,spe:91},abilities:{0:"Cute Charm",1:"Quick Feet"},heightm:0.5,weightkg:2.1,color:"Black",evos:["honchkrow"],eggGroups:["Flying"]},
<del>honchkrow:{num:430,species:"Honchkrow",types:["Dark","Flying"],baseStats:{hp:100,atk:125,def:52,spa:105,spd:52,spe:71},abilities:{0:"Poison Heal",1:"Harvest"},heightm:0.9,weightkg:27.3,color:"Black",prevo:"murkrow",evoLevel:1,eggGroups:["Flying"]},
<add>slowking:{num:199,species:"Slowking",types:["Water","Psychic"],baseStats:{hp:95,atk:75,def:80,spa:100,spd:110,spe:30},abilities:{0:"Harvest",1:"Torrent"},heightm:2,weightkg:79.5,color:"Pink",prevo:"slowpoke",evoLevel:1,eggGroups:["Monster","Water 1"]},
<ide> misdreavus:{num:200,species:"Misdreavus",types:["Ghost"],baseStats:{hp:60,atk:60,def:60,spa:85,spd:85,spe:85},abilities:{0:"Shed Skin",1:"Inner Focus"},heightm:0.7,weightkg:1,color:"Gray",evos:["mismagius"],eggGroups:["Indeterminate"]},
<del>mismagius:{num:429,species:"Mismagius",types:["Ghost"],baseStats:{hp:60,atk:60,def:60,spa:105,spd:105,spe:105},abilities:{0:"Sticky Hold",1:"Defiant"},heightm:0.9,weightkg:4.4,color:"Purple",prevo:"misdreavus",evoLevel:1,eggGroups:["Indeterminate"]},
<ide> unown:{num:201,species:"Unown",baseForme:"A",types:["Psychic"],gender:"N",baseStats:{hp:48,atk:72,def:48,spa:72,spd:48,spe:48},abilities:{0:"Solid Rock",1:"Rain Dish"},heightm:0.5,weightkg:5,color:"Black",eggGroups:["No Eggs"],otherForms:["unownb","unownc","unownd","unowne","unownf","unowng","unownh","unowni","unownj","unownk","unownl","unownm","unownn","unowno","unownp","unownq","unownr","unowns","unownt","unownu","unownv","unownw","unownx","unowny","unownz","unownem","unownqm"]},
<del>wynaut:{num:360,species:"Wynaut",types:["Psychic"],baseStats:{hp:95,atk:23,def:48,spa:23,spd:48,spe:23},abilities:{0:"Mold Breaker",1:"Mummy"},heightm:0.6,weightkg:14,color:"Blue",evos:["wobbuffet"],eggGroups:["No Eggs"]},
<ide> wobbuffet:{num:202,species:"Wobbuffet",types:["Psychic"],baseStats:{hp:190,atk:33,def:58,spa:33,spd:58,spe:33},abilities:{0:"Own Tempo",1:"Suction Cups"},heightm:1.3,weightkg:28.5,color:"Blue",prevo:"wynaut",evoLevel:15,eggGroups:["Indeterminate"]},
<ide> girafarig:{num:203,species:"Girafarig",types:["Normal","Psychic"],baseStats:{hp:70,atk:80,def:65,spa:90,spd:65,spe:85},abilities:{0:"Color Change",1:"Big Pecks"},heightm:1.5,weightkg:41.5,color:"Yellow",eggGroups:["Ground"]},
<ide> pineco:{num:204,species:"Pineco",types:["Bug"],baseStats:{hp:50,atk:65,def:90,spa:35,spd:35,spe:15},abilities:{0:"Damp",1:"Iron Barbs"},heightm:0.6,weightkg:7.2,color:"Gray",evos:["forretress"],eggGroups:["Bug"]},
<ide> forretress:{num:205,species:"Forretress",types:["Bug","Steel"],baseStats:{hp:75,atk:90,def:140,spa:60,spd:60,spe:40},abilities:{0:"Imposter",1:"Gluttony"},heightm:1.2,weightkg:125.8,color:"Purple",prevo:"pineco",evoLevel:31,eggGroups:["Bug"]},
<ide> dunsparce:{num:206,species:"Dunsparce",types:["Normal"],baseStats:{hp:100,atk:70,def:70,spa:65,spd:65,spe:45},abilities:{0:"Tangled Feet",1:"Speed Boost"},heightm:1.5,weightkg:14,color:"Yellow",eggGroups:["Ground"]},
<ide> gligar:{num:207,species:"Gligar",types:["Ground","Flying"],baseStats:{hp:65,atk:75,def:105,spa:35,spd:65,spe:85},abilities:{0:"Flare Boost",1:"Suction Cups"},heightm:1.1,weightkg:64.8,color:"Purple",evos:["gliscor"],eggGroups:["Bug"]},
<del>gliscor:{num:472,species:"Gliscor",types:["Ground","Flying"],baseStats:{hp:75,atk:95,def:125,spa:45,spd:75,spe:95},abilities:{0:"Drought",1:"Clear Body"},heightm:2,weightkg:42.5,color:"Purple",prevo:"gligar",evoLevel:1,eggGroups:["Bug"]},
<add>steelix:{num:208,species:"Steelix",types:["Steel","Ground"],baseStats:{hp:75,atk:85,def:200,spa:55,spd:65,spe:30},abilities:{0:"Multiscale",1:"Anticipation"},heightm:9.2,weightkg:400,color:"Gray",prevo:"onix",evoLevel:1,eggGroups:["Mineral"]},
<ide> snubbull:{num:209,species:"Snubbull",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:60,atk:80,def:50,spa:40,spd:40,spe:30},abilities:{0:"Compoundeyes",1:"Hydration"},heightm:0.6,weightkg:7.8,color:"Pink",evos:["granbull"],eggGroups:["Ground","Fairy"]},
<ide> granbull:{num:210,species:"Granbull",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:90,atk:120,def:75,spa:60,spd:60,spe:45},abilities:{0:"Poison Heal",1:"Static"},heightm:1.4,weightkg:48.7,color:"Purple",prevo:"snubbull",evoLevel:23,eggGroups:["Ground","Fairy"]},
<ide> qwilfish:{num:211,species:"Qwilfish",types:["Water","Poison"],baseStats:{hp:65,atk:95,def:75,spa:55,spd:55,spe:85},abilities:{0:"Storm Drain",1:"Simple"},heightm:0.5,weightkg:3.9,color:"Gray",eggGroups:["Water 2"]},
<add>scizor:{num:212,species:"Scizor",types:["Bug","Steel"],baseStats:{hp:70,atk:130,def:100,spa:55,spd:80,spe:65},abilities:{0:"Iron Barbs",1:"Magma Armor"},heightm:1.8,weightkg:118,color:"Red",prevo:"scyther",evoLevel:1,eggGroups:["Bug"]},
<ide> shuckle:{num:213,species:"Shuckle",types:["Bug","Rock"],baseStats:{hp:20,atk:10,def:230,spa:10,spd:230,spe:5},abilities:{0:"Drought",1:"Compoundeyes"},heightm:0.6,weightkg:20.5,color:"Yellow",eggGroups:["Bug"]},
<ide> heracross:{num:214,species:"Heracross",types:["Bug","Fighting"],baseStats:{hp:80,atk:125,def:75,spa:40,spd:95,spe:85},abilities:{0:"Heavy Metal",1:"Contrary"},heightm:1.5,weightkg:54,color:"Blue",eggGroups:["Bug"]},
<ide> sneasel:{num:215,species:"Sneasel",types:["Dark","Ice"],baseStats:{hp:55,atk:95,def:55,spa:35,spd:75,spe:115},abilities:{0:"Sap Sipper",1:"Compoundeyes"},heightm:0.9,weightkg:28,color:"Black",evos:["weavile"],eggGroups:["Ground"]},
<del>weavile:{num:461,species:"Weavile",types:["Dark","Ice"],baseStats:{hp:70,atk:120,def:65,spa:45,spd:85,spe:125},abilities:{0:"Solid Rock",1:"Chlorophyll"},heightm:1.1,weightkg:34,color:"Black",prevo:"sneasel",evoLevel:1,eggGroups:["Ground"]},
<ide> teddiursa:{num:216,species:"Teddiursa",types:["Normal"],baseStats:{hp:60,atk:80,def:50,spa:50,spd:50,spe:40},abilities:{0:"Analytic",1:"Color Change"},heightm:0.6,weightkg:8.8,color:"Brown",evos:["ursaring"],eggGroups:["Ground"]},
<ide> ursaring:{num:217,species:"Ursaring",types:["Normal"],baseStats:{hp:90,atk:130,def:75,spa:75,spd:75,spe:55},abilities:{0:"Soundproof",1:"Synchronize"},heightm:1.8,weightkg:125.8,color:"Brown",prevo:"teddiursa",evoLevel:30,eggGroups:["Ground"]},
<ide> slugma:{num:218,species:"Slugma",types:["Fire"],baseStats:{hp:40,atk:40,def:40,spa:70,spd:40,spe:20},abilities:{0:"Shield Dust",1:"Intimidate"},heightm:0.7,weightkg:35,color:"Red",evos:["magcargo"],eggGroups:["Indeterminate"]},
<ide> magcargo:{num:219,species:"Magcargo",types:["Fire","Rock"],baseStats:{hp:50,atk:50,def:120,spa:80,spd:80,spe:30},abilities:{0:"Clear Body",1:"Tinted Lens"},heightm:0.8,weightkg:55,color:"Red",prevo:"slugma",evoLevel:38,eggGroups:["Indeterminate"]},
<ide> swinub:{num:220,species:"Swinub",types:["Ice","Ground"],baseStats:{hp:50,atk:50,def:40,spa:30,spd:30,spe:50},abilities:{0:"Cursed Body",1:"Technician"},heightm:0.4,weightkg:6.5,color:"Brown",evos:["piloswine"],eggGroups:["Ground"]},
<ide> piloswine:{num:221,species:"Piloswine",types:["Ice","Ground"],baseStats:{hp:100,atk:100,def:80,spa:60,spd:60,spe:50},abilities:{0:"Simple",1:"Rivalry"},heightm:1.1,weightkg:55.8,color:"Brown",prevo:"swinub",evos:["mamoswine"],evoLevel:33,eggGroups:["Ground"]},
<del>mamoswine:{num:473,species:"Mamoswine",types:["Ice","Ground"],baseStats:{hp:110,atk:130,def:80,spa:70,spd:60,spe:80},abilities:{0:"Liquid Ooze",1:"Tangled Feet"},heightm:2.5,weightkg:291,color:"Brown",prevo:"piloswine",evoLevel:1,evoMove:"AncientPower",eggGroups:["Ground"]},
<ide> corsola:{num:222,species:"Corsola",types:["Water","Rock"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:55,atk:55,def:85,spa:65,spd:85,spe:35},abilities:{0:"Color Change",1:"Tinted Lens"},heightm:0.6,weightkg:5,color:"Pink",eggGroups:["Water 1","Water 3"]},
<ide> remoraid:{num:223,species:"Remoraid",types:["Water"],baseStats:{hp:35,atk:65,def:35,spa:65,spd:35,spe:65},abilities:{0:"Effect Spore",1:"Water Absorb"},heightm:0.6,weightkg:12,color:"Gray",evos:["octillery"],eggGroups:["Water 1","Water 2"]},
<ide> octillery:{num:224,species:"Octillery",types:["Water"],baseStats:{hp:75,atk:105,def:75,spa:105,spd:75,spe:45},abilities:{0:"Tangled Feet",1:"Cloud Nine"},heightm:0.9,weightkg:28.5,color:"Red",prevo:"remoraid",evoLevel:25,eggGroups:["Water 1","Water 2"]},
<ide> delibird:{num:225,species:"Delibird",types:["Ice","Flying"],baseStats:{hp:45,atk:55,def:45,spa:65,spd:45,spe:75},abilities:{0:"Reckless",1:"Keen Eye"},heightm:0.9,weightkg:16,color:"Red",eggGroups:["Water 1","Ground"]},
<del>mantyke:{num:458,species:"Mantyke",types:["Water","Flying"],baseStats:{hp:45,atk:20,def:50,spa:60,spd:120,spe:50},abilities:{0:"Arena Trap",1:"Battle Armor"},heightm:1,weightkg:65,color:"Blue",evos:["mantine"],eggGroups:["No Eggs"]},
<ide> mantine:{num:226,species:"Mantine",types:["Water","Flying"],baseStats:{hp:65,atk:40,def:70,spa:80,spd:140,spe:70},abilities:{0:"Chlorophyll",1:"Flare Boost"},heightm:2.1,weightkg:220,color:"Purple",prevo:"mantyke",evoLevel:1,eggGroups:["Water 1"]},
<ide> skarmory:{num:227,species:"Skarmory",types:["Steel","Flying"],baseStats:{hp:65,atk:80,def:140,spa:40,spd:70,spe:70},abilities:{0:"Rivalry",1:"Rock Head"},heightm:1.7,weightkg:50.5,color:"Gray",eggGroups:["Flying"]},
<ide> houndour:{num:228,species:"Houndour",types:["Dark","Fire"],baseStats:{hp:45,atk:60,def:30,spa:80,spd:50,spe:65},abilities:{0:"Victory Star",1:"Unburden"},heightm:0.6,weightkg:10.8,color:"Black",evos:["houndoom"],eggGroups:["Ground"]},
<ide> houndoom:{num:229,species:"Houndoom",types:["Dark","Fire"],baseStats:{hp:75,atk:90,def:50,spa:110,spd:80,spe:95},abilities:{0:"Shed Skin",1:"Sand Force"},heightm:1.4,weightkg:35,color:"Black",prevo:"houndour",evoLevel:24,eggGroups:["Ground"]},
<add>kingdra:{num:230,species:"Kingdra",types:["Water","Dragon"],baseStats:{hp:75,atk:95,def:95,spa:95,spd:95,spe:85},abilities:{0:"Cloud Nine",1:"Pickpocket"},heightm:1.8,weightkg:152,color:"Blue",prevo:"seadra",evoLevel:32,eggGroups:["Water 1","Dragon"]},
<ide> phanpy:{num:231,species:"Phanpy",types:["Ground"],baseStats:{hp:90,atk:60,def:60,spa:40,spd:40,spe:40},abilities:{0:"Flash Fire",1:"Levitate"},heightm:0.5,weightkg:33.5,color:"Blue",evos:["donphan"],eggGroups:["Ground"]},
<ide> donphan:{num:232,species:"Donphan",types:["Ground"],baseStats:{hp:90,atk:120,def:120,spa:60,spd:60,spe:50},abilities:{0:"Hyper Cutter",1:"Damp"},heightm:1.1,weightkg:120,color:"Gray",prevo:"phanpy",evoLevel:25,eggGroups:["Ground"]},
<add>porygon2:{num:233,species:"Porygon2",types:["Normal"],gender:"N",baseStats:{hp:85,atk:80,def:90,spa:105,spd:95,spe:60},abilities:{0:"Battle Armor",1:"Drought"},heightm:0.6,weightkg:32.5,color:"Red",prevo:"porygon",evos:["porygonz"],evoLevel:1,eggGroups:["Mineral"]},
<ide> stantler:{num:234,species:"Stantler",types:["Normal"],baseStats:{hp:73,atk:95,def:62,spa:85,spd:65,spe:85},abilities:{0:"Swarm",1:"Lightningrod"},heightm:1.4,weightkg:71.2,color:"Brown",eggGroups:["Ground"]},
<ide> smeargle:{num:235,species:"Smeargle",types:["Normal"],baseStats:{hp:55,atk:20,def:35,spa:20,spd:45,spe:75},abilities:{0:"Gluttony",1:"Super Luck"},heightm:1.2,weightkg:58,color:"White",eggGroups:["Ground"]},
<add>tyrogue:{num:236,species:"Tyrogue",types:["Fighting"],gender:"M",baseStats:{hp:35,atk:35,def:35,spa:35,spd:35,spe:35},abilities:{0:"Flare Boost",1:"Imposter"},heightm:0.7,weightkg:21,color:"Purple",evos:["hitmonlee","hitmonchan","hitmontop"],eggGroups:["No Eggs"]},
<add>hitmontop:{num:237,species:"Hitmontop",types:["Fighting"],gender:"M",baseStats:{hp:50,atk:95,def:95,spa:35,spd:110,spe:70},abilities:{0:"Klutz",1:"Aftermath"},heightm:1.4,weightkg:48,color:"Brown",prevo:"tyrogue",evoLevel:20,eggGroups:["Humanshape"]},
<add>smoochum:{num:238,species:"Smoochum",types:["Ice","Psychic"],gender:"F",baseStats:{hp:45,atk:30,def:15,spa:85,spd:65,spe:65},abilities:{0:"Rock Head",1:"Water Absorb"},heightm:0.4,weightkg:6,color:"Pink",evos:["jynx"],eggGroups:["No Eggs"]},
<add>elekid:{num:239,species:"Elekid",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:45,atk:63,def:37,spa:65,spd:55,spe:95},abilities:{0:"Wonder Guard",1:"Unaware"},heightm:0.6,weightkg:23.5,color:"Yellow",evos:["electabuzz"],eggGroups:["No Eggs"]},
<add>magby:{num:240,species:"Magby",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:45,atk:75,def:37,spa:70,spd:55,spe:83},abilities:{0:"Static",1:"Adaptability"},heightm:0.7,weightkg:21.4,color:"Red",evos:["magmar"],eggGroups:["No Eggs"]},
<ide> miltank:{num:241,species:"Miltank",types:["Normal"],gender:"F",baseStats:{hp:95,atk:80,def:105,spa:40,spd:70,spe:100},abilities:{0:"Defiant",1:"Normalize"},heightm:1.2,weightkg:75.5,color:"Pink",eggGroups:["Ground"]},
<add>blissey:{num:242,species:"Blissey",types:["Normal"],gender:"F",baseStats:{hp:255,atk:10,def:10,spa:75,spd:135,spe:55},abilities:{0:"Shed Skin",1:"Early Bird"},heightm:1.5,weightkg:46.8,color:"Pink",prevo:"chansey",evoLevel:2,eggGroups:["Fairy"]},
<ide> raikou:{num:243,species:"Raikou",types:["Electric"],gender:"N",baseStats:{hp:90,atk:85,def:75,spa:115,spd:100,spe:115},abilities:{0:"Lightningrod",1:"Iron Barbs"},heightm:1.9,weightkg:178,color:"Yellow",eggGroups:["No Eggs"]},
<ide> entei:{num:244,species:"Entei",types:["Fire"],gender:"N",baseStats:{hp:115,atk:115,def:85,spa:90,spd:75,spe:100},abilities:{0:"Thick Fat",1:"Dry Skin"},heightm:2.1,weightkg:198,color:"Brown",eggGroups:["No Eggs"]},
<ide> suicune:{num:245,species:"Suicune",types:["Water"],gender:"N",baseStats:{hp:100,atk:75,def:115,spa:90,spd:115,spe:85},abilities:{0:"Forewarn",1:"Poison Heal"},heightm:2,weightkg:187,color:"Blue",eggGroups:["No Eggs"]},
<ide> dustox:{num:269,species:"Dustox",types:["Bug","Poison"],baseStats:{hp:60,atk:50,def:70,spa:50,spd:90,spe:65},abilities:{0:"Justified",1:"Victory Star"},heightm:1.2,weightkg:31.6,color:"Green",prevo:"cascoon",evoLevel:10,eggGroups:["Bug"]},
<ide> lotad:{num:270,species:"Lotad",types:["Water","Grass"],baseStats:{hp:40,atk:30,def:30,spa:40,spd:50,spe:30},abilities:{0:"Technician",1:"Magma Armor"},heightm:0.5,weightkg:2.6,color:"Green",evos:["lombre"],eggGroups:["Water 1","Plant"]},
<ide> lombre:{num:271,species:"Lombre",types:["Water","Grass"],baseStats:{hp:60,atk:50,def:50,spa:60,spd:70,spe:50},abilities:{0:"Magic Bounce",1:"Effect Spore"},heightm:1.2,weightkg:32.5,color:"Green",prevo:"lotad",evos:["ludicolo"],evoLevel:14,eggGroups:["Water 1","Plant"]},
<del>ludicolo:{num:272,species:"Ludicolo",types:["Water","Grass"],baseStats:{hp:80,atk:70,def:70,spa:90,spd:100,spe:70},abilities:{0:"Forewarn",1:"Damp"},heightm:1.5,weightkg:55,color:"Green",prevo:"lombre",evoLevel:1,eggGroups:["Water 1","Plant"]},
<add>ludicolo:{num:272,species:"Ludicolo",types:["Water","Grass"],baseStats:{hp:80,atk:70,def:70,spa:90,spd:100,spe:70},abilities:{0:"Forewarn",1:"Damp"},heightm:1.5,weightkg:55,color:"Green",prevo:"lombre",evoLevel:14,eggGroups:["Water 1","Plant"]},
<ide> seedot:{num:273,species:"Seedot",types:["Grass"],baseStats:{hp:40,atk:40,def:50,spa:30,spd:30,spe:30},abilities:{0:"Sturdy",1:"Forewarn"},heightm:0.5,weightkg:4,color:"Brown",evos:["nuzleaf"],eggGroups:["Ground","Plant"]},
<ide> nuzleaf:{num:274,species:"Nuzleaf",types:["Grass","Dark"],baseStats:{hp:70,atk:70,def:40,spa:60,spd:40,spe:60},abilities:{0:"Flash Fire",1:"Flame Body"},heightm:1,weightkg:28,color:"Brown",prevo:"seedot",evos:["shiftry"],evoLevel:14,eggGroups:["Ground","Plant"]},
<del>shiftry:{num:275,species:"Shiftry",types:["Grass","Dark"],baseStats:{hp:90,atk:100,def:60,spa:90,spd:60,spe:80},abilities:{0:"Moxie",1:"Sand Veil"},heightm:1.3,weightkg:59.6,color:"Brown",prevo:"nuzleaf",evoLevel:1,eggGroups:["Ground","Plant"]},
<add>shiftry:{num:275,species:"Shiftry",types:["Grass","Dark"],baseStats:{hp:90,atk:100,def:60,spa:90,spd:60,spe:80},abilities:{0:"Moxie",1:"Sand Veil"},heightm:1.3,weightkg:59.6,color:"Brown",prevo:"nuzleaf",evoLevel:14,eggGroups:["Ground","Plant"]},
<ide> taillow:{num:276,species:"Taillow",types:["Normal","Flying"],baseStats:{hp:40,atk:55,def:30,spa:30,spd:30,spe:85},abilities:{0:"Sturdy",1:"Serene Grace"},heightm:0.3,weightkg:2.3,color:"Blue",evos:["swellow"],eggGroups:["Flying"]},
<ide> swellow:{num:277,species:"Swellow",types:["Normal","Flying"],baseStats:{hp:60,atk:85,def:60,spa:50,spd:50,spe:125},abilities:{0:"Klutz",1:"Poison Touch"},heightm:0.7,weightkg:19.8,color:"Blue",prevo:"taillow",evoLevel:22,eggGroups:["Flying"]},
<ide> wingull:{num:278,species:"Wingull",types:["Water","Flying"],baseStats:{hp:40,atk:30,def:30,spa:55,spd:30,spe:85},abilities:{0:"Defiant",1:"Synchronize"},heightm:0.6,weightkg:9.5,color:"White",evos:["pelipper"],eggGroups:["Water 1","Flying"]},
<del>pelipper:{num:279,species:"Pelipper",types:["Water","Flying"],baseStats:{hp:60,atk:50,def:100,spa:85,spd:70,spe:65},abilities:{0:"Own Tempo",1:"Heatproof"},heightm:1.2,weightkg:28,color:"Yellow",prevo:"wingull",evoLevel:25,eggGroups:["Water 1","Flying"]},
<add>pelipper:{num:279,species:"Pelipper",types:["Water","Flying"],baseStats:{hp:60,atk:50,def:100,spa:85,spd:70,spe:65},abilities:{0:"Own Tempo",1:"Heatproof"},heightm:1.2,weightkg:28,color:"Yellow",prevo:"wingull",evoLevel:25,eggGroups:["Water 1","Flying"]},
<ide> ralts:{num:280,species:"Ralts",types:["Psychic"],baseStats:{hp:28,atk:25,def:25,spa:45,spd:35,spe:40},abilities:{0:"Sand Force",1:"Heatproof"},heightm:0.4,weightkg:6.6,color:"White",evos:["kirlia"],eggGroups:["Indeterminate"]},
<ide> kirlia:{num:281,species:"Kirlia",types:["Psychic"],baseStats:{hp:38,atk:35,def:35,spa:65,spd:55,spe:50},abilities:{0:"Static",1:"Hustle"},heightm:0.8,weightkg:20.2,color:"White",prevo:"ralts",evos:["gardevoir","gallade"],evoLevel:20,eggGroups:["Indeterminate"]},
<ide> gardevoir:{num:282,species:"Gardevoir",types:["Psychic"],baseStats:{hp:68,atk:65,def:65,spa:125,spd:115,spe:80},abilities:{0:"Battle Armor",1:"Tinted Lens"},heightm:1.6,weightkg:48.4,color:"White",prevo:"kirlia",evoLevel:30,eggGroups:["Indeterminate"]},
<del>gallade:{num:475,species:"Gallade",types:["Psychic","Fighting"],gender:"M",baseStats:{hp:68,atk:125,def:65,spa:65,spd:115,spe:80},abilities:{0:"Ice Body",1:"Chlorophyll"},heightm:1.6,weightkg:52,color:"White",prevo:"kirlia",evoLevel:1,eggGroups:["Indeterminate"]},
<ide> surskit:{num:283,species:"Surskit",types:["Bug","Water"],baseStats:{hp:40,atk:30,def:32,spa:50,spd:52,spe:65},abilities:{0:"Thick Fat",1:"Soundproof"},heightm:0.5,weightkg:1.7,color:"Blue",evos:["masquerain"],eggGroups:["Water 1","Bug"]},
<ide> masquerain:{num:284,species:"Masquerain",types:["Bug","Flying"],baseStats:{hp:70,atk:60,def:62,spa:80,spd:82,spe:60},abilities:{0:"Frisk",1:"Magic Bounce"},heightm:0.8,weightkg:3.6,color:"Blue",prevo:"surskit",evoLevel:22,eggGroups:["Water 1","Bug"]},
<ide> shroomish:{num:285,species:"Shroomish",types:["Grass"],baseStats:{hp:60,atk:40,def:60,spa:40,spd:60,spe:35},abilities:{0:"Heatproof",1:"Oblivious"},heightm:0.4,weightkg:4.5,color:"Brown",evos:["breloom"],eggGroups:["Fairy","Plant"]},
<ide> breloom:{num:286,species:"Breloom",types:["Grass","Fighting"],baseStats:{hp:60,atk:130,def:80,spa:60,spd:60,spe:70},abilities:{0:"Simple",1:"Damp"},heightm:1.2,weightkg:39.2,color:"Green",prevo:"shroomish",evoLevel:23,eggGroups:["Fairy","Plant"]},
<ide> slakoth:{num:287,species:"Slakoth",types:["Normal"],baseStats:{hp:60,atk:60,def:60,spa:35,spd:35,spe:30},abilities:{0:"Compoundeyes",1:"Tinted Lens"},heightm:0.8,weightkg:24,color:"Brown",evos:["vigoroth"],eggGroups:["Ground"]},
<ide> vigoroth:{num:288,species:"Vigoroth",types:["Normal"],baseStats:{hp:80,atk:80,def:80,spa:55,spd:55,spe:90},abilities:{0:"Rock Head",1:"Weak Armor"},heightm:1.4,weightkg:46.5,color:"White",prevo:"slakoth",evos:["slaking"],evoLevel:18,eggGroups:["Ground"]},
<del>slaking:{num:289,species:"Slaking",types:["Normal"],baseStats:{hp:150,atk:160,def:100,spa:95,spd:65,spe:100},abilities:{0:"Compoundeyes",1:"Levitate"},heightm:2,weightkg:130.5,color:"Brown",prevo:"vigoroth",evoLevel:36,eggGroups:["Ground"]},
<add>slaking:{num:289,species:"Slaking",types:["Normal"],baseStats:{hp:150,atk:160,def:100,spa:95,spd:65,spe:100},abilities:{0:"Skill Link",1:"Levitate"},heightm:2,weightkg:130.5,color:"Brown",prevo:"vigoroth",evoLevel:36,eggGroups:["Ground"]},
<ide> nincada:{num:290,species:"Nincada",types:["Bug","Ground"],baseStats:{hp:31,atk:45,def:90,spa:30,spd:30,spe:40},abilities:{0:"Overcoat",1:"Magic Bounce"},heightm:0.5,weightkg:5.5,color:"Gray",evos:["ninjask","shedinja"],eggGroups:["Bug"]},
<ide> ninjask:{num:291,species:"Ninjask",types:["Bug","Flying"],baseStats:{hp:61,atk:90,def:45,spa:50,spd:50,spe:160},abilities:{0:"Frisk",1:"Magic Guard"},heightm:0.8,weightkg:12,color:"Yellow",prevo:"nincada",evoLevel:20,eggGroups:["Bug"]},
<del>shedinja:{num:292,species:"Shedinja",types:["Bug","Ghost"],gender:"N",baseStats:{hp:1,atk:90,def:45,spa:30,spd:30,spe:40},abilities:{0:"Skill Link",1:"Leaf Guard"},heightm:0.8,weightkg:1.2,color:"Brown",prevo:"nincada",evoLevel:1,eggGroups:["Mineral"]},
<add>shedinja:{num:292,species:"Shedinja",types:["Bug","Ghost"],gender:"N",baseStats:{hp:1,atk:90,def:45,spa:30,spd:30,spe:40},abilities:{0:"Skill Link",1:"Leaf Guard"},heightm:0.8,weightkg:1.2,color:"Brown",prevo:"nincada",evoLevel:20,eggGroups:["Mineral"]},
<ide> whismur:{num:293,species:"Whismur",types:["Normal"],baseStats:{hp:64,atk:51,def:23,spa:51,spd:23,spe:28},abilities:{0:"Color Change",1:"Contrary"},heightm:0.6,weightkg:16.3,color:"Pink",evos:["loudred"],eggGroups:["Monster","Ground"]},
<ide> loudred:{num:294,species:"Loudred",types:["Normal"],baseStats:{hp:84,atk:71,def:43,spa:71,spd:43,spe:48},abilities:{0:"Heatproof",1:"Sand Veil"},heightm:1,weightkg:40.5,color:"Blue",prevo:"whismur",evos:["exploud"],evoLevel:20,eggGroups:["Monster","Ground"]},
<ide> exploud:{num:295,species:"Exploud",types:["Normal"],baseStats:{hp:104,atk:91,def:63,spa:91,spd:63,spe:68},abilities:{0:"Clear Body",1:"Infiltrator"},heightm:1.5,weightkg:84,color:"Blue",prevo:"loudred",evoLevel:40,eggGroups:["Monster","Ground"]},
<ide> makuhita:{num:296,species:"Makuhita",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:72,atk:60,def:30,spa:20,spd:30,spe:25},abilities:{0:"Poison Heal",1:"Poison Point"},heightm:1,weightkg:86.4,color:"Yellow",evos:["hariyama"],eggGroups:["Humanshape"]},
<ide> hariyama:{num:297,species:"Hariyama",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:144,atk:120,def:60,spa:40,spd:60,spe:50},abilities:{0:"Harvest",1:"Battle Armor"},heightm:2.3,weightkg:253.8,color:"Brown",prevo:"makuhita",evoLevel:24,eggGroups:["Humanshape"]},
<add>azurill:{num:298,species:"Azurill",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:20,def:40,spa:20,spd:40,spe:20},abilities:{0:"Flame Body",1:"Early Bird"},heightm:0.2,weightkg:2,color:"Blue",evos:["marill"],eggGroups:["No Eggs"]},
<ide> nosepass:{num:299,species:"Nosepass",types:["Rock"],baseStats:{hp:30,atk:45,def:135,spa:45,spd:90,spe:30},abilities:{0:"Motor Drive",1:"Big Pecks"},heightm:1,weightkg:97,color:"Gray",evos:["probopass"],eggGroups:["Mineral"]},
<del>probopass:{num:476,species:"Probopass",types:["Rock","Steel"],baseStats:{hp:60,atk:55,def:145,spa:75,spd:150,spe:40},abilities:{0:"No Guard",1:"Heatproof"},heightm:1.4,weightkg:340,color:"Gray",prevo:"nosepass",evoLevel:1,eggGroups:["Mineral"]},
<ide> skitty:{num:300,species:"Skitty",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:50,atk:45,def:45,spa:35,spd:35,spe:50},abilities:{0:"Synchronize",1:"Weak Armor"},heightm:0.6,weightkg:11,color:"Pink",evos:["delcatty"],eggGroups:["Ground","Fairy"]},
<ide> delcatty:{num:301,species:"Delcatty",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:70,atk:65,def:65,spa:55,spd:55,spe:70},abilities:{0:"Magnet Pull",1:"Poison Heal"},heightm:1.1,weightkg:32.6,color:"Purple",prevo:"skitty",evoLevel:1,eggGroups:["Ground","Fairy"]},
<ide> sableye:{num:302,species:"Sableye",types:["Dark","Ghost"],baseStats:{hp:50,atk:75,def:75,spa:65,spd:65,spe:50},abilities:{0:"Soundproof",1:"Magic Bounce"},heightm:0.5,weightkg:11,color:"Purple",eggGroups:["Humanshape"]},
<ide> minun:{num:312,species:"Minun",types:["Electric"],baseStats:{hp:60,atk:40,def:50,spa:75,spd:85,spe:95},abilities:{0:"Unnerve",1:"Battle Armor"},heightm:0.4,weightkg:4.2,color:"Yellow",eggGroups:["Fairy"]},
<ide> volbeat:{num:313,species:"Volbeat",types:["Bug"],gender:"M",baseStats:{hp:65,atk:73,def:55,spa:47,spd:75,spe:85},abilities:{0:"Rain Dish",1:"Cursed Body"},heightm:0.7,weightkg:17.7,color:"Gray",eggGroups:["Bug","Humanshape"]},
<ide> illumise:{num:314,species:"Illumise",types:["Bug"],gender:"F",baseStats:{hp:65,atk:47,def:55,spa:73,spd:75,spe:85},abilities:{0:"Victory Star",1:"Leaf Guard"},heightm:0.6,weightkg:17.7,color:"Purple",eggGroups:["Bug","Humanshape"]},
<del>budew:{num:406,species:"Budew",types:["Grass","Poison"],baseStats:{hp:40,atk:30,def:35,spa:50,spd:70,spe:55},abilities:{0:"Sheer Force",1:"Victory Star"},heightm:0.2,weightkg:1.2,color:"Green",evos:["roselia"],eggGroups:["No Eggs"]},
<ide> roselia:{num:315,species:"Roselia",types:["Grass","Poison"],baseStats:{hp:50,atk:60,def:45,spa:100,spd:80,spe:65},abilities:{0:"Adaptability",1:"Stall"},heightm:0.3,weightkg:2,color:"Green",prevo:"budew",evos:["roserade"],evoLevel:1,eggGroups:["Fairy","Plant"]},
<del>roserade:{num:407,species:"Roserade",types:["Grass","Poison"],baseStats:{hp:60,atk:70,def:55,spa:125,spd:105,spe:90},abilities:{0:"Victory Star",1:"Gluttony"},heightm:0.9,weightkg:14.5,color:"Green",prevo:"roselia",evoLevel:1,eggGroups:["Fairy","Plant"]},
<ide> gulpin:{num:316,species:"Gulpin",types:["Poison"],baseStats:{hp:70,atk:43,def:53,spa:43,spd:53,spe:40},abilities:{0:"Imposter",1:"Flash Fire"},heightm:0.4,weightkg:10.3,color:"Green",evos:["swalot"],eggGroups:["Indeterminate"]},
<ide> swalot:{num:317,species:"Swalot",types:["Poison"],baseStats:{hp:100,atk:73,def:83,spa:73,spd:83,spe:55},abilities:{0:"Iron Barbs",1:"Unnerve"},heightm:1.7,weightkg:80,color:"Purple",prevo:"gulpin",evoLevel:26,eggGroups:["Indeterminate"]},
<ide> carvanha:{num:318,species:"Carvanha",types:["Water","Dark"],baseStats:{hp:45,atk:90,def:20,spa:65,spd:20,spe:65},abilities:{0:"Magma Armor",1:"Quick Feet"},heightm:0.8,weightkg:20.8,color:"Red",evos:["sharpedo"],eggGroups:["Water 2"]},
<ide> feebas:{num:349,species:"Feebas",types:["Water"],baseStats:{hp:20,atk:15,def:20,spa:10,spd:55,spe:80},abilities:{0:"Clear Body",1:"Iron Barbs"},heightm:0.6,weightkg:7.4,color:"Brown",evos:["milotic"],eggGroups:["Water 1","Dragon"]},
<ide> milotic:{num:350,species:"Milotic",types:["Water"],baseStats:{hp:95,atk:60,def:79,spa:100,spd:125,spe:81},abilities:{0:"Big Pecks",1:"Snow Warning"},heightm:6.2,weightkg:162,color:"Pink",prevo:"feebas",evoLevel:1,eggGroups:["Water 1","Dragon"]},
<ide> castform:{num:351,species:"Castform",types:["Normal"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Wonder Guard",1:"Sap Sipper"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Indeterminate"],otherFormes:["castformsunny","castformrainy","castformsnowy"]},
<del>castformsunny:{num:351,species:"Castform-Sunny",baseSpecies:"Castform",forme:"Sunny",formeLetter:"S",types:["Fire"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Wonder Guard",1:"Sap Sipper"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Indeterminate"]},
<del>castformrainy:{num:351,species:"Castform-Rainy",baseSpecies:"Castform",forme:"Rainy",formeLetter:"R",types:["Water"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Wonder Guard",1:"Sap Sipper"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Indeterminate"]},
<del>castformsnowy:{num:351,species:"Castform-Snowy",baseSpecies:"Castform",forme:"Snowy",formeLetter:"S",types:["Ice"],baseStats:{hp:70,atk:70,def:70,spa:70,spd:70,spe:70},abilities:{0:"Wonder Guard",1:"Sap Sipper"},heightm:0.3,weightkg:0.8,color:"White",eggGroups:["Fairy","Indeterminate"]},
<ide> kecleon:{num:352,species:"Kecleon",types:["Normal"],baseStats:{hp:60,atk:90,def:70,spa:60,spd:120,spe:40},abilities:{0:"Inner Focus",1:"Dry Skin"},heightm:1,weightkg:22,color:"Green",eggGroups:["Ground"]},
<ide> shuppet:{num:353,species:"Shuppet",types:["Ghost"],baseStats:{hp:44,atk:75,def:35,spa:63,spd:33,spe:45},abilities:{0:"Chlorophyll",1:"Defiant"},heightm:0.6,weightkg:2.3,color:"Black",evos:["banette"],eggGroups:["Indeterminate"]},
<ide> banette:{num:354,species:"Banette",types:["Ghost"],baseStats:{hp:64,atk:115,def:65,spa:83,spd:63,spe:65},abilities:{0:"Clear Body",1:"Volt Absorb"},heightm:1.1,weightkg:12.5,color:"Black",prevo:"shuppet",evoLevel:37,eggGroups:["Indeterminate"]},
<ide> duskull:{num:355,species:"Duskull",types:["Ghost"],baseStats:{hp:20,atk:40,def:90,spa:30,spd:90,spe:25},abilities:{0:"Natural Cure",1:"Swift Swim"},heightm:0.8,weightkg:15,color:"Black",evos:["dusclops"],eggGroups:["Indeterminate"]},
<ide> dusclops:{num:356,species:"Dusclops",types:["Ghost"],baseStats:{hp:40,atk:70,def:130,spa:60,spd:130,spe:25},abilities:{0:"Oblivious",1:"Wonder Skin"},heightm:1.6,weightkg:30.6,color:"Black",prevo:"duskull",evos:["dusknoir"],evoLevel:37,eggGroups:["Indeterminate"]},
<del>dusknoir:{num:477,species:"Dusknoir",types:["Ghost"],baseStats:{hp:45,atk:100,def:135,spa:65,spd:135,spe:45},abilities:{0:"Natural Cure",1:"Sand Force"},heightm:2.2,weightkg:106.6,color:"Black",prevo:"dusclops",evoLevel:1,eggGroups:["Indeterminate"]},
<ide> tropius:{num:357,species:"Tropius",types:["Grass","Flying"],baseStats:{hp:99,atk:68,def:83,spa:72,spd:87,spe:51},abilities:{0:"Cursed Body",1:"Immunity"},heightm:2,weightkg:100,color:"Green",eggGroups:["Monster","Plant"]},
<del>chingling:{num:433,species:"Chingling",types:["Psychic"],baseStats:{hp:45,atk:30,def:50,spa:65,spd:50,spe:45},abilities:{0:"Magnet Pull",1:"Flare Boost"},heightm:0.2,weightkg:0.6,color:"Yellow",evos:["chimecho"],eggGroups:["No Eggs"]},
<ide> chimecho:{num:358,species:"Chimecho",types:["Psychic"],baseStats:{hp:65,atk:50,def:70,spa:95,spd:80,spe:65},abilities:{0:"Swift Swim",1:"Rock Head"},heightm:0.6,weightkg:1,color:"Blue",prevo:"chingling",evoLevel:1,eggGroups:["Indeterminate"]},
<ide> absol:{num:359,species:"Absol",types:["Dark"],baseStats:{hp:65,atk:130,def:60,spa:75,spd:60,spe:75},abilities:{0:"Volt Absorb",1:"Sticky Hold"},heightm:1.2,weightkg:47,color:"White",eggGroups:["Ground"]},
<add>wynaut:{num:360,species:"Wynaut",types:["Psychic"],baseStats:{hp:95,atk:23,def:48,spa:23,spd:48,spe:23},abilities:{0:"Mold Breaker",1:"Mummy"},heightm:0.6,weightkg:14,color:"Blue",evos:["wobbuffet"],eggGroups:["No Eggs"]},
<ide> snorunt:{num:361,species:"Snorunt",types:["Ice"],baseStats:{hp:50,atk:50,def:50,spa:50,spd:50,spe:50},abilities:{0:"No Guard",1:"Insomnia"},heightm:0.7,weightkg:16.8,color:"Gray",evos:["glalie","froslass"],eggGroups:["Fairy","Mineral"]},
<ide> glalie:{num:362,species:"Glalie",types:["Ice"],baseStats:{hp:80,atk:80,def:80,spa:80,spd:80,spe:80},abilities:{0:"Overcoat",1:"Clear Body"},heightm:1.5,weightkg:256.5,color:"Gray",prevo:"snorunt",evoLevel:42,eggGroups:["Fairy","Mineral"]},
<del>froslass:{num:478,species:"Froslass",types:["Ice","Ghost"],gender:"F",baseStats:{hp:70,atk:80,def:70,spa:80,spd:70,spe:110},abilities:{0:"Overcoat",1:"Heatproof"},heightm:1.3,weightkg:26.6,color:"White",prevo:"snorunt",evoLevel:1,eggGroups:["Fairy","Mineral"]},
<ide> spheal:{num:363,species:"Spheal",types:["Ice","Water"],baseStats:{hp:70,atk:40,def:50,spa:55,spd:50,spe:25},abilities:{0:"Multiscale",1:"Static"},heightm:0.8,weightkg:39.5,color:"Blue",evos:["sealeo"],eggGroups:["Water 1","Ground"]},
<ide> sealeo:{num:364,species:"Sealeo",types:["Ice","Water"],baseStats:{hp:90,atk:60,def:70,spa:75,spd:70,spe:45},abilities:{0:"Pressure",1:"Drought"},heightm:1.1,weightkg:87.6,color:"Blue",prevo:"spheal",evos:["walrein"],evoLevel:32,eggGroups:["Water 1","Ground"]},
<ide> walrein:{num:365,species:"Walrein",types:["Ice","Water"],baseStats:{hp:110,atk:80,def:90,spa:95,spd:90,spe:65},abilities:{0:"Sap Sipper",1:"Mold Breaker"},heightm:1.4,weightkg:150.6,color:"Blue",prevo:"sealeo",evoLevel:44,eggGroups:["Water 1","Ground"]},
<ide> clamperl:{num:366,species:"Clamperl",types:["Water"],baseStats:{hp:35,atk:64,def:85,spa:74,spd:55,spe:32},abilities:{0:"Heavy Metal",1:"Sand Rush"},heightm:0.4,weightkg:52.5,color:"Blue",evos:["huntail","gorebyss"],eggGroups:["Water 1"]},
<del>huntail:{num:367,species:"Huntail",types:["Water"],baseStats:{hp:55,atk:104,def:105,spa:94,spd:75,spe:52},abilities:{0:"Anger Point",1:"Multiscale"},heightm:1.7,weightkg:27,color:"Blue",prevo:"clamperl",evoLevel:1,eggGroups:["Water 1"]},
<add>huntail:{num:367,species:"Huntail",types:["Water"],baseStats:{hp:55,atk:104,def:105,spa:94,spd:75,spe:52},abilities:{0:"Anger Point",1:"Marvel Scale"},heightm:1.7,weightkg:27,color:"Blue",prevo:"clamperl",evoLevel:1,eggGroups:["Water 1"]},
<ide> gorebyss:{num:368,species:"Gorebyss",types:["Water"],baseStats:{hp:55,atk:84,def:105,spa:114,spd:75,spe:52},abilities:{0:"Cloud Nine",1:"Rivalry"},heightm:1.8,weightkg:22.6,color:"Pink",prevo:"clamperl",evoLevel:1,eggGroups:["Water 1"]},
<ide> relicanth:{num:369,species:"Relicanth",types:["Water","Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:100,atk:90,def:130,spa:45,spd:65,spe:55},abilities:{0:"Flare Boost",1:"Anticipation"},heightm:1,weightkg:23.4,color:"Gray",eggGroups:["Water 1","Water 2"]},
<ide> luvdisc:{num:370,species:"Luvdisc",types:["Water"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:43,atk:30,def:55,spa:40,spd:65,spe:97},abilities:{0:"Unaware",1:"Adaptability"},heightm:0.6,weightkg:8.7,color:"Pink",eggGroups:["Water 2"]},
<ide> kricketot:{num:401,species:"Kricketot",types:["Bug"],baseStats:{hp:37,atk:25,def:41,spa:25,spd:41,spe:25},abilities:{0:"Sturdy",1:"Quick Feet"},heightm:0.3,weightkg:2.2,color:"Red",evos:["kricketune"],eggGroups:["Bug"]},
<ide> kricketune:{num:402,species:"Kricketune",types:["Bug"],baseStats:{hp:77,atk:85,def:51,spa:55,spd:51,spe:65},abilities:{0:"Steadfast",1:"Clear Body"},heightm:1,weightkg:25.5,color:"Red",prevo:"kricketot",evoLevel:10,eggGroups:["Bug"]},
<ide> shinx:{num:403,species:"Shinx",types:["Electric"],baseStats:{hp:45,atk:65,def:34,spa:40,spd:34,spe:45},abilities:{0:"Pickpocket",1:"Sheer Force"},heightm:0.5,weightkg:9.5,color:"Blue",evos:["luxio"],eggGroups:["Ground"]},
<del>luxio:{num:404,species:"Luxio",types:["Electric"],baseStats:{hp:60,atk:85,def:49,spa:60,spd:49,spe:60},abilities:{0:"Motor Drive",1:"Solar Power"},heightm:0.9,weightkg:30.5,color:"Blue",prevo:"shinx",evos:["luxray"],evoLevel:15,eggGroups:["Ground"]},
<add>luxio:{num:404,species:"Luxio",types:["Electric"],baseStats:{hp:60,atk:85,def:49,spa:60,spd:49,spe:60},abilities:{0:"Motor Drive",1:"Solar Power"},heightm:0.9,weightkg:30.5,color:"Blue",prevo:"shinx",evos:["luxray"],evoLevel:15,eggGroups:["Ground"]},
<ide> luxray:{num:405,species:"Luxray",types:["Electric"],baseStats:{hp:80,atk:120,def:79,spa:95,spd:79,spe:70},abilities:{0:"Weak Armor",1:"Insomnia"},heightm:1.4,weightkg:42,color:"Blue",prevo:"luxio",evoLevel:30,eggGroups:["Ground"]},
<add>budew:{num:406,species:"Budew",types:["Grass","Poison"],baseStats:{hp:40,atk:30,def:35,spa:50,spd:70,spe:55},abilities:{0:"Sheer Force",1:"Victory Star"},heightm:0.2,weightkg:1.2,color:"Green",evos:["roselia"],eggGroups:["No Eggs"]},
<add>roserade:{num:407,species:"Roserade",types:["Grass","Poison"],baseStats:{hp:60,atk:70,def:55,spa:125,spd:105,spe:90},abilities:{0:"Victory Star",1:"Gluttony"},heightm:0.9,weightkg:14.5,color:"Green",prevo:"roselia",evoLevel:1,eggGroups:["Fairy","Plant"]},
<ide> cranidos:{num:408,species:"Cranidos",types:["Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:67,atk:125,def:40,spa:30,spd:30,spe:58},abilities:{0:"Quick Feet",1:"Color Change"},heightm:0.9,weightkg:31.5,color:"Blue",evos:["rampardos"],eggGroups:["Monster"]},
<ide> rampardos:{num:409,species:"Rampardos",types:["Rock"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:97,atk:165,def:60,spa:65,spd:50,spe:58},abilities:{0:"Victory Star",1:"Sniper"},heightm:1.6,weightkg:102.5,color:"Blue",prevo:"cranidos",evoLevel:30,eggGroups:["Monster"]},
<ide> shieldon:{num:410,species:"Shieldon",types:["Rock","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:42,def:118,spa:42,spd:88,spe:30},abilities:{0:"Normalize",1:"Sap Sipper"},heightm:0.5,weightkg:57,color:"Gray",evos:["bastiodon"],eggGroups:["Monster"]},
<ide> wormadamtrash:{num:413,species:"Wormadam-Trash",baseSpecies:"Wormadam",forme:"Trash",formeLetter:"S",types:["Bug","Steel"],gender:"F",baseStats:{hp:60,atk:69,def:95,spa:69,spd:95,spe:36},abilities:{0:"Limber",1:"Motor Drive"},heightm:0.5,weightkg:6.5,color:"Gray",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]},
<ide> mothim:{num:414,species:"Mothim",types:["Bug","Flying"],gender:"M",baseStats:{hp:70,atk:94,def:50,spa:94,spd:50,spe:66},abilities:{0:"Defiant",1:"Unburden"},heightm:0.9,weightkg:23.3,color:"Yellow",prevo:"burmy",evoLevel:20,eggGroups:["Bug"]},
<ide> combee:{num:415,species:"Combee",types:["Bug","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:30,atk:30,def:42,spa:30,spd:42,spe:70},abilities:{0:"Lightningrod",1:"Normalize"},heightm:0.3,weightkg:5.5,color:"Yellow",evos:["vespiquen"],eggGroups:["Bug"]},
<del>vespiquen:{num:416,species:"Vespiquen",types:["Bug","Flying"],gender:"F",baseStats:{hp:70,atk:80,def:102,spa:80,spd:102,spe:40},abilities:{0:"Simpe",1:"Tangled Feet"},heightm:1.2,weightkg:38.5,color:"Yellow",prevo:"combee",evoLevel:21,eggGroups:["Bug"]},
<add>vespiquen:{num:416,species:"Vespiquen",types:["Bug","Flying"],gender:"F",baseStats:{hp:70,atk:80,def:102,spa:80,spd:102,spe:40},abilities:{0:"Simple",1:"Tangled Feet"},heightm:1.2,weightkg:38.5,color:"Yellow",prevo:"combee",evoLevel:21,eggGroups:["Bug"]},
<ide> pachirisu:{num:417,species:"Pachirisu",types:["Electric"],baseStats:{hp:60,atk:45,def:70,spa:45,spd:90,spe:95},abilities:{0:"Super Luck",1:"Heavy Metal"},heightm:0.4,weightkg:3.9,color:"White",eggGroups:["Ground","Fairy"]},
<ide> buizel:{num:418,species:"Buizel",types:["Water"],baseStats:{hp:55,atk:65,def:35,spa:60,spd:30,spe:85},abilities:{0:"Storm Drain",1:"Pressure"},heightm:0.7,weightkg:29.5,color:"Brown",evos:["floatzel"],eggGroups:["Water 1","Ground"]},
<ide> floatzel:{num:419,species:"Floatzel",types:["Water"],baseStats:{hp:85,atk:105,def:55,spa:85,spd:50,spe:115},abilities:{0:"Imposter",1:"Mold Breaker"},heightm:1.1,weightkg:33.5,color:"Brown",prevo:"buizel",evoLevel:26,eggGroups:["Water 1","Ground"]},
<ide> cherubi:{num:420,species:"Cherubi",types:["Grass"],baseStats:{hp:45,atk:35,def:45,spa:62,spd:53,spe:35},abilities:{0:"Flash Fire",1:"Guts"},heightm:0.4,weightkg:3.3,color:"Pink",evos:["cherrim"],eggGroups:["Fairy","Plant"]},
<del>cherrim:{num:421,species:"Cherrim",baseForme:"Overcast",types:["Grass"],baseStats:{hp:70,atk:60,def:70,spa:87,spd:78,spe:85},abilities:{0:"Leaf Guard",1:"Battle Armor"},heightm:0.5,weightkg:9.3,color:"Pink",prevo:"cherubi",evoLevel:25,eggGroups:["Fairy","Plant"],otherFormes:["cherrimsunshine"]},
<del>cherrimsunshine:{num:421,species:"Cherrim-Sunshine",baseSpecies:"Cherrim",forme:"Sunshine",formeLetter:"S",types:["Grass"],baseStats:{hp:70,atk:60,def:70,spa:87,spd:78,spe:85},abilities:{0:"Leaf Guard",1:"Battle Armor"},heightm:0.5,weightkg:9.3,color:"Pink",prevo:"cherubi",evoLevel:25,eggGroups:["Fairy","Plant"]},
<add>cherrim:{num:421,species:"Cherrim",baseForme:"Overcast",types:["Grass"],baseStats:{hp:70,atk:60,def:70,spa:87,spd:78,spe:85},abilities:{0:"Leaf Guard",1:"Battle Armor"},heightm:0.5,weightkg:9.3,color:"Pink",prevo:"cherubi",evoLevel:25,eggGroups:["Fairy","Plant"]},
<ide> shellos:{num:422,species:"Shellos",baseForme:"West",types:["Water"],baseStats:{hp:76,atk:48,def:48,spa:57,spd:62,spe:34},abilities:{0:"Own Tempo",1:"Swift Swim"},heightm:0.3,weightkg:6.3,color:"Purple",evos:["gastrodon"],eggGroups:["Water 1","Indeterminate"],otherForms:["shelloseast"]},
<ide> gastrodon:{num:423,species:"Gastrodon",baseForme:"West",types:["Water","Ground"],baseStats:{hp:111,atk:83,def:68,spa:92,spd:82,spe:39},abilities:{0:"Hustle",1:"Rivalry"},heightm:0.9,weightkg:29.9,color:"Purple",prevo:"shellos",evoLevel:30,eggGroups:["Water 1","Indeterminate"],otherForms:["gastrodoneast"]},
<add>ambipom:{num:424,species:"Ambipom",types:["Normal"],baseStats:{hp:75,atk:100,def:66,spa:60,spd:66,spe:115},abilities:{0:"Unaware",1:"Drizzle"},heightm:1.2,weightkg:20.3,color:"Purple",prevo:"aipom",evoLevel:32,evoMove:"Double Hit",eggGroups:["Ground"]},
<ide> drifloon:{num:425,species:"Drifloon",types:["Ghost","Flying"],baseStats:{hp:90,atk:50,def:34,spa:60,spd:44,spe:70},abilities:{0:"Drought",1:"Adaptability"},heightm:0.4,weightkg:1.2,color:"Purple",evos:["drifblim"],eggGroups:["Indeterminate"]},
<ide> drifblim:{num:426,species:"Drifblim",types:["Ghost","Flying"],baseStats:{hp:150,atk:80,def:44,spa:90,spd:54,spe:80},abilities:{0:"Bad Dreams",1:"Cute Charm"},heightm:1.2,weightkg:15,color:"Purple",prevo:"drifloon",evoLevel:28,eggGroups:["Indeterminate"]},
<ide> buneary:{num:427,species:"Buneary",types:["Normal"],baseStats:{hp:55,atk:66,def:44,spa:44,spd:56,spe:85},abilities:{0:"Rattled",1:"Early Bird"},heightm:0.4,weightkg:5.5,color:"Brown",evos:["lopunny"],eggGroups:["Ground","Humanshape"]},
<del>lopunny:{num:428,species:"Lopunny",types:["Normal"],baseStats:{hp:65,atk:76,def:84,spa:54,spd:96,spe:105},abilities:{0:"Snow Warning",1:"Justified"},heightm:1.2,weightkg:33.3,color:"Brown",prevo:"buneary",evoLevel:1,eggGroups:["Ground","Humanshape"]},
<add>lopunny:{num:428,species:"Lopunny",types:["Normal"],baseStats:{hp:65,atk:76,def:84,spa:54,spd:96,spe:105},abilities:{0:"Snow Warning",1:"Justified"},heightm:1.2,weightkg:33.3,color:"Brown",prevo:"buneary",evoLevel:2,eggGroups:["Ground","Humanshape"]},
<add>mismagius:{num:429,species:"Mismagius",types:["Ghost"],baseStats:{hp:60,atk:60,def:60,spa:105,spd:105,spe:105},abilities:{0:"Sticky Hold",1:"Defiant"},heightm:0.9,weightkg:4.4,color:"Purple",prevo:"misdreavus",evoLevel:1,eggGroups:["Indeterminate"]},
<add>honchkrow:{num:430,species:"Honchkrow",types:["Dark","Flying"],baseStats:{hp:100,atk:125,def:52,spa:105,spd:52,spe:71},abilities:{0:"Poison Heal",1:"Harvest"},heightm:0.9,weightkg:27.3,color:"Black",prevo:"murkrow",evoLevel:1,eggGroups:["Flying"]},
<ide> glameow:{num:431,species:"Glameow",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:49,atk:55,def:42,spa:42,spd:37,spe:85},abilities:{0:"Toxic Boost",1:"Light Metal"},heightm:0.5,weightkg:3.9,color:"Gray",evos:["purugly"],eggGroups:["Ground"]},
<ide> purugly:{num:432,species:"Purugly",types:["Normal"],genderRatio:{M:0.25,F:0.75},baseStats:{hp:71,atk:82,def:64,spa:64,spd:59,spe:112},abilities:{0:"Shadow Tag",1:"Sturdy"},heightm:1,weightkg:43.8,color:"Gray",prevo:"glameow",evoLevel:38,eggGroups:["Ground"]},
<add>chingling:{num:433,species:"Chingling",types:["Psychic"],baseStats:{hp:45,atk:30,def:50,spa:65,spd:50,spe:45},abilities:{0:"Magnet Pull",1:"Flare Boost"},heightm:0.2,weightkg:0.6,color:"Yellow",evos:["chimecho"],eggGroups:["No Eggs"]},
<ide> stunky:{num:434,species:"Stunky",types:["Poison","Dark"],baseStats:{hp:63,atk:63,def:47,spa:41,spd:41,spe:74},abilities:{0:"Super Luck",1:"Download"},heightm:0.4,weightkg:19.2,color:"Purple",evos:["skuntank"],eggGroups:["Ground"]},
<ide> skuntank:{num:435,species:"Skuntank",types:["Poison","Dark"],baseStats:{hp:103,atk:93,def:67,spa:71,spd:61,spe:84},abilities:{0:"Wonder Skin",1:"Leaf Guard"},heightm:1,weightkg:38,color:"Purple",prevo:"stunky",evoLevel:34,eggGroups:["Ground"]},
<ide> bronzor:{num:436,species:"Bronzor",types:["Steel","Psychic"],gender:"N",baseStats:{hp:57,atk:24,def:86,spa:24,spd:86,spe:23},abilities:{0:"Mummy",1:"Hustle"},heightm:0.5,weightkg:60.5,color:"Green",evos:["bronzong"],eggGroups:["Mineral"]},
<ide> bronzong:{num:437,species:"Bronzong",types:["Steel","Psychic"],gender:"N",baseStats:{hp:67,atk:89,def:116,spa:79,spd:116,spe:33},abilities:{0:"Defiant",1:"No Guard"},heightm:1.3,weightkg:187,color:"Green",prevo:"bronzor",evoLevel:33,eggGroups:["Mineral"]},
<add>bonsly:{num:438,species:"Bonsly",types:["Rock"],baseStats:{hp:50,atk:80,def:95,spa:10,spd:45,spe:10},abilities:{0:"Tangled Feet",1:"Soundproof"},heightm:0.5,weightkg:15,color:"Brown",evos:["sudowoodo"],eggGroups:["No Eggs"]},
<add>mimejr:{num:439,species:"Mime Jr.",types:["Psychic"],baseStats:{hp:20,atk:25,def:45,spa:70,spd:90,spe:60},abilities:{0:"Flame Body",1:"Victory Star"},heightm:0.6,weightkg:13,color:"Pink",evos:["mrmime"],eggGroups:["No Eggs"]},
<add>happiny:{num:440,species:"Happiny",types:["Normal"],gender:"F",baseStats:{hp:100,atk:5,def:5,spa:15,spd:65,spe:30},abilities:{0:"Stench",1:"Unnerve"},heightm:0.6,weightkg:24.4,color:"Pink",evos:["chansey"],eggGroups:["No Eggs"]},
<ide> chatot:{num:441,species:"Chatot",types:["Normal","Flying"],baseStats:{hp:76,atk:65,def:45,spa:92,spd:42,spe:91},abilities:{0:"Wonder Skin",1:"Sap Sipper"},heightm:0.5,weightkg:1.9,color:"Black",eggGroups:["Flying"]},
<ide> spiritomb:{num:442,species:"Spiritomb",types:["Ghost","Dark"],baseStats:{hp:50,atk:92,def:108,spa:92,spd:108,spe:35},abilities:{0:"Effect Spore",1:"Cute Charm"},heightm:1,weightkg:108,color:"Purple",eggGroups:["Indeterminate"]},
<ide> gible:{num:443,species:"Gible",types:["Dragon","Ground"],baseStats:{hp:58,atk:70,def:45,spa:40,spd:45,spe:42},abilities:{0:"Drizzle",1:"Magma Armor"},heightm:0.7,weightkg:20.5,color:"Blue",evos:["gabite"],eggGroups:["Monster","Dragon"]},
<ide> gabite:{num:444,species:"Gabite",types:["Dragon","Ground"],baseStats:{hp:68,atk:90,def:65,spa:50,spd:55,spe:82},abilities:{0:"Wonder Guard",1:"Bad Dreams"},heightm:1.4,weightkg:56,color:"Blue",prevo:"gible",evos:["garchomp"],evoLevel:24,eggGroups:["Monster","Dragon"]},
<ide> garchomp:{num:445,species:"Garchomp",types:["Dragon","Ground"],baseStats:{hp:108,atk:130,def:95,spa:80,spd:85,spe:102},abilities:{0:"Sticky Hold",1:"Normalize"},heightm:1.9,weightkg:95,color:"Blue",prevo:"gabite",evoLevel:48,eggGroups:["Monster","Dragon"]},
<add>munchlax:{num:446,species:"Munchlax",types:["Normal"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:135,atk:85,def:40,spa:40,spd:85,spe:5},abilities:{0:"Marvel Scale",1:"Drought"},heightm:0.6,weightkg:105,color:"Black",evos:["snorlax"],eggGroups:["No Eggs"]},
<ide> riolu:{num:447,species:"Riolu",types:["Fighting"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:40,atk:70,def:40,spa:35,spd:40,spe:60},abilities:{0:"Analytic",1:"Tangled Feet"},heightm:0.7,weightkg:20.2,color:"Blue",evos:["lucario"],eggGroups:["No Eggs"]},
<del>lucario:{num:448,species:"Lucario",types:["Fighting","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:110,def:70,spa:115,spd:70,spe:90},abilities:{0:"Magnet Pull",1:"Poison Touch"},heightm:1.2,weightkg:54,color:"Blue",prevo:"riolu",evoLevel:1,eggGroups:["Ground","Humanshape"]},
<add>lucario:{num:448,species:"Lucario",types:["Fighting","Steel"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:70,atk:110,def:70,spa:115,spd:70,spe:90},abilities:{0:"Magnet Pull",1:"Poison Touch"},heightm:1.2,weightkg:54,color:"Blue",prevo:"riolu",evoLevel:2,eggGroups:["Ground","Humanshape"]},
<ide> hippopotas:{num:449,species:"Hippopotas",types:["Ground"],baseStats:{hp:68,atk:72,def:78,spa:38,spd:42,spe:32},abilities:{0:"Klutz",1:"Clear Body"},heightm:0.8,weightkg:49.5,color:"Brown",evos:["hippowdon"],eggGroups:["Ground"]},
<ide> hippowdon:{num:450,species:"Hippowdon",types:["Ground"],baseStats:{hp:108,atk:112,def:118,spa:68,spd:72,spe:47},abilities:{0:"Swift Swim",1:"Gluttony"},heightm:2,weightkg:300,color:"Brown",prevo:"hippopotas",evoLevel:34,eggGroups:["Ground"]},
<ide> skorupi:{num:451,species:"Skorupi",types:["Poison","Bug"],baseStats:{hp:40,atk:50,def:90,spa:30,spd:55,spe:65},abilities:{0:"Cursed Body",1:"Pickpocket"},heightm:0.8,weightkg:12,color:"Purple",evos:["drapion"],eggGroups:["Bug","Water 3"]},
<ide> carnivine:{num:455,species:"Carnivine",types:["Grass"],baseStats:{hp:74,atk:100,def:72,spa:90,spd:72,spe:46},abilities:{0:"Bad Dreams",1:"Defiant"},heightm:1.4,weightkg:27,color:"Green",eggGroups:["Plant"]},
<ide> finneon:{num:456,species:"Finneon",types:["Water"],baseStats:{hp:49,atk:49,def:56,spa:49,spd:61,spe:66},abilities:{0:"Leaf Guard",1:"Mummy"},heightm:0.4,weightkg:7,color:"Blue",evos:["lumineon"],eggGroups:["Water 2"]},
<ide> lumineon:{num:457,species:"Lumineon",types:["Water"],baseStats:{hp:69,atk:69,def:76,spa:69,spd:86,spe:91},abilities:{0:"Pickpocket",1:"Big Pecks"},heightm:1.2,weightkg:24,color:"Blue",prevo:"finneon",evoLevel:31,eggGroups:["Water 2"]},
<add>mantyke:{num:458,species:"Mantyke",types:["Water","Flying"],baseStats:{hp:45,atk:20,def:50,spa:60,spd:120,spe:50},abilities:{0:"Arena Trap",1:"Battle Armor"},heightm:1,weightkg:65,color:"Blue",evos:["mantine"],eggGroups:["No Eggs"]},
<ide> snover:{num:459,species:"Snover",types:["Grass","Ice"],baseStats:{hp:60,atk:62,def:50,spa:62,spd:60,spe:40},abilities:{0:"Storm Drain",1:"Inner Focus"},heightm:1,weightkg:50.5,color:"White",evos:["abomasnow"],eggGroups:["Monster","Plant"]},
<ide> abomasnow:{num:460,species:"Abomasnow",types:["Grass","Ice"],baseStats:{hp:90,atk:92,def:75,spa:92,spd:85,spe:60},abilities:{0:"Clear Body",1:"Own Tempo"},heightm:2.2,weightkg:135.5,color:"White",prevo:"snover",evoLevel:40,eggGroups:["Monster","Plant"]},
<add>weavile:{num:461,species:"Weavile",types:["Dark","Ice"],baseStats:{hp:70,atk:120,def:65,spa:45,spd:85,spe:125},abilities:{0:"Solid Rock",1:"Chlorophyll"},heightm:1.1,weightkg:34,color:"Black",prevo:"sneasel",evoLevel:2,eggGroups:["Ground"]},
<add>magnezone:{num:462,species:"Magnezone",types:["Electric","Steel"],gender:"N",baseStats:{hp:70,atk:70,def:115,spa:130,spd:90,spe:60},abilities:{0:"Reckless",1:"Swift Swim"},heightm:1.2,weightkg:180,color:"Gray",prevo:"magneton",evoLevel:31,eggGroups:["Mineral"]},
<add>lickilicky:{num:463,species:"Lickilicky",types:["Normal"],baseStats:{hp:110,atk:85,def:95,spa:80,spd:95,spe:50},abilities:{0:"Download",1:"Arena Trap"},heightm:1.7,weightkg:140,color:"Pink",prevo:"lickitung",evoLevel:2,evoMove:"Rollout",eggGroups:["Monster"]},
<add>rhyperior:{num:464,species:"Rhyperior",types:["Ground","Rock"],baseStats:{hp:115,atk:140,def:130,spa:55,spd:55,spe:40},abilities:{0:"Scrappy",1:"Mummy"},heightm:2.4,weightkg:282.8,color:"Gray",prevo:"rhydon",evoLevel:42,eggGroups:["Monster","Ground"]},
<add>tangrowth:{num:465,species:"Tangrowth",types:["Grass"],baseStats:{hp:100,atk:100,def:125,spa:110,spd:50,spe:50},abilities:{0:"Defiant",1:"Simple"},heightm:2,weightkg:128.6,color:"Blue",prevo:"tangela",evoLevel:2,evoMove:"AncientPower",eggGroups:["Plant"]},
<add>electivire:{num:466,species:"Electivire",types:["Electric"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:123,def:67,spa:95,spd:85,spe:95},abilities:{0:"Adaptability",1:"Toxic Boost"},heightm:1.8,weightkg:138.6,color:"Yellow",prevo:"electabuzz",evoLevel:30,eggGroups:["Humanshape"]},
<add>magmortar:{num:467,species:"Magmortar",types:["Fire"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:95,def:67,spa:125,spd:95,spe:83},abilities:{0:"Immunity",1:"Cloud Nine"},heightm:1.6,weightkg:68,color:"Red",prevo:"magmar",evoLevel:30,eggGroups:["Humanshape"]},
<add>togekiss:{num:468,species:"Togekiss",types:["Normal","Flying"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:85,atk:50,def:95,spa:120,spd:115,spe:80},abilities:{0:"Intimidate",1:"Pickpocket"},heightm:1.5,weightkg:38,color:"White",prevo:"togetic",evoLevel:2,eggGroups:["Flying","Fairy"]},
<add>yanmega:{num:469,species:"Yanmega",types:["Bug","Flying"],baseStats:{hp:86,atk:76,def:86,spa:116,spd:56,spe:95},abilities:{0:"Prankster",1:"Clear Body"},heightm:1.9,weightkg:51.5,color:"Green",prevo:"yanma",evoLevel:2,evoMove:"AncientPower",eggGroups:["Bug"]},
<add>leafeon:{num:470,species:"Leafeon",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:110,def:130,spa:60,spd:65,spe:95},abilities:{0:"Water Absorb",1:"Cursed Body"},heightm:1,weightkg:25.5,color:"Green",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<add>glaceon:{num:471,species:"Glaceon",types:["Ice"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:60,def:110,spa:130,spd:95,spe:65},abilities:{0:"Color Change",1:"Trace"},heightm:0.8,weightkg:25.9,color:"Blue",prevo:"eevee",evoLevel:1,eggGroups:["Ground"]},
<add>gliscor:{num:472,species:"Gliscor",types:["Ground","Flying"],baseStats:{hp:75,atk:95,def:125,spa:45,spd:75,spe:95},abilities:{0:"Drought",1:"Clear Body"},heightm:2,weightkg:42.5,color:"Purple",prevo:"gligar",evoLevel:2,eggGroups:["Bug"]},
<add>mamoswine:{num:473,species:"Mamoswine",types:["Ice","Ground"],baseStats:{hp:110,atk:130,def:80,spa:70,spd:60,spe:80},abilities:{0:"Liquid Ooze",1:"Tangled Feet"},heightm:2.5,weightkg:291,color:"Brown",prevo:"piloswine",evoLevel:34,evoMove:"AncientPower",eggGroups:["Ground"]},
<add>porygonz:{num:474,species:"Porygon-Z",types:["Normal"],gender:"N",baseStats:{hp:85,atk:80,def:70,spa:135,spd:75,spe:90},abilities:{0:"Soundproof",1:"Compoundeyes"},heightm:0.9,weightkg:34,color:"Red",prevo:"porygon2",evoLevel:1,eggGroups:["Mineral"]},
<add>gallade:{num:475,species:"Gallade",types:["Psychic","Fighting"],gender:"M",baseStats:{hp:68,atk:125,def:65,spa:65,spd:115,spe:80},abilities:{0:"Ice Body",1:"Chlorophyll"},heightm:1.6,weightkg:52,color:"White",prevo:"kirlia",evoLevel:20,eggGroups:["Indeterminate"]},
<add>probopass:{num:476,species:"Probopass",types:["Rock","Steel"],baseStats:{hp:60,atk:55,def:145,spa:75,spd:150,spe:40},abilities:{0:"No Guard",1:"Heatproof"},heightm:1.4,weightkg:340,color:"Gray",prevo:"nosepass",evoLevel:2,eggGroups:["Mineral"]},
<add>dusknoir:{num:477,species:"Dusknoir",types:["Ghost"],baseStats:{hp:45,atk:100,def:135,spa:65,spd:135,spe:45},abilities:{0:"Natural Cure",1:"Sand Force"},heightm:2.2,weightkg:106.6,color:"Black",prevo:"dusclops",evoLevel:37,eggGroups:["Indeterminate"]},
<add>froslass:{num:478,species:"Froslass",types:["Ice","Ghost"],gender:"F",baseStats:{hp:70,atk:80,def:70,spa:80,spd:70,spe:110},abilities:{0:"Overcoat",1:"Heatproof"},heightm:1.3,weightkg:26.6,color:"White",prevo:"snorunt",evoLevel:1,eggGroups:["Fairy","Mineral"]},
<ide> rotom:{num:479,species:"Rotom",types:["Electric","Ghost"],gender:"N",baseStats:{hp:50,atk:50,def:77,spa:95,spd:77,spe:91},abilities:{0:"Steadfast",1:"Gluttony"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"],otherFormes:["rotomheat","rotomwash","rotomfrost","rotomfan","rotommow"]},
<ide> rotomheat:{num:479,species:"Rotom-Heat",baseSpecies:"Rotom",forme:"Heat",formeLetter:"H",types:["Electric","Fire"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Rain Dish",1:"Clear Body"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
<ide> rotomwash:{num:479,species:"Rotom-Wash",baseSpecies:"Rotom",forme:"Wash",formeLetter:"W",types:["Electric","Water"],gender:"N",baseStats:{hp:50,atk:65,def:107,spa:105,spd:107,spe:86},abilities:{0:"Torrent",1:"Overcoat"},heightm:0.3,weightkg:0.3,color:"Red",eggGroups:["Indeterminate"]},
<ide> shayminsky:{num:492,species:"Shaymin-Sky",baseSpecies:"Shaymin",forme:"Sky",formeLetter:"S",types:["Grass","Flying"],gender:"N",baseStats:{hp:100,atk:103,def:75,spa:120,spd:75,spe:127},abilities:{0:"Quick Feet",1:"Rattled"},heightm:0.4,weightkg:5.2,color:"Green",eggGroups:["No Eggs"]},
<ide> arceus:{num:493,species:"Arceus",baseForme:"Normal",types:["Normal"],gender:"N",baseStats:{hp:120,atk:120,def:120,spa:120,spd:120,spe:120},abilities:{0:"Tangled Feet",1:"Hyper Cutter"},heightm:3.2,weightkg:320,color:"Gray",eggGroups:["No Eggs"]},
<ide> victini:{num:494,species:"Victini",types:["Psychic","Fire"],gender:"N",baseStats:{hp:100,atk:100,def:100,spa:100,spd:100,spe:100},abilities:{0:"Compoundeyes",1:"Aftermath"},heightm:0.4,weightkg:4,color:"Yellow",eggGroups:["No Eggs"]},
<del>snivy:{num:495,species:"Snivy",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:45,def:55,spa:45,spd:55,spe:63},abilities:{0:"Gluttony",1:"Storm Drain"},heightm:0.6,weightkg:8.1,color:"Green",evos:["servine"],eggGroups:["Ground","Plant"]},
<add>snivy:{num:495,species:"Snivy",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:45,atk:45,def:55,spa:45,spd:55,spe:63},abilities:{0:"Gluttony",1:"Storm Drain"},heightm:0.6,weightkg:8.1,color:"Green",evos:["servine"],eggGroups:["Ground","Plant"]},
<ide> servine:{num:496,species:"Servine",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:60,atk:60,def:75,spa:60,spd:75,spe:83},abilities:{0:"Sap Sipper",1:"Solar Power"},heightm:0.8,weightkg:16,color:"Green",prevo:"snivy",evos:["serperior"],evoLevel:17,eggGroups:["Ground","Plant"]},
<ide> serperior:{num:497,species:"Serperior",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:75,def:95,spa:75,spd:95,spe:113},abilities:{0:"Anger Point",1:"Forewarn"},heightm:3.3,weightkg:63,color:"Green",prevo:"servine",evoLevel:36,eggGroups:["Ground","Plant"]},
<ide> tepig:{num:498,species:"Tepig",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:65,atk:63,def:45,spa:45,spd:45,spe:45},abilities:{0:"Damp",1:"Tinted Lens"},heightm:0.5,weightkg:9.9,color:"Red",evos:["pignite"],eggGroups:["Ground"]},
<ide> pansage:{num:511,species:"Pansage",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Steadfast",1:"Own Tempo"},heightm:0.6,weightkg:10.5,color:"Green",evos:["simisage"],eggGroups:["Ground"]},
<ide> simisage:{num:512,species:"Simisage",types:["Grass"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Static",1:"Own Tempo"},heightm:1.1,weightkg:30.5,color:"Green",prevo:"pansage",evoLevel:1,eggGroups:["Ground"]},
<ide> pansear:{num:513,species:"Pansear",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Technician",1:"Drizzle"},heightm:0.6,weightkg:11,color:"Red",evos:["simisear"],eggGroups:["Ground"]},
<del>simisear:{num:514,species:"Simisear",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Tinted Lens",1:"Sniper"},heightm:1,weightkg:28,color:"Red",prevo:"pansear",evoLevel:1,eggGroups:["Ground"]},
<add>simisear:{num:514,species:"Simisear",types:["Fire"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Tinted Lens",1:"Sniper"},heightm:1,weightkg:28,color:"Red",prevo:"pansear",evoLevel:1,eggGroups:["Ground"]},
<ide> panpour:{num:515,species:"Panpour",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:50,atk:53,def:48,spa:53,spd:48,spe:64},abilities:{0:"Swift Swim",1:"Poison Touch"},heightm:0.6,weightkg:13.5,color:"Blue",evos:["simipour"],eggGroups:["Ground"]},
<ide> simipour:{num:516,species:"Simipour",types:["Water"],genderRatio:{M:0.875,F:0.125},baseStats:{hp:75,atk:98,def:63,spa:98,spd:63,spe:101},abilities:{0:"Analytic",1:"Storm Drain"},heightm:1,weightkg:29,color:"Blue",prevo:"panpour",evoLevel:1,eggGroups:["Ground"]},
<ide> munna:{num:517,species:"Munna",types:["Psychic"],baseStats:{hp:76,atk:25,def:45,spa:67,spd:55,spe:24},abilities:{0:"Pure Power",1:"Volt Absorb"},heightm:0.6,weightkg:23.3,color:"Pink",evos:["musharna"],eggGroups:["Ground"]},
<ide> zebstrika:{num:523,species:"Zebstrika",types:["Electric"],baseStats:{hp:75,atk:100,def:63,spa:80,spd:63,spe:116},abilities:{0:"Contrary",1:"Adaptability"},heightm:1.6,weightkg:79.5,color:"Black",prevo:"blitzle",evoLevel:27,eggGroups:["Ground"]},
<ide> roggenrola:{num:524,species:"Roggenrola",types:["Rock"],baseStats:{hp:55,atk:75,def:85,spa:25,spd:25,spe:15},abilities:{0:"Chlorophyll",1:"Natural Cure"},heightm:0.4,weightkg:18,color:"Blue",evos:["boldore"],eggGroups:["Mineral"]},
<ide> boldore:{num:525,species:"Boldore",types:["Rock"],baseStats:{hp:70,atk:105,def:105,spa:50,spd:40,spe:20},abilities:{0:"Keen Eye",1:"Flare Boost"},heightm:0.9,weightkg:102,color:"Blue",prevo:"roggenrola",evos:["gigalith"],evoLevel:25,eggGroups:["Mineral"]},
<del>gigalith:{num:526,species:"Gigalith",types:["Rock"],baseStats:{hp:85,atk:135,def:130,spa:60,spd:70,spe:25},abilities:{0:"Compoundeyes",1:"Iron Barbs"},heightm:1.7,weightkg:260,color:"Blue",prevo:"boldore",evoLevel:1,eggGroups:["Mineral"]},
<add>gigalith:{num:526,species:"Gigalith",types:["Rock"],baseStats:{hp:85,atk:135,def:130,spa:60,spd:70,spe:25},abilities:{0:"Compoundeyes",1:"Iron Barbs"},heightm:1.7,weightkg:260,color:"Blue",prevo:"boldore",evoLevel:25,eggGroups:["Mineral"]},
<ide> woobat:{num:527,species:"Woobat",types:["Psychic","Flying"],baseStats:{hp:55,atk:45,def:43,spa:55,spd:43,spe:72},abilities:{0:"Compoundeyes",1:"Poison Point"},heightm:0.4,weightkg:2.1,color:"Blue",evos:["swoobat"],eggGroups:["Flying","Ground"]},
<del>swoobat:{num:528,species:"Swoobat",types:["Psychic","Flying"],baseStats:{hp:67,atk:57,def:55,spa:77,spd:55,spe:114},abilities:{0:"Rain Dish",1:"Sand Rush"},heightm:0.9,weightkg:10.5,color:"Blue",prevo:"woobat",evoLevel:1,eggGroups:["Flying","Ground"]},
<add>swoobat:{num:528,species:"Swoobat",types:["Psychic","Flying"],baseStats:{hp:67,atk:57,def:55,spa:77,spd:55,spe:114},abilities:{0:"Rain Dish",1:"Sand Rush"},heightm:0.9,weightkg:10.5,color:"Blue",prevo:"woobat",evoLevel:2,eggGroups:["Flying","Ground"]},
<ide> drilbur:{num:529,species:"Drilbur",types:["Ground"],baseStats:{hp:60,atk:85,def:40,spa:30,spd:45,spe:68},abilities:{0:"Pickpocket",1:"Natural Cure"},heightm:0.3,weightkg:8.5,color:"Gray",evos:["excadrill"],eggGroups:["Ground"]},
<ide> excadrill:{num:530,species:"Excadrill",types:["Ground","Steel"],baseStats:{hp:110,atk:135,def:60,spa:50,spd:65,spe:88},abilities:{0:"Rain Dish",1:"Tinted Lens"},heightm:0.7,weightkg:40.4,color:"Gray",prevo:"drilbur",evoLevel:31,eggGroups:["Ground"]},
<ide> audino:{num:531,species:"Audino",types:["Normal"],baseStats:{hp:103,atk:60,def:86,spa:60,spd:86,spe:50},abilities:{0:"Magic Bounce",1:"Sand Veil"},heightm:1.1,weightkg:31,color:"Pink",eggGroups:["Fairy"]},
<ide> timburr:{num:532,species:"Timburr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:75,atk:80,def:55,spa:25,spd:35,spe:35},abilities:{0:"Levitate",1:"Immunity"},heightm:0.6,weightkg:12.5,color:"Gray",evos:["gurdurr"],eggGroups:["Humanshape"]},
<ide> gurdurr:{num:533,species:"Gurdurr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:85,atk:105,def:85,spa:40,spd:50,spe:40},abilities:{0:"Pressure",1:"Storm Drain"},heightm:1.2,weightkg:40,color:"Gray",prevo:"timburr",evos:["conkeldurr"],evoLevel:25,eggGroups:["Humanshape"]},
<del>conkeldurr:{num:534,species:"Conkeldurr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:105,atk:140,def:95,spa:55,spd:65,spe:45},abilities:{0:"Poison Heal",1:"Mold Breaker"},heightm:1.4,weightkg:87,color:"Brown",prevo:"gurdurr",evoLevel:1,eggGroups:["Humanshape"]},
<add>conkeldurr:{num:534,species:"Conkeldurr",types:["Fighting"],genderRatio:{M:0.75,F:0.25},baseStats:{hp:105,atk:140,def:95,spa:55,spd:65,spe:45},abilities:{0:"Poison Heal",1:"Mold Breaker"},heightm:1.4,weightkg:87,color:"Brown",prevo:"gurdurr",evoLevel:25,eggGroups:["Humanshape"]},
<ide> tympole:{num:535,species:"Tympole",types:["Water"],baseStats:{hp:50,atk:50,def:40,spa:50,spd:40,spe:64},abilities:{0:"Liquid Ooze",1:"Sheer Force"},heightm:0.5,weightkg:4.5,color:"Blue",evos:["palpitoad"],eggGroups:["Water 1"]},
<ide> palpitoad:{num:536,species:"Palpitoad",types:["Water","Ground"],baseStats:{hp:75,atk:65,def:55,spa:65,spd:55,spe:69},abilities:{0:"Super Luck",1:"Tinted Lens"},heightm:0.8,weightkg:17,color:"Blue",prevo:"tympole",evos:["seismitoad"],evoLevel:25,eggGroups:["Water 1"]},
<ide> seismitoad:{num:537,species:"Seismitoad",types:["Water","Ground"],baseStats:{hp:105,atk:85,def:75,spa:85,spd:75,spe:74},abilities:{0:"Anger Point",1:"Liquid Ooze"},heightm:1.5,weightkg:62,color:"Blue",prevo:"palpitoad",evoLevel:36,eggGroups:["Water 1"]},
<ide> throh:{num:538,species:"Throh",types:["Fighting"],gender:"M",baseStats:{hp:120,atk:100,def:85,spa:30,spd:85,spe:45},abilities:{0:"Sap Sipper",1:"Analytic"},heightm:1.3,weightkg:55.5,color:"Red",eggGroups:["Humanshape"]},
<ide> sawk:{num:539,species:"Sawk",types:["Fighting"],gender:"M",baseStats:{hp:75,atk:125,def:75,spa:30,spd:75,spe:85},abilities:{0:"Stench",1:"Flash Fire"},heightm:1.4,weightkg:51,color:"Blue",eggGroups:["Humanshape"]},
<del>sewaddle:{num:540,species:"Sewaddle",types:["Bug","Grass"],baseStats:{hp:45,atk:53,def:70,spa:40,spd:60,spe:42},abilities:{0:"Stikcy Hold",1:"Unaware"},heightm:0.3,weightkg:2.5,color:"Yellow",evos:["swadloon"],eggGroups:["Bug"]},
<add>sewaddle:{num:540,species:"Sewaddle",types:["Bug","Grass"],baseStats:{hp:45,atk:53,def:70,spa:40,spd:60,spe:42},abilities:{0:"Sticky Hold",1:"Unaware"},heightm:0.3,weightkg:2.5,color:"Yellow",evos:["swadloon"],eggGroups:["Bug"]},
<ide> swadloon:{num:541,species:"Swadloon",types:["Bug","Grass"],baseStats:{hp:55,atk:63,def:90,spa:50,spd:80,spe:42},abilities:{0:"Magnet Pull",1:"Magma Armor"},heightm:0.5,weightkg:7.3,color:"Green",prevo:"sewaddle",evos:["leavanny"],evoLevel:20,eggGroups:["Bug"]},
<del>leavanny:{num:542,species:"Leavanny",types:["Bug","Grass"],baseStats:{hp:75,atk:103,def:80,spa:70,spd:70,spe:92},abilities:{0:"Wonder Skin",1:"Unburden"},heightm:1.2,weightkg:20.5,color:"Yellow",prevo:"swadloon",evoLevel:1,eggGroups:["Bug"]},
<add>leavanny:{num:542,species:"Leavanny",types:["Bug","Grass"],baseStats:{hp:75,atk:103,def:80,spa:70,spd:70,spe:92},abilities:{0:"Wonder Skin",1:"Unburden"},heightm:1.2,weightkg:20.5,color:"Yellow",prevo:"swadloon",evoLevel:21,eggGroups:["Bug"]},
<ide> venipede:{num:543,species:"Venipede",types:["Bug","Poison"],baseStats:{hp:30,atk:45,def:59,spa:30,spd:39,spe:57},abilities:{0:"Battle Armor",1:"Sticky Hold"},heightm:0.4,weightkg:5.3,color:"Red",evos:["whirlipede"],eggGroups:["Bug"]},
<ide> whirlipede:{num:544,species:"Whirlipede",types:["Bug","Poison"],baseStats:{hp:40,atk:55,def:99,spa:40,spd:79,spe:47},abilities:{0:"Trace",1:"Rain Dish"},heightm:1.2,weightkg:58.5,color:"Gray",prevo:"venipede",evos:["scolipede"],evoLevel:22,eggGroups:["Bug"]},
<ide> scolipede:{num:545,species:"Scolipede",types:["Bug","Poison"],baseStats:{hp:60,atk:90,def:89,spa:55,spd:69,spe:112},abilities:{0:"Trace",1:"Technician"},heightm:2.5,weightkg:200.5,color:"Red",prevo:"whirlipede",evoLevel:30,eggGroups:["Bug"]},
<ide> petilil:{num:548,species:"Petilil",types:["Grass"],gender:"F",baseStats:{hp:45,atk:35,def:50,spa:70,spd:50,spe:30},abilities:{0:"Sturdy",1:"Weak Armor"},heightm:0.5,weightkg:6.6,color:"Green",evos:["lilligant"],eggGroups:["Plant"]},
<ide> lilligant:{num:549,species:"Lilligant",types:["Grass"],gender:"F",baseStats:{hp:70,atk:60,def:75,spa:110,spd:75,spe:90},abilities:{0:"Lightningrod",1:"Overgrow"},heightm:1.1,weightkg:16.3,color:"Green",prevo:"petilil",evoLevel:1,eggGroups:["Plant"]},
<ide> basculin:{num:550,species:"Basculin",baseForme:"Red-Striped",types:["Water"],baseStats:{hp:70,atk:92,def:65,spa:80,spd:55,spe:98},abilities:{0:"Contrary",1:"Volt Absorb"},heightm:1,weightkg:18,color:"Green",eggGroups:["Water 2"],otherFormes:["basculinbluestriped"]},
<del>basculinbluestriped:{num:550,species:"Basculin-Blue-Striped",baseSpecies:"Basculin",forme:"Blue-Striped",formeLetter:"B",types:["Water"],baseStats:{hp:70,atk:92,def:65,spa:80,spd:55,spe:98},abilities:{0:"Contrary",1:"Volt Absorb"},heightm:1,weightkg:18,color:"Green",eggGroups:["Water 2"]},
<ide> sandile:{num:551,species:"Sandile",types:["Ground","Dark"],baseStats:{hp:50,atk:72,def:35,spa:35,spd:35,spe:65},abilities:{0:"Suction Cups",1:"Weak Armor"},heightm:0.7,weightkg:15.2,color:"Brown",evos:["krokorok"],eggGroups:["Ground"]},
<ide> krokorok:{num:552,species:"Krokorok",types:["Ground","Dark"],baseStats:{hp:60,atk:82,def:45,spa:45,spd:45,spe:74},abilities:{0:"Water Absorb",1:"Infiltrator"},heightm:1,weightkg:33.4,color:"Brown",prevo:"sandile",evos:["krookodile"],evoLevel:29,eggGroups:["Ground"]},
<ide> krookodile:{num:553,species:"Krookodile",types:["Ground","Dark"],baseStats:{hp:95,atk:117,def:70,spa:65,spd:70,spe:92},abilities:{0:"Tangled Feet",1:"Magic Guard"},heightm:1.5,weightkg:96.3,color:"Red",prevo:"krokorok",evoLevel:40,eggGroups:["Ground"]},
<ide> maractus:{num:556,species:"Maractus",types:["Grass"],baseStats:{hp:75,atk:86,def:67,spa:106,spd:67,spe:60},abilities:{0:"Solid Rock",1:"Hyper Cutter"},heightm:1,weightkg:28,color:"Green",eggGroups:["Plant"]},
<ide> dwebble:{num:557,species:"Dwebble",types:["Bug","Rock"],baseStats:{hp:50,atk:65,def:85,spa:35,spd:35,spe:55},abilities:{0:"Water Absorb",1:"Ice Body"},heightm:0.3,weightkg:14.5,color:"Red",evos:["crustle"],eggGroups:["Bug","Mineral"]},
<ide> crustle:{num:558,species:"Crustle",types:["Bug","Rock"],baseStats:{hp:70,atk:95,def:125,spa:65,spd:75,spe:45},abilities:{0:"Magic Bounce",1:"Super Luck"},heightm:1.4,weightkg:200,color:"Red",prevo:"dwebble",evoLevel:34,eggGroups:["Bug","Mineral"]},
<del>scraggy:{num:559,species:"Scraggy",types:["Dark","Fighting"],baseStats:{hp:50,atk:75,def:70,spa:35,spd:70,spe:48},abilities:{0:"Solar Power",1:"Solid Rock"},heightm:0.6,weightkg:11.8,color:"Yellow",evos:["scrafty"],eggGroups:["Ground","Dragon"]},
<add>scraggy:{num:559,species:"Scraggy",types:["Dark","Fighting"],baseStats:{hp:50,atk:75,def:70,spa:35,spd:70,spe:48},abilities:{0:"Solar Power",1:"Solid Rock"},heightm:0.6,weightkg:11.8,color:"Yellow",evos:["scrafty"],eggGroups:["Ground","Dragon"]},
<ide> scrafty:{num:560,species:"Scrafty",types:["Dark","Fighting"],baseStats:{hp:65,atk:90,def:115,spa:45,spd:115,spe:58},abilities:{0:"Sturdy",1:"Sand Rush"},heightm:1.1,weightkg:30,color:"Red",prevo:"scraggy",evoLevel:39,eggGroups:["Ground","Dragon"]},
<ide> sigilyph:{num:561,species:"Sigilyph",types:["Psychic","Flying"],baseStats:{hp:72,atk:58,def:80,spa:103,spd:80,spe:97},abilities:{0:"Swarm",1:"Tangled Feet"},heightm:1.4,weightkg:14,color:"Black",eggGroups:["Flying"]},
<ide> yamask:{num:562,species:"Yamask",types:["Ghost"],baseStats:{hp:38,atk:30,def:85,spa:55,spd:65,spe:30},abilities:{0:"Suction Cups",1:"Poison Heal"},heightm:0.5,weightkg:1.5,color:"Black",evos:["cofagrigus"],eggGroups:["Mineral","Indeterminate"]},
<ide> solosis:{num:577,species:"Solosis",types:["Psychic"],baseStats:{hp:45,atk:30,def:40,spa:105,spd:50,spe:20},abilities:{0:"Imposter",1:"Synchronize"},heightm:0.3,weightkg:1,color:"Green",evos:["duosion"],eggGroups:["Indeterminate"]},
<ide> duosion:{num:578,species:"Duosion",types:["Psychic"],baseStats:{hp:65,atk:40,def:50,spa:125,spd:60,spe:30},abilities:{0:"Analytic",1:"Magnet Pull"},heightm:0.6,weightkg:8,color:"Green",prevo:"solosis",evos:["reuniclus"],evoLevel:32,eggGroups:["Indeterminate"]},
<ide> reuniclus:{num:579,species:"Reuniclus",types:["Psychic"],baseStats:{hp:110,atk:65,def:75,spa:125,spd:85,spe:30},abilities:{0:"Natural Cure",1:"Analytic"},heightm:1,weightkg:20.1,color:"Green",prevo:"duosion",evoLevel:41,eggGroups:["Indeterminate"]},
<del>ducklett:{num:580,species:"Ducklett",types:["Water","Flying"],baseStats:{hp:62,atk:44,def:50,spa:44,spd:50,spe:55},abilities:{0:"Magma Armor",1:"Victory Star"},heightm:0.5,weightkg:5.5,color:"Blue",evos:["swanna"],eggGroups:["Water 1","Flying"]},
<add>ducklett:{num:580,species:"Ducklett",types:["Water","Flying"],baseStats:{hp:62,atk:44,def:50,spa:44,spd:50,spe:55},abilities:{0:"Magma Armor",1:"Victory Star"},heightm:0.5,weightkg:5.5,color:"Blue",evos:["swanna"],eggGroups:["Water 1","Flying"]},
<ide> swanna:{num:581,species:"Swanna",types:["Water","Flying"],baseStats:{hp:75,atk:87,def:63,spa:87,spd:63,spe:98},abilities:{0:"Shield Dust",1:"Early Bird"},heightm:1.3,weightkg:24.2,color:"White",prevo:"ducklett",evoLevel:35,eggGroups:["Water 1","Flying"]},
<ide> vanillite:{num:582,species:"Vanillite",types:["Ice"],baseStats:{hp:36,atk:50,def:50,spa:65,spd:60,spe:44},abilities:{0:"Arena Trap",1:"Magma Armor"},heightm:0.4,weightkg:5.7,color:"White",evos:["vanillish"],eggGroups:["Mineral"]},
<ide> vanillish:{num:583,species:"Vanillish",types:["Ice"],baseStats:{hp:51,atk:65,def:65,spa:80,spd:75,spe:59},abilities:{0:"Insomnia",1:"No Guard"},heightm:1.1,weightkg:41,color:"White",prevo:"vanillite",evos:["vanilluxe"],evoLevel:35,eggGroups:["Mineral"]},
<ide> sawsbuck:{num:586,species:"Sawsbuck",baseForme:"Spring",types:["Normal","Grass"],baseStats:{hp:80,atk:100,def:70,spa:60,spd:70,spe:95},abilities:{0:"Stench",1:"Speed Boost"},heightm:1.9,weightkg:92.5,color:"Brown",prevo:"deerling",evoLevel:34,eggGroups:["Ground"],otherForms:["sawsbucksummer","sawsbuckautumn","sawsbuckwinter"]},
<ide> emolga:{num:587,species:"Emolga",types:["Electric","Flying"],baseStats:{hp:55,atk:75,def:60,spa:75,spd:60,spe:103},abilities:{0:"Stall",1:"Sticky Hold"},heightm:0.4,weightkg:5,color:"White",eggGroups:["Ground"]},
<ide> karrablast:{num:588,species:"Karrablast",types:["Bug"],baseStats:{hp:50,atk:75,def:45,spa:40,spd:45,spe:60},abilities:{0:"Solid Rock",1:"Own Tempo"},heightm:0.5,weightkg:5.9,color:"Blue",evos:["escavalier"],eggGroups:["Bug"]},
<del>escavalier:{num:589,species:"Escavalier",types:["Bug","Steel"],baseStats:{hp:70,atk:135,def:105,spa:60,spd:105,spe:20},abilities:{0:"Unnerve",1:"Compoundeyes"},heightm:1,weightkg:33,color:"Gray",prevo:"karrablast",evoLevel:1,eggGroups:["Bug"]},
<add>escavalier:{num:589,species:"Escavalier",types:["Bug","Steel"],baseStats:{hp:70,atk:135,def:105,spa:60,spd:105,spe:20},abilities:{0:"Unnerve",1:"Compoundeyes"},heightm:1,weightkg:33,color:"Gray",prevo:"karrablast",evoLevel:1,eggGroups:["Bug"]},
<ide> foongus:{num:590,species:"Foongus",types:["Grass","Poison"],baseStats:{hp:69,atk:55,def:45,spa:55,spd:55,spe:15},abilities:{0:"Clear Body",1:"Imposter"},heightm:0.2,weightkg:1,color:"White",evos:["amoonguss"],eggGroups:["Plant"]},
<ide> amoonguss:{num:591,species:"Amoonguss",types:["Grass","Poison"],baseStats:{hp:114,atk:85,def:70,spa:85,spd:80,spe:30},abilities:{0:"Overcoat",1:"Gluttony"},heightm:0.6,weightkg:10.5,color:"White",prevo:"foongus",evoLevel:39,eggGroups:["Plant"]},
<del>frillish:{num:592,species:"Frillish",types:["Water","Ghost"],baseStats:{hp:55,atk:40,def:50,spa:65,spd:85,spe:40},abilities:{0:"Levitate",1:"Poison Heal"},heightm:1.2,weightkg:33,color:"White",evos:["jellicent"],eggGroups:["Indeterminate"]},
<add>frillish:{num:592,species:"Frillish",types:["Water","Ghost"],baseStats:{hp:55,atk:40,def:50,spa:65,spd:85,spe:40},abilities:{0:"Levitate",1:"Poison Heal"},heightm:1.2,weightkg:33,color:"White",evos:["jellicent"],eggGroups:["Indeterminate"]},
<ide> jellicent:{num:593,species:"Jellicent",types:["Water","Ghost"],baseStats:{hp:100,atk:60,def:70,spa:85,spd:105,spe:60},abilities:{0:"Thick Fat",1:"Intimidate"},heightm:2.2,weightkg:135,color:"White",prevo:"frillish",evoLevel:40,eggGroups:["Indeterminate"]},
<ide> alomomola:{num:594,species:"Alomomola",types:["Water"],baseStats:{hp:165,atk:75,def:80,spa:40,spd:45,spe:65},abilities:{0:"Cloud Nine",1:"Serene Grace"},heightm:1.2,weightkg:31.6,color:"Pink",eggGroups:["Water 1","Water 2"]},
<ide> joltik:{num:595,species:"Joltik",types:["Bug","Electric"],baseStats:{hp:50,atk:47,def:50,spa:57,spd:50,spe:65},abilities:{0:"Super Luck",1:"Flash Fire"},heightm:0.1,weightkg:0.6,color:"Yellow",evos:["galvantula"],eggGroups:["Bug"]},
<ide> klinklang:{num:601,species:"Klinklang",types:["Steel"],gender:"N",baseStats:{hp:60,atk:100,def:115,spa:70,spd:85,spe:90},abilities:{0:"Flame Body",1:"Scrappy"},heightm:0.6,weightkg:81,color:"Gray",prevo:"klang",evoLevel:49,eggGroups:["Mineral"]},
<ide> tynamo:{num:602,species:"Tynamo",types:["Electric"],baseStats:{hp:35,atk:55,def:40,spa:45,spd:40,spe:60},abilities:{0:"Color Change",1:"Prankster"},heightm:0.2,weightkg:0.3,color:"White",evos:["eelektrik"],eggGroups:["Indeterminate"]},
<ide> eelektrik:{num:603,species:"Eelektrik",types:["Electric"],baseStats:{hp:65,atk:85,def:70,spa:75,spd:70,spe:40},abilities:{0:"Moxie",1:"Anticipation"},heightm:1.2,weightkg:22,color:"Blue",prevo:"tynamo",evos:["eelektross"],evoLevel:39,eggGroups:["Indeterminate"]},
<del>eelektross:{num:604,species:"Eelektross",types:["Electric"],baseStats:{hp:85,atk:115,def:80,spa:105,spd:80,spe:50},abilities:{0:"Liqiud Ooze",1:"Rattled"},heightm:2.1,weightkg:80.5,color:"Blue",prevo:"eelektrik",evoLevel:1,eggGroups:["Indeterminate"]},
<add>eelektross:{num:604,species:"Eelektross",types:["Electric"],baseStats:{hp:85,atk:115,def:80,spa:105,spd:80,spe:50},abilities:{0:"Liquid Ooze",1:"Rattled"},heightm:2.1,weightkg:80.5,color:"Blue",prevo:"eelektrik",evoLevel:39,eggGroups:["Indeterminate"]},
<ide> elgyem:{num:605,species:"Elgyem",types:["Psychic"],baseStats:{hp:55,atk:55,def:55,spa:85,spd:55,spe:30},abilities:{0:"Inner Focus",1:"Illusion"},heightm:0.5,weightkg:9,color:"Blue",evos:["beheeyem"],eggGroups:["Humanshape"]},
<ide> beheeyem:{num:606,species:"Beheeyem",types:["Psychic"],baseStats:{hp:75,atk:75,def:75,spa:125,spd:95,spe:40},abilities:{0:"Dry Skin",1:"Damp"},heightm:1,weightkg:34.5,color:"Brown",prevo:"elgyem",evoLevel:42,eggGroups:["Humanshape"]},
<ide> litwick:{num:607,species:"Litwick",types:["Ghost","Fire"],baseStats:{hp:50,atk:30,def:55,spa:65,spd:55,spe:20},abilities:{0:"Victory Star",1:"Snow Cloak"},heightm:0.3,weightkg:3.1,color:"White",evos:["lampent"],eggGroups:["Indeterminate"]},
<ide> lampent:{num:608,species:"Lampent",types:["Ghost","Fire"],baseStats:{hp:60,atk:40,def:60,spa:95,spd:60,spe:55},abilities:{0:"Snow Cloak",1:"Drought"},heightm:0.6,weightkg:13,color:"Black",prevo:"litwick",evos:["chandelure"],evoLevel:41,eggGroups:["Indeterminate"]},
<del>chandelure:{num:609,species:"Chandelure",types:["Ghost","Fire"],baseStats:{hp:60,atk:55,def:90,spa:145,spd:90,spe:80},abilities:{0:"Keen Eye",1:"Magic Guard"},heightm:1,weightkg:34.3,color:"Black",prevo:"lampent",evoLevel:1,eggGroups:["Indeterminate"]},
<add>chandelure:{num:609,species:"Chandelure",types:["Ghost","Fire"],baseStats:{hp:60,atk:55,def:90,spa:145,spd:90,spe:80},abilities:{0:"Keen Eye",1:"Magic Guard"},heightm:1,weightkg:34.3,color:"Black",prevo:"lampent",evoLevel:41,eggGroups:["Indeterminate"]},
<ide> axew:{num:610,species:"Axew",types:["Dragon"],baseStats:{hp:46,atk:87,def:60,spa:30,spd:40,spe:57},abilities:{0:"Sap Sipper",1:"Guts"},heightm:0.6,weightkg:18,color:"Green",evos:["fraxure"],eggGroups:["Monster","Dragon"]},
<ide> fraxure:{num:611,species:"Fraxure",types:["Dragon"],baseStats:{hp:66,atk:117,def:70,spa:40,spd:50,spe:67},abilities:{0:"Early Bird",1:"Light Metal"},heightm:1,weightkg:36,color:"Green",prevo:"axew",evos:["haxorus"],evoLevel:38,eggGroups:["Monster","Dragon"]},
<ide> haxorus:{num:612,species:"Haxorus",types:["Dragon"],baseStats:{hp:76,atk:147,def:90,spa:60,spd:70,spe:97},abilities:{0:"Motor Drive",1:"Sand Veil"},heightm:1.8,weightkg:105.5,color:"Yellow",prevo:"fraxure",evoLevel:48,eggGroups:["Monster","Dragon"]},
<ide> kyuremblack:{num:646,species:"Kyurem-Black",baseSpecies:"Kyurem",forme:"Black",formeLetter:"B",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:170,def:100,spa:120,spd:90,spe:95},abilities:{0:"Weak Armor",1:"Shadow Tag"},heightm:3.3,weightkg:325,color:"Gray",eggGroups:["No Eggs"]},
<ide> kyuremwhite:{num:646,species:"Kyurem-White",baseSpecies:"Kyurem",forme:"White",formeLetter:"W",types:["Dragon","Ice"],gender:"N",baseStats:{hp:125,atk:120,def:90,spa:170,spd:100,spe:95},abilities:{0:"No Guard",1:"Gluttony"},heightm:3.6,weightkg:325,color:"Gray",eggGroups:["No Eggs"]},
<ide> keldeo:{num:647,species:"Keldeo",baseForme:"Ordinary",types:["Water","Fighting"],gender:"N",baseStats:{hp:91,atk:72,def:90,spa:129,spd:90,spe:108},abilities:{0:"Shed Skin",1:"Speed Boost"},heightm:1.4,weightkg:48.5,color:"Yellow",eggGroups:["No Eggs"],otherFormes:["keldeoresolute"]},
<del>keldeoresolute:{num:647,species:"Keldeo-Resolute",baseSpecies:"Keldeo",forme:"Resolute",formeLetter:"R",types:["Water","Fighting"],gender:"N",baseStats:{hp:91,atk:72,def:90,spa:129,spd:90,spe:108},abilities:{0:"Shed Skin",1:"Speed Boost"},heightm:1.4,weightkg:48.5,color:"Yellow",eggGroups:["No Eggs"]},
<ide> meloetta:{num:648,species:"Meloetta",baseForme:"Aria",types:["Normal","Psychic"],gender:"N",baseStats:{hp:100,atk:77,def:77,spa:128,spd:128,spe:90},abilities:{0:"Multiscale",1:"Moxie"},heightm:0.6,weightkg:6.5,color:"White",eggGroups:["No Eggs"],otherFormes:["meloettapirouette"]},
<ide> meloettapirouette:{num:648,species:"Meloetta-Pirouette",baseSpecies:"Meloetta",forme:"Pirouette",formeLetter:"P",types:["Normal","Fighting"],gender:"N",baseStats:{hp:100,atk:128,def:90,spa:77,spd:77,spe:128},abilities:{0:"Multiscale",1:"Moxie"},heightm:0.6,weightkg:6.5,color:"White",eggGroups:["No Eggs"]},
<ide> genesect:{num:649,species:"Genesect",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"],otherFormes:["genesectdouse","genesectshock","genesectburn","genesectchill"]},
<del>genesectdouse:{num:649,species:"Genesect-Douse",baseSpecies:"Genesect",forme:"Douse",formeLetter:"D",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"]},
<del>genesectshock:{num:649,species:"Genesect-Shock",baseSpecies:"Genesect",forme:"Shock",formeLetter:"S",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities:{0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"]},
<del>genesectburn:{num:649,species:"Genesect-Burn",baseSpecies:"Genesect",forme:"Burn",formeLetter:"B",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities: {0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"]},
<del>genesectchill:{num:649,species:"Genesect-Chill",baseSpecies:"Genesect",forme:"Chill",formeLetter:"C",types:["Bug","Steel"],gender:"N",baseStats:{hp:71,atk:120,def:95,spa:120,spd:95,spe:99},abilities: {0:"Effect Spore",1:"Magma Armor"},heightm:1.5,weightkg:82.5,color:"Purple",eggGroups:["No Eggs"]}
<ide> }; |
|
Java | apache-2.0 | bf50517f7fb01c850ce0e68bf97a95f88875c8f2 | 0 | BlackSourceLabs/BlackNectar-Service,BlackSourceLabs/BlackNectar-Service | /*
* Copyright 2017 BlackSource, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 tech.blacksource.blacknectar.service.data;
import java.util.List;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import sir.wellington.alchemy.collections.lists.Lists;
import sir.wellington.alchemy.collections.sets.Sets;
import tech.aroma.client.Aroma;
import tech.blacksource.blacknectar.service.TestingResources;
import tech.blacksource.blacknectar.service.exceptions.DoesNotExistException;
import tech.blacksource.blacknectar.service.images.Image;
import tech.blacksource.blacknectar.service.stores.Store;
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner;
import tech.sirwellington.alchemy.test.junit.runners.Repeat;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static tech.blacksource.blacknectar.service.BlackNectarGenerators.images;
import static tech.sirwellington.alchemy.generator.CollectionGenerators.listOf;
import static tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows;
/**
*
* @author SirWellington
*/
@Repeat(5)
@RunWith(AlchemyTestRunner.class)
public class SQLImageRepositoryIT
{
private Aroma aroma;
private JdbcTemplate database;
private SQLImageMapper mapper;
private SQLImageRepository instance;
private List<Image> images;
private Store store;
private StoreRepository storeRepository;
private Image image;
private UUID storeId;
private String imageId;
@Before
public void setUp() throws Exception
{
setupResources();
setupData();
instance = new SQLImageRepository(aroma, database, mapper);
}
private void setupResources() throws Exception
{
aroma = TestingResources.getAroma();
database = TestingResources.createDatabaseConnection();
mapper = TestingResources.getImageMapper();
storeRepository = TestingResources.getStoreRepository();
}
private void setupData() throws Exception
{
store = storeRepository.getAllStores(1).get(0);
images = listOf(images());
images = images.stream()
.map(img -> Image.Builder.fromImage(img).withStoreID(store.getStoreId()).build())
.collect(toList());
image = Lists.oneOf(images);
storeId = image.getStoreId();
imageId = image.getImageId();
}
@After
public void tearDown() throws Exception
{
instance.deleteImage(image);
images.forEach(instance::deleteImage);
}
@Test
public void testAddImage()
{
instance.addImage(image);
assertTrue(instance.hasImages(storeId));
}
@Test
public void testGetImage()
{
instance.addImage(image);
Image result = instance.getImage(storeId, imageId);
assertThat(result, is(image));
}
@Test
public void testGetImageWhenNotExist() throws Exception
{
assertThrows(() -> instance.getImage(storeId, imageId)).isInstanceOf(DoesNotExistException.class);
}
@Test
@SuppressWarnings("unchecked")
public void testGetImagesForStore()
{
images.forEach(instance::addImage);
List<Image> result = instance.getImagesForStore(storeId);
assertTrue(Sets.containTheSameElements(result, images));
}
@Test
public void testGetImagesForStoreWhenNoImages() throws Exception
{
List<Image> results = instance.getImagesForStore(storeId);
assertThat(results, notNullValue());
assertThat(results, is(empty()));
}
@Test
public void testHasImages()
{
assertFalse(instance.hasImages(storeId));
instance.addImage(image);
assertTrue(instance.hasImages(storeId));
}
@Test
public void testDeleteImage()
{
instance.addImage(image);
assertTrue(instance.hasImages(storeId));
instance.deleteImage(image);
assertFalse(instance.hasImages(storeId));
}
@Test
public void testDeleteImageWhenNotExist() throws Exception
{
instance.deleteImage(image);
}
}
| src/test/java/tech/blacksource/blacknectar/service/data/SQLImageRepositoryIT.java | /*
* Copyright 2017 BlackSource, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 tech.blacksource.blacknectar.service.data;
import java.util.List;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import sir.wellington.alchemy.collections.lists.Lists;
import sir.wellington.alchemy.collections.sets.Sets;
import tech.aroma.client.Aroma;
import tech.blacksource.blacknectar.service.TestingResources;
import tech.blacksource.blacknectar.service.exceptions.DoesNotExistException;
import tech.blacksource.blacknectar.service.images.Image;
import tech.blacksource.blacknectar.service.stores.Store;
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner;
import tech.sirwellington.alchemy.test.junit.runners.Repeat;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static tech.blacksource.blacknectar.service.BlackNectarGenerators.images;
import static tech.sirwellington.alchemy.generator.CollectionGenerators.listOf;
import static tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows;
/**
*
* @author SirWellington
*/
@Repeat(5)
@RunWith(AlchemyTestRunner.class)
public class SQLImageRepositoryIT
{
private Aroma aroma;
private JdbcTemplate database;
private SQLImageMapper mapper;
private SQLImageRepository instance;
private List<Image> images;
private Store store;
private StoreRepository storeRepository;
private Image image;
private UUID storeId;
private String imageId;
@Before
public void setUp() throws Exception
{
setupResources();
setupData();
instance = new SQLImageRepository(aroma, database, mapper);
}
private void setupResources() throws Exception
{
aroma = TestingResources.getAroma();
database = TestingResources.createDatabaseConnection();
mapper = TestingResources.getImageMapper();
storeRepository = TestingResources.getStoreRepository();
}
private void setupData() throws Exception
{
store = storeRepository.getAllStores(1).get(0);
images = listOf(images());
images = images.stream()
.map(img -> Image.Builder.fromImage(img).withStoreID(store.getStoreId()).build())
.collect(toList());
image = Lists.oneOf(images);
storeId = image.getStoreId();
imageId = image.getImageId();
}
@After
public void tearDown() throws Exception
{
instance.deleteImage(image);
images.forEach(instance::deleteImage);
}
@Test
public void testAddImage()
{
instance.addImage(image);
assertTrue(instance.hasImages(storeId));
}
@Test
public void testGetImage()
{
instance.addImage(image);
Image result = instance.getImage(storeId, imageId);
assertThat(result, is(image));
}
@Test
public void testGetImageWhenNotExist() throws Exception
{
assertThrows(() -> instance.getImage(storeId, imageId)).isInstanceOf(DoesNotExistException.class);
}
@Test
@SuppressWarnings("unchecked")
public void testGetImagesForStore()
{
images.forEach(instance::addImage);
List<Image> result = instance.getImagesForStore(storeId);
assertTrue(Sets.containTheSameElements(result, images));
}
@Test
public void testGetImagesForStoreWhenNoImages() throws Exception
{
List<Image> results = instance.getImagesForStore(storeId);
assertThat(results, notNullValue());
assertThat(results, is(empty()));
}
@Test
public void testHasImages()
{
assertFalse(instance.hasImages(storeId));
instance.addImage(image);
assertTrue(instance.hasImages(storeId));
}
@Test
public void testDeleteImage()
{
instance.addImage(image);
assertTrue(instance.hasImages(storeId));
instance.deleteImage(image);
assertFalse(instance.hasImages(storeId));
}
@Test
public void testDeleteImageWhenNotExist() throws Exception
{
instance.deleteImage(image);
}
}
| #53 - Cleans things up a little | src/test/java/tech/blacksource/blacknectar/service/data/SQLImageRepositoryIT.java | #53 - Cleans things up a little | <ide><path>rc/test/java/tech/blacksource/blacknectar/service/data/SQLImageRepositoryIT.java
<ide> assertThrows(() -> instance.getImage(storeId, imageId)).isInstanceOf(DoesNotExistException.class);
<ide> }
<ide>
<del>
<ide> @Test
<ide> @SuppressWarnings("unchecked")
<ide> public void testGetImagesForStore()
<ide> images.forEach(instance::addImage);
<ide>
<ide> List<Image> result = instance.getImagesForStore(storeId);
<del>
<add>
<ide> assertTrue(Sets.containTheSameElements(result, images));
<ide> }
<ide> |
|
Java | apache-2.0 | 4c789b75f34d720d373085a2e57afd3608648655 | 0 | diffplug/spotless,jbduncan/spotless,gaborbernat/spotless,nedtwigg/spotless,diffplug/spotless,gdecaso/spotless,diffplug/spotless,diffplug/spotless,diffplug/spotless,gdecaso/spotless,nedtwigg/spotless,jbduncan/spotless,diffplug/spotless,gaborbernat/spotless,jbduncan/spotless | package com.diffplug.gradle.spotless.java;
import java.util.List;
import org.gradle.api.GradleException;
import org.gradle.api.internal.file.UnionFileCollection;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.SourceSet;
import com.diffplug.gradle.spotless.FormatExtension;
import com.diffplug.gradle.spotless.FormatTask;
import com.diffplug.gradle.spotless.SpotlessExtension;
public class JavaExtension extends FormatExtension {
public static final String NAME = "java";
public JavaExtension(SpotlessExtension rootExtension) {
super(NAME, rootExtension);
}
public static final String LICENSE_HEADER_DELIMITER = "package ";
public void licenseHeader(String licenseHeader) {
licenseHeader(licenseHeader, LICENSE_HEADER_DELIMITER);
}
public void licenseHeaderFile(Object licenseHeaderFile) {
licenseHeaderFile(licenseHeaderFile, LICENSE_HEADER_DELIMITER);
}
public void importOrder(List<String> importOrder) {
customLazy(ImportSorterStep.NAME, () -> new ImportSorterStep(importOrder)::format);
}
public void importOrderFile(Object importOrderFile) {
customLazy(ImportSorterStep.NAME, () -> new ImportSorterStep(getProject().file(importOrderFile))::format);
}
public void eclipseFormatFile(Object eclipseFormatFile) {
customLazy(EclipseFormatterStep.NAME, () -> EclipseFormatterStep.load(getProject().file(eclipseFormatFile))::format);
}
/** If the user hasn't specified the files yet, we'll assume he/she means all of the java files. */
@Override
protected void setupTask(FormatTask task) throws Exception {
if (target == null) {
JavaPluginConvention javaPlugin = getProject().getConvention().getPlugin(JavaPluginConvention.class);
if (javaPlugin == null) {
throw new GradleException("You must apply the java plugin before the spotless plugin if you are using the java extension.");
}
UnionFileCollection union = new UnionFileCollection();
for (SourceSet sourceSet : javaPlugin.getSourceSets()) {
union.add(sourceSet.getJava());
}
target = union;
}
super.setupTask(task);
}
}
| src/main/java/com/diffplug/gradle/spotless/java/JavaExtension.java | package com.diffplug.gradle.spotless.java;
import java.util.List;
import org.gradle.api.GradleException;
import org.gradle.api.internal.file.UnionFileCollection;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.SourceSet;
import com.diffplug.gradle.spotless.FormatExtension;
import com.diffplug.gradle.spotless.FormatTask;
import com.diffplug.gradle.spotless.SpotlessExtension;
public class JavaExtension extends FormatExtension {
public static final String NAME = "java";
public JavaExtension(SpotlessExtension rootExtension) {
super(NAME, rootExtension);
}
public static final String LICENSE_HEADER_DELIMITER = "package ";
public void licenseHeader(String licenseHeader) {
licenseHeader(licenseHeader, LICENSE_HEADER_DELIMITER);
}
public void licenseHeaderFile(Object licenseHeaderFile) {
licenseHeaderFile(licenseHeaderFile, LICENSE_HEADER_DELIMITER);
}
public void importOrder(List<String> importOrder) {
customLazy(ImportSorterStep.NAME, () -> new ImportSorterStep(importOrder)::format);
}
public void importOrderFile(Object importOrderFile) {
customLazy(ImportSorterStep.NAME, () -> new ImportSorterStep(getProject().file(importOrderFile))::format);
}
public void eclipseFormatFile(Object eclipseFormatFile) {
customLazy(EclipseFormatterStep.NAME, () -> EclipseFormatterStep.load(getProject().file(eclipseFormatFile))::format);
}
/** If the user hasn't specified the files yet, we'll assume he/she means all of the java files. */
@Override
protected void setupTask(FormatTask task) throws Exception {
if (target == null) {
JavaPluginConvention javaPlugin = getProject().getConvention().getPlugin(JavaPluginConvention.class);
if (javaPlugin == null) {
throw new GradleException("Must apply the java plugin before you apply the spotless plugin.");
}
UnionFileCollection union = new UnionFileCollection();
for (SourceSet sourceSet : javaPlugin.getSourceSets()) {
union.add(sourceSet.getJava());
}
target = union;
}
super.setupTask(task);
}
}
| Improved the error message in the JavaExtension plugin. | src/main/java/com/diffplug/gradle/spotless/java/JavaExtension.java | Improved the error message in the JavaExtension plugin. | <ide><path>rc/main/java/com/diffplug/gradle/spotless/java/JavaExtension.java
<ide> if (target == null) {
<ide> JavaPluginConvention javaPlugin = getProject().getConvention().getPlugin(JavaPluginConvention.class);
<ide> if (javaPlugin == null) {
<del> throw new GradleException("Must apply the java plugin before you apply the spotless plugin.");
<add> throw new GradleException("You must apply the java plugin before the spotless plugin if you are using the java extension.");
<ide> }
<ide> UnionFileCollection union = new UnionFileCollection();
<ide> for (SourceSet sourceSet : javaPlugin.getSourceSets()) { |
|
Java | epl-1.0 | 13839c9314e5b28b07e2ad102a36304c9d33efbd | 0 | boniatillo-com/PhaserEditor,boniatillo-com/PhaserEditor,boniatillo-com/PhaserEditor,boniatillo-com/PhaserEditor,boniatillo-com/PhaserEditor,boniatillo-com/PhaserEditor | // The MIT License (MIT)
//
// Copyright (c) 2015, 2018 Arian Fornaris
//
// 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 phasereditor.scene.ui.editor.properties;
import java.util.function.Function;
import org.eclipse.core.commands.operations.IUndoableOperation;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.Text;
import phasereditor.assetpack.core.AssetFinder;
import phasereditor.inspect.core.InspectCore;
import phasereditor.scene.core.ObjectModel;
import phasereditor.scene.core.PackReferencesCollector;
import phasereditor.scene.core.SceneModel;
import phasereditor.scene.ui.editor.SceneEditor;
import phasereditor.scene.ui.editor.messages.LoadAssetsMessage;
import phasereditor.scene.ui.editor.messages.ResetSceneMessage;
import phasereditor.scene.ui.editor.messages.SelectObjectsMessage;
import phasereditor.scene.ui.editor.messages.UpdateObjectsMessage;
import phasereditor.scene.ui.editor.undo.SingleObjectSnapshotOperation;
import phasereditor.scene.ui.editor.undo.WorldSnapshotOperation;
import phasereditor.ui.properties.CheckListener;
import phasereditor.ui.properties.FormPropertyPage;
import phasereditor.ui.properties.FormPropertySection;
import phasereditor.ui.properties.ScaleListener;
/**
* @author arian
*
*/
public abstract class ScenePropertySection extends FormPropertySection<ObjectModel> {
private FormPropertyPage _page;
public ScenePropertySection(String name, FormPropertyPage page) {
super(name);
_page = page;
}
public FormPropertyPage getPage() {
return _page;
}
public SceneEditor getEditor() {
return ((ScenePropertyPage) _page).getEditor();
}
public AssetFinder getAssetFinder() {
return getEditor().getAssetFinder();
}
public SceneModel getSceneModel() {
return getEditor().getSceneModel();
}
protected abstract class SceneText extends phasereditor.ui.properties.TextListener {
protected boolean dirtyModels;
protected Function<ObjectModel, Boolean> filterDirtyModels;
public SceneText(Text widget) {
super(widget);
dirtyModels = false;
filterDirtyModels = null;
}
@Override
protected void accept(String value) {
wrapOperation(() -> accept2(value));
}
protected abstract void accept2(String value);
}
protected abstract class SceneTextToFloat extends phasereditor.ui.properties.TextToFloatListener {
protected boolean dirtyModels;
protected Function<ObjectModel, Boolean> filterDirtyModels;
public SceneTextToFloat(Text widget) {
super(widget);
dirtyModels = false;
filterDirtyModels = null;
}
@Override
protected void accept(float value) {
wrapOperation(() -> accept2(value));
}
protected abstract void accept2(float value);
}
protected abstract class SceneTextToInt extends phasereditor.ui.properties.TextToIntListener {
protected boolean dirtyModels;
protected Function<ObjectModel, Boolean> filterDirtyModels;
public SceneTextToInt(Text widget) {
super(widget);
dirtyModels = false;
filterDirtyModels = null;
}
@Override
protected void accept(int value) {
wrapOperation(() -> accept2(value));
}
protected abstract void accept2(int value);
}
protected void wrapOperation(Runnable run) {
var models = getModels();
var beforeData = SingleObjectSnapshotOperation.takeSnapshot(models);
run.run();
var afterData = SingleObjectSnapshotOperation.takeSnapshot(models);
getEditor().executeOperation(new SingleObjectSnapshotOperation(beforeData, afterData, "Change object property"));
getEditor().getBroker().sendAll(UpdateObjectsMessage.createFromSnapshot(afterData));
}
protected void wrapWorldOperation(Runnable run) {
var editor = getEditor();
var collector = new PackReferencesCollector(editor.getSceneModel(), editor.getAssetFinder());
var packData = collector.collectNewPack(() -> {
var beforeData = WorldSnapshotOperation.takeSnapshot(getEditor());
run.run();
var afterData = WorldSnapshotOperation.takeSnapshot(getEditor());
IUndoableOperation op = new WorldSnapshotOperation(beforeData, afterData, "Change object property");
getEditor().executeOperation(op);
});
editor.getBroker().sendAllBatch(
new LoadAssetsMessage(packData),
new ResetSceneMessage(editor),
new SelectObjectsMessage(editor)
);
}
protected abstract class SceneCheckListener extends CheckListener {
public SceneCheckListener(Button button) {
super(button);
}
@Override
protected void accept(boolean value) {
wrapOperation(() -> accept2(value));
getEditor().setDirty(true);
}
protected abstract void accept2(boolean value);
}
protected abstract class SceneScaleListener extends ScaleListener {
public SceneScaleListener(Scale scale) {
super(scale);
}
@Override
protected void accept(float value) {
wrapOperation(() -> accept2(value));
}
protected abstract void accept2(float value);
}
@Override
protected String getHelp(String helpHint) {
if (helpHint.startsWith("*")) {
return helpHint.substring(1);
}
return InspectCore.getPhaserHelp().getMemberHelp(helpHint);
}
}
| source/v2/phasereditor/phasereditor.scene.ui.editor/src/phasereditor/scene/ui/editor/properties/ScenePropertySection.java | // The MIT License (MIT)
//
// Copyright (c) 2015, 2018 Arian Fornaris
//
// 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 phasereditor.scene.ui.editor.properties;
import java.util.function.Function;
import org.eclipse.core.commands.operations.IUndoableOperation;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.Text;
import phasereditor.assetpack.core.AssetFinder;
import phasereditor.inspect.core.InspectCore;
import phasereditor.scene.core.ObjectModel;
import phasereditor.scene.core.PackReferencesCollector;
import phasereditor.scene.core.SceneModel;
import phasereditor.scene.ui.editor.SceneEditor;
import phasereditor.scene.ui.editor.messages.LoadAssetsMessage;
import phasereditor.scene.ui.editor.messages.ResetSceneMessage;
import phasereditor.scene.ui.editor.messages.SelectObjectsMessage;
import phasereditor.scene.ui.editor.messages.UpdateObjectsMessage;
import phasereditor.scene.ui.editor.undo.SingleObjectSnapshotOperation;
import phasereditor.scene.ui.editor.undo.WorldSnapshotOperation;
import phasereditor.ui.properties.CheckListener;
import phasereditor.ui.properties.FormPropertyPage;
import phasereditor.ui.properties.FormPropertySection;
import phasereditor.ui.properties.ScaleListener;
/**
* @author arian
*
*/
public abstract class ScenePropertySection extends FormPropertySection<ObjectModel> {
private FormPropertyPage _page;
public ScenePropertySection(String name, FormPropertyPage page) {
super(name);
_page = page;
}
public FormPropertyPage getPage() {
return _page;
}
public SceneEditor getEditor() {
return ((ScenePropertyPage) _page).getEditor();
}
public AssetFinder getAssetFinder() {
return getEditor().getAssetFinder();
}
public SceneModel getSceneModel() {
return getEditor().getSceneModel();
}
protected abstract class SceneText extends phasereditor.ui.properties.TextListener {
protected boolean dirtyModels;
protected Function<ObjectModel, Boolean> filterDirtyModels;
public SceneText(Text widget) {
super(widget);
dirtyModels = false;
filterDirtyModels = null;
}
@Override
protected void accept(String value) {
wrapOperation(() -> accept2(value));
}
protected abstract void accept2(String value);
}
protected abstract class SceneTextToFloat extends phasereditor.ui.properties.TextToFloatListener {
protected boolean dirtyModels;
protected Function<ObjectModel, Boolean> filterDirtyModels;
public SceneTextToFloat(Text widget) {
super(widget);
dirtyModels = false;
filterDirtyModels = null;
}
@Override
protected void accept(float value) {
wrapOperation(() -> accept2(value));
}
protected abstract void accept2(float value);
}
protected abstract class SceneTextToInt extends phasereditor.ui.properties.TextToIntListener {
protected boolean dirtyModels;
protected Function<ObjectModel, Boolean> filterDirtyModels;
public SceneTextToInt(Text widget) {
super(widget);
dirtyModels = false;
filterDirtyModels = null;
}
@Override
protected void accept(int value) {
wrapOperation(() -> accept2(value));
}
protected abstract void accept2(int value);
}
protected void wrapOperation(Runnable run) {
var models = getModels();
var beforeData = SingleObjectSnapshotOperation.takeSnapshot(models);
run.run();
var afterData = SingleObjectSnapshotOperation.takeSnapshot(models);
getEditor().executeOperation(new SingleObjectSnapshotOperation(beforeData, afterData, "Change object property"));
getEditor().getBroker().sendAll(UpdateObjectsMessage.createFromSnapshot(afterData));
}
protected void wrapWorldOperation(Runnable run) {
var editor = getEditor();
var collector = new PackReferencesCollector(editor.getSceneModel(), editor.getAssetFinder());
var packData = collector.collectNewPack(() -> {
var beforeData = WorldSnapshotOperation.takeSnapshot(getEditor());
run.run();
var afterData = WorldSnapshotOperation.takeSnapshot(getEditor());
IUndoableOperation op = new WorldSnapshotOperation(beforeData, afterData, "Change object property");
getEditor().executeOperation(op);
});
editor.getBroker().sendAllBatch(
new LoadAssetsMessage(packData),
new ResetSceneMessage(editor),
new SelectObjectsMessage(editor)
);
}
protected abstract class SceneCheckListener extends CheckListener {
public SceneCheckListener(Button button) {
super(button);
}
@Override
protected void accept(boolean value) {
wrapOperation(() -> accept2(value));
getEditor().setDirty(value);
}
protected abstract void accept2(boolean value);
}
protected abstract class SceneScaleListener extends ScaleListener {
public SceneScaleListener(Scale scale) {
super(scale);
}
@Override
protected void accept(float value) {
wrapOperation(() -> accept2(value));
}
protected abstract void accept2(float value);
}
@Override
protected String getHelp(String helpHint) {
if (helpHint.startsWith("*")) {
return helpHint.substring(1);
}
return InspectCore.getPhaserHelp().getMemberHelp(helpHint);
}
}
| Fixes scene editor properties bug. | source/v2/phasereditor/phasereditor.scene.ui.editor/src/phasereditor/scene/ui/editor/properties/ScenePropertySection.java | Fixes scene editor properties bug. | <ide><path>ource/v2/phasereditor/phasereditor.scene.ui.editor/src/phasereditor/scene/ui/editor/properties/ScenePropertySection.java
<ide> @Override
<ide> protected void accept(boolean value) {
<ide> wrapOperation(() -> accept2(value));
<del> getEditor().setDirty(value);
<add> getEditor().setDirty(true);
<ide> }
<ide>
<ide> protected abstract void accept2(boolean value); |
|
Java | agpl-3.0 | a9efa547076c7cd1af9e09c45c7d45ddbd4b585e | 0 | mnlipp/jgrapes,mnlipp/jgrapes | /*
* JGrapes Event Driven Framework
* Copyright (C) 2017 Michael N. Lipp
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package org.jgrapes.http.demo.httpserver;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Components;
import org.jgrapes.core.Event;
import org.jgrapes.core.Manager;
import org.jgrapes.core.annotation.Handler;
import org.jgrapes.io.IOSubchannel;
import org.jgrapes.portal.AbstractPortlet;
import org.jgrapes.portal.PortalView;
import org.jgrapes.portal.events.AddPortletResources;
import org.jgrapes.portal.events.PortalReady;
import org.jgrapes.portal.events.RenderPortletFromProvider;
import org.jgrapes.portal.events.RenderPortletRequest;
import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;
import static org.jgrapes.portal.Portlet.*;
import java.io.IOException;
/**
*
*/
public class HelloWorldPortlet extends AbstractPortlet {
private String portletId;
/**
* Creates a new component with its channel set to
* itself.
*/
public HelloWorldPortlet() {
this(Channel.SELF);
}
/**
* Creates a new component with its channel set to the given
* channel.
*
* @param componentChannel the channel that the component's
* handlers listen on by default and that
* {@link Manager#fire(Event, Channel...)} sends the event to
*/
public HelloWorldPortlet(Channel componentChannel) {
super(componentChannel);
portletId = Components.objectFullName(this);
}
@Handler
public void onPortalReady(PortalReady event, IOSubchannel channel)
throws TemplateNotFoundException, MalformedTemplateNameException,
ParseException, IOException {
channel.respond(new AddPortletResources(getClass().getName())
.addScript(PortalView.uriFromPath("HelloWorld-functions.js"))
.addCss(PortalView.uriFromPath("HelloWorld-style.css")));
Template tpl = freemarkerConfig().getTemplate("HelloWorld-preview.ftlh");
channel.respond(new RenderPortletFromProvider(
portletId, "Hello World", RenderMode.Preview,
VIEWABLE_PORTLET_MODES, newContentProvider(
tpl, freemarkerModel(event.renderSupport()))));
}
@Handler
public void onRenderPortletRequest(RenderPortletRequest event,
IOSubchannel channel)
throws TemplateNotFoundException,
MalformedTemplateNameException, ParseException,
IOException {
if (!event.portletId().equals(portletId)) {
return;
}
event.stop();
Template tpl = freemarkerConfig().getTemplate("HelloWorld-view.ftlh");
channel.respond(new RenderPortletFromProvider(
portletId, "Hello World", RenderMode.View,
VIEWABLE_PORTLET_MODES, newContentProvider(
tpl, freemarkerModel(event.renderSupport()))));
}
}
| HttpServerDemo/src/org/jgrapes/http/demo/httpserver/HelloWorldPortlet.java | /*
* JGrapes Event Driven Framework
* Copyright (C) 2017 Michael N. Lipp
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package org.jgrapes.http.demo.httpserver;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Components;
import org.jgrapes.core.Event;
import org.jgrapes.core.Manager;
import org.jgrapes.core.annotation.Handler;
import org.jgrapes.io.IOSubchannel;
import org.jgrapes.portal.AbstractPortlet;
import org.jgrapes.portal.PortalView;
import org.jgrapes.portal.events.AddPortletResources;
import org.jgrapes.portal.events.PortalReady;
import org.jgrapes.portal.events.RenderPortletFromProvider;
import org.jgrapes.portal.events.RenderPortletFromString;
import org.jgrapes.portal.events.RenderPortletRequest;
import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;
import static org.jgrapes.portal.Portlet.*;
import java.io.IOException;
/**
*
*/
public class HelloWorldPortlet extends AbstractPortlet {
private String portletId;
/**
* Creates a new component with its channel set to
* itself.
*/
public HelloWorldPortlet() {
this(Channel.SELF);
}
/**
* Creates a new component with its channel set to the given
* channel.
*
* @param componentChannel the channel that the component's
* handlers listen on by default and that
* {@link Manager#fire(Event, Channel...)} sends the event to
*/
public HelloWorldPortlet(Channel componentChannel) {
super(componentChannel);
portletId = Components.objectFullName(this);
}
@Handler
public void onPortalReady(PortalReady event, IOSubchannel channel)
throws TemplateNotFoundException, MalformedTemplateNameException,
ParseException, IOException {
channel.respond(new AddPortletResources(getClass().getName())
.addScript(PortalView.uriFromPath("HelloWorld-functions.js"))
.addCss(PortalView.uriFromPath("HelloWorld-style.css")));
Template tpl = freemarkerConfig().getTemplate("HelloWorld-preview.ftlh");
channel.respond(new RenderPortletFromProvider(
portletId, "Hello World", RenderMode.Preview,
VIEWABLE_PORTLET_MODES, newContentProvider(
tpl, freemarkerModel(event.renderSupport()))));
}
@Handler
public void onRenderPortletRequest(RenderPortletRequest event,
IOSubchannel channel)
throws TemplateNotFoundException,
MalformedTemplateNameException, ParseException,
IOException {
if (!event.portletId().equals(portletId)) {
return;
}
event.stop();
Template tpl = freemarkerConfig().getTemplate("HelloWorld-view.ftlh");
channel.respond(new RenderPortletFromProvider(
portletId, "Hello World", RenderMode.View,
VIEWABLE_PORTLET_MODES, newContentProvider(
tpl, freemarkerModel(event.renderSupport()))));
}
}
| Removed superfluous import. | HttpServerDemo/src/org/jgrapes/http/demo/httpserver/HelloWorldPortlet.java | Removed superfluous import. | <ide><path>ttpServerDemo/src/org/jgrapes/http/demo/httpserver/HelloWorldPortlet.java
<ide> import org.jgrapes.portal.events.AddPortletResources;
<ide> import org.jgrapes.portal.events.PortalReady;
<ide> import org.jgrapes.portal.events.RenderPortletFromProvider;
<del>import org.jgrapes.portal.events.RenderPortletFromString;
<ide> import org.jgrapes.portal.events.RenderPortletRequest;
<ide>
<ide> import freemarker.core.ParseException; |
|
Java | bsd-3-clause | ed907e5d9aeeb19fec8787430ff3cf8f5766cf39 | 0 | erasche/Apollo,erasche/Apollo,erasche/Apollo,erasche/Apollo,erasche/Apollo | package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.*;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.builder.shared.DivBuilder;
import com.google.gwt.dom.builder.shared.TableCellBuilder;
import com.google.gwt.dom.builder.shared.TableRowBuilder;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.http.client.*;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.SequenceInfo;
import org.bbop.apollo.gwt.client.event.*;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.SequenceRestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.bbop.apollo.gwt.shared.PermissionEnum;
import org.gwtbootstrap3.client.shared.event.TabEvent;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.CheckBox;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.constants.ButtonType;
import org.gwtbootstrap3.client.ui.constants.IconType;
import java.util.*;
/**
* Created by ndunn on 12/17/14.
*/
public class AnnotatorPanel extends Composite {
interface AnnotatorPanelUiBinder extends UiBinder<com.google.gwt.user.client.ui.Widget, AnnotatorPanel> {
}
private static AnnotatorPanelUiBinder ourUiBinder = GWT.create(AnnotatorPanelUiBinder.class);
Dictionary dictionary = Dictionary.getDictionary("Options");
String rootUrl = dictionary.get("rootUrl");
private String selectedSequenceName = null;
private Column<AnnotationInfo, String> nameColumn;
// private TextColumn<AnnotationInfo> filterColumn;
private TextColumn<AnnotationInfo> typeColumn;
private Column<AnnotationInfo, Number> lengthColumn;
long requestIndex = 0 ;
@UiField
TextBox nameSearchBox;
@UiField(provided = true)
SuggestBox sequenceList;
// Tree.Resources tablecss = GWT.create(Tree.Resources.class);
// @UiField(provided = true)
// Tree features = new Tree(tablecss);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<AnnotationInfo> dataGrid = new DataGrid<>(10, tablecss);
@UiField(provided = true)
SimplePager pager = null;
@UiField
ListBox typeList;
@UiField
static GeneDetailPanel geneDetailPanel;
@UiField
static TranscriptDetailPanel transcriptDetailPanel;
@UiField
static ExonDetailPanel exonDetailPanel;
@UiField
static TabLayoutPanel tabPanel;
@UiField
Button cdsButton;
@UiField
Button stopCodonButton;
// @UiField
// ListBox userField;
// @UiField
// ListBox groupField;
private MultiWordSuggestOracle sequenceOracle = new MultiWordSuggestOracle();
private static ListDataProvider<AnnotationInfo> dataProvider = new ListDataProvider<>();
private static List<AnnotationInfo> annotationInfoList = new ArrayList<>();
private static List<AnnotationInfo> filteredAnnotationList = dataProvider.getList();
// private List<AnnotationInfo> filteredAnnotationList = dataProvider.getList();
private final Set<String> showingTranscripts = new HashSet<String>();
private SingleSelectionModel<AnnotationInfo> selectionModel = new SingleSelectionModel<>();
private static Boolean transcriptSelected ;
public AnnotatorPanel() {
pager = new SimplePager(SimplePager.TextLocation.CENTER);
sequenceList = new SuggestBox(sequenceOracle);
sequenceList.getElement().setAttribute("placeHolder", "All Reference Sequences");
dataGrid.setWidth("100%");
// dataGrid.setEmptyTableWidget(new Label("Loading"));
initializeTable();
dataGrid.setTableBuilder(new CustomTableBuilder());
dataProvider.addDataDisplay(dataGrid);
pager.setDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
if (transcriptSelected) {
transcriptSelected = false;
return;
}
AnnotationInfo annotationInfo = selectionModel.getSelectedObject();
GWT.log(selectionModel.getSelectedObject().getName());
updateAnnotationInfo(annotationInfo);
}
});
exportStaticMethod(this);
initWidget(ourUiBinder.createAndBindUi(this));
initializeTypes();
initializeUsers();
initializeGroups();
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
exonDetailPanel.redrawExonTable();
}
});
Annotator.eventBus.addHandler(ContextSwitchEvent.TYPE, new ContextSwitchEventHandler() {
@Override
public void onContextSwitched(ContextSwitchEvent contextSwitchEvent) {
selectedSequenceName = contextSwitchEvent.getSequenceInfo().getName();
sequenceList.setText(selectedSequenceName);
loadSequences();
annotationInfoList.clear();
filterList();
// sequenceList.setText(contextSwitchEvent.getSequenceInfo().getName());
}
});
Annotator.eventBus.addHandler(AnnotationInfoChangeEvent.TYPE, new AnnotationInfoChangeEventHandler() {
@Override
public void onAnnotationChanged(AnnotationInfoChangeEvent annotationInfoChangeEvent) {
reload();
}
});
Annotator.eventBus.addHandler(UserChangeEvent.TYPE,
new UserChangeEventHandler() {
@Override
public void onUserChanged(UserChangeEvent authenticationEvent) {
switch(authenticationEvent.getAction()){
case PERMISSION_CHANGED:
PermissionEnum hiPermissionEnum = authenticationEvent.getHighestPermission();
if(MainPanel.isCurrentUserAdmin()){
hiPermissionEnum = PermissionEnum.ADMINISTRATE;
}
boolean editable = false;
switch(hiPermissionEnum){
case ADMINISTRATE:
case WRITE:
editable = true ;
break;
// default is false
}
transcriptDetailPanel.setEditable(editable);
geneDetailPanel.setEditable(editable);
exonDetailPanel.setEditable(editable);
reload();
break;
}
}
}
);
}
private void initializeGroups() {
// groupField.addItem("All Groups");
}
private void initializeUsers() {
// userField.addItem("All Users");
}
private void initializeTypes() {
typeList.addItem("All Types", "");
typeList.addItem("Gene");
typeList.addItem("Pseudogene");
typeList.addItem("mRNA");
typeList.addItem("ncRNA");
typeList.addItem("tRNA");
// TODO: add rest
}
private static void updateAnnotationInfo(AnnotationInfo annotationInfo) {
String type = annotationInfo.getType();
GWT.log("annoation type: " + type);
geneDetailPanel.setVisible(false);
transcriptDetailPanel.setVisible(false);
switch (type) {
case "gene":
case "pseduogene":
geneDetailPanel.updateData(annotationInfo);
// exonDetailPanel.setVisible(false);
tabPanel.getTabWidget(1).getParent().setVisible(false);
tabPanel.selectTab(0);
break;
case "mRNA":
case "tRNA":
transcriptDetailPanel.updateData(annotationInfo);
tabPanel.getTabWidget(1).getParent().setVisible(true);
exonDetailPanel.updateData(annotationInfo);
// exonDetailPanel.setVisible(true);
break;
// case "exon":
// exonDetailPanel.updateData(annotationInfo);
// break;
// case "CDS":
// cdsDetailPanel.updateDetailData(AnnotationRestService.convertAnnotationInfoToJSONObject(annotationInfo));
// break;
default:
GWT.log("not sure what to do with " + type);
}
}
@UiHandler("stopCodonButton")
// switch betwen states
public void handleStopCodonStuff(ClickEvent clickEvent){
if(stopCodonButton.getIcon().equals(IconType.BAN)){
stopCodonButton.setIcon(IconType.WARNING);
stopCodonButton.setType(ButtonType.WARNING);
}
else
if(stopCodonButton.getIcon().equals(IconType.WARNING)){
stopCodonButton.setIcon(IconType.FILTER);
stopCodonButton.setType(ButtonType.PRIMARY);
}
else{
stopCodonButton.setIcon(IconType.BAN);
stopCodonButton.setType(ButtonType.DEFAULT);
}
filterList();
}
@UiHandler("cdsButton")
// switch betwen states
public void handleCdsStuff(ClickEvent clickEvent){
if(cdsButton.getIcon().equals(IconType.BAN)){
cdsButton.setIcon(IconType.WARNING);
cdsButton.setType(ButtonType.WARNING);
}
else
if(cdsButton.getIcon().equals(IconType.WARNING)){
cdsButton.setIcon(IconType.FILTER);
cdsButton.setType(ButtonType.PRIMARY);
}
else{
cdsButton.setIcon(IconType.BAN);
cdsButton.setType(ButtonType.DEFAULT);
}
filterList();
}
private void initializeTable() {
// View friends.
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
@Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<a href=\"javascript:;\">").appendEscaped(object)
.appendHtmlConstant("</a>");
return sb.toSafeHtml();
}
};
nameColumn = new Column<AnnotationInfo, String>(new ClickableTextCell(anchorRenderer)) {
@Override
public String getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getName();
}
};
nameColumn.setFieldUpdater(new FieldUpdater<AnnotationInfo, String>() {
@Override
public void update(int index, AnnotationInfo annotationInfo, String value) {
if (showingTranscripts.contains(annotationInfo.getUniqueName())) {
showingTranscripts.remove(annotationInfo.getUniqueName());
} else {
showingTranscripts.add(annotationInfo.getUniqueName());
}
// Redraw the modified row.
dataGrid.redrawRow(index);
}
});
nameColumn.setSortable(true);
typeColumn = new TextColumn<AnnotationInfo>() {
@Override
public String getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getType();
}
};
typeColumn.setSortable(true);
lengthColumn = new Column<AnnotationInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getLength();
}
};
lengthColumn.setSortable(true);
// dataGrid.addColumn(nameColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
dataGrid.addColumn(nameColumn, "Name");
dataGrid.addColumn(typeColumn, "Type");
dataGrid.addColumn(lengthColumn, "Length");
// dataGrid.addColumn(filterColumn, "Warnings");
dataGrid.setColumnWidth(0, "50%");
ColumnSortEvent.ListHandler<AnnotationInfo> sortHandler = new ColumnSortEvent.ListHandler<AnnotationInfo>(filteredAnnotationList);
dataGrid.addColumnSortHandler(sortHandler);
// Specify a custom table.
// dataGrid.setTableBuilder(new AnnotationInfoTableBuilder(dataGrid,sortHandler,showingTranscripts));
sortHandler.setComparator(nameColumn, new Comparator<AnnotationInfo>() {
@Override
public int compare(AnnotationInfo o1, AnnotationInfo o2) {
return o1.getName().compareTo(o2.getName());
}
});
sortHandler.setComparator(typeColumn, new Comparator<AnnotationInfo>() {
@Override
public int compare(AnnotationInfo o1, AnnotationInfo o2) {
return o1.getType().compareTo(o2.getType());
}
});
sortHandler.setComparator(lengthColumn, new Comparator<AnnotationInfo>() {
@Override
public int compare(AnnotationInfo o1, AnnotationInfo o2) {
return o1.getLength() - o2.getLength();
}
});
}
private void loadSequences() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
JSONArray array = returnValue.isArray();
if (selectedSequenceName == null && array.size() > 0) {
selectedSequenceName = array.get(0).isObject().get("name").isString().stringValue();
}
sequenceOracle.clear();
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.get(i).isObject();
SequenceInfo sequenceInfo = new SequenceInfo();
sequenceInfo.setName(object.get("name").isString().stringValue());
sequenceInfo.setLength((int) object.get("length").isNumber().isNumber().doubleValue());
sequenceOracle.add(sequenceInfo.getName());
// sequenceList.addItem(sequenceInfo.getName());
if (selectedSequenceName.equals(sequenceInfo.getName())) {
sequenceList.setText(sequenceInfo.getName());
// sequenceList.setSelectedIndex(i);
}
}
// reload();
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("Error loading organisms");
}
};
SequenceRestService.loadSequences(requestCallback, MainPanel.currentOrganismId);
}
private String getType(JSONObject internalData) {
return internalData.get("type").isObject().get("name").isString().stringValue();
}
public void reload() {
if (selectedSequenceName == null) {
selectedSequenceName = MainPanel.currentSequenceId;
loadSequences();
}
String url = rootUrl + "/annotator/findAnnotationsForSequence/?sequenceName=" + selectedSequenceName+"&request="+requestIndex;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
long localRequestValue = (long) returnValue.isObject().get(FeatureStringEnum.REQUEST_INDEX.getValue()).isNumber().doubleValue();
// returns
if(localRequestValue<=requestIndex){
return;
}
else{
requestIndex = localRequestValue ;
}
JSONArray array = returnValue.isObject().get("features").isArray();
annotationInfoList.clear();
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.get(i).isObject();
GWT.log(object.toString());
AnnotationInfo annotationInfo = generateAnnotationInfo(object);
annotationInfoList.add(annotationInfo);
}
// features.setAnimationEnabled(true);
GWT.log("# of annoations: " + filteredAnnotationList.size());
filterList();
dataGrid.redraw();
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("Error loading organisms");
}
};
try {
builder.setCallback(requestCallback);
builder.send();
} catch (RequestException e) {
// Couldn't connect to server
Window.alert(e.getMessage());
}
}
private void filterList() {
filteredAnnotationList.clear();
for(int i = 0 ; i < annotationInfoList.size() ; i++){
AnnotationInfo annotationInfo = annotationInfoList.get(i);
if(searchMatches(annotationInfo)){
filteredAnnotationList.add(annotationInfo);
}
else{
if(searchMatches(annotationInfo.getAnnotationInfoSet())){
filteredAnnotationList.add(annotationInfo);
}
}
}
}
private boolean searchMatches(Set<AnnotationInfo> annotationInfoSet) {
for(AnnotationInfo annotationInfo : annotationInfoSet){
if(searchMatches(annotationInfo)){
return true ;
}
}
return false;
}
private boolean searchMatches(AnnotationInfo annotationInfo) {
String nameText = nameSearchBox.getText() ;
String typeText = typeList.getSelectedValue();
return (
(annotationInfo.getName().toLowerCase().contains(nameText.toLowerCase()))
&&
annotationInfo.getType().toLowerCase().contains(typeText.toLowerCase())
);
}
private AnnotationInfo generateAnnotationInfo(JSONObject object) {
return generateAnnotationInfo(object, true);
}
private AnnotationInfo generateAnnotationInfo(JSONObject object, boolean processChildren) {
AnnotationInfo annotationInfo = new AnnotationInfo();
annotationInfo.setName(object.get("name").isString().stringValue());
GWT.log("top-level processing: " + annotationInfo.getName());
annotationInfo.setType(object.get("type").isObject().get("name").isString().stringValue());
if(object.get("symbol")!=null){
annotationInfo.setSymbol(object.get("symbol").isString().stringValue());
}
if(object.get("description")!=null){
annotationInfo.setDescription(object.get("description").isString().stringValue());
}
annotationInfo.setMin((int) object.get("location").isObject().get("fmin").isNumber().doubleValue());
annotationInfo.setMax((int) object.get("location").isObject().get("fmax").isNumber().doubleValue());
annotationInfo.setStrand((int) object.get("location").isObject().get("strand").isNumber().doubleValue());
annotationInfo.setUniqueName(object.get("uniquename").isString().stringValue());
annotationInfo.setSequence(object.get("sequence").isString().stringValue());
if(object.get("owner")!=null){
annotationInfo.setOwner(object.get("owner").isString().stringValue());
}
List<String> noteList = new ArrayList<>();
if(object.get("notes")!=null){
JSONArray jsonArray = object.get("notes").isArray();
for(int i = 0 ; i< jsonArray.size() ; i++){
String note = jsonArray.get(i).isString().stringValue();
noteList.add(note) ;
}
}
annotationInfo.setNoteList(noteList);
if (processChildren && object.get("children") != null) {
JSONArray jsonArray = object.get("children").isArray();
for (int i = 0; i < jsonArray.size(); i++) {
AnnotationInfo childAnnotation = generateAnnotationInfo(jsonArray.get(i).isObject(), true);
annotationInfo.addChildAnnotation(childAnnotation);
}
}
return annotationInfo;
}
@UiHandler("typeList")
public void searchType(ChangeEvent changeEvent){
filterList();
}
@UiHandler("nameSearchBox")
public void searchName(KeyUpEvent keyUpEvent){
filterList();
}
@UiHandler("sequenceList")
public void changeRefSequence(KeyUpEvent changeEvent) {
selectedSequenceName = sequenceList.getText();
reload();
}
// TODO: need to cache these or retrieve from the backend
public static void displayTranscript(int geneIndex, String uniqueName) {
transcriptSelected = true ;
// 1 - get the correct gene
AnnotationInfo annotationInfo = filteredAnnotationList.get(geneIndex);
AnnotationInfoChangeEvent annotationInfoChangeEvent = new AnnotationInfoChangeEvent(annotationInfo, AnnotationInfoChangeEvent.Action.SET_FOCUS);
for (AnnotationInfo childAnnotation : annotationInfo.getAnnotationInfoSet()) {
if (childAnnotation.getUniqueName().equalsIgnoreCase(uniqueName)) {
exonDetailPanel.updateData(childAnnotation);
updateAnnotationInfo(childAnnotation);
Annotator.eventBus.fireEvent(annotationInfoChangeEvent);
return;
}
}
}
public static native void exportStaticMethod(AnnotatorPanel annotatorPanel) /*-{
$wnd.displayTranscript = $entry(@org.bbop.apollo.gwt.client.AnnotatorPanel::displayTranscript(ILjava/lang/String;));
}-*/;
private class CustomTableBuilder extends AbstractCellTableBuilder<AnnotationInfo> {
// TODO: delete this .. just for demo version
Random random = new Random();
public CustomTableBuilder() {
super(dataGrid);
}
@Override
protected void buildRowImpl(AnnotationInfo rowValue, int absRowIndex) {
buildAnnotationRow(rowValue, absRowIndex, false);
if (showingTranscripts.contains(rowValue.getUniqueName())) {
// add some random rows
Set<AnnotationInfo> annotationInfoSet = rowValue.getAnnotationInfoSet();
if (annotationInfoSet.size() > 0) {
for (AnnotationInfo annotationInfo : annotationInfoSet) {
buildAnnotationRow(annotationInfo, absRowIndex, true);
}
}
}
}
private void buildAnnotationRow(final AnnotationInfo rowValue, int absRowIndex, boolean showTranscripts) {
// final SingleSelectionModel<AnnotationInfo> selectionModel = (SingleSelectionModel<AnnotationInfo>) dataGrid.getSelectionModel();
TableRowBuilder row = startRow();
TableCellBuilder td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
// TODO: this is ugly, but it works
// a custom cell rendering might work as well, but not sure
String transcriptStyle = "margin-left: 10px; color: green; padding-left: 5px; padding-right: 5px; border-radius: 15px; background-color: #EEEEEE;";
HTML html = new HTML("<a style='" + transcriptStyle + "' onclick=\"displayTranscript(" + absRowIndex + ",'" + rowValue.getUniqueName() + "');\">" + rowValue.getName() + "</a>");
SafeHtml htmlString = new SafeHtmlBuilder().appendHtmlConstant(html.getHTML()).toSafeHtml();
// updateAnnotationInfo(rowValue);
td.html(htmlString);
} else {
renderCell(td, createContext(0), nameColumn, rowValue);
}
td.endTD();
// Type column.
td = row.startTD();
// td.className(cellStyles);
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
DivBuilder div = td.startDiv();
div.style().trustedColor("green").endStyle();
div.text(rowValue.getType());
td.endDiv();
} else {
renderCell(td, createContext(1), typeColumn, rowValue);
}
td.endTD();
// Length column.
td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
DivBuilder div = td.startDiv();
div.style().trustedColor("green").endStyle();
div.text(NumberFormat.getDecimalFormat().format(rowValue.getLength()));
td.endDiv();
td.endTD();
} else {
td.text(NumberFormat.getDecimalFormat().format(rowValue.getLength())).endTD();
}
td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
// TODO: is it necessary to have two separte ones?
// if(showTranscripts){
DivBuilder div = td.startDiv();
SafeHtmlBuilder safeHtmlBuilder = new SafeHtmlBuilder();
for(String error : rowValue.getNoteList()){
safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>"+error+"</div>");
}
// if(random.nextBoolean()){
// safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>CDS-3</div>");
// }
// else
// if(random.nextBoolean()){
// safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>Stop Codon</div>");
// }
// else{
//// safeHtmlBuilder.appendHtmlConstant("<pre>abcd</pre>");
// }
div.html(safeHtmlBuilder.toSafeHtml());
td.endDiv();
td.endTD();
// }
// else{
// DivBuilder div = td.startDiv();
// SafeHtmlBuilder safeHtmlBuilder = new SafeHtmlBuilder();
//
// if(random.nextBoolean()){
// safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>CDS-3</div>");
// }
// else
// if(random.nextBoolean()){
// safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>Stop Codon</div>");
// }
// else{
//// safeHtmlBuilder.appendHtmlConstant("<pre>abcd</pre>");
// }
//
// div.html(safeHtmlBuilder.toSafeHtml());
// td.endDiv();
// td.endTD();
// }
// row.endTD();
row.endTR();
}
}
} | src/gwt/org/bbop/apollo/gwt/client/AnnotatorPanel.java | package org.bbop.apollo.gwt.client;
import com.google.gwt.cell.client.*;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.builder.shared.DivBuilder;
import com.google.gwt.dom.builder.shared.TableCellBuilder;
import com.google.gwt.dom.builder.shared.TableRowBuilder;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.http.client.*;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.*;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import org.bbop.apollo.gwt.client.dto.AnnotationInfo;
import org.bbop.apollo.gwt.client.dto.SequenceInfo;
import org.bbop.apollo.gwt.client.event.*;
import org.bbop.apollo.gwt.client.resources.TableResources;
import org.bbop.apollo.gwt.client.rest.SequenceRestService;
import org.bbop.apollo.gwt.shared.FeatureStringEnum;
import org.bbop.apollo.gwt.shared.PermissionEnum;
import org.gwtbootstrap3.client.shared.event.TabEvent;
import org.gwtbootstrap3.client.ui.*;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.CheckBox;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.constants.ButtonType;
import org.gwtbootstrap3.client.ui.constants.IconType;
import java.util.*;
/**
* Created by ndunn on 12/17/14.
*/
public class AnnotatorPanel extends Composite {
interface AnnotatorPanelUiBinder extends UiBinder<com.google.gwt.user.client.ui.Widget, AnnotatorPanel> {
}
private static AnnotatorPanelUiBinder ourUiBinder = GWT.create(AnnotatorPanelUiBinder.class);
Dictionary dictionary = Dictionary.getDictionary("Options");
String rootUrl = dictionary.get("rootUrl");
private String selectedSequenceName = null;
private Column<AnnotationInfo, String> nameColumn;
// private TextColumn<AnnotationInfo> filterColumn;
private TextColumn<AnnotationInfo> typeColumn;
private Column<AnnotationInfo, Number> lengthColumn;
long requestIndex = 0 ;
@UiField
TextBox nameSearchBox;
@UiField(provided = true)
SuggestBox sequenceList;
// Tree.Resources tablecss = GWT.create(Tree.Resources.class);
// @UiField(provided = true)
// Tree features = new Tree(tablecss);
DataGrid.Resources tablecss = GWT.create(TableResources.TableCss.class);
@UiField(provided = true)
DataGrid<AnnotationInfo> dataGrid = new DataGrid<>(10, tablecss);
@UiField(provided = true)
SimplePager pager = null;
@UiField
ListBox typeList;
@UiField
static GeneDetailPanel geneDetailPanel;
@UiField
static TranscriptDetailPanel transcriptDetailPanel;
@UiField
static ExonDetailPanel exonDetailPanel;
@UiField
static TabLayoutPanel tabPanel;
@UiField
Button cdsButton;
@UiField
Button stopCodonButton;
// @UiField
// ListBox userField;
// @UiField
// ListBox groupField;
private MultiWordSuggestOracle sequenceOracle = new MultiWordSuggestOracle();
private static ListDataProvider<AnnotationInfo> dataProvider = new ListDataProvider<>();
private static List<AnnotationInfo> annotationInfoList = new ArrayList<>();
private static List<AnnotationInfo> filteredAnnotationList = dataProvider.getList();
// private List<AnnotationInfo> filteredAnnotationList = dataProvider.getList();
private final Set<String> showingTranscripts = new HashSet<String>();
private SingleSelectionModel<AnnotationInfo> selectionModel = new SingleSelectionModel<>();
private static Boolean transcriptSelected ;
public AnnotatorPanel() {
pager = new SimplePager(SimplePager.TextLocation.CENTER);
sequenceList = new SuggestBox(sequenceOracle);
dataGrid.setWidth("100%");
// dataGrid.setEmptyTableWidget(new Label("Loading"));
initializeTable();
dataGrid.setTableBuilder(new CustomTableBuilder());
dataProvider.addDataDisplay(dataGrid);
pager.setDisplay(dataGrid);
dataGrid.setSelectionModel(selectionModel);
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
if (transcriptSelected) {
transcriptSelected = false;
return;
}
AnnotationInfo annotationInfo = selectionModel.getSelectedObject();
GWT.log(selectionModel.getSelectedObject().getName());
updateAnnotationInfo(annotationInfo);
}
});
exportStaticMethod(this);
initWidget(ourUiBinder.createAndBindUi(this));
initializeTypes();
initializeUsers();
initializeGroups();
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
@Override
public void onSelection(SelectionEvent<Integer> event) {
exonDetailPanel.redrawExonTable();
}
});
Annotator.eventBus.addHandler(ContextSwitchEvent.TYPE, new ContextSwitchEventHandler() {
@Override
public void onContextSwitched(ContextSwitchEvent contextSwitchEvent) {
selectedSequenceName = contextSwitchEvent.getSequenceInfo().getName();
sequenceList.setText(selectedSequenceName);
loadSequences();
annotationInfoList.clear();
filterList();
// sequenceList.setText(contextSwitchEvent.getSequenceInfo().getName());
}
});
Annotator.eventBus.addHandler(AnnotationInfoChangeEvent.TYPE, new AnnotationInfoChangeEventHandler() {
@Override
public void onAnnotationChanged(AnnotationInfoChangeEvent annotationInfoChangeEvent) {
reload();
}
});
Annotator.eventBus.addHandler(UserChangeEvent.TYPE,
new UserChangeEventHandler() {
@Override
public void onUserChanged(UserChangeEvent authenticationEvent) {
switch(authenticationEvent.getAction()){
case PERMISSION_CHANGED:
PermissionEnum hiPermissionEnum = authenticationEvent.getHighestPermission();
if(MainPanel.isCurrentUserAdmin()){
hiPermissionEnum = PermissionEnum.ADMINISTRATE;
}
boolean editable = false;
switch(hiPermissionEnum){
case ADMINISTRATE:
case WRITE:
editable = true ;
break;
// default is false
}
transcriptDetailPanel.setEditable(editable);
geneDetailPanel.setEditable(editable);
exonDetailPanel.setEditable(editable);
reload();
break;
}
}
}
);
}
private void initializeGroups() {
// groupField.addItem("All Groups");
}
private void initializeUsers() {
// userField.addItem("All Users");
}
private void initializeTypes() {
typeList.addItem("All Types", "");
typeList.addItem("Gene");
typeList.addItem("Pseudogene");
typeList.addItem("mRNA");
typeList.addItem("ncRNA");
typeList.addItem("tRNA");
// TODO: add rest
}
private static void updateAnnotationInfo(AnnotationInfo annotationInfo) {
String type = annotationInfo.getType();
GWT.log("annoation type: " + type);
geneDetailPanel.setVisible(false);
transcriptDetailPanel.setVisible(false);
switch (type) {
case "gene":
case "pseduogene":
geneDetailPanel.updateData(annotationInfo);
// exonDetailPanel.setVisible(false);
tabPanel.getTabWidget(1).getParent().setVisible(false);
tabPanel.selectTab(0);
break;
case "mRNA":
case "tRNA":
transcriptDetailPanel.updateData(annotationInfo);
tabPanel.getTabWidget(1).getParent().setVisible(true);
exonDetailPanel.updateData(annotationInfo);
// exonDetailPanel.setVisible(true);
break;
// case "exon":
// exonDetailPanel.updateData(annotationInfo);
// break;
// case "CDS":
// cdsDetailPanel.updateDetailData(AnnotationRestService.convertAnnotationInfoToJSONObject(annotationInfo));
// break;
default:
GWT.log("not sure what to do with " + type);
}
}
@UiHandler("stopCodonButton")
// switch betwen states
public void handleStopCodonStuff(ClickEvent clickEvent){
if(stopCodonButton.getIcon().equals(IconType.BAN)){
stopCodonButton.setIcon(IconType.WARNING);
stopCodonButton.setType(ButtonType.WARNING);
}
else
if(stopCodonButton.getIcon().equals(IconType.WARNING)){
stopCodonButton.setIcon(IconType.FILTER);
stopCodonButton.setType(ButtonType.PRIMARY);
}
else{
stopCodonButton.setIcon(IconType.BAN);
stopCodonButton.setType(ButtonType.DEFAULT);
}
filterList();
}
@UiHandler("cdsButton")
// switch betwen states
public void handleCdsStuff(ClickEvent clickEvent){
if(cdsButton.getIcon().equals(IconType.BAN)){
cdsButton.setIcon(IconType.WARNING);
cdsButton.setType(ButtonType.WARNING);
}
else
if(cdsButton.getIcon().equals(IconType.WARNING)){
cdsButton.setIcon(IconType.FILTER);
cdsButton.setType(ButtonType.PRIMARY);
}
else{
cdsButton.setIcon(IconType.BAN);
cdsButton.setType(ButtonType.DEFAULT);
}
filterList();
}
private void initializeTable() {
// View friends.
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
@Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<a href=\"javascript:;\">").appendEscaped(object)
.appendHtmlConstant("</a>");
return sb.toSafeHtml();
}
};
nameColumn = new Column<AnnotationInfo, String>(new ClickableTextCell(anchorRenderer)) {
@Override
public String getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getName();
}
};
nameColumn.setFieldUpdater(new FieldUpdater<AnnotationInfo, String>() {
@Override
public void update(int index, AnnotationInfo annotationInfo, String value) {
if (showingTranscripts.contains(annotationInfo.getUniqueName())) {
showingTranscripts.remove(annotationInfo.getUniqueName());
} else {
showingTranscripts.add(annotationInfo.getUniqueName());
}
// Redraw the modified row.
dataGrid.redrawRow(index);
}
});
nameColumn.setSortable(true);
typeColumn = new TextColumn<AnnotationInfo>() {
@Override
public String getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getType();
}
};
typeColumn.setSortable(true);
lengthColumn = new Column<AnnotationInfo, Number>(new NumberCell()) {
@Override
public Integer getValue(AnnotationInfo annotationInfo) {
return annotationInfo.getLength();
}
};
lengthColumn.setSortable(true);
// dataGrid.addColumn(nameColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
dataGrid.addColumn(nameColumn, "Name");
dataGrid.addColumn(typeColumn, "Type");
dataGrid.addColumn(lengthColumn, "Length");
// dataGrid.addColumn(filterColumn, "Warnings");
dataGrid.setColumnWidth(0, "50%");
ColumnSortEvent.ListHandler<AnnotationInfo> sortHandler = new ColumnSortEvent.ListHandler<AnnotationInfo>(filteredAnnotationList);
dataGrid.addColumnSortHandler(sortHandler);
// Specify a custom table.
// dataGrid.setTableBuilder(new AnnotationInfoTableBuilder(dataGrid,sortHandler,showingTranscripts));
sortHandler.setComparator(nameColumn, new Comparator<AnnotationInfo>() {
@Override
public int compare(AnnotationInfo o1, AnnotationInfo o2) {
return o1.getName().compareTo(o2.getName());
}
});
sortHandler.setComparator(typeColumn, new Comparator<AnnotationInfo>() {
@Override
public int compare(AnnotationInfo o1, AnnotationInfo o2) {
return o1.getType().compareTo(o2.getType());
}
});
sortHandler.setComparator(lengthColumn, new Comparator<AnnotationInfo>() {
@Override
public int compare(AnnotationInfo o1, AnnotationInfo o2) {
return o1.getLength() - o2.getLength();
}
});
}
private void loadSequences() {
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
JSONArray array = returnValue.isArray();
if (selectedSequenceName == null && array.size() > 0) {
selectedSequenceName = array.get(0).isObject().get("name").isString().stringValue();
}
sequenceOracle.clear();
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.get(i).isObject();
SequenceInfo sequenceInfo = new SequenceInfo();
sequenceInfo.setName(object.get("name").isString().stringValue());
sequenceInfo.setLength((int) object.get("length").isNumber().isNumber().doubleValue());
sequenceOracle.add(sequenceInfo.getName());
// sequenceList.addItem(sequenceInfo.getName());
if (selectedSequenceName.equals(sequenceInfo.getName())) {
sequenceList.setText(sequenceInfo.getName());
// sequenceList.setSelectedIndex(i);
}
}
// reload();
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("Error loading organisms");
}
};
SequenceRestService.loadSequences(requestCallback, MainPanel.currentOrganismId);
}
private String getType(JSONObject internalData) {
return internalData.get("type").isObject().get("name").isString().stringValue();
}
public void reload() {
if (selectedSequenceName == null) {
selectedSequenceName = MainPanel.currentSequenceId;
loadSequences();
}
String url = rootUrl + "/annotator/findAnnotationsForSequence/?sequenceName=" + selectedSequenceName+"&request="+requestIndex;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
RequestCallback requestCallback = new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue returnValue = JSONParser.parseStrict(response.getText());
long localRequestValue = (long) returnValue.isObject().get(FeatureStringEnum.REQUEST_INDEX.getValue()).isNumber().doubleValue();
// returns
if(localRequestValue<=requestIndex){
return;
}
else{
requestIndex = localRequestValue ;
}
JSONArray array = returnValue.isObject().get("features").isArray();
annotationInfoList.clear();
for (int i = 0; i < array.size(); i++) {
JSONObject object = array.get(i).isObject();
GWT.log(object.toString());
AnnotationInfo annotationInfo = generateAnnotationInfo(object);
annotationInfoList.add(annotationInfo);
}
// features.setAnimationEnabled(true);
GWT.log("# of annoations: " + filteredAnnotationList.size());
filterList();
dataGrid.redraw();
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("Error loading organisms");
}
};
try {
builder.setCallback(requestCallback);
builder.send();
} catch (RequestException e) {
// Couldn't connect to server
Window.alert(e.getMessage());
}
}
private void filterList() {
filteredAnnotationList.clear();
for(int i = 0 ; i < annotationInfoList.size() ; i++){
AnnotationInfo annotationInfo = annotationInfoList.get(i);
if(searchMatches(annotationInfo)){
filteredAnnotationList.add(annotationInfo);
}
else{
if(searchMatches(annotationInfo.getAnnotationInfoSet())){
filteredAnnotationList.add(annotationInfo);
}
}
}
}
private boolean searchMatches(Set<AnnotationInfo> annotationInfoSet) {
for(AnnotationInfo annotationInfo : annotationInfoSet){
if(searchMatches(annotationInfo)){
return true ;
}
}
return false;
}
private boolean searchMatches(AnnotationInfo annotationInfo) {
String nameText = nameSearchBox.getText() ;
String typeText = typeList.getSelectedValue();
return (
(annotationInfo.getName().toLowerCase().contains(nameText.toLowerCase()))
&&
annotationInfo.getType().toLowerCase().contains(typeText.toLowerCase())
);
}
private AnnotationInfo generateAnnotationInfo(JSONObject object) {
return generateAnnotationInfo(object, true);
}
private AnnotationInfo generateAnnotationInfo(JSONObject object, boolean processChildren) {
AnnotationInfo annotationInfo = new AnnotationInfo();
annotationInfo.setName(object.get("name").isString().stringValue());
GWT.log("top-level processing: " + annotationInfo.getName());
annotationInfo.setType(object.get("type").isObject().get("name").isString().stringValue());
if(object.get("symbol")!=null){
annotationInfo.setSymbol(object.get("symbol").isString().stringValue());
}
if(object.get("description")!=null){
annotationInfo.setDescription(object.get("description").isString().stringValue());
}
annotationInfo.setMin((int) object.get("location").isObject().get("fmin").isNumber().doubleValue());
annotationInfo.setMax((int) object.get("location").isObject().get("fmax").isNumber().doubleValue());
annotationInfo.setStrand((int) object.get("location").isObject().get("strand").isNumber().doubleValue());
annotationInfo.setUniqueName(object.get("uniquename").isString().stringValue());
annotationInfo.setSequence(object.get("sequence").isString().stringValue());
if(object.get("owner")!=null){
annotationInfo.setOwner(object.get("owner").isString().stringValue());
}
List<String> noteList = new ArrayList<>();
if(object.get("notes")!=null){
JSONArray jsonArray = object.get("notes").isArray();
for(int i = 0 ; i< jsonArray.size() ; i++){
String note = jsonArray.get(i).isString().stringValue();
noteList.add(note) ;
}
}
annotationInfo.setNoteList(noteList);
if (processChildren && object.get("children") != null) {
JSONArray jsonArray = object.get("children").isArray();
for (int i = 0; i < jsonArray.size(); i++) {
AnnotationInfo childAnnotation = generateAnnotationInfo(jsonArray.get(i).isObject(), true);
annotationInfo.addChildAnnotation(childAnnotation);
}
}
return annotationInfo;
}
@UiHandler("typeList")
public void searchType(ChangeEvent changeEvent){
filterList();
}
@UiHandler("nameSearchBox")
public void searchName(KeyUpEvent keyUpEvent){
filterList();
}
@UiHandler("sequenceList")
public void changeRefSequence(KeyUpEvent changeEvent) {
selectedSequenceName = sequenceList.getText();
reload();
}
// TODO: need to cache these or retrieve from the backend
public static void displayTranscript(int geneIndex, String uniqueName) {
transcriptSelected = true ;
// 1 - get the correct gene
AnnotationInfo annotationInfo = filteredAnnotationList.get(geneIndex);
AnnotationInfoChangeEvent annotationInfoChangeEvent = new AnnotationInfoChangeEvent(annotationInfo, AnnotationInfoChangeEvent.Action.SET_FOCUS);
for (AnnotationInfo childAnnotation : annotationInfo.getAnnotationInfoSet()) {
if (childAnnotation.getUniqueName().equalsIgnoreCase(uniqueName)) {
exonDetailPanel.updateData(childAnnotation);
updateAnnotationInfo(childAnnotation);
Annotator.eventBus.fireEvent(annotationInfoChangeEvent);
return;
}
}
}
public static native void exportStaticMethod(AnnotatorPanel annotatorPanel) /*-{
$wnd.displayTranscript = $entry(@org.bbop.apollo.gwt.client.AnnotatorPanel::displayTranscript(ILjava/lang/String;));
}-*/;
private class CustomTableBuilder extends AbstractCellTableBuilder<AnnotationInfo> {
// TODO: delete this .. just for demo version
Random random = new Random();
public CustomTableBuilder() {
super(dataGrid);
}
@Override
protected void buildRowImpl(AnnotationInfo rowValue, int absRowIndex) {
buildAnnotationRow(rowValue, absRowIndex, false);
if (showingTranscripts.contains(rowValue.getUniqueName())) {
// add some random rows
Set<AnnotationInfo> annotationInfoSet = rowValue.getAnnotationInfoSet();
if (annotationInfoSet.size() > 0) {
for (AnnotationInfo annotationInfo : annotationInfoSet) {
buildAnnotationRow(annotationInfo, absRowIndex, true);
}
}
}
}
private void buildAnnotationRow(final AnnotationInfo rowValue, int absRowIndex, boolean showTranscripts) {
// final SingleSelectionModel<AnnotationInfo> selectionModel = (SingleSelectionModel<AnnotationInfo>) dataGrid.getSelectionModel();
TableRowBuilder row = startRow();
TableCellBuilder td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
// TODO: this is ugly, but it works
// a custom cell rendering might work as well, but not sure
String transcriptStyle = "margin-left: 10px; color: green; padding-left: 5px; padding-right: 5px; border-radius: 15px; background-color: #EEEEEE;";
HTML html = new HTML("<a style='" + transcriptStyle + "' onclick=\"displayTranscript(" + absRowIndex + ",'" + rowValue.getUniqueName() + "');\">" + rowValue.getName() + "</a>");
SafeHtml htmlString = new SafeHtmlBuilder().appendHtmlConstant(html.getHTML()).toSafeHtml();
// updateAnnotationInfo(rowValue);
td.html(htmlString);
} else {
renderCell(td, createContext(0), nameColumn, rowValue);
}
td.endTD();
// Type column.
td = row.startTD();
// td.className(cellStyles);
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
DivBuilder div = td.startDiv();
div.style().trustedColor("green").endStyle();
div.text(rowValue.getType());
td.endDiv();
} else {
renderCell(td, createContext(1), typeColumn, rowValue);
}
td.endTD();
// Length column.
td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
if (showTranscripts) {
DivBuilder div = td.startDiv();
div.style().trustedColor("green").endStyle();
div.text(NumberFormat.getDecimalFormat().format(rowValue.getLength()));
td.endDiv();
td.endTD();
} else {
td.text(NumberFormat.getDecimalFormat().format(rowValue.getLength())).endTD();
}
td = row.startTD();
td.style().outlineStyle(Style.OutlineStyle.NONE).endStyle();
// TODO: is it necessary to have two separte ones?
// if(showTranscripts){
DivBuilder div = td.startDiv();
SafeHtmlBuilder safeHtmlBuilder = new SafeHtmlBuilder();
for(String error : rowValue.getNoteList()){
safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>"+error+"</div>");
}
// if(random.nextBoolean()){
// safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>CDS-3</div>");
// }
// else
// if(random.nextBoolean()){
// safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>Stop Codon</div>");
// }
// else{
//// safeHtmlBuilder.appendHtmlConstant("<pre>abcd</pre>");
// }
div.html(safeHtmlBuilder.toSafeHtml());
td.endDiv();
td.endTD();
// }
// else{
// DivBuilder div = td.startDiv();
// SafeHtmlBuilder safeHtmlBuilder = new SafeHtmlBuilder();
//
// if(random.nextBoolean()){
// safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>CDS-3</div>");
// }
// else
// if(random.nextBoolean()){
// safeHtmlBuilder.appendHtmlConstant("<div class='label label-warning'>Stop Codon</div>");
// }
// else{
//// safeHtmlBuilder.appendHtmlConstant("<pre>abcd</pre>");
// }
//
// div.html(safeHtmlBuilder.toSafeHtml());
// td.endDiv();
// td.endTD();
// }
// row.endTD();
row.endTR();
}
}
} | #239 - ref seq placeholder
| src/gwt/org/bbop/apollo/gwt/client/AnnotatorPanel.java | #239 - ref seq placeholder | <ide><path>rc/gwt/org/bbop/apollo/gwt/client/AnnotatorPanel.java
<ide> public AnnotatorPanel() {
<ide> pager = new SimplePager(SimplePager.TextLocation.CENTER);
<ide> sequenceList = new SuggestBox(sequenceOracle);
<add> sequenceList.getElement().setAttribute("placeHolder", "All Reference Sequences");
<ide> dataGrid.setWidth("100%");
<ide>
<ide> // dataGrid.setEmptyTableWidget(new Label("Loading")); |
|
Java | agpl-3.0 | cfb7cbb0fcb3391a3283314ed7f7ef4333088c0b | 0 | aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms,aihua/opennms | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.trapd;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.opennms.core.ipc.sink.api.Message;
import org.opennms.core.network.InetAddressXmlAdapter;
import org.opennms.netmgt.snmp.SnmpResult;
import org.opennms.netmgt.snmp.SnmpVarBindDTO;
import org.opennms.netmgt.snmp.TrapInformation;
import com.google.common.base.MoreObjects;
@XmlRootElement(name = "trap-dto")
@XmlAccessorType(XmlAccessType.NONE)
public class TrapDTO implements Message {
@XmlElement(name = "agent-address")
@XmlJavaTypeAdapter(InetAddressXmlAdapter.class)
private InetAddress agentAddress;
@XmlElement(name = "community")
private String community;
@XmlElement(name = "version", required=true)
private String version;
@XmlElement(name = "timestamp")
private long timestamp;
@XmlElement(name = "pdu-length")
private int pduLength;
@XmlElement(name = "creation-time")
private long creationTime;
@XmlElement(name = "raw-message")
private byte[] rawMessage;
@XmlElement(name = "trap-identity")
private TrapIdentityDTO trapIdentity;
@XmlElementWrapper(name = "results")
@XmlElement(name = "result")
private List<SnmpResult> results = new ArrayList<>();
// No-arg constructor for JAXB
public TrapDTO() {
}
public TrapDTO(TrapInformation trapInfo) {
setAgentAddress(trapInfo.getAgentAddress());
setCommunity(trapInfo.getCommunity());
setVersion(trapInfo.getVersion());
setTimestamp(trapInfo.getTimeStamp());
setPduLength(trapInfo.getPduLength());
setCreationTime(trapInfo.getCreationTime());
setTrapIdentity(new TrapIdentityDTO(trapInfo.getTrapIdentity()));
// Map variable bindings
final List<SnmpResult> results = new ArrayList<>();
for (int i = 0; i < trapInfo.getPduLength(); i++) {
final SnmpVarBindDTO varBindDTO = trapInfo.getSnmpVarBindDTO(i);
if (varBindDTO != null) {
final SnmpResult snmpResult = new SnmpResult(varBindDTO.getSnmpObjectId(), null, varBindDTO.getSnmpValue());
results.add(snmpResult);
}
}
setResults(results);
}
private void setResults(List<SnmpResult> results) {
this.results = new ArrayList<>(results);
}
public void setAgentAddress(InetAddress agentAddress) {
this.agentAddress = agentAddress;
}
public InetAddress getAgentAddress() {
return agentAddress;
}
public void setCommunity(String community) {
this.community = community;
}
public String getCommunity() {
return community;
}
public void setVersion(String version) {
this.version = version;
}
public String getVersion() {
return version;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public long getTimestamp() {
return timestamp;
}
public void setPduLength(int pduLength) {
this.pduLength = pduLength;
}
public int getPduLength() {
return pduLength;
}
public void setCreationTime(long creationTime) {
this.creationTime = creationTime;
}
public long getCreationTime() {
return creationTime;
}
public void setTrapIdentity(TrapIdentityDTO trapIdentity) {
this.trapIdentity = trapIdentity;
}
public TrapIdentityDTO getTrapIdentity() {
return trapIdentity;
}
public List<SnmpResult> getResults() {
return results;
}
public byte[] getRawMessage() {
return rawMessage;
}
public void setRawMessage(byte[] rawMessage) {
this.rawMessage = rawMessage;
}
@Override
public int hashCode() {
return Objects.hash(community, version, timestamp, pduLength, creationTime, rawMessage, trapIdentity, results, agentAddress);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (null == obj) return false;
if (getClass() != obj.getClass()) return false;
final TrapDTO other = (TrapDTO) obj;
boolean equals = Objects.equals(community, other.community)
&& Objects.equals(version, other.version)
&& Objects.equals(timestamp, other.timestamp)
&& Objects.equals(pduLength, other.pduLength)
&& Objects.equals(creationTime, other.creationTime)
&& Objects.equals(rawMessage, other.rawMessage)
&& Objects.equals(trapIdentity, other.trapIdentity)
&& Objects.equals(results, other.results)
&& Objects.equals(agentAddress, other.agentAddress);
return equals;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("agentAddress", agentAddress)
.add("community", community)
.add("trapIdentity", trapIdentity)
.add("creationTime", creationTime)
.add("pduLength", pduLength)
.add("timestamp", timestamp)
.add("version", version)
.add("rawMessage", rawMessage).toString();
}
}
| features/events/traps/src/main/java/org/opennms/netmgt/trapd/TrapDTO.java | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.trapd;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.opennms.core.ipc.sink.api.Message;
import org.opennms.core.network.InetAddressXmlAdapter;
import org.opennms.netmgt.snmp.SnmpResult;
import org.opennms.netmgt.snmp.SnmpVarBindDTO;
import org.opennms.netmgt.snmp.TrapInformation;
import com.google.common.base.MoreObjects;
@XmlRootElement(name = "trap-dto")
@XmlAccessorType(XmlAccessType.NONE)
public class TrapDTO implements Message {
@XmlElement(name = "agent-address")
@XmlJavaTypeAdapter(InetAddressXmlAdapter.class)
private InetAddress agentAddress;
@XmlElement(name = "community")
private String community;
@XmlElement(name = "version", required=true)
private String version;
@XmlElement(name = "timestamp")
private long timestamp;
@XmlElement(name = "pdu-length")
private int pduLength;
@XmlElement(name = "creation-time")
private long creationTime;
@XmlElement(name = "rawMessage")
private byte[] rawMessage;
@XmlElement(name = "trap-identity")
private TrapIdentityDTO trapIdentity;
@XmlElementWrapper(name = "results")
@XmlElement(name = "result")
private List<SnmpResult> results = new ArrayList<>();
// No-arg constructor for JAXB
public TrapDTO() {
}
public TrapDTO(TrapInformation trapInfo) {
setAgentAddress(trapInfo.getAgentAddress());
setCommunity(trapInfo.getCommunity());
setVersion(trapInfo.getVersion());
setTimestamp(trapInfo.getTimeStamp());
setPduLength(trapInfo.getPduLength());
setCreationTime(trapInfo.getCreationTime());
setTrapIdentity(new TrapIdentityDTO(trapInfo.getTrapIdentity()));
// Map variable bindings
final List<SnmpResult> results = new ArrayList<>();
for (int i = 0; i < trapInfo.getPduLength(); i++) {
final SnmpVarBindDTO varBindDTO = trapInfo.getSnmpVarBindDTO(i);
if (varBindDTO != null) {
final SnmpResult snmpResult = new SnmpResult(varBindDTO.getSnmpObjectId(), null, varBindDTO.getSnmpValue());
results.add(snmpResult);
}
}
setResults(results);
}
private void setResults(List<SnmpResult> results) {
this.results = new ArrayList<>(results);
}
public void setAgentAddress(InetAddress agentAddress) {
this.agentAddress = agentAddress;
}
public InetAddress getAgentAddress() {
return agentAddress;
}
public void setCommunity(String community) {
this.community = community;
}
public String getCommunity() {
return community;
}
public void setVersion(String version) {
this.version = version;
}
public String getVersion() {
return version;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public long getTimestamp() {
return timestamp;
}
public void setPduLength(int pduLength) {
this.pduLength = pduLength;
}
public int getPduLength() {
return pduLength;
}
public void setCreationTime(long creationTime) {
this.creationTime = creationTime;
}
public long getCreationTime() {
return creationTime;
}
public void setTrapIdentity(TrapIdentityDTO trapIdentity) {
this.trapIdentity = trapIdentity;
}
public TrapIdentityDTO getTrapIdentity() {
return trapIdentity;
}
public List<SnmpResult> getResults() {
return results;
}
public byte[] getRawMessage() {
return rawMessage;
}
public void setRawMessage(byte[] rawMessage) {
this.rawMessage = rawMessage;
}
@Override
public int hashCode() {
return Objects.hash(community, version, timestamp, pduLength, creationTime, rawMessage, trapIdentity, results, agentAddress);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (null == obj) return false;
if (getClass() != obj.getClass()) return false;
final TrapDTO other = (TrapDTO) obj;
boolean equals = Objects.equals(community, other.community)
&& Objects.equals(version, other.version)
&& Objects.equals(timestamp, other.timestamp)
&& Objects.equals(pduLength, other.pduLength)
&& Objects.equals(creationTime, other.creationTime)
&& Objects.equals(rawMessage, other.rawMessage)
&& Objects.equals(trapIdentity, other.trapIdentity)
&& Objects.equals(results, other.results)
&& Objects.equals(agentAddress, other.agentAddress);
return equals;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("agentAddress", agentAddress)
.add("community", community)
.add("trapIdentity", trapIdentity)
.add("creationTime", creationTime)
.add("pduLength", pduLength)
.add("timestamp", timestamp)
.add("version", version)
.add("rawMessage", rawMessage).toString();
}
}
| HZN-965: Adjust xml element name to match the other attributes/elements
| features/events/traps/src/main/java/org/opennms/netmgt/trapd/TrapDTO.java | HZN-965: Adjust xml element name to match the other attributes/elements | <ide><path>eatures/events/traps/src/main/java/org/opennms/netmgt/trapd/TrapDTO.java
<ide> private int pduLength;
<ide> @XmlElement(name = "creation-time")
<ide> private long creationTime;
<del> @XmlElement(name = "rawMessage")
<add> @XmlElement(name = "raw-message")
<ide> private byte[] rawMessage;
<ide> @XmlElement(name = "trap-identity")
<ide> private TrapIdentityDTO trapIdentity; |
|
Java | mpl-2.0 | 3bd44ba25fe4cc31d816c5ffd8798b60b78e378b | 0 | GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app,GreenDelta/olca-app | package org.openlca.app.editors.processes.allocation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.openlca.app.M;
import org.openlca.app.editors.comments.CommentDialogModifier;
import org.openlca.app.editors.comments.CommentPaths;
import org.openlca.app.editors.processes.ProcessEditor;
import org.openlca.app.rcp.images.Images;
import org.openlca.app.util.Actions;
import org.openlca.app.util.Labels;
import org.openlca.app.util.Numbers;
import org.openlca.app.util.UI;
import org.openlca.app.viewers.tables.TableClipboard;
import org.openlca.app.viewers.tables.Tables;
import org.openlca.app.viewers.tables.modify.ModifySupport;
import org.openlca.app.viewers.tables.modify.TextCellModifier;
import org.openlca.core.model.AllocationFactor;
import org.openlca.core.model.AllocationMethod;
import org.openlca.core.model.Exchange;
import org.openlca.core.model.Process;
import org.openlca.io.CategoryPath;
import org.openlca.util.Strings;
/**
* A table for the display and editing of the causal allocation factors of a
* process. The output products are displayed in columns.
*/
class CausalFactorTable {
private final ProcessEditor editor;
private final AllocationPage page;
private final boolean withComments;
private final List<Column> columns = new ArrayList<>();
private TableViewer viewer;
public CausalFactorTable(AllocationPage page) {
this.page = page;
this.editor = page.editor;
this.withComments = editor.hasAnyComment("allocationFactors");
initColumns();
}
void render(Section section, FormToolkit tk) {
var comp = UI.sectionClient(section, tk, 1);
var titles = getColumnTitles();
viewer = Tables.createViewer(comp, titles);
viewer.setLabelProvider(new FactorLabel());
var copy = TableClipboard.onCopySelected(viewer);
Actions.bind(viewer, copy);
Tables.bindColumnWidths(viewer, 0.2, 0.1, 0.1, 0.1);
var modifier = new ModifySupport<Exchange>(viewer);
Table table = viewer.getTable();
for (int i = 0; i < table.getColumnCount(); i++) {
if (i < 4)
continue;
var col = table.getColumn(i);
if (withComments && i % 2 == 0) {
col.setWidth(24);
} else {
col.setWidth(80);
col.setToolTipText(titles[i]);
}
}
for (int i = 3; i < table.getColumnCount(); i++) {
viewer.getTable().getColumns()[i].setAlignment(SWT.RIGHT);
}
}
private Process process() {
return editor.getModel();
}
void refresh() {
List<Exchange> products = Util.getProviderFlows(process());
List<Exchange> newProducts = new ArrayList<>(products);
List<Integer> removalIndices = new ArrayList<>();
for (int i = 0; i < columns.length; i++) {
Exchange product = columns[i].product;
if (products.contains(product))
newProducts.remove(product);
else
removalIndices.add(i);
}
for (int col : removalIndices)
removeColumn(col);
for (Exchange product : newProducts)
addColumn(product);
viewer.setInput(Util.getNonProviderFlows(process()));
createModifySupport();
viewer.refresh(true);
}
private void removeColumn(int col) {
Column[] newColumns = new Column[columns.length - 1];
System.arraycopy(columns, 0, newColumns, 0, col);
if ((col + 1) < columns.length)
System.arraycopy(columns, col + 1, newColumns, col,
newColumns.length - col);
columns = newColumns;
Table table = viewer.getTable();
table.getColumn(col + 4).dispose();
if (withComments) {
table.getColumn(col + 5).dispose();
}
}
private void addColumn(Exchange product) {
Column newColumn = new Column(product);
Table table = viewer.getTable();
var col = new TableColumn(table, SWT.VIRTUAL);
col.setText(newColumn.title());
col.setToolTipText(newColumn.title());
col.setWidth(80);
Column[] newColumns = new Column[columns.length + 1];
System.arraycopy(columns, 0, newColumns, 0, columns.length);
newColumns[columns.length] = newColumn;
columns = newColumns;
if (withComments) {
new TableColumn(table, SWT.VIRTUAL).setWidth(24);
}
}
private void initColumns() {
var products = Util.getProviderFlows(process());
columns = new Column[products.size()];
for (int i = 0; i < columns.length; i++) {
columns[i] = new Column(products.get(i));
}
Arrays.sort(columns);
}
void setInitialInput() {
viewer.setInput(Util.getNonProviderFlows(process()));
}
private void createModifySupport() {
if (!editor.isEditable())
return;
String[] keys = getColumnTitles();
for (int i = 0; i < columns.length; i++) {
int index = withComments ? 2 * i : i;
keys[index + 4] = columns[i].key;
if (withComments) {
keys[index + 5] = columns[i].key + "-comment";
}
}
viewer.setColumnProperties(keys);
for (int i = 0; i < columns.length; i++) {
int index = withComments ? 2 * i : i;
modifier.bind(keys[index + 4], columns[i]);
if (withComments) {
var product = columns[i].product;
modifier.bind(keys[index + 5], new CommentDialogModifier<>(editor.getComments(),
(e) -> CommentPaths.get(getFactor(product, e), product, e)));
}
}
}
private String[] getColumnTitles() {
boolean showComments = editor.hasAnyComment("allocationFactors");
int cols = showComments ? columns.length * 2 : columns.length;
String[] titles = new String[cols + 4];
titles[0] = M.Flow;
titles[1] = M.Direction;
titles[2] = M.Category;
titles[3] = M.Amount;
for (int i = 0; i < columns.length; i++) {
int index = showComments ? 2 * i : i;
titles[index + 4] = columns[i].title();
if (showComments) {
titles[index + 5] = "";
}
}
return titles;
}
private Column columnOf(int tableIdx) {
int idx = tableIdx - 4;
if (withComments) {
idx /= 2;
}
return idx >= 0 && idx < columns.length
? columns[idx]
: null;
}
private class FactorLabel extends LabelProvider implements
ITableLabelProvider {
@Override
public Image getColumnImage(Object element, int col) {
if (!(element instanceof Exchange exchange))
return null;
if (exchange.flow == null)
return null;
if (col == 0)
return Images.get(exchange.flow);
if (isCommentColumn(col)) {
var column = columnOf(col);
if (column == null)
return null;
var factor = column.factorOf(exchange);
if (factor == null)
return null;
return Images.get(editor.getComments(),
CommentPaths.get(factor, column.product, exchange));
}
return null;
}
@Override
public String getColumnText(Object element, int col) {
if (!(element instanceof Exchange exchange))
return null;
if (exchange.flow == null || exchange.unit == null)
return null;
return switch (col) {
case 0 -> Labels.name(exchange.flow);
case 1 -> exchange.isInput ? M.Input : M.Output;
case 2 -> CategoryPath.getShort(exchange.flow.category);
case 3 -> Numbers.format(exchange.amount) + " "
+ exchange.unit.name;
default -> {
// factor value or formula
if (isCommentColumn(col))
yield null;
var column = columnOf(col);
if (column == null)
yield null;
var f = column.factorOf(exchange);
if (f == null)
yield "";
yield Strings.nullOrEmpty(f.formula)
? Double.toString(f.value)
: f.formula + " = " + f.value;
}
};
}
private boolean isCommentColumn(int col) {
return withComments && col > 4 && col % 2 == 1;
}
}
private class Column extends TextCellModifier<Exchange> {
private final Exchange product;
private final String key;
private final int idx;
private final int commentIdx;
public Column(Exchange product) {
this.product = Objects.requireNonNull(product);
key = UUID.randomUUID().toString();
// create the table column; if comments are active
// an additional comment column is created on the
// right side of the column
var table = viewer.getTable();
var col = new TableColumn(table, SWT.VIRTUAL);
col.setText(title());
col.setToolTipText(title());
col.setWidth(80);
idx = table.indexOf(col);
if (withComments) {
var commentCol = new TableColumn(table, SWT.VIRTUAL);
commentCol.setWidth(24);
commentIdx = table.indexOf(commentCol);
} else {
commentIdx = -1;
}
}
public String title() {
return Labels.name(product.flow);
}
void dispose() {
var table = viewer.getTable();
var col = table.getColumn(idx);
if (col != null) {
col.dispose();
}
if (commentIdx >= 0) {
var commentCol = table.getColumn(commentIdx);
if (commentCol != null) {
commentCol.dispose();
}
}
}
AllocationFactor factorOf(Exchange exchange) {
if (exchange == null)
return null;
for (var factor : process().allocationFactors) {
if (factor.method != AllocationMethod.CAUSAL
|| product.flow.id != factor.productId)
continue;
if (Objects.equals(factor.exchange, exchange))
return factor;
}
return null;
}
@Override
protected String getText(Exchange exchange) {
var factor = factorOf(exchange);
if (factor == null)
return "";
return Strings.nullOrEmpty(factor.formula)
? Double.toString(factor.value)
: factor.formula;
}
@Override
protected void setText(Exchange exchange, String text) {
var factor =factorOf(exchange);
boolean isNew = factor == null;
if (isNew) {
factor = new AllocationFactor();
factor.method = AllocationMethod.CAUSAL;
factor.exchange = exchange;
factor.productId = product.flow.id;
}
if (page.update(factor, text)) {
if (isNew) {
process().allocationFactors.add(factor);
}
editor.setDirty(true);
}
}
}
}
| olca-app/src/org/openlca/app/editors/processes/allocation/CausalFactorTable.java | package org.openlca.app.editors.processes.allocation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.openlca.app.M;
import org.openlca.app.editors.comments.CommentDialogModifier;
import org.openlca.app.editors.comments.CommentPaths;
import org.openlca.app.editors.processes.ProcessEditor;
import org.openlca.app.rcp.images.Images;
import org.openlca.app.util.Actions;
import org.openlca.app.util.Labels;
import org.openlca.app.util.Numbers;
import org.openlca.app.util.UI;
import org.openlca.app.viewers.tables.TableClipboard;
import org.openlca.app.viewers.tables.Tables;
import org.openlca.app.viewers.tables.modify.ModifySupport;
import org.openlca.app.viewers.tables.modify.TextCellModifier;
import org.openlca.core.model.AllocationFactor;
import org.openlca.core.model.AllocationMethod;
import org.openlca.core.model.Exchange;
import org.openlca.core.model.Process;
import org.openlca.io.CategoryPath;
import org.openlca.util.Strings;
/**
* A table for the display and editing of the causal allocation factors of a
* process. The output products are displayed in columns.
*/
class CausalFactorTable {
private final ProcessEditor editor;
private final AllocationPage page;
// When comments are available, each column has a respective comment column
// on the right-side
private final boolean withComments;
private Column[] columns;
private TableViewer viewer;
public CausalFactorTable(AllocationPage page) {
this.page = page;
this.editor = page.editor;
this.withComments = editor.hasAnyComment("allocationFactors");
initColumns();
}
private Process process() {
return editor.getModel();
}
public void refresh() {
List<Exchange> products = Util.getProviderFlows(process());
List<Exchange> newProducts = new ArrayList<>(products);
List<Integer> removalIndices = new ArrayList<>();
for (int i = 0; i < columns.length; i++) {
Exchange product = columns[i].product;
if (products.contains(product))
newProducts.remove(product);
else
removalIndices.add(i);
}
for (int col : removalIndices)
removeColumn(col);
for (Exchange product : newProducts)
addColumn(product);
viewer.setInput(Util.getNonProviderFlows(process()));
createModifySupport();
viewer.refresh(true);
}
private void removeColumn(int col) {
Column[] newColumns = new Column[columns.length - 1];
System.arraycopy(columns, 0, newColumns, 0, col);
if ((col + 1) < columns.length)
System.arraycopy(columns, col + 1, newColumns, col,
newColumns.length - col);
columns = newColumns;
Table table = viewer.getTable();
table.getColumn(col + 4).dispose();
if (withComments) {
table.getColumn(col + 5).dispose();
}
}
private void addColumn(Exchange product) {
Column newColumn = new Column(product);
Table table = viewer.getTable();
var col = new TableColumn(table, SWT.VIRTUAL);
col.setText(newColumn.title());
col.setToolTipText(newColumn.title());
col.setWidth(80);
Column[] newColumns = new Column[columns.length + 1];
System.arraycopy(columns, 0, newColumns, 0, columns.length);
newColumns[columns.length] = newColumn;
columns = newColumns;
if (withComments) {
new TableColumn(table, SWT.VIRTUAL).setWidth(24);
}
}
private void initColumns() {
var products = Util.getProviderFlows(process());
columns = new Column[products.size()];
for (int i = 0; i < columns.length; i++) {
columns[i] = new Column(products.get(i));
}
Arrays.sort(columns);
}
public void render(Section section, FormToolkit tk) {
var comp = UI.sectionClient(section, tk, 1);
var titles = getColumnTitles();
viewer = Tables.createViewer(comp, titles);
viewer.setLabelProvider(new FactorLabel());
var copy = TableClipboard.onCopySelected(viewer);
Actions.bind(viewer, copy);
Tables.bindColumnWidths(viewer, 0.2, 0.1, 0.1, 0.1);
createModifySupport();
Table table = viewer.getTable();
for (int i = 0; i < table.getColumnCount(); i++) {
if (i < 4)
continue;
var col = table.getColumn(i);
if (withComments && i % 2 == 0) {
col.setWidth(24);
} else {
col.setWidth(80);
col.setToolTipText(titles[i]);
}
}
for (int i = 3; i < table.getColumnCount(); i++) {
viewer.getTable().getColumns()[i].setAlignment(SWT.RIGHT);
}
}
void setInitialInput() {
viewer.setInput(Util.getNonProviderFlows(process()));
}
private void createModifySupport() {
if (!editor.isEditable())
return;
String[] keys = getColumnTitles();
for (int i = 0; i < columns.length; i++) {
int index = withComments ? 2 * i : i;
keys[index + 4] = columns[i].key;
if (withComments) {
keys[index + 5] = columns[i].key + "-comment";
}
}
viewer.setColumnProperties(keys);
var modifier = new ModifySupport<Exchange>(viewer);
for (int i = 0; i < columns.length; i++) {
int index = withComments ? 2 * i : i;
modifier.bind(keys[index + 4], columns[i]);
if (withComments) {
var product = columns[i].product;
modifier.bind(keys[index + 5], new CommentDialogModifier<>(editor.getComments(),
(e) -> CommentPaths.get(getFactor(product, e), product, e)));
}
}
}
private String[] getColumnTitles() {
boolean showComments = editor.hasAnyComment("allocationFactors");
int cols = showComments ? columns.length * 2 : columns.length;
String[] titles = new String[cols + 4];
titles[0] = M.Flow;
titles[1] = M.Direction;
titles[2] = M.Category;
titles[3] = M.Amount;
for (int i = 0; i < columns.length; i++) {
int index = showComments ? 2 * i : i;
titles[index + 4] = columns[i].title();
if (showComments) {
titles[index + 5] = "";
}
}
return titles;
}
private Column columnOf(int tableIdx) {
int idx = tableIdx - 4;
if (withComments) {
idx /= 2;
}
return idx >= 0 && idx < columns.length
? columns[idx]
: null;
}
private class FactorLabel extends LabelProvider implements
ITableLabelProvider {
@Override
public Image getColumnImage(Object element, int col) {
if (!(element instanceof Exchange exchange))
return null;
if (exchange.flow == null)
return null;
if (col == 0)
return Images.get(exchange.flow);
if (isCommentColumn(col)) {
var column = columnOf(col);
if (column == null)
return null;
var factor = column.factorOf(exchange);
if (factor == null)
return null;
return Images.get(editor.getComments(),
CommentPaths.get(factor, column.product, exchange));
}
return null;
}
@Override
public String getColumnText(Object element, int col) {
if (!(element instanceof Exchange exchange))
return null;
if (exchange.flow == null || exchange.unit == null)
return null;
return switch (col) {
case 0 -> Labels.name(exchange.flow);
case 1 -> exchange.isInput ? M.Input : M.Output;
case 2 -> CategoryPath.getShort(exchange.flow.category);
case 3 -> Numbers.format(exchange.amount) + " "
+ exchange.unit.name;
default -> {
// factor value or formula
if (isCommentColumn(col))
yield null;
var column = columnOf(col);
if (column == null)
yield null;
var f = column.factorOf(exchange);
if (f == null)
yield "1";
yield Strings.nullOrEmpty(f.formula)
? Double.toString(f.value)
: f.formula + " = " + f.value;
}
};
}
private boolean isCommentColumn(int col) {
return withComments && col > 4 && col % 2 == 1;
}
}
private class Column extends TextCellModifier<Exchange> {
private final Exchange product;
private final String key;
public Column(Exchange product) {
this.product = Objects.requireNonNull(product);
key = UUID.randomUUID().toString();
}
public String title() {
return Labels.name(product.flow);
}
AllocationFactor factorOf(Exchange exchange) {
if (exchange == null)
return null;
for (var factor : process().allocationFactors) {
if (factor.method != AllocationMethod.CAUSAL
|| product.flow.id != factor.productId)
continue;
if (Objects.equals(factor.exchange, exchange))
return factor;
}
return null;
}
@Override
protected String getText(Exchange exchange) {
var factor = factorOf(exchange);
if (factor == null)
return "1";
return Strings.nullOrEmpty(factor.formula)
? Double.toString(factor.value)
: factor.formula;
}
@Override
protected void setText(Exchange exchange, String text) {
var factor =factorOf(exchange);
boolean isNew = factor == null;
if (isNew) {
factor = new AllocationFactor();
factor.method = AllocationMethod.CAUSAL;
factor.exchange = exchange;
factor.productId = product.flow.id;
}
if (page.update(factor, text)) {
if (isNew) {
process().allocationFactors.add(factor);
}
editor.setDirty(true);
}
}
}
}
| move `render` and `dispose` into the column object
| olca-app/src/org/openlca/app/editors/processes/allocation/CausalFactorTable.java | move `render` and `dispose` into the column object | <ide><path>lca-app/src/org/openlca/app/editors/processes/allocation/CausalFactorTable.java
<ide>
<ide> private final ProcessEditor editor;
<ide> private final AllocationPage page;
<del>
<del> // When comments are available, each column has a respective comment column
<del> // on the right-side
<ide> private final boolean withComments;
<del>
<del> private Column[] columns;
<add> private final List<Column> columns = new ArrayList<>();
<add>
<ide> private TableViewer viewer;
<ide>
<ide> public CausalFactorTable(AllocationPage page) {
<ide> initColumns();
<ide> }
<ide>
<add> void render(Section section, FormToolkit tk) {
<add> var comp = UI.sectionClient(section, tk, 1);
<add> var titles = getColumnTitles();
<add> viewer = Tables.createViewer(comp, titles);
<add> viewer.setLabelProvider(new FactorLabel());
<add> var copy = TableClipboard.onCopySelected(viewer);
<add> Actions.bind(viewer, copy);
<add> Tables.bindColumnWidths(viewer, 0.2, 0.1, 0.1, 0.1);
<add> var modifier = new ModifySupport<Exchange>(viewer);
<add>
<add>
<add> Table table = viewer.getTable();
<add> for (int i = 0; i < table.getColumnCount(); i++) {
<add> if (i < 4)
<add> continue;
<add> var col = table.getColumn(i);
<add> if (withComments && i % 2 == 0) {
<add> col.setWidth(24);
<add> } else {
<add> col.setWidth(80);
<add> col.setToolTipText(titles[i]);
<add> }
<add> }
<add> for (int i = 3; i < table.getColumnCount(); i++) {
<add> viewer.getTable().getColumns()[i].setAlignment(SWT.RIGHT);
<add> }
<add>
<add> }
<add>
<ide> private Process process() {
<ide> return editor.getModel();
<ide> }
<ide>
<del> public void refresh() {
<add> void refresh() {
<ide> List<Exchange> products = Util.getProviderFlows(process());
<ide> List<Exchange> newProducts = new ArrayList<>(products);
<ide> List<Integer> removalIndices = new ArrayList<>();
<ide> Arrays.sort(columns);
<ide> }
<ide>
<del> public void render(Section section, FormToolkit tk) {
<del> var comp = UI.sectionClient(section, tk, 1);
<del> var titles = getColumnTitles();
<del> viewer = Tables.createViewer(comp, titles);
<del> viewer.setLabelProvider(new FactorLabel());
<del> var copy = TableClipboard.onCopySelected(viewer);
<del> Actions.bind(viewer, copy);
<del> Tables.bindColumnWidths(viewer, 0.2, 0.1, 0.1, 0.1);
<del> createModifySupport();
<del> Table table = viewer.getTable();
<del> for (int i = 0; i < table.getColumnCount(); i++) {
<del> if (i < 4)
<del> continue;
<del> var col = table.getColumn(i);
<del> if (withComments && i % 2 == 0) {
<del> col.setWidth(24);
<del> } else {
<del> col.setWidth(80);
<del> col.setToolTipText(titles[i]);
<del> }
<del> }
<del> for (int i = 3; i < table.getColumnCount(); i++) {
<del> viewer.getTable().getColumns()[i].setAlignment(SWT.RIGHT);
<del> }
<del> }
<del>
<ide> void setInitialInput() {
<ide> viewer.setInput(Util.getNonProviderFlows(process()));
<ide> }
<ide> }
<ide> viewer.setColumnProperties(keys);
<ide>
<del> var modifier = new ModifySupport<Exchange>(viewer);
<add>
<ide>
<ide> for (int i = 0; i < columns.length; i++) {
<ide> int index = withComments ? 2 * i : i;
<ide> yield null;
<ide> var f = column.factorOf(exchange);
<ide> if (f == null)
<del> yield "1";
<add> yield "";
<ide> yield Strings.nullOrEmpty(f.formula)
<ide> ? Double.toString(f.value)
<ide> : f.formula + " = " + f.value;
<ide>
<ide> private final Exchange product;
<ide> private final String key;
<add> private final int idx;
<add> private final int commentIdx;
<ide>
<ide> public Column(Exchange product) {
<ide> this.product = Objects.requireNonNull(product);
<ide> key = UUID.randomUUID().toString();
<add>
<add> // create the table column; if comments are active
<add> // an additional comment column is created on the
<add> // right side of the column
<add> var table = viewer.getTable();
<add> var col = new TableColumn(table, SWT.VIRTUAL);
<add> col.setText(title());
<add> col.setToolTipText(title());
<add> col.setWidth(80);
<add> idx = table.indexOf(col);
<add> if (withComments) {
<add> var commentCol = new TableColumn(table, SWT.VIRTUAL);
<add> commentCol.setWidth(24);
<add> commentIdx = table.indexOf(commentCol);
<add> } else {
<add> commentIdx = -1;
<add> }
<ide> }
<ide>
<ide> public String title() {
<ide> return Labels.name(product.flow);
<add> }
<add>
<add> void dispose() {
<add> var table = viewer.getTable();
<add> var col = table.getColumn(idx);
<add> if (col != null) {
<add> col.dispose();
<add> }
<add> if (commentIdx >= 0) {
<add> var commentCol = table.getColumn(commentIdx);
<add> if (commentCol != null) {
<add> commentCol.dispose();
<add> }
<add> }
<ide> }
<ide>
<ide> AllocationFactor factorOf(Exchange exchange) {
<ide> protected String getText(Exchange exchange) {
<ide> var factor = factorOf(exchange);
<ide> if (factor == null)
<del> return "1";
<add> return "";
<ide> return Strings.nullOrEmpty(factor.formula)
<ide> ? Double.toString(factor.value)
<ide> : factor.formula; |
|
Java | apache-2.0 | 31c185f1fa36322465f7b4341e9777f8d74d12de | 0 | ivakegg/accumulo,joshelser/accumulo,apache/accumulo,milleruntime/accumulo,joshelser/accumulo,apache/accumulo,mikewalch/accumulo,ctubbsii/accumulo,wjsl/jaredcumulo,adamjshook/accumulo,wjsl/jaredcumulo,dhutchis/accumulo,adamjshook/accumulo,mikewalch/accumulo,ivakegg/accumulo,dhutchis/accumulo,apache/accumulo,dhutchis/accumulo,ivakegg/accumulo,adamjshook/accumulo,wjsl/jaredcumulo,adamjshook/accumulo,phrocker/accumulo,dhutchis/accumulo,ctubbsii/accumulo,dhutchis/accumulo,phrocker/accumulo-1,adamjshook/accumulo,adamjshook/accumulo,ctubbsii/accumulo,lstav/accumulo,mikewalch/accumulo,dhutchis/accumulo,wjsl/jaredcumulo,keith-turner/accumulo,ctubbsii/accumulo,lstav/accumulo,joshelser/accumulo,joshelser/accumulo,mjwall/accumulo,phrocker/accumulo,dhutchis/accumulo,lstav/accumulo,keith-turner/accumulo,lstav/accumulo,mjwall/accumulo,mikewalch/accumulo,apache/accumulo,milleruntime/accumulo,keith-turner/accumulo,phrocker/accumulo-1,dhutchis/accumulo,milleruntime/accumulo,keith-turner/accumulo,wjsl/jaredcumulo,wjsl/jaredcumulo,phrocker/accumulo,lstav/accumulo,apache/accumulo,mikewalch/accumulo,ivakegg/accumulo,ctubbsii/accumulo,mikewalch/accumulo,phrocker/accumulo,dhutchis/accumulo,joshelser/accumulo,phrocker/accumulo,mjwall/accumulo,phrocker/accumulo,keith-turner/accumulo,milleruntime/accumulo,wjsl/jaredcumulo,mikewalch/accumulo,lstav/accumulo,phrocker/accumulo-1,mjwall/accumulo,phrocker/accumulo-1,ivakegg/accumulo,phrocker/accumulo,joshelser/accumulo,phrocker/accumulo,mjwall/accumulo,ivakegg/accumulo,joshelser/accumulo,keith-turner/accumulo,milleruntime/accumulo,ivakegg/accumulo,mjwall/accumulo,mjwall/accumulo,wjsl/jaredcumulo,keith-turner/accumulo,adamjshook/accumulo,apache/accumulo,apache/accumulo,lstav/accumulo,phrocker/accumulo,ctubbsii/accumulo,milleruntime/accumulo,adamjshook/accumulo,mikewalch/accumulo,joshelser/accumulo,phrocker/accumulo-1,adamjshook/accumulo,phrocker/accumulo-1,phrocker/accumulo-1,milleruntime/accumulo,ctubbsii/accumulo | /*
* 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.accumulo.core.client.impl;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchDeleter;
import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.MultiTableBatchWriter;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.TableOfflineException;
import org.apache.accumulo.core.client.admin.InstanceOperations;
import org.apache.accumulo.core.client.admin.InstanceOperationsImpl;
import org.apache.accumulo.core.client.admin.SecurityOperations;
import org.apache.accumulo.core.client.admin.SecurityOperationsImpl;
import org.apache.accumulo.core.client.admin.TableOperations;
import org.apache.accumulo.core.client.admin.TableOperationsImpl;
import org.apache.accumulo.core.client.impl.thrift.ClientService;
import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.thrift.Credentials;
import org.apache.accumulo.core.security.thrift.SecurityErrorCode;
import org.apache.accumulo.core.util.ArgumentChecker;
import org.apache.accumulo.trace.instrument.Tracer;
public class ConnectorImpl extends Connector {
private Instance instance;
private Credentials credentials;
private SecurityOperations secops = null;
private TableOperations tableops = null;
private InstanceOperations instanceops = null;
/**
*
* Use {@link Instance#getConnector(String, byte[])}
*
* @param instance
* @param user
* @param password
* @throws AccumuloException
* @throws AccumuloSecurityException
* @see Instance#getConnector(String user, byte[] password)
* @deprecated Not for client use
*/
@Deprecated
public ConnectorImpl(Instance instance, String user, byte[] password) throws AccumuloException, AccumuloSecurityException {
ArgumentChecker.notNull(instance, user, password);
this.instance = instance;
// copy password so that user can clear it.... in future versions we can clear it...
byte[] passCopy = new byte[password.length];
System.arraycopy(password, 0, passCopy, 0, password.length);
this.credentials = new Credentials(user, ByteBuffer.wrap(password), instance.getInstanceID());
// hardcoded string for SYSTEM user since the definition is
// in server code
if (!user.equals("!SYSTEM")) {
ServerClient.execute(instance, new ClientExec<ClientService.Client>() {
@Override
public void execute(ClientService.Client iface) throws Exception {
if (!iface.authenticateUser(Tracer.traceInfo(), credentials, credentials.getPrincipal(), credentials.token))
throw new AccumuloSecurityException("Authentication failed, access denied", SecurityErrorCode.BAD_CREDENTIALS);
}
});
}
}
private String getTableId(String tableName) throws TableNotFoundException {
String tableId = Tables.getTableId(instance, tableName);
if (Tables.getTableState(instance, tableId) == TableState.OFFLINE)
throw new TableOfflineException(instance, tableId);
return tableId;
}
@Override
public Instance getInstance() {
return instance;
}
@Override
public BatchScanner createBatchScanner(String tableName, Authorizations authorizations, int numQueryThreads) throws TableNotFoundException {
ArgumentChecker.notNull(tableName, authorizations);
return new TabletServerBatchReader(instance, credentials, getTableId(tableName), authorizations, numQueryThreads);
}
@Deprecated
@Override
public BatchDeleter createBatchDeleter(String tableName, Authorizations authorizations, int numQueryThreads, long maxMemory, long maxLatency,
int maxWriteThreads) throws TableNotFoundException {
ArgumentChecker.notNull(tableName, authorizations);
return new TabletServerBatchDeleter(instance, credentials, getTableId(tableName), authorizations, numQueryThreads, new BatchWriterConfig()
.setMaxMemory(maxMemory).setMaxLatency(maxLatency, TimeUnit.MILLISECONDS).setMaxWriteThreads(maxWriteThreads));
}
@Override
public BatchDeleter createBatchDeleter(String tableName, Authorizations authorizations, int numQueryThreads, BatchWriterConfig config)
throws TableNotFoundException {
ArgumentChecker.notNull(tableName, authorizations);
return new TabletServerBatchDeleter(instance, credentials, getTableId(tableName), authorizations, numQueryThreads, config);
}
@Deprecated
@Override
public BatchWriter createBatchWriter(String tableName, long maxMemory, long maxLatency, int maxWriteThreads) throws TableNotFoundException {
ArgumentChecker.notNull(tableName);
return new BatchWriterImpl(instance, credentials, getTableId(tableName), new BatchWriterConfig().setMaxMemory(maxMemory)
.setMaxLatency(maxLatency, TimeUnit.MILLISECONDS).setMaxWriteThreads(maxWriteThreads));
}
@Override
public BatchWriter createBatchWriter(String tableName, BatchWriterConfig config) throws TableNotFoundException {
ArgumentChecker.notNull(tableName);
return new BatchWriterImpl(instance, credentials, getTableId(tableName), config);
}
@Deprecated
@Override
public MultiTableBatchWriter createMultiTableBatchWriter(long maxMemory, long maxLatency, int maxWriteThreads) {
return new MultiTableBatchWriterImpl(instance, credentials, new BatchWriterConfig().setMaxMemory(maxMemory)
.setMaxLatency(maxLatency, TimeUnit.MILLISECONDS).setMaxWriteThreads(maxWriteThreads));
}
@Override
public MultiTableBatchWriter createMultiTableBatchWriter(BatchWriterConfig config) {
return new MultiTableBatchWriterImpl(instance, credentials, config);
}
@Override
public Scanner createScanner(String tableName, Authorizations authorizations) throws TableNotFoundException {
ArgumentChecker.notNull(tableName, authorizations);
return new ScannerImpl(instance, credentials, getTableId(tableName), authorizations);
}
@Override
public String whoami() {
return credentials.getPrincipal();
}
@Override
public synchronized TableOperations tableOperations() {
if (tableops == null)
tableops = new TableOperationsImpl(instance, credentials);
return tableops;
}
@Override
public synchronized SecurityOperations securityOperations() {
if (secops == null)
secops = new SecurityOperationsImpl(instance, credentials);
return secops;
}
@Override
public synchronized InstanceOperations instanceOperations() {
if (instanceops == null)
instanceops = new InstanceOperationsImpl(instance, credentials);
return instanceops;
}
}
| core/src/main/java/org/apache/accumulo/core/client/impl/ConnectorImpl.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.accumulo.core.client.impl;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchDeleter;
import org.apache.accumulo.core.client.BatchScanner;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.MultiTableBatchWriter;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.TableOfflineException;
import org.apache.accumulo.core.client.admin.InstanceOperations;
import org.apache.accumulo.core.client.admin.InstanceOperationsImpl;
import org.apache.accumulo.core.client.admin.SecurityOperations;
import org.apache.accumulo.core.client.admin.SecurityOperationsImpl;
import org.apache.accumulo.core.client.admin.TableOperations;
import org.apache.accumulo.core.client.admin.TableOperationsImpl;
import org.apache.accumulo.core.client.impl.thrift.ClientService;
import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.thrift.Credentials;
import org.apache.accumulo.core.security.thrift.SecurityErrorCode;
import org.apache.accumulo.core.util.ArgumentChecker;
import org.apache.accumulo.trace.instrument.Tracer;
public class ConnectorImpl extends Connector {
private Instance instance;
private Credentials credentials;
private SecurityOperations secops = null;
private TableOperations tableops = null;
private InstanceOperations instanceops = null;
/**
*
* Use {@link Instance#getConnector(String, byte[])}
*
<<<<<<< .working
=======
* @param instance
* @param user
* @param password
* @throws AccumuloException
* @throws AccumuloSecurityException
>>>>>>> .merge-right.r1438353
* @see Instance#getConnector(String user, byte[] password)
* @deprecated Not for client use
*/
@Deprecated
public ConnectorImpl(Instance instance, String user, byte[] password) throws AccumuloException, AccumuloSecurityException {
ArgumentChecker.notNull(instance, user, password);
this.instance = instance;
// copy password so that user can clear it.... in future versions we can clear it...
byte[] passCopy = new byte[password.length];
System.arraycopy(password, 0, passCopy, 0, password.length);
this.credentials = new Credentials(user, ByteBuffer.wrap(password), instance.getInstanceID());
// hardcoded string for SYSTEM user since the definition is
// in server code
if (!user.equals("!SYSTEM")) {
ServerClient.execute(instance, new ClientExec<ClientService.Client>() {
@Override
public void execute(ClientService.Client iface) throws Exception {
if (!iface.authenticateUser(Tracer.traceInfo(), credentials, credentials.getPrincipal(), credentials.token))
throw new AccumuloSecurityException("Authentication failed, access denied", SecurityErrorCode.BAD_CREDENTIALS);
}
});
}
}
private String getTableId(String tableName) throws TableNotFoundException {
String tableId = Tables.getTableId(instance, tableName);
if (Tables.getTableState(instance, tableId) == TableState.OFFLINE)
throw new TableOfflineException(instance, tableId);
return tableId;
}
@Override
public Instance getInstance() {
return instance;
}
@Override
public BatchScanner createBatchScanner(String tableName, Authorizations authorizations, int numQueryThreads) throws TableNotFoundException {
ArgumentChecker.notNull(tableName, authorizations);
return new TabletServerBatchReader(instance, credentials, getTableId(tableName), authorizations, numQueryThreads);
}
@Deprecated
@Override
public BatchDeleter createBatchDeleter(String tableName, Authorizations authorizations, int numQueryThreads, long maxMemory, long maxLatency,
int maxWriteThreads) throws TableNotFoundException {
ArgumentChecker.notNull(tableName, authorizations);
return new TabletServerBatchDeleter(instance, credentials, getTableId(tableName), authorizations, numQueryThreads, new BatchWriterConfig()
.setMaxMemory(maxMemory).setMaxLatency(maxLatency, TimeUnit.MILLISECONDS).setMaxWriteThreads(maxWriteThreads));
}
@Override
public BatchDeleter createBatchDeleter(String tableName, Authorizations authorizations, int numQueryThreads, BatchWriterConfig config)
throws TableNotFoundException {
ArgumentChecker.notNull(tableName, authorizations);
return new TabletServerBatchDeleter(instance, credentials, getTableId(tableName), authorizations, numQueryThreads, config);
}
@Deprecated
@Override
public BatchWriter createBatchWriter(String tableName, long maxMemory, long maxLatency, int maxWriteThreads) throws TableNotFoundException {
ArgumentChecker.notNull(tableName);
return new BatchWriterImpl(instance, credentials, getTableId(tableName), new BatchWriterConfig().setMaxMemory(maxMemory)
.setMaxLatency(maxLatency, TimeUnit.MILLISECONDS).setMaxWriteThreads(maxWriteThreads));
}
@Override
public BatchWriter createBatchWriter(String tableName, BatchWriterConfig config) throws TableNotFoundException {
ArgumentChecker.notNull(tableName);
return new BatchWriterImpl(instance, credentials, getTableId(tableName), config);
}
@Deprecated
@Override
public MultiTableBatchWriter createMultiTableBatchWriter(long maxMemory, long maxLatency, int maxWriteThreads) {
return new MultiTableBatchWriterImpl(instance, credentials, new BatchWriterConfig().setMaxMemory(maxMemory)
.setMaxLatency(maxLatency, TimeUnit.MILLISECONDS).setMaxWriteThreads(maxWriteThreads));
}
@Override
public MultiTableBatchWriter createMultiTableBatchWriter(BatchWriterConfig config) {
return new MultiTableBatchWriterImpl(instance, credentials, config);
}
@Override
public Scanner createScanner(String tableName, Authorizations authorizations) throws TableNotFoundException {
ArgumentChecker.notNull(tableName, authorizations);
return new ScannerImpl(instance, credentials, getTableId(tableName), authorizations);
}
@Override
public String whoami() {
return credentials.getPrincipal();
}
@Override
public synchronized TableOperations tableOperations() {
if (tableops == null)
tableops = new TableOperationsImpl(instance, credentials);
return tableops;
}
@Override
public synchronized SecurityOperations securityOperations() {
if (secops == null)
secops = new SecurityOperationsImpl(instance, credentials);
return secops;
}
@Override
public synchronized InstanceOperations instanceOperations() {
if (instanceops == null)
instanceops = new InstanceOperationsImpl(instance, credentials);
return instanceops;
}
}
| ACCUMULO-259 - had unmerged stuff in the javadocs
git-svn-id: f2032a8f7e7e147e9bd2f47faaf2ba5297dc4bdd@1442437 13f79535-47bb-0310-9956-ffa450edef68
| core/src/main/java/org/apache/accumulo/core/client/impl/ConnectorImpl.java | ACCUMULO-259 - had unmerged stuff in the javadocs | <ide><path>ore/src/main/java/org/apache/accumulo/core/client/impl/ConnectorImpl.java
<ide> *
<ide> * Use {@link Instance#getConnector(String, byte[])}
<ide> *
<del><<<<<<< .working
<del>=======
<ide> * @param instance
<ide> * @param user
<ide> * @param password
<ide> * @throws AccumuloException
<ide> * @throws AccumuloSecurityException
<del>>>>>>>> .merge-right.r1438353
<ide> * @see Instance#getConnector(String user, byte[] password)
<ide> * @deprecated Not for client use
<ide> */ |
|
Java | apache-2.0 | 256840c632be26bd7ab9dc98c860169abd335fe2 | 0 | swift-lang/swift-t,blue42u/swift-t,basheersubei/swift-t,basheersubei/swift-t,blue42u/swift-t,swift-lang/swift-t,basheersubei/swift-t,JohnPJenkins/swift-t,basheersubei/swift-t,swift-lang/swift-t,basheersubei/swift-t,blue42u/swift-t,JohnPJenkins/swift-t,swift-lang/swift-t,swift-lang/swift-t,blue42u/swift-t,blue42u/swift-t,JohnPJenkins/swift-t,JohnPJenkins/swift-t,blue42u/swift-t,blue42u/swift-t,basheersubei/swift-t,swift-lang/swift-t,JohnPJenkins/swift-t,swift-lang/swift-t,basheersubei/swift-t,JohnPJenkins/swift-t,JohnPJenkins/swift-t | /*
* Copyright 2013 University of Chicago and Argonne National Laboratory
*
* 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 exm.stc.ic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import exm.stc.common.exceptions.STCRuntimeError;
import exm.stc.common.lang.Arg;
import exm.stc.common.lang.Operators.BuiltinOpcode;
import exm.stc.common.lang.Types;
import exm.stc.common.lang.Types.Type;
import exm.stc.common.lang.Var;
import exm.stc.common.lang.Var.Alloc;
import exm.stc.common.lang.Var.DefType;
import exm.stc.common.lang.Var.VarProvenance;
import exm.stc.common.lang.WaitVar;
import exm.stc.common.util.Pair;
import exm.stc.common.util.TernaryLogic.Ternary;
import exm.stc.ic.opt.OptUtil;
import exm.stc.ic.tree.Conditionals.IfStatement;
import exm.stc.ic.tree.ICInstructions;
import exm.stc.ic.tree.ICInstructions.Builtin;
import exm.stc.ic.tree.ICInstructions.Instruction;
import exm.stc.ic.tree.ICTree.Block;
import exm.stc.ic.tree.ICTree.Statement;
import exm.stc.ic.tree.TurbineOp;
/**
* Utility functions used to generate wrappers for local operations
* @author tim
*
*/
public class WrapUtil {
/**
* Fetch the value of a variable
* @param block
* @param instBuffer append fetch instruction to this list
* @param var the variable to fetch the value of
* @param acquireWrite if the var is a reference, do we acquire
* write refcounts?
* @return variable holding value
*/
public static Var fetchValueOf(Block block,
List<? super Instruction> instBuffer,
Var var, String valName, boolean recursive, boolean acquireWrite) {
Type valueT;
if (recursive && Types.isContainer(var)) {
valueT = Types.unpackedContainerType(var);
} else {
valueT = Types.retrievedType(var);
}
if (Types.isPrimUpdateable(var)) {
Var value_v = createValueVar(valName, valueT, var);
block.addVariable(value_v);
instBuffer.add(TurbineOp.latestValue(value_v, var));
return value_v;
} else if (Types.isPrimFuture(var)) {
// The result will be a value
// Use the OPT_VALUE_VAR_PREFIX to make sure we don't clash with
// something inserted by the frontend (this caused problems before)
Var value_v = createValueVar(valName, valueT, var);
block.addVariable(value_v);
instBuffer.add(ICInstructions.retrievePrim(value_v, var));
// Add cleanup action if needed
if (Types.isBlobVal(valueT)) {
block.addCleanup(value_v, TurbineOp.freeBlob(value_v));
}
return value_v;
} else if (Types.isRef(var)) {
// The result will be an alias
Var deref = new Var(valueT, valName,
Alloc.ALIAS, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(var));
block.addVariable(deref);
instBuffer.add(TurbineOp.retrieveRef(deref, var, acquireWrite));
return deref;
} else if (Types.isContainer(var) && recursive) {
Var deref = new Var(valueT, valName,
Alloc.LOCAL, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(var));
block.addVariable(deref);
instBuffer.add(TurbineOp.retrieveRecursive(deref, var));
return deref;
} else if (Types.isStruct(var) && recursive) {
Var deref = new Var(valueT, valName,
Alloc.LOCAL, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(var));
block.addVariable(deref);
instBuffer.add(TurbineOp.retrieveStruct(deref, var));
return deref;
} else if ((Types.isContainer(var) || Types.isStruct(var))
&& !recursive) {
Var deref = new Var(valueT, valName,
Alloc.LOCAL, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(var));
block.addVariable(deref);
if (Types.isArray(var)) {
instBuffer.add(TurbineOp.retrieveArray(deref, var));
} else if (Types.isBag(var)) {
instBuffer.add(TurbineOp.retrieveBag(deref, var));
} else {
assert(Types.isStruct(var));
instBuffer.add(TurbineOp.retrieveStruct(deref, var));
}
return deref;
} else {
throw new STCRuntimeError("shouldn't be possible to get here");
}
}
public static Var createValueVar(String name, Type type, Var orig) {
Var value_v = new Var(type, name, Alloc.LOCAL, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(orig));
return value_v;
}
/**
* Work out which inputs/outputs need to be waited for before
* executing a statement depending on them
* @param block
* @param instInsertIt position to insert instructions
* @param inArgs
* @param outArgs
* @param mustMapOutFiles
* @return (a list of variables to wait for,
* the mapping from file output vars to filenames)
*/
public static Pair<List<WaitVar>, Map<Var, Var>> buildWaitVars(
Block block, ListIterator<Statement> instInsertIt,
List<Var> inArgs, List<Var> otherWaitArgs, List<Var> outArgs,
boolean mustMapOutFiles) {
List<WaitVar> waitVars = new ArrayList<WaitVar>(inArgs.size());
Map<Var, Var> filenameVars = new HashMap<Var, Var>();
for (List<Var> waitArgList: Arrays.asList(inArgs, otherWaitArgs)) {
for (Var in: waitArgList) {
if (inputMustWait(in)) {
waitVars.add(new WaitVar(in, false));
}
}
}
for (Var out: outArgs) {
Var waitMapping = getWaitOutputMapping(block, instInsertIt,
mustMapOutFiles, filenameVars, out);
if (waitMapping != null) {
waitVars.add(new WaitVar(waitMapping, false));
}
}
return Pair.create(waitVars, filenameVars);
}
/**
*
* @param block
* @param instInsertIt
* @param mustMapOutFiles
* @param waitVars
* @param filenameVars updated with any filenames
* @param out
* @return wait var if must wait, null otherwise
*/
public static Var getWaitOutputMapping(Block block,
ListIterator<Statement> instInsertIt, boolean mustMapOutFiles,
Map<Var, Var> filenameVars, Var out) {
if (Types.isFile(out)) {
// Must wait on filename of output var
String name = block.uniqueVarName(Var.WRAP_FILENAME_PREFIX +
out.name());
Var filenameTmp = block.declareUnmapped(Types.F_STRING,
name, Alloc.ALIAS, DefType.LOCAL_COMPILER,
VarProvenance.filenameOf(out));
boolean initIfUnmapped = mustMapOutFiles;
Var filenameWaitVar =
initOrGetFileName(block, instInsertIt, filenameTmp, out, initIfUnmapped);
filenameVars.put(out, filenameTmp);
return filenameWaitVar;
}
return null;
}
public static boolean inputMustWait(Var in) {
return !Types.isPrimUpdateable(in.type()) &&
in.storage() != Alloc.GLOBAL_CONST;
}
/**
* Get the filename for a file, initializing it to a temporary value in
* the case where it's not mapped.
* @param block
* @param filename alias to be initialized
* @param file
* @param initIfUnmapped
* @return variable to wait on for filename
*/
public static Var initOrGetFileName(Block block,
ListIterator<Statement> insertPos, Var filename, Var file,
boolean initIfUnmapped) {
assert(Types.isString(filename.type()));
assert(filename.storage() == Alloc.ALIAS);
assert(Types.isFile(file.type()));
Instruction getFileName = TurbineOp.getFileNameAlias(filename, file);
if (file.isMapped() == Ternary.TRUE ||
!file.type().fileKind().supportsTmpImmediate()) {
// Just get the mapping in these cases:
// - File is definitely mapped
// - The file type doesn't support temporary creation
insertPos.add(getFileName);
return filename;
} else {
Var waitVar = null;
if (!initIfUnmapped) {
waitVar = block.declareUnmapped(Types.F_STRING,
OptUtil.optVPrefix(block, file.name() + "filename-wait"),
Alloc.ALIAS, DefType.LOCAL_COMPILER,
VarProvenance.filenameOf(file));
}
// Use optimizer var prefixes to avoid clash with any frontend vars
Var isMapped = getIsMapped(block, insertPos, file);
IfStatement ifMapped = new IfStatement(isMapped.asArg());
ifMapped.setParent(block);
if (!initIfUnmapped) {
// Wait on filename
insertPos.add(getFileName);
ifMapped.thenBlock().addStatement(
TurbineOp.copyRef(waitVar, filename));
}
// Case when not mapped: init with tmp
Block elseB = ifMapped.elseBlock();
if (initIfUnmapped) {
Var filenameVal = elseB.declareUnmapped(Types.V_STRING,
OptUtil.optFilenamePrefix(elseB, file), Alloc.LOCAL,
DefType.LOCAL_COMPILER, VarProvenance.filenameOf(file));
initTemporaryFileName(elseB.statementEndIterator(), file, filenameVal);
// Get the filename again but can assume mapping initialized
insertPos.add(getFileName);
} else {
// Dummy wait variable
elseB.addStatement(TurbineOp.copyRef(waitVar,
Var.NO_WAIT_STRING_VAR));
}
insertPos.add(ifMapped);
if (initIfUnmapped) {
return filename;
} else {
return waitVar;
}
}
}
public static Var getIsMapped(Block block,
ListIterator<? super Instruction> insertPos, Var file) {
Var isMapped = block.declareUnmapped(Types.V_BOOL,
OptUtil.optVPrefix(block, "mapped_" + file.name()), Alloc.LOCAL,
DefType.LOCAL_COMPILER, VarProvenance.optimizerTmp());
insertPos.add(TurbineOp.isMapped(isMapped, file));
return isMapped;
}
/**
* Initialize a file variable with a mapping to a temp file
* @param insertPos place to insert instructions
* @param file this is the file variable to be mapped
* @param filenameVal this is filename
*/
public static void initTemporaryFileName(
ListIterator<? super Statement> insertPos, Var file, Var filenameVal) {
assert(Types.isFile(file));
assert(Types.isStringVal(filenameVal));
assert(file.type().fileKind().supportsTmpImmediate()) :
"Can't create temporary file for type " + file.type();
// Select temporary file name
insertPos.add(TurbineOp.chooseTmpFilename(filenameVal));
// TODO: would be ideal to be able to just keep local
// Set the filename on the file var
insertPos.add(TurbineOp.setFilenameVal(file, filenameVal.asArg()));
}
/**
* Declare and fetch inputs for local operation
* @param block
* @param inputs
* @param instBuffer
* @param uniquifyNames
* @return
*/
public static List<Arg> fetchLocalOpInputs(Block block, List<Var> inputs,
List<Statement> instBuffer, boolean uniquifyNames) {
if (inputs == null) {
// Gracefully handle null as empty list
inputs = Var.NONE;
}
List<Arg> inVals = new ArrayList<Arg>(inputs.size());
for (Var inArg: inputs) {
String name = valName(block, inArg, uniquifyNames);
inVals.add(WrapUtil.fetchValueOf(block, instBuffer,
inArg, name, true, false).asArg());
}
return inVals;
}
/**
* Build output variable list for local operation
* @param block
* @param outputFutures
* @param filenameVars
* @param instBuffer
* @param uniquifyNames if it isn't safe to use default name prefix,
* e.g. if we're in the middle of optimizations
* @param mustInitOutputMapping
* @param store recursively
* @return
*/
public static List<Var> createLocalOpOutputs(Block block,
List<Var> outputFutures, Map<Var, Var> filenameVars,
List<Statement> instBuffer, boolean uniquifyNames,
boolean mustInitOutputMapping, boolean recursive) {
if (outputFutures == null) {
// Gracefully handle null as empty list
outputFutures = Var.NONE;
}
List<Var> outVals = new ArrayList<Var>();
for (Var outArg: outputFutures) {
outVals.add(WrapUtil.createLocalOutputVar(outArg, filenameVars,
block, instBuffer, uniquifyNames, mustInitOutputMapping,
recursive));
}
return outVals;
}
/**
* Declare a local output variable for an operation
* @param block
* @param var
* @param valName
* @return
*/
public static Var declareLocalOutputVar(Block block, Var var,
String valName, boolean recursive) {
return block.declareUnmapped(Types.retrievedType(var.type(), recursive),
valName, Alloc.LOCAL, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(var));
}
/**
* Create an output variable for an operation, and
* perform initialization and cleanup actions
* @param outFut
* @param filenameVars map from file futures to filename
* vals/futures if this is a file var
* @param block
* @param instBuffer buffer for initialization actions
* @param uniquifyName if it isn't safe to use default name prefix,
* e.g. if we're in the middle of optimizations
* @param mustInitOutputMapping whether to initialize mappings for output files
* @param recursive if the fetch will be recursive
* @return
*/
public static Var createLocalOutputVar(Var outFut,
Map<Var, Var> filenameVars,
Block block, List<Statement> instBuffer, boolean uniquifyName,
boolean mustInitOutputMapping, boolean recursive) {
if (Types.isPrimUpdateable(outFut)) {
// Use standard representation
return outFut;
} else {
String outValName = valName(block, outFut, uniquifyName);
Var outVal = WrapUtil.declareLocalOutputVar(block, outFut, outValName,
recursive);
WrapUtil.initLocalOutputVar(block, filenameVars, instBuffer,
outFut, outVal, mustInitOutputMapping);
WrapUtil.cleanupLocalOutputVar(block, outFut, outVal);
return outVal;
}
}
private static String valName(Block block, Var future, boolean uniquifyName) {
String outValName;
if (uniquifyName) {
outValName = OptUtil.optVPrefix(block, future.name());
} else {
outValName = Var.LOCAL_VALUE_VAR_PREFIX + future.name();
}
return outValName;
}
/**
* Initialize a local output variable for an operation
* @param block
* @param filenameVars map of file future to filename future
* @param instBuffer append initialize instructions to this buffer
* @param outFut
* @param outVal
* @param mapOutFile
*/
private static void initLocalOutputVar(Block block, Map<Var, Var> filenameVars,
List<Statement> instBuffer, Var outFut, Var outVal, boolean mustInitOutputMapping) {
if (Types.isFile(outFut)) {
// Initialize filename in local variable
Var isMapped = getIsMapped(block, instBuffer.listIterator(), outFut);
Var outFilename = filenameVars.get(outFut);
IfStatement ifMapped = null;
List<Statement> fetchInstBuffer;
if (mustInitOutputMapping) {
fetchInstBuffer = instBuffer;
} else {
ifMapped = new IfStatement(isMapped.asArg());
instBuffer.add(ifMapped);
fetchInstBuffer = new ArrayList<Statement>();
}
assert(outFilename != null) : "Expected filename in map for " + outFut;
Var outFilenameVal;
if (Types.isString(outFilename)) {
String valName = block.uniqueVarName(Var.VALUEOF_VAR_PREFIX +
outFilename.name());
outFilenameVal = WrapUtil.fetchValueOf(block, fetchInstBuffer,
outFilename, valName, false, false);
if (!mustInitOutputMapping) {
// Read filename if mapped
ifMapped.thenBlock().addStatements(fetchInstBuffer);
// Set filename to something arbitrary if not mapped
ifMapped.elseBlock().addStatement(ICInstructions.valueSet(outFilenameVal,
Arg.createStringLit("")));
}
} else {
// Already a value
assert(Types.isStringVal(outFilename));
outFilenameVal = outFilename;
}
instBuffer.add(TurbineOp.initLocalOutFile(outVal,
outFilenameVal.asArg(), isMapped.asArg()));
}
}
private static void cleanupLocalOutputVar(Block block, Var outFut, Var outVal) {
if (Types.isBlobVal(outVal)) {
block.addCleanup(outVal, TurbineOp.freeBlob(outVal));
} else if (Types.isFileVal(outVal)) {
// Cleanup temporary file (if created) if not copied to file future
if (outFut.isMapped() != Ternary.TRUE &&
outFut.type().fileKind().supportsTmpImmediate()) {
block.addCleanup(outVal, TurbineOp.decrLocalFileRef(outVal));
}
}
}
/**
* Set futures from output values
* @param outFuts
* @param outVals
* @param instBuffer
*/
public static void setLocalOpOutputs(Block block,
List<Var> outFuts, List<Var> outVals,
List<Statement> instBuffer, boolean storeOutputMapping,
boolean recursive) {
if (outFuts == null) {
assert(outVals == null || outVals.isEmpty());
return;
}
assert(outVals.size() == outFuts.size());
for (int i = 0; i < outVals.size(); i++) {
Var outArg = outFuts.get(i);
Var outVal = outVals.get(i);
if (outArg.equals(outVal)) {
// Do nothing: the variable wasn't substituted
} else {
assignOutput(block, instBuffer, storeOutputMapping, outArg, outVal,
recursive);
}
}
}
public static void assignOutput(Block block, List<Statement> instBuffer,
boolean storeOutputMapping, Var outArg, Var outVal, boolean recursive) {
if (Types.isFile(outArg)) {
assignOutputFile(block, instBuffer, storeOutputMapping, outArg, outVal);
} else {
instBuffer.add(TurbineOp.storeAny(outArg, outVal.asArg(), recursive));
}
}
public static void assignOutputFile(Block block,
List<Statement> instBuffer, boolean storeOutputMapping,
Var file, Var fileVal) {
// Can't be sure if output file is already mapped
Arg storeFilename;
if (storeOutputMapping) {
// Store filename conditional on it not being mapped already
Var isMapped = block.declareUnmapped(Types.V_BOOL,
block.uniqueVarName(Var.OPT_VAR_PREFIX + "ismapped"),
Alloc.LOCAL, DefType.LOCAL_COMPILER, VarProvenance.unknown());
Var storeFilenameV = block.declareUnmapped(Types.V_BOOL,
block.uniqueVarName(Var.OPT_VAR_PREFIX + "store"),
Alloc.LOCAL, DefType.LOCAL_COMPILER, VarProvenance.unknown());
instBuffer.add(TurbineOp.isMapped(isMapped, file));
instBuffer.add(Builtin.createLocal(BuiltinOpcode.NOT,
storeFilenameV, isMapped.asArg()));
storeFilename = storeFilenameV.asArg();
} else {
// Definitely don't store
storeFilename = Arg.FALSE;
}
instBuffer.add(TurbineOp.assignFile(file, fileVal.asArg(), storeFilename));
}
}
| code/src/exm/stc/ic/WrapUtil.java | /*
* Copyright 2013 University of Chicago and Argonne National Laboratory
*
* 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 exm.stc.ic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import exm.stc.common.exceptions.STCRuntimeError;
import exm.stc.common.lang.Arg;
import exm.stc.common.lang.Operators.BuiltinOpcode;
import exm.stc.common.lang.Types;
import exm.stc.common.lang.Types.StructType;
import exm.stc.common.lang.Types.StructType.StructField;
import exm.stc.common.lang.Types.Type;
import exm.stc.common.lang.Var;
import exm.stc.common.lang.Var.Alloc;
import exm.stc.common.lang.Var.DefType;
import exm.stc.common.lang.Var.VarProvenance;
import exm.stc.common.lang.WaitVar;
import exm.stc.common.util.Pair;
import exm.stc.common.util.TernaryLogic.Ternary;
import exm.stc.ic.opt.OptUtil;
import exm.stc.ic.tree.Conditionals.IfStatement;
import exm.stc.ic.tree.ICInstructions;
import exm.stc.ic.tree.ICInstructions.Builtin;
import exm.stc.ic.tree.ICInstructions.Instruction;
import exm.stc.ic.tree.ICTree.Block;
import exm.stc.ic.tree.ICTree.Statement;
import exm.stc.ic.tree.TurbineOp;
/**
* Utility functions used to generate wrappers for local operations
* @author tim
*
*/
public class WrapUtil {
/**
* Fetch the value of a variable
* @param block
* @param instBuffer append fetch instruction to this list
* @param var the variable to fetch the value of
* @param acquireWrite if the var is a reference, do we acquire
* write refcounts?
* @return variable holding value
*/
public static Var fetchValueOf(Block block,
List<? super Instruction> instBuffer,
Var var, String valName, boolean recursive, boolean acquireWrite) {
Type valueT;
if (recursive && Types.isContainer(var)) {
valueT = Types.unpackedContainerType(var);
} else {
valueT = Types.retrievedType(var);
}
if (Types.isPrimUpdateable(var)) {
Var value_v = createValueVar(valName, valueT, var);
block.addVariable(value_v);
instBuffer.add(TurbineOp.latestValue(value_v, var));
return value_v;
} else if (Types.isPrimFuture(var)) {
// The result will be a value
// Use the OPT_VALUE_VAR_PREFIX to make sure we don't clash with
// something inserted by the frontend (this caused problems before)
Var value_v = createValueVar(valName, valueT, var);
block.addVariable(value_v);
instBuffer.add(ICInstructions.retrievePrim(value_v, var));
// Add cleanup action if needed
if (Types.isBlobVal(valueT)) {
block.addCleanup(value_v, TurbineOp.freeBlob(value_v));
}
return value_v;
} else if (Types.isRef(var)) {
// The result will be an alias
Var deref = new Var(valueT, valName,
Alloc.ALIAS, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(var));
block.addVariable(deref);
instBuffer.add(TurbineOp.retrieveRef(deref, var, acquireWrite));
return deref;
} else if (Types.isContainer(var) && recursive) {
Var deref = new Var(valueT, valName,
Alloc.LOCAL, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(var));
block.addVariable(deref);
instBuffer.add(TurbineOp.retrieveRecursive(deref, var));
return deref;
} else if (Types.isStruct(var) && recursive) {
for (StructField f: ((StructType)var.type().getImplType()).getFields()) {
if (Types.isRef(f.getType())) {
throw new STCRuntimeError("Recursive fetch of struct with ref field "
+ "not supported yet " + var.type());
}
}
Var deref = new Var(valueT, valName,
Alloc.LOCAL, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(var));
block.addVariable(deref);
instBuffer.add(TurbineOp.retrieveStruct(deref, var));
return deref;
} else if ((Types.isContainer(var) || Types.isStruct(var))
&& !recursive) {
Var deref = new Var(valueT, valName,
Alloc.LOCAL, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(var));
block.addVariable(deref);
if (Types.isArray(var)) {
instBuffer.add(TurbineOp.retrieveArray(deref, var));
} else if (Types.isBag(var)) {
instBuffer.add(TurbineOp.retrieveBag(deref, var));
} else {
assert(Types.isStruct(var));
instBuffer.add(TurbineOp.retrieveStruct(deref, var));
}
return deref;
} else {
throw new STCRuntimeError("shouldn't be possible to get here");
}
}
public static Var createValueVar(String name, Type type, Var orig) {
Var value_v = new Var(type, name, Alloc.LOCAL, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(orig));
return value_v;
}
/**
* Work out which inputs/outputs need to be waited for before
* executing a statement depending on them
* @param block
* @param instInsertIt position to insert instructions
* @param inArgs
* @param outArgs
* @param mustMapOutFiles
* @return (a list of variables to wait for,
* the mapping from file output vars to filenames)
*/
public static Pair<List<WaitVar>, Map<Var, Var>> buildWaitVars(
Block block, ListIterator<Statement> instInsertIt,
List<Var> inArgs, List<Var> otherWaitArgs, List<Var> outArgs,
boolean mustMapOutFiles) {
List<WaitVar> waitVars = new ArrayList<WaitVar>(inArgs.size());
Map<Var, Var> filenameVars = new HashMap<Var, Var>();
for (List<Var> waitArgList: Arrays.asList(inArgs, otherWaitArgs)) {
for (Var in: waitArgList) {
if (inputMustWait(in)) {
waitVars.add(new WaitVar(in, false));
}
}
}
for (Var out: outArgs) {
Var waitMapping = getWaitOutputMapping(block, instInsertIt,
mustMapOutFiles, filenameVars, out);
if (waitMapping != null) {
waitVars.add(new WaitVar(waitMapping, false));
}
}
return Pair.create(waitVars, filenameVars);
}
/**
*
* @param block
* @param instInsertIt
* @param mustMapOutFiles
* @param waitVars
* @param filenameVars updated with any filenames
* @param out
* @return wait var if must wait, null otherwise
*/
public static Var getWaitOutputMapping(Block block,
ListIterator<Statement> instInsertIt, boolean mustMapOutFiles,
Map<Var, Var> filenameVars, Var out) {
if (Types.isFile(out)) {
// Must wait on filename of output var
String name = block.uniqueVarName(Var.WRAP_FILENAME_PREFIX +
out.name());
Var filenameTmp = block.declareUnmapped(Types.F_STRING,
name, Alloc.ALIAS, DefType.LOCAL_COMPILER,
VarProvenance.filenameOf(out));
boolean initIfUnmapped = mustMapOutFiles;
Var filenameWaitVar =
initOrGetFileName(block, instInsertIt, filenameTmp, out, initIfUnmapped);
filenameVars.put(out, filenameTmp);
return filenameWaitVar;
}
return null;
}
public static boolean inputMustWait(Var in) {
return !Types.isPrimUpdateable(in.type()) &&
in.storage() != Alloc.GLOBAL_CONST;
}
/**
* Get the filename for a file, initializing it to a temporary value in
* the case where it's not mapped.
* @param block
* @param filename alias to be initialized
* @param file
* @param initIfUnmapped
* @return variable to wait on for filename
*/
public static Var initOrGetFileName(Block block,
ListIterator<Statement> insertPos, Var filename, Var file,
boolean initIfUnmapped) {
assert(Types.isString(filename.type()));
assert(filename.storage() == Alloc.ALIAS);
assert(Types.isFile(file.type()));
Instruction getFileName = TurbineOp.getFileNameAlias(filename, file);
if (file.isMapped() == Ternary.TRUE ||
!file.type().fileKind().supportsTmpImmediate()) {
// Just get the mapping in these cases:
// - File is definitely mapped
// - The file type doesn't support temporary creation
insertPos.add(getFileName);
return filename;
} else {
Var waitVar = null;
if (!initIfUnmapped) {
waitVar = block.declareUnmapped(Types.F_STRING,
OptUtil.optVPrefix(block, file.name() + "filename-wait"),
Alloc.ALIAS, DefType.LOCAL_COMPILER,
VarProvenance.filenameOf(file));
}
// Use optimizer var prefixes to avoid clash with any frontend vars
Var isMapped = getIsMapped(block, insertPos, file);
IfStatement ifMapped = new IfStatement(isMapped.asArg());
ifMapped.setParent(block);
if (!initIfUnmapped) {
// Wait on filename
insertPos.add(getFileName);
ifMapped.thenBlock().addStatement(
TurbineOp.copyRef(waitVar, filename));
}
// Case when not mapped: init with tmp
Block elseB = ifMapped.elseBlock();
if (initIfUnmapped) {
Var filenameVal = elseB.declareUnmapped(Types.V_STRING,
OptUtil.optFilenamePrefix(elseB, file), Alloc.LOCAL,
DefType.LOCAL_COMPILER, VarProvenance.filenameOf(file));
initTemporaryFileName(elseB.statementEndIterator(), file, filenameVal);
// Get the filename again but can assume mapping initialized
insertPos.add(getFileName);
} else {
// Dummy wait variable
elseB.addStatement(TurbineOp.copyRef(waitVar,
Var.NO_WAIT_STRING_VAR));
}
insertPos.add(ifMapped);
if (initIfUnmapped) {
return filename;
} else {
return waitVar;
}
}
}
public static Var getIsMapped(Block block,
ListIterator<? super Instruction> insertPos, Var file) {
Var isMapped = block.declareUnmapped(Types.V_BOOL,
OptUtil.optVPrefix(block, "mapped_" + file.name()), Alloc.LOCAL,
DefType.LOCAL_COMPILER, VarProvenance.optimizerTmp());
insertPos.add(TurbineOp.isMapped(isMapped, file));
return isMapped;
}
/**
* Initialize a file variable with a mapping to a temp file
* @param insertPos place to insert instructions
* @param file this is the file variable to be mapped
* @param filenameVal this is filename
*/
public static void initTemporaryFileName(
ListIterator<? super Statement> insertPos, Var file, Var filenameVal) {
assert(Types.isFile(file));
assert(Types.isStringVal(filenameVal));
assert(file.type().fileKind().supportsTmpImmediate()) :
"Can't create temporary file for type " + file.type();
// Select temporary file name
insertPos.add(TurbineOp.chooseTmpFilename(filenameVal));
// TODO: would be ideal to be able to just keep local
// Set the filename on the file var
insertPos.add(TurbineOp.setFilenameVal(file, filenameVal.asArg()));
}
/**
* Declare and fetch inputs for local operation
* @param block
* @param inputs
* @param instBuffer
* @param uniquifyNames
* @return
*/
public static List<Arg> fetchLocalOpInputs(Block block, List<Var> inputs,
List<Statement> instBuffer, boolean uniquifyNames) {
if (inputs == null) {
// Gracefully handle null as empty list
inputs = Var.NONE;
}
List<Arg> inVals = new ArrayList<Arg>(inputs.size());
for (Var inArg: inputs) {
String name = valName(block, inArg, uniquifyNames);
inVals.add(WrapUtil.fetchValueOf(block, instBuffer,
inArg, name, true, false).asArg());
}
return inVals;
}
/**
* Build output variable list for local operation
* @param block
* @param outputFutures
* @param filenameVars
* @param instBuffer
* @param uniquifyNames if it isn't safe to use default name prefix,
* e.g. if we're in the middle of optimizations
* @param mustInitOutputMapping
* @param store recursively
* @return
*/
public static List<Var> createLocalOpOutputs(Block block,
List<Var> outputFutures, Map<Var, Var> filenameVars,
List<Statement> instBuffer, boolean uniquifyNames,
boolean mustInitOutputMapping, boolean recursive) {
if (outputFutures == null) {
// Gracefully handle null as empty list
outputFutures = Var.NONE;
}
List<Var> outVals = new ArrayList<Var>();
for (Var outArg: outputFutures) {
outVals.add(WrapUtil.createLocalOutputVar(outArg, filenameVars,
block, instBuffer, uniquifyNames, mustInitOutputMapping,
recursive));
}
return outVals;
}
/**
* Declare a local output variable for an operation
* @param block
* @param var
* @param valName
* @return
*/
public static Var declareLocalOutputVar(Block block, Var var,
String valName, boolean recursive) {
return block.declareUnmapped(Types.retrievedType(var.type(), recursive),
valName, Alloc.LOCAL, DefType.LOCAL_COMPILER,
VarProvenance.valueOf(var));
}
/**
* Create an output variable for an operation, and
* perform initialization and cleanup actions
* @param outFut
* @param filenameVars map from file futures to filename
* vals/futures if this is a file var
* @param block
* @param instBuffer buffer for initialization actions
* @param uniquifyName if it isn't safe to use default name prefix,
* e.g. if we're in the middle of optimizations
* @param mustInitOutputMapping whether to initialize mappings for output files
* @param recursive if the fetch will be recursive
* @return
*/
public static Var createLocalOutputVar(Var outFut,
Map<Var, Var> filenameVars,
Block block, List<Statement> instBuffer, boolean uniquifyName,
boolean mustInitOutputMapping, boolean recursive) {
if (Types.isPrimUpdateable(outFut)) {
// Use standard representation
return outFut;
} else {
String outValName = valName(block, outFut, uniquifyName);
Var outVal = WrapUtil.declareLocalOutputVar(block, outFut, outValName,
recursive);
WrapUtil.initLocalOutputVar(block, filenameVars, instBuffer,
outFut, outVal, mustInitOutputMapping);
WrapUtil.cleanupLocalOutputVar(block, outFut, outVal);
return outVal;
}
}
private static String valName(Block block, Var future, boolean uniquifyName) {
String outValName;
if (uniquifyName) {
outValName = OptUtil.optVPrefix(block, future.name());
} else {
outValName = Var.LOCAL_VALUE_VAR_PREFIX + future.name();
}
return outValName;
}
/**
* Initialize a local output variable for an operation
* @param block
* @param filenameVars map of file future to filename future
* @param instBuffer append initialize instructions to this buffer
* @param outFut
* @param outVal
* @param mapOutFile
*/
private static void initLocalOutputVar(Block block, Map<Var, Var> filenameVars,
List<Statement> instBuffer, Var outFut, Var outVal, boolean mustInitOutputMapping) {
if (Types.isFile(outFut)) {
// Initialize filename in local variable
Var isMapped = getIsMapped(block, instBuffer.listIterator(), outFut);
Var outFilename = filenameVars.get(outFut);
IfStatement ifMapped = null;
List<Statement> fetchInstBuffer;
if (mustInitOutputMapping) {
fetchInstBuffer = instBuffer;
} else {
ifMapped = new IfStatement(isMapped.asArg());
instBuffer.add(ifMapped);
fetchInstBuffer = new ArrayList<Statement>();
}
assert(outFilename != null) : "Expected filename in map for " + outFut;
Var outFilenameVal;
if (Types.isString(outFilename)) {
String valName = block.uniqueVarName(Var.VALUEOF_VAR_PREFIX +
outFilename.name());
outFilenameVal = WrapUtil.fetchValueOf(block, fetchInstBuffer,
outFilename, valName, false, false);
if (!mustInitOutputMapping) {
// Read filename if mapped
ifMapped.thenBlock().addStatements(fetchInstBuffer);
// Set filename to something arbitrary if not mapped
ifMapped.elseBlock().addStatement(ICInstructions.valueSet(outFilenameVal,
Arg.createStringLit("")));
}
} else {
// Already a value
assert(Types.isStringVal(outFilename));
outFilenameVal = outFilename;
}
instBuffer.add(TurbineOp.initLocalOutFile(outVal,
outFilenameVal.asArg(), isMapped.asArg()));
}
}
private static void cleanupLocalOutputVar(Block block, Var outFut, Var outVal) {
if (Types.isBlobVal(outVal)) {
block.addCleanup(outVal, TurbineOp.freeBlob(outVal));
} else if (Types.isFileVal(outVal)) {
// Cleanup temporary file (if created) if not copied to file future
if (outFut.isMapped() != Ternary.TRUE &&
outFut.type().fileKind().supportsTmpImmediate()) {
block.addCleanup(outVal, TurbineOp.decrLocalFileRef(outVal));
}
}
}
/**
* Set futures from output values
* @param outFuts
* @param outVals
* @param instBuffer
*/
public static void setLocalOpOutputs(Block block,
List<Var> outFuts, List<Var> outVals,
List<Statement> instBuffer, boolean storeOutputMapping,
boolean recursive) {
if (outFuts == null) {
assert(outVals == null || outVals.isEmpty());
return;
}
assert(outVals.size() == outFuts.size());
for (int i = 0; i < outVals.size(); i++) {
Var outArg = outFuts.get(i);
Var outVal = outVals.get(i);
if (outArg.equals(outVal)) {
// Do nothing: the variable wasn't substituted
} else {
assignOutput(block, instBuffer, storeOutputMapping, outArg, outVal,
recursive);
}
}
}
public static void assignOutput(Block block, List<Statement> instBuffer,
boolean storeOutputMapping, Var outArg, Var outVal, boolean recursive) {
if (Types.isFile(outArg)) {
assignOutputFile(block, instBuffer, storeOutputMapping, outArg, outVal);
} else {
instBuffer.add(TurbineOp.storeAny(outArg, outVal.asArg(), recursive));
}
}
public static void assignOutputFile(Block block,
List<Statement> instBuffer, boolean storeOutputMapping,
Var file, Var fileVal) {
// Can't be sure if output file is already mapped
Arg storeFilename;
if (storeOutputMapping) {
// Store filename conditional on it not being mapped already
Var isMapped = block.declareUnmapped(Types.V_BOOL,
block.uniqueVarName(Var.OPT_VAR_PREFIX + "ismapped"),
Alloc.LOCAL, DefType.LOCAL_COMPILER, VarProvenance.unknown());
Var storeFilenameV = block.declareUnmapped(Types.V_BOOL,
block.uniqueVarName(Var.OPT_VAR_PREFIX + "store"),
Alloc.LOCAL, DefType.LOCAL_COMPILER, VarProvenance.unknown());
instBuffer.add(TurbineOp.isMapped(isMapped, file));
instBuffer.add(Builtin.createLocal(BuiltinOpcode.NOT,
storeFilenameV, isMapped.asArg()));
storeFilename = storeFilenameV.asArg();
} else {
// Definitely don't store
storeFilename = Arg.FALSE;
}
instBuffer.add(TurbineOp.assignFile(file, fileVal.asArg(), storeFilename));
}
}
| WIP on runtime code to recursively wait on structs
git-svn-id: 47705994653588c662f4ea400dfe88107361c0e2@14286 dc4e9af1-7f46-4ead-bba6-71afc04862de
| code/src/exm/stc/ic/WrapUtil.java | WIP on runtime code to recursively wait on structs | <ide><path>ode/src/exm/stc/ic/WrapUtil.java
<ide> import exm.stc.common.lang.Arg;
<ide> import exm.stc.common.lang.Operators.BuiltinOpcode;
<ide> import exm.stc.common.lang.Types;
<del>import exm.stc.common.lang.Types.StructType;
<del>import exm.stc.common.lang.Types.StructType.StructField;
<ide> import exm.stc.common.lang.Types.Type;
<ide> import exm.stc.common.lang.Var;
<ide> import exm.stc.common.lang.Var.Alloc;
<ide> instBuffer.add(TurbineOp.retrieveRecursive(deref, var));
<ide> return deref;
<ide> } else if (Types.isStruct(var) && recursive) {
<del> for (StructField f: ((StructType)var.type().getImplType()).getFields()) {
<del> if (Types.isRef(f.getType())) {
<del> throw new STCRuntimeError("Recursive fetch of struct with ref field "
<del> + "not supported yet " + var.type());
<del> }
<del> }
<del>
<ide> Var deref = new Var(valueT, valName,
<ide> Alloc.LOCAL, DefType.LOCAL_COMPILER,
<ide> VarProvenance.valueOf(var)); |
|
JavaScript | mit | c770232c716ca50016799f17e55841136d31b217 | 0 | alextreppass/backbone-component,yammer/backbone-component,alextreppass/backbone-component,yammer/backbone-component | // Backbone.Component
// ==================
//
// A thin layer on top of Backbone's view class to add nested child views.
Backbone.Component = Backbone.View.extend({
// Override constructor so Components can use `initialize` normally.
constructor: function() {
this._setup();
Backbone.View.apply(this, arguments);
},
// Public API
// ----------
// Add a child view to the end of the element.
// Optionally specify a selector within the view to attach to.
// Aliased to `add`.
append: function(view, selector) {
this._addChild(view, selector, 'append');
return this;
},
// Add a child view to the beginning of the view's element.
// Optionally specify a selector within the view to attach to.
prepend: function(view, selector) {
this._addChild(view, selector, 'prepend');
return this;
},
// Retrieve the list of child views.
children: function() {
return _.pluck(this._children, 'view');
},
// Remove all child views added to this one.
empty: function() {
this._removeChildren();
return this;
},
// Render the existing template with the provided data.
renderTemplate: function(data) {
this.$el.html(this._compile(this.template)(data));
return this;
},
// Wraps `_.template`. Can be replaced by any object that responds to
// `compile` and returns a compiled template function.
renderer: {
compile: function(template) {
this._template = this._template || _.partial(_.template, template);
return this._template;
}
},
// Private methods
// ---------------
// Initial setup. Create new child array, and wrap `render` and `remove`
// methods.
_setup: function() {
// Mixin renderer to view instance, so that compiled templates aren't
// shared.
_.extend(this, { _compile: this.renderer.compile });
this._children = [];
this.render = this._wrapRender();
this.remove = this._wrapRemove();
},
// Add a child view to an internal array, keeping a reference to the element
// and attach method it should use.
_addChild: function(view, selector, method) {
var child = { view: view, selector: selector, method: method || 'append' };
// Assign a method to the child so it can remove itself from `_children`
// array when it's removed.
// Written as an anonymous function to prevent it being bound multiple times
// in grandparent-parent-child situations.
var removeFromParent = function(child) {
this._children = _.without(this._children, child);
};
view._removeFromParent = _.bind(removeFromParent, this, child);
this._children.push(child);
},
// Call `remove` for each child added to the view.
_removeChildren: function() {
_.invoke(this.children(), 'remove');
this._children = [];
},
// Replaced by a function scoped to the parent if the component is added as a
// child (in `_addChild`) but otherwise does nothing (as the component
// wouldn't have a parent).
_removeFromParent: function() {
},
// Wrap `render` to automatically attach all children.
_wrapRender: function() {
var wrapper = function(render) {
var args = _.rest(arguments);
if (this._isIE) {
this._detachChildren();
}
render.apply(this, args);
this._attachChildren();
return Backbone.Component.prototype.render.apply(this, args);
};
var originalRender = _.bind(this.render, this);
return _.wrap(originalRender, wrapper);
},
// Wrap `remove` to automatically remove all children and itself from its
// parent.
_wrapRemove: function() {
var wrapper = function(remove) {
var args = _.rest(arguments);
this._removeFromParent();
this._removeChildren();
remove.apply(this, args);
return Backbone.Component.prototype.remove.apply(this, args);
};
var originalRemove = _.bind(this.remove, this);
return _.wrap(originalRemove, wrapper);
},
// Attach child to the correct element and with the correct method. Defaults
// to `this.$el` and `append`.
// Only call `render` on the child the first time.
_attachChild: function(child) {
var target = child.selector ? this.$(child.selector) : this.$el;
if (!child.rendered) {
child.view.render();
}
target[child.method](child.view.$el);
},
// Attach all children in the right order, and call `delegateEvents` for each
// child view so handlers are correctly bound after being attached.
// Only call `delegateEvents` on the child the first time.
_attachChildren: function() {
_.each(this._children, function(child) {
this._attachChild(child);
if (!child.rendered) {
child.view.delegateEvents();
}
child.rendered = true;
}, this);
},
_detachChildren: function() {
_.each(this._children, function(child) {
if (child.view.el) {
child.view.$el.detach();
}
}, this);
},
_isIE: (function() {
// old MSIE < IE 11
if (document.all) {
return true;
}
// MSIE 11
return (!(window.ActiveXObject) && 'ActiveXObject' in window);
})()
});
// Alias `add` to `append`.
Backbone.Component.prototype.add = Backbone.Component.prototype.append;
| backbone-component.js | // Backbone.Component
// ==================
//
// A thin layer on top of Backbone's view class to add nested child views.
Backbone.Component = Backbone.View.extend({
// Override constructor so Components can use `initialize` normally.
constructor: function() {
this._setup();
Backbone.View.apply(this, arguments);
},
// Public API
// ----------
// Add a child view to the end of the element.
// Optionally specify a selector within the view to attach to.
// Aliased to `add`.
append: function(view, selector) {
this._addChild(view, selector, 'append');
return this;
},
// Add a child view to the beginning of the view's element.
// Optionally specify a selector within the view to attach to.
prepend: function(view, selector) {
this._addChild(view, selector, 'prepend');
return this;
},
// Retrieve the list of child views.
children: function() {
return _.pluck(this._children, 'view');
},
// Remove all child views added to this one.
empty: function() {
this._removeChildren();
return this;
},
// Render the existing template with the provided data.
renderTemplate: function(data) {
this.$el.html(this._compile(this.template)(data));
return this;
},
// Wraps `_.template`. Can be replaced by any object that responds to
// `compile` and returns a compiled template function.
renderer: {
compile: function(template) {
this._template = this._template || _.partial(_.template, template);
return this._template;
}
},
// Private methods
// ---------------
// Initial setup. Create new child array, and wrap `render` and `remove`
// methods.
_setup: function() {
// Mixin renderer to view instance, so that compiled templates aren't
// shared.
_.extend(this, { _compile: this.renderer.compile });
this._children = [];
this.render = this._wrapRender();
this.remove = this._wrapRemove();
},
// Add a child view to an internal array, keeping a reference to the element
// and attach method it should use.
_addChild: function(view, selector, method) {
var child = { view: view, selector: selector, method: method || 'append' };
// Assign a method to the child so it can remove itself from `_children`
// array when it's removed.
// Written as an anonymous function to prevent it being bound multiple times
// in grandparent-parent-child situations.
var removeFromParent = function(child) {
this._children = _.without(this._children, child);
};
view._removeFromParent = _.bind(removeFromParent, this, child);
this._children.push(child);
},
// Call `remove` for each child added to the view.
_removeChildren: function() {
_.invoke(this.children(), 'remove');
this._children = [];
},
// Replaced by a function scoped to the parent if the component is added as a
// child (in `_addChild`) but otherwise does nothing (as the component
// wouldn't have a parent).
_removeFromParent: function() {
},
// Wrap `render` to automatically attach all children.
_wrapRender: function() {
var wrapper = function(render) {
var args = _.rest(arguments);
if (this._isIE) {
this._detachChildren();
}
render.apply(this, args);
this._attachChildren();
return Backbone.Component.prototype.render.apply(this, args);
};
var originalRender = _.bind(this.render, this);
return _.wrap(originalRender, wrapper);
},
// Wrap `remove` to automatically remove all children and itself from its
// parent.
_wrapRemove: function() {
var wrapper = function(remove) {
var args = _.rest(arguments);
this._removeFromParent();
this._removeChildren();
remove.apply(this, args);
return Backbone.Component.prototype.remove.apply(this, args);
};
var originalRemove = _.bind(this.remove, this);
return _.wrap(originalRemove, wrapper);
},
// Attach child to the correct element and with the correct method. Defaults
// to `this.$el` and `append`.
// Only call `render` on the child the first time.
_attachChild: function(child) {
var target = child.selector ? this.$(child.selector) : this.$el;
if (!child.rendered) {
child.view.render();
}
target[child.method](child.view.$el);
},
// Attach all children in the right order, and call `delegateEvents` for each
// child view so handlers are correctly bound after being attached.
// Only call `delegateEvents` on the child the first time.
_attachChildren: function() {
_.each(this._children, function(child) {
this._attachChild(child);
if (!child.rendered) {
child.view.delegateEvents();
}
child.rendered = true;
}, this);
},
_detachChildren: function() {
_.each(this._children, function(child) {
if (child.view.el) {
child.view.$el.detach();
}
}, this);
},
_isIE: (function() {
// old MSIE < IE 11
if (document.all) {
return true;
}
// MSIE 11
return (!(window.ActiveXObject) && "ActiveXObject" in window);
})()
});
// Alias `add` to `append`.
Backbone.Component.prototype.add = Backbone.Component.prototype.append;
| silly style guide
| backbone-component.js | silly style guide | <ide><path>ackbone-component.js
<ide> return true;
<ide> }
<ide> // MSIE 11
<del> return (!(window.ActiveXObject) && "ActiveXObject" in window);
<add> return (!(window.ActiveXObject) && 'ActiveXObject' in window);
<ide> })()
<ide>
<ide> }); |
|
Java | agpl-3.0 | 5c8dea2a3ff189afcf83f1adae955808e119b346 | 0 | raiedsiddiqui/tapcm,raiedsiddiqui/tapcm,raiedsiddiqui/tapcm | package org.tapestry.controller;
import org.springframework.stereotype.Controller;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.tapestry.dao.UserDao;
import org.tapestry.dao.PatientDao;
import org.tapestry.dao.AppointmentDao;
import org.tapestry.dao.MessageDao;
import org.tapestry.dao.SurveyTemplateDao;
import org.tapestry.dao.PictureDao;
import org.tapestry.dao.ActivityDao;
import org.tapestry.objects.User;
import org.tapestry.objects.Patient;
import org.tapestry.objects.Appointment;
import org.tapestry.objects.Message;
import org.tapestry.objects.SurveyTemplate;
import org.tapestry.objects.Activity;
import java.util.ArrayList;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.util.Map;
import org.springframework.core.io.ClassPathResource;
import javax.annotation.PostConstruct;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* Main controller class
* This class is responsible for interpreting URLs and returning the appropriate pages.
* It is the 'brain' of the application. Each function is tagged with @RequestMapping and
* one of either RequestMethod.GET or RequestMethod.POST, which determines which requests
* the function will be triggered in response to.
* The function returns a string, which is the name of a web page to render. For example,
* the login() function returns "login" when an HTTP request like "HTTP 1.1 GET /login"
* is received. The application then loads the page "login.jsp" (the extension is added
* automatically).
*/
@Controller
public class TapestryController{
private ClassPathResource dbConfigFile;
private Map<String, String> config;
private Yaml yaml;
private UserDao userDao;
private PatientDao patientDao;
private AppointmentDao appointmentDao;
private MessageDao messageDao;
private PictureDao pictureDao;
private SurveyTemplateDao surveyTemplateDao;
private ActivityDao activityDao;
//Mail-related settings;
private Properties props;
private String mailAddress = "";
private Session session;
/**
* Reads the file /WEB-INF/classes/db.yaml and gets the values contained therein
*/
@PostConstruct
public void readConfig(){
String database = "";
String dbUsername = "";
String dbPassword = "";
String mailHost = "";
String mailUser = "";
String mailPassword = "";
String mailPort = "";
String useTLS = "";
String useAuth = "";
try{
dbConfigFile = new ClassPathResource("tapestry.yaml");
yaml = new Yaml();
config = (Map<String, String>) yaml.load(dbConfigFile.getInputStream());
database = config.get("url");
dbUsername = config.get("username");
dbPassword = config.get("password");
mailHost = config.get("mailHost");
mailUser = config.get("mailUser");
mailPassword = config.get("mailPassword");
mailAddress = config.get("mailAddress");
mailPort = config.get("mailPort");
useTLS = config.get("mailUsesTLS");
useAuth = config.get("mailRequiresAuth");
} catch (IOException e) {
System.out.println("Error reading from config file");
System.out.println(e.toString());
}
//Create the DAOs
userDao = new UserDao(database, dbUsername, dbPassword);
patientDao = new PatientDao(database, dbUsername, dbPassword);
appointmentDao = new AppointmentDao(database, dbUsername, dbPassword);
messageDao = new MessageDao(database, dbUsername, dbPassword);
pictureDao = new PictureDao(database, dbUsername, dbPassword);
activityDao = new ActivityDao(database, dbUsername, dbPassword);
//Mail-related settings
final String username = mailUser;
final String password = mailPassword;
props = System.getProperties();
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
surveyTemplateDao = new SurveyTemplateDao(database, dbUsername, dbPassword);
props.setProperty("mail.smtp.host", mailHost);
props.setProperty("mail.smtp.socketFactory.port", mailPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.auth", useAuth);
props.setProperty("mail.smtp.starttls.enable", useTLS);
props.setProperty("mail.user", mailUser);
props.setProperty("mail.password", mailPassword);
}
//Everything below this point is a RequestMapping
@RequestMapping(value="/login", method=RequestMethod.GET)
public String login(@RequestParam(value="usernameChanged", required=false) Boolean usernameChanged, ModelMap model){
if (usernameChanged != null)
model.addAttribute("usernameChanged", usernameChanged);
return "login";
}
@RequestMapping(value={"/", "/loginsuccess"}, method=RequestMethod.GET)
//Note that messageSent is Boolean, not boolean, to allow it to be null
public String welcome(@RequestParam(value="success", required=false) Boolean messageSent, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
if (request.isUserInRole("ROLE_USER")){
String username = request.getUserPrincipal().getName();
User u = userDao.getUserByUsername(username);
ArrayList<Patient> patientsForUser = patientDao.getPatientsForVolunteer(u.getUserID());
ArrayList<Appointment> appointmentsForToday = appointmentDao.getAllAppointmentsForVolunteerForToday(u.getUserID());
ArrayList<Appointment> allAppointments = appointmentDao.getAllAppointmentsForVolunteer(u.getUserID());
ArrayList<Activity> activityLog = activityDao.getLastNActivitiesForVolunteer(u.getUserID(), 5); //Cap recent activities at 5
//ArrayList<String> activityLog = activityDao.getAllActivitiesForVolunteer(u.getUserID());
model.addAttribute("name", u.getName());
model.addAttribute("patients", patientsForUser);
model.addAttribute("appointments_today", appointmentsForToday);
model.addAttribute("appointments_all", allAppointments);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(u.getUserID());
model.addAttribute("unread", unreadMessages);
model.addAttribute("activities", activityLog);
return "volunteer/index";
}
else if (request.isUserInRole("ROLE_ADMIN")){
String name = request.getUserPrincipal().getName();
model.addAttribute("name", name);
ArrayList<User> volunteers = userDao.getAllUsersWithRole("ROLE_USER");
model.addAttribute("volunteers", volunteers);
if (messageSent != null)
model.addAttribute("success", messageSent);
return "admin/index";
}
else{ //This should not happen, but catch any unforseen behavior
return "redirect:/login";
}
}
@RequestMapping(value="/loginfailed", method=RequestMethod.GET)
public String failed(ModelMap model){
model.addAttribute("error", "true");
return "login";
}
@RequestMapping(value="/manage_users", method=RequestMethod.GET)
public String manageUsers(ModelMap model){
ArrayList<User> userList = userDao.getAllUsers();
model.addAttribute("users", userList);
return "admin/manage_users";
}
@RequestMapping(value="/manage_patients", method=RequestMethod.GET)
public String managePatients(ModelMap model){
ArrayList<User> volunteers = userDao.getAllUsersWithRole("ROLE_USER");
model.addAttribute("volunteers", volunteers);
ArrayList<Patient> patientList = patientDao.getAllPatients();
model.addAttribute("patients", patientList);
return "admin/manage_patients";
}
@RequestMapping(value="/add_user", method=RequestMethod.POST)
public String addUser(SecurityContextHolderAwareRequestWrapper request){
//Add a new user
User u = new User();
u.setName(request.getParameter("name"));
u.setUsername(request.getParameter("username"));
u.setRole(request.getParameter("role"));
ShaPasswordEncoder enc = new ShaPasswordEncoder();
String hashedPassword = enc.encodePassword("password", null); //Default
u.setPassword(hashedPassword);
u.setEmail(request.getParameter("email"));
userDao.createUser(u);
activityDao.logActivity("Added user: " + u.getName(), u.getUserID());
if (mailAddress != null){
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailAddress));
message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(u.getEmail()));
message.setSubject("Welcome to Tapestry");
String msg = "";
msg += "Thank you for volunteering with Tapestry. Your accout has successfully been created.\n";
msg += "Your username and password are as follows:\n";
msg += "Username: " + u.getUsername() + "\n";
msg += "Password: password\n";
message.setText(msg);
System.out.println(msg);
System.out.println("Sending...");
Transport.send(message);
System.out.println("Email sent containing credentials to " + u.getEmail());
} catch (MessagingException e) {
System.out.println("Error: Could not send email");
System.out.println(e.toString());
}
}
//Display page again
return "redirect:/manage_users";
}
@RequestMapping(value="/remove_user/{user_id}", method=RequestMethod.GET)
public String removeUser(@PathVariable("user_id") int id){
userDao.removeUserWithId(id);
activityDao.logActivity("Removed user: " + id, id);
return "redirect:/manage_users";
}
@RequestMapping(value="/add_patient", method=RequestMethod.POST)
public String addPatient(SecurityContextHolderAwareRequestWrapper request){
//Add a new patient
Patient p = new Patient();
p.setFirstName(request.getParameter("firstname"));
p.setLastName(request.getParameter("lastname"));
int v = Integer.parseInt(request.getParameter("volunteer"));
p.setVolunteer(v);
p.setColor(request.getParameter("backgroundColor"));
p.setBirthdate(request.getParameter("birthdate"));
p.setGender(request.getParameter("gender"));
patientDao.createPatient(p);
activityDao.logActivity("Added patient: " + p.getDisplayName(), v);
return "redirect:/manage_patients";
}
@RequestMapping(value="/remove_patient/{patient_id}", method=RequestMethod.GET)
public String removePatient(@PathVariable("patient_id") int id){
Patient p = patientDao.getPatientByID(id);
patientDao.removePatientWithId(id);
activityDao.logActivity("Removed patient: " + p.getDisplayName(), p.getVolunteer(), p.getPatientID());
return "redirect:/manage_patients";
}
@RequestMapping(value="/patient/{patient_id}", method=RequestMethod.GET)
public String viewPatient(@PathVariable("patient_id") int id, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
Patient patient = patientDao.getPatientByID(id);
//Find the name of the current user
User u = userDao.getUserByUsername(request.getUserPrincipal().getName());
String loggedInUser = u.getName();
//Make sure that the user is actually responsible for the patient in question
int volunteerForPatient = patient.getVolunteer();
if (!(u.getUserID() == patient.getVolunteer())){
model.addAttribute("loggedIn", loggedInUser);
model.addAttribute("patientOwner", volunteerForPatient);
return "redirect:/403";
}
model.addAttribute("patient", patient);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(u.getUserID());
model.addAttribute("unread", unreadMessages);
return "/patient";
}
@RequestMapping(value="/book_appointment", method=RequestMethod.POST)
public String addAppointment(SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User u = userDao.getUserByUsername(request.getUserPrincipal().getName());
int loggedInUser = u.getUserID();
Appointment a = new Appointment();
a.setVolunteer(loggedInUser);
int pid = Integer.parseInt(request.getParameter("patient"));
a.setPatientID(pid);
a.setDate(request.getParameter("appointmentDate"));
a.setTime(request.getParameter("appointmentTime"));
appointmentDao.createAppointment(a);
Patient p = patientDao.getPatientByID(pid);
activityDao.logActivity("Booked appointment with " + p.getDisplayName(), loggedInUser, pid);
return "redirect:/";
}
@RequestMapping(value="/profile", method=RequestMethod.GET)
public String viewProfile(@RequestParam(value="error", required=false) String errorsPresent, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
model.addAttribute("vol", loggedInUser);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("unread", unreadMessages);
if (errorsPresent != null)
model.addAttribute("errors", errorsPresent);
ArrayList<String> pics = pictureDao.getPicturesForUser(loggedInUser.getUserID());
model.addAttribute("pictures", pics);
return "/volunteer/profile";
}
@RequestMapping(value="/inbox", method=RequestMethod.GET)
public String viewInbox(SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
ArrayList<Message> messages = messageDao.getAllMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("messages", messages);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("unread", unreadMessages);
return "/volunteer/inbox";
}
@RequestMapping(value="/view_message/{msgID}", method=RequestMethod.GET)
public String viewMessage(@PathVariable("msgID") int id, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
Message m = messageDao.getMessageByID(id);
if (!(m.getRecipient() == loggedInUser.getUserID()))
return "redirect:/403";
if (!(m.isRead()))
messageDao.markAsRead(id);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("unread", unreadMessages);
model.addAttribute("message", m);
return "/volunteer/view_message";
}
@RequestMapping(value="/send_message", method=RequestMethod.POST)
public String sendMessage(SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
Message m = new Message();
m.setSender(loggedInUser.getName());
m.setRecipient(Integer.parseInt(request.getParameter("recipient")));
m.setText(request.getParameter("msgBody"));
m.setSubject(request.getParameter("msgSubject"));
messageDao.sendMessage(m);
return "redirect:/?success=true";
}
@RequestMapping(value="/delete_message/{msgID}", method=RequestMethod.GET)
public String deleteMessage(@PathVariable("msgID") int id, ModelMap model){
messageDao.deleteMessage(id);
return "redirect:/inbox";
}
//Error pages
@RequestMapping(value="/403", method=RequestMethod.GET)
public String forbiddenError(){
return "error-forbidden";
}
@RequestMapping(value="/update_user", method=RequestMethod.POST)
public String updateUser(SecurityContextHolderAwareRequestWrapper request){
String currentUsername = request.getUserPrincipal().getName();
User loggedInUser = userDao.getUserByUsername(currentUsername);
User u = new User();
u.setUserID(loggedInUser.getUserID());
u.setUsername(request.getParameter("volUsername"));
u.setName(request.getParameter("volName"));
u.setEmail(request.getParameter("volEmail"));
userDao.modifyUser(u);
activityDao.logActivity("Updated user information", loggedInUser.getUserID());
if (!(currentUsername.equals(u.getUsername())))
return "redirect:/login?usernameChanged=true";
else
return "redirect:/profile";
}
@RequestMapping(value="/manage_survey_templates", method=RequestMethod.GET)
public String manageSurveyTemplates(ModelMap model){
ArrayList<SurveyTemplate> surveyTemplateList = surveyTemplateDao.getAllSurveyTemplates();
model.addAttribute("survey_templates", surveyTemplateList);
return "admin/manage_survey_templates";
}
@RequestMapping(value="/change_password", method=RequestMethod.POST)
public String changePassword(SecurityContextHolderAwareRequestWrapper request){
String currentUsername = request.getUserPrincipal().getName();
User loggedInUser = userDao.getUserByUsername(currentUsername);
String currentPassword = request.getParameter("currentPassword");
String newPassword = request.getParameter("newPassword");
String confirmPassword = request.getParameter("confirmPassword");
if (!newPassword.equals(confirmPassword)){
return "redirect:/profile?error=confirm";
}
if (!userDao.userHasPassword(loggedInUser.getUserID(), currentPassword)){
return "redirect:/profile?error=current";
}
ShaPasswordEncoder enc = new ShaPasswordEncoder();
String hashedPassword = enc.encodePassword(newPassword, null);
userDao.setPasswordForUser(loggedInUser.getUserID(), hashedPassword);
activityDao.logActivity("Changed password", loggedInUser.getUserID());
return "redirect:/profile";
}
}
| src/main/java/org/tapestry/controller/TapestryController.java | package org.tapestry.controller;
import org.springframework.stereotype.Controller;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.tapestry.dao.UserDao;
import org.tapestry.dao.PatientDao;
import org.tapestry.dao.AppointmentDao;
import org.tapestry.dao.MessageDao;
import org.tapestry.dao.SurveyTemplateDao;
import org.tapestry.dao.PictureDao;
import org.tapestry.dao.ActivityDao;
import org.tapestry.objects.User;
import org.tapestry.objects.Patient;
import org.tapestry.objects.Appointment;
import org.tapestry.objects.Message;
import org.tapestry.objects.SurveyTemplate;
import org.tapestry.objects.Activity;
import java.util.ArrayList;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.util.Map;
import org.springframework.core.io.ClassPathResource;
import javax.annotation.PostConstruct;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* Main controller class
* This class is responsible for interpreting URLs and returning the appropriate pages.
* It is the 'brain' of the application. Each function is tagged with @RequestMapping and
* one of either RequestMethod.GET or RequestMethod.POST, which determines which requests
* the function will be triggered in response to.
* The function returns a string, which is the name of a web page to render. For example,
* the login() function returns "login" when an HTTP request like "HTTP 1.1 GET /login"
* is received. The application then loads the page "login.jsp" (the extension is added
* automatically).
*/
@Controller
public class TapestryController{
private ClassPathResource dbConfigFile;
private Map<String, String> config;
private Yaml yaml;
private UserDao userDao;
private PatientDao patientDao;
private AppointmentDao appointmentDao;
private MessageDao messageDao;
private PictureDao pictureDao;
private SurveyTemplateDao surveyTemplateDao;
private ActivityDao activityDao;
//Mail-related settings;
private Properties props;
private String mailAddress;
private Session session;
/**
* Reads the file /WEB-INF/classes/db.yaml and gets the values contained therein
*/
@PostConstruct
public void readConfig(){
String database = "";
String dbUsername = "";
String dbPassword = "";
String mailHost = "";
String mailUser = "";
String mailPassword = "";
String mailPort = "";
String useTLS = "";
String useAuth = "";
mailAddress = "";
try{
dbConfigFile = new ClassPathResource("tapestry.yaml");
yaml = new Yaml();
config = (Map<String, String>) yaml.load(dbConfigFile.getInputStream());
database = config.get("url");
dbUsername = config.get("username");
dbPassword = config.get("password");
mailHost = config.get("mailHost");
mailUser = config.get("mailUser");
mailPassword = config.get("mailPassword");
mailAddress = config.get("mailAddress");
mailPort = config.get("mailPort");
useTLS = config.get("mailUsesTLS");
useAuth = config.get("mailRequiresAuth");
} catch (IOException e) {
System.out.println("Error reading from config file");
System.out.println(e.toString());
}
//Create the DAOs
userDao = new UserDao(database, dbUsername, dbPassword);
patientDao = new PatientDao(database, dbUsername, dbPassword);
appointmentDao = new AppointmentDao(database, dbUsername, dbPassword);
messageDao = new MessageDao(database, dbUsername, dbPassword);
pictureDao = new PictureDao(database, dbUsername, dbPassword);
activityDao = new ActivityDao(database, dbUsername, dbPassword);
//Mail-related settings
final String username = mailUser;
final String password = mailPassword;
props = System.getProperties();
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
surveyTemplateDao = new SurveyTemplateDao(database, dbUsername, dbPassword);
props.setProperty("mail.smtp.host", mailHost);
props.setProperty("mail.smtp.socketFactory.port", mailPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.auth", useAuth);
props.setProperty("mail.smtp.starttls.enable", useTLS);
props.setProperty("mail.user", mailUser);
props.setProperty("mail.password", mailPassword);
}
//Everything below this point is a RequestMapping
@RequestMapping(value="/login", method=RequestMethod.GET)
public String login(@RequestParam(value="usernameChanged", required=false) Boolean usernameChanged, ModelMap model){
if (usernameChanged != null)
model.addAttribute("usernameChanged", usernameChanged);
return "login";
}
@RequestMapping(value={"/", "/loginsuccess"}, method=RequestMethod.GET)
//Note that messageSent is Boolean, not boolean, to allow it to be null
public String welcome(@RequestParam(value="success", required=false) Boolean messageSent, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
if (request.isUserInRole("ROLE_USER")){
String username = request.getUserPrincipal().getName();
User u = userDao.getUserByUsername(username);
ArrayList<Patient> patientsForUser = patientDao.getPatientsForVolunteer(u.getUserID());
ArrayList<Appointment> appointmentsForToday = appointmentDao.getAllAppointmentsForVolunteerForToday(u.getUserID());
ArrayList<Appointment> allAppointments = appointmentDao.getAllAppointmentsForVolunteer(u.getUserID());
ArrayList<Activity> activityLog = activityDao.getLastNActivitiesForVolunteer(u.getUserID(), 5); //Cap recent activities at 5
//ArrayList<String> activityLog = activityDao.getAllActivitiesForVolunteer(u.getUserID());
model.addAttribute("name", u.getName());
model.addAttribute("patients", patientsForUser);
model.addAttribute("appointments_today", appointmentsForToday);
model.addAttribute("appointments_all", allAppointments);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(u.getUserID());
model.addAttribute("unread", unreadMessages);
model.addAttribute("activities", activityLog);
return "volunteer/index";
}
else if (request.isUserInRole("ROLE_ADMIN")){
String name = request.getUserPrincipal().getName();
model.addAttribute("name", name);
ArrayList<User> volunteers = userDao.getAllUsersWithRole("ROLE_USER");
model.addAttribute("volunteers", volunteers);
if (messageSent != null)
model.addAttribute("success", messageSent);
return "admin/index";
}
else{ //This should not happen, but catch any unforseen behavior
return "redirect:/login";
}
}
@RequestMapping(value="/loginfailed", method=RequestMethod.GET)
public String failed(ModelMap model){
model.addAttribute("error", "true");
return "login";
}
@RequestMapping(value="/manage_users", method=RequestMethod.GET)
public String manageUsers(ModelMap model){
ArrayList<User> userList = userDao.getAllUsers();
model.addAttribute("users", userList);
return "admin/manage_users";
}
@RequestMapping(value="/manage_patients", method=RequestMethod.GET)
public String managePatients(ModelMap model){
ArrayList<User> volunteers = userDao.getAllUsersWithRole("ROLE_USER");
model.addAttribute("volunteers", volunteers);
ArrayList<Patient> patientList = patientDao.getAllPatients();
model.addAttribute("patients", patientList);
return "admin/manage_patients";
}
@RequestMapping(value="/add_user", method=RequestMethod.POST)
public String addUser(SecurityContextHolderAwareRequestWrapper request){
//Add a new user
User u = new User();
u.setName(request.getParameter("name"));
u.setUsername(request.getParameter("username"));
u.setRole(request.getParameter("role"));
ShaPasswordEncoder enc = new ShaPasswordEncoder();
String hashedPassword = enc.encodePassword("password", null); //Default
u.setPassword(hashedPassword);
u.setEmail(request.getParameter("email"));
userDao.createUser(u);
activityDao.logActivity("Added user: " + u.getName(), u.getUserID());
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(mailAddress));
message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(u.getEmail()));
message.setSubject("Welcome to Tapestry");
String msg = "";
msg += "Thank you for volunteering with Tapestry. Your accout has successfully been created.\n";
msg += "Your username and password are as follows:\n";
msg += "Username: " + u.getUsername() + "\n";
msg += "Password: password\n";
message.setText(msg);
System.out.println(msg);
System.out.println("Sending...");
Transport.send(message);
System.out.println("Email sent containing credentials to " + u.getEmail());
} catch (MessagingException e) {
System.out.println("Error: Could not send email");
System.out.println(e.toString());
}
//Display page again
return "redirect:/manage_users";
}
@RequestMapping(value="/remove_user/{user_id}", method=RequestMethod.GET)
public String removeUser(@PathVariable("user_id") int id){
userDao.removeUserWithId(id);
activityDao.logActivity("Removed user: " + id, id);
return "redirect:/manage_users";
}
@RequestMapping(value="/add_patient", method=RequestMethod.POST)
public String addPatient(SecurityContextHolderAwareRequestWrapper request){
//Add a new patient
Patient p = new Patient();
p.setFirstName(request.getParameter("firstname"));
p.setLastName(request.getParameter("lastname"));
int v = Integer.parseInt(request.getParameter("volunteer"));
p.setVolunteer(v);
p.setColor(request.getParameter("backgroundColor"));
p.setBirthdate(request.getParameter("birthdate"));
p.setGender(request.getParameter("gender"));
patientDao.createPatient(p);
activityDao.logActivity("Added patient: " + p.getDisplayName(), v);
return "redirect:/manage_patients";
}
@RequestMapping(value="/remove_patient/{patient_id}", method=RequestMethod.GET)
public String removePatient(@PathVariable("patient_id") int id){
Patient p = patientDao.getPatientByID(id);
patientDao.removePatientWithId(id);
activityDao.logActivity("Removed patient: " + p.getDisplayName(), p.getVolunteer(), p.getPatientID());
return "redirect:/manage_patients";
}
@RequestMapping(value="/patient/{patient_id}", method=RequestMethod.GET)
public String viewPatient(@PathVariable("patient_id") int id, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
Patient patient = patientDao.getPatientByID(id);
//Find the name of the current user
User u = userDao.getUserByUsername(request.getUserPrincipal().getName());
String loggedInUser = u.getName();
//Make sure that the user is actually responsible for the patient in question
int volunteerForPatient = patient.getVolunteer();
if (!(u.getUserID() == patient.getVolunteer())){
model.addAttribute("loggedIn", loggedInUser);
model.addAttribute("patientOwner", volunteerForPatient);
return "redirect:/403";
}
model.addAttribute("patient", patient);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(u.getUserID());
model.addAttribute("unread", unreadMessages);
return "/patient";
}
@RequestMapping(value="/book_appointment", method=RequestMethod.POST)
public String addAppointment(SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User u = userDao.getUserByUsername(request.getUserPrincipal().getName());
int loggedInUser = u.getUserID();
Appointment a = new Appointment();
a.setVolunteer(loggedInUser);
int pid = Integer.parseInt(request.getParameter("patient"));
a.setPatientID(pid);
a.setDate(request.getParameter("appointmentDate"));
a.setTime(request.getParameter("appointmentTime"));
appointmentDao.createAppointment(a);
Patient p = patientDao.getPatientByID(pid);
activityDao.logActivity("Booked appointment with " + p.getDisplayName(), loggedInUser, pid);
return "redirect:/";
}
@RequestMapping(value="/profile", method=RequestMethod.GET)
public String viewProfile(@RequestParam(value="error", required=false) String errorsPresent, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
model.addAttribute("vol", loggedInUser);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("unread", unreadMessages);
if (errorsPresent != null)
model.addAttribute("errors", errorsPresent);
ArrayList<String> pics = pictureDao.getPicturesForUser(loggedInUser.getUserID());
model.addAttribute("pictures", pics);
return "/volunteer/profile";
}
@RequestMapping(value="/inbox", method=RequestMethod.GET)
public String viewInbox(SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
ArrayList<Message> messages = messageDao.getAllMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("messages", messages);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("unread", unreadMessages);
return "/volunteer/inbox";
}
@RequestMapping(value="/view_message/{msgID}", method=RequestMethod.GET)
public String viewMessage(@PathVariable("msgID") int id, SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
Message m = messageDao.getMessageByID(id);
if (!(m.getRecipient() == loggedInUser.getUserID()))
return "redirect:/403";
if (!(m.isRead()))
messageDao.markAsRead(id);
int unreadMessages = messageDao.countUnreadMessagesForRecipient(loggedInUser.getUserID());
model.addAttribute("unread", unreadMessages);
model.addAttribute("message", m);
return "/volunteer/view_message";
}
@RequestMapping(value="/send_message", method=RequestMethod.POST)
public String sendMessage(SecurityContextHolderAwareRequestWrapper request, ModelMap model){
User loggedInUser = userDao.getUserByUsername(request.getUserPrincipal().getName());
Message m = new Message();
m.setSender(loggedInUser.getName());
m.setRecipient(Integer.parseInt(request.getParameter("recipient")));
m.setText(request.getParameter("msgBody"));
m.setSubject(request.getParameter("msgSubject"));
messageDao.sendMessage(m);
return "redirect:/?success=true";
}
@RequestMapping(value="/delete_message/{msgID}", method=RequestMethod.GET)
public String deleteMessage(@PathVariable("msgID") int id, ModelMap model){
messageDao.deleteMessage(id);
return "redirect:/inbox";
}
//Error pages
@RequestMapping(value="/403", method=RequestMethod.GET)
public String forbiddenError(){
return "error-forbidden";
}
@RequestMapping(value="/update_user", method=RequestMethod.POST)
public String updateUser(SecurityContextHolderAwareRequestWrapper request){
String currentUsername = request.getUserPrincipal().getName();
User loggedInUser = userDao.getUserByUsername(currentUsername);
User u = new User();
u.setUserID(loggedInUser.getUserID());
u.setUsername(request.getParameter("volUsername"));
u.setName(request.getParameter("volName"));
u.setEmail(request.getParameter("volEmail"));
userDao.modifyUser(u);
activityDao.logActivity("Updated user information", loggedInUser.getUserID());
if (!(currentUsername.equals(u.getUsername())))
return "redirect:/login?usernameChanged=true";
else
return "redirect:/profile";
}
@RequestMapping(value="/manage_survey_templates", method=RequestMethod.GET)
public String manageSurveyTemplates(ModelMap model){
ArrayList<SurveyTemplate> surveyTemplateList = surveyTemplateDao.getAllSurveyTemplates();
model.addAttribute("survey_templates", surveyTemplateList);
return "admin/manage_survey_templates";
}
@RequestMapping(value="/change_password", method=RequestMethod.POST)
public String changePassword(SecurityContextHolderAwareRequestWrapper request){
String currentUsername = request.getUserPrincipal().getName();
User loggedInUser = userDao.getUserByUsername(currentUsername);
String currentPassword = request.getParameter("currentPassword");
String newPassword = request.getParameter("newPassword");
String confirmPassword = request.getParameter("confirmPassword");
if (!newPassword.equals(confirmPassword)){
return "redirect:/profile?error=confirm";
}
if (!userDao.userHasPassword(loggedInUser.getUserID(), currentPassword)){
return "redirect:/profile?error=current";
}
ShaPasswordEncoder enc = new ShaPasswordEncoder();
String hashedPassword = enc.encodePassword(newPassword, null);
userDao.setPasswordForUser(loggedInUser.getUserID(), hashedPassword);
activityDao.logActivity("Changed password", loggedInUser.getUserID());
return "redirect:/profile";
}
}
| Prevent breaking when email is not set
| src/main/java/org/tapestry/controller/TapestryController.java | Prevent breaking when email is not set | <ide><path>rc/main/java/org/tapestry/controller/TapestryController.java
<ide>
<ide> //Mail-related settings;
<ide> private Properties props;
<del> private String mailAddress;
<add> private String mailAddress = "";
<ide> private Session session;
<ide>
<ide> /**
<ide> String mailPort = "";
<ide> String useTLS = "";
<ide> String useAuth = "";
<del> mailAddress = "";
<ide> try{
<ide> dbConfigFile = new ClassPathResource("tapestry.yaml");
<ide> yaml = new Yaml();
<ide> u.setEmail(request.getParameter("email"));
<ide> userDao.createUser(u);
<ide> activityDao.logActivity("Added user: " + u.getName(), u.getUserID());
<del> try{
<del> MimeMessage message = new MimeMessage(session);
<del> message.setFrom(new InternetAddress(mailAddress));
<del> message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(u.getEmail()));
<del> message.setSubject("Welcome to Tapestry");
<del> String msg = "";
<del> msg += "Thank you for volunteering with Tapestry. Your accout has successfully been created.\n";
<del> msg += "Your username and password are as follows:\n";
<del> msg += "Username: " + u.getUsername() + "\n";
<del> msg += "Password: password\n";
<del> message.setText(msg);
<del> System.out.println(msg);
<del> System.out.println("Sending...");
<del> Transport.send(message);
<del> System.out.println("Email sent containing credentials to " + u.getEmail());
<del> } catch (MessagingException e) {
<del> System.out.println("Error: Could not send email");
<del> System.out.println(e.toString());
<add> if (mailAddress != null){
<add> try{
<add> MimeMessage message = new MimeMessage(session);
<add> message.setFrom(new InternetAddress(mailAddress));
<add> message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(u.getEmail()));
<add> message.setSubject("Welcome to Tapestry");
<add> String msg = "";
<add> msg += "Thank you for volunteering with Tapestry. Your accout has successfully been created.\n";
<add> msg += "Your username and password are as follows:\n";
<add> msg += "Username: " + u.getUsername() + "\n";
<add> msg += "Password: password\n";
<add> message.setText(msg);
<add> System.out.println(msg);
<add> System.out.println("Sending...");
<add> Transport.send(message);
<add> System.out.println("Email sent containing credentials to " + u.getEmail());
<add> } catch (MessagingException e) {
<add> System.out.println("Error: Could not send email");
<add> System.out.println(e.toString());
<add> }
<ide> }
<ide> //Display page again
<ide> return "redirect:/manage_users"; |
|
Java | bsd-2-clause | 5f84854ace9517263ecda088f608e53754cff89e | 0 | imagej/ij1-patcher | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2014 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imagej.patcher;
import java.util.HashSet;
import java.util.Set;
/**
* Assorted legacy patches / extension points for use in the legacy mode.
*
* <p>
* The Fiji distribution of ImageJ accumulated patches and extensions to ImageJ
* 1.x over the years.
* </p>
*
* <p>
* However, there was a lot of overlap with the ImageJ2 project, so it was
* decided to focus Fiji more on the life-science specific part and move all the
* parts that are of more general use into ImageJ2. That way, it is pretty
* clear-cut what goes into Fiji and what goes into ImageJ2.
* </p>
*
* <p>
* This class contains the extension points (such as being able to override the
* macro editor) ported from Fiji as well as the code for runtime patching
* ImageJ 1.x needed both for the extension points and for more backwards
* compatibility than ImageJ 1.x wanted to provide (e.g. when public methods or
* classes that were used by Fiji plugins were removed all of a sudden, without
* being deprecated first).
* </p>
*
* <p>
* The code in this class is only used in the legacy mode.
* </p>
*
* @author Johannes Schindelin
*/
class LegacyExtensions {
/*
* Extension points
*/
/*
* Runtime patches (using CodeHacker for patching)
*/
/**
* Applies runtime patches to ImageJ 1.x for backwards-compatibility and extension points.
*
* <p>
* These patches enable a patched ImageJ 1.x to call a different script editor or to override
* the application icon.
* </p>
*
* <p>
* This method is called by {@link LegacyInjector#injectHooks(ClassLoader)}.
* </p>
*
* @param hacker the {@link CodeHacker} instance
*/
public static void injectHooks(final CodeHacker hacker, boolean headless) {
//
// Below are patches to make ImageJ 1.x more backwards-compatible
//
// add back the (deprecated) killProcessor(), and overlay methods
final String[] imagePlusMethods = {
"public void killProcessor()",
"{}",
"public void setDisplayList(java.util.Vector list)",
"getCanvas().setDisplayList(list);",
"public java.util.Vector getDisplayList()",
"return getCanvas().getDisplayList();",
"public void setDisplayList(ij.gui.Roi roi, java.awt.Color strokeColor,"
+ " int strokeWidth, java.awt.Color fillColor)",
"setOverlay(roi, strokeColor, strokeWidth, fillColor);"
};
for (int i = 0; i < imagePlusMethods.length; i++) try {
hacker.insertNewMethod("ij.ImagePlus",
imagePlusMethods[i], imagePlusMethods[++i]);
} catch (Exception e) { /* ignore */ }
// make sure that ImageJ has been initialized in batch mode
hacker.insertAtTopOfMethod("ij.IJ",
"public static java.lang.String runMacro(java.lang.String macro, java.lang.String arg)",
"if (ij==null && ij.Menus.getCommands()==null) init();");
try {
hacker.insertNewMethod("ij.CompositeImage",
"public ij.ImagePlus[] splitChannels(boolean closeAfter)",
"ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(this);"
+ "if (closeAfter) close();"
+ "return result;");
hacker.insertNewMethod("ij.plugin.filter.RGBStackSplitter",
"public static ij.ImagePlus[] splitChannelsToArray(ij.ImagePlus imp, boolean closeAfter)",
"if (!imp.isComposite()) {"
+ " ij.IJ.error(\"splitChannelsToArray was called on a non-composite image\");"
+ " return null;"
+ "}"
+ "ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(imp);"
+ "if (closeAfter)"
+ " imp.close();"
+ "return result;");
} catch (IllegalArgumentException e) {
final Throwable cause = e.getCause();
if (cause != null && !cause.getClass().getName().endsWith("DuplicateMemberException")) {
throw e;
}
}
// handle mighty mouse (at least on old Linux, Java mistakes the horizontal wheel for a popup trigger)
for (String fullClass : new String[] {
"ij.gui.ImageCanvas",
"ij.plugin.frame.RoiManager",
"ij.text.TextPanel",
"ij.gui.Toolbar"
}) {
hacker.handleMightyMousePressed(fullClass);
}
// tell IJ#runUserPlugIn to catch NoSuchMethodErrors
final String runUserPlugInSig = "static java.lang.Object runUserPlugIn(java.lang.String commandName, java.lang.String className, java.lang.String arg, boolean createNewLoader)";
hacker.addCatch("ij.IJ", runUserPlugInSig, "java.lang.NoSuchMethodError",
"if (ij.IJ._hooks.handleNoSuchMethodError($e))"
+ " throw new RuntimeException(ij.Macro.MACRO_CANCELED);"
+ "throw $e;");
// tell IJ#runUserPlugIn to be more careful about catching NoClassDefFoundError
hacker.insertPrivateStaticField("ij.IJ", String.class, "originalClassName");
hacker.insertAtTopOfMethod("ij.IJ", runUserPlugInSig, "originalClassName = $2;");
hacker.insertAtTopOfExceptionHandlers("ij.IJ", runUserPlugInSig, "java.lang.NoClassDefFoundError",
"java.lang.String realClassName = $1.getMessage();"
+ "int spaceParen = realClassName.indexOf(\" (\");"
+ "if (spaceParen > 0) realClassName = realClassName.substring(0, spaceParen);"
+ "if (!originalClassName.replace('.', '/').equals(realClassName)) {"
+ " if (realClassName.startsWith(\"javax/vecmath/\") || realClassName.startsWith(\"com/sun/j3d/\") || realClassName.startsWith(\"javax/media/j3d/\"))"
+ " ij.IJ.error(\"The class \" + originalClassName + \" did not find Java3D (\" + realClassName + \")\\nPlease call Plugins>3D Viewer to install\");"
+ " else"
+ " ij.IJ.handleException($1);"
+ " return null;"
+ "}");
// let the plugin class loader find stuff in $HOME/.plugins, too
addExtraPlugins(hacker);
// make sure that the GenericDialog is disposed in macro mode
if (hacker.hasMethod("ij.gui.GenericDialog", "public void showDialog()")) {
hacker.insertAtTopOfMethod("ij.gui.GenericDialog", "public void showDialog()", "if (macro) dispose();");
}
// make sure NonBlockingGenericDialog does not wait in macro mode
hacker.replaceCallInMethod("ij.gui.NonBlockingGenericDialog", "public void showDialog()", "java.lang.Object", "wait", "if (isShowing()) wait();");
// tell the showStatus() method to show the version() instead of empty status
hacker.insertAtTopOfMethod("ij.ImageJ", "void showStatus(java.lang.String s)", "if ($1 == null || \"\".equals($1)) $1 = version();");
// make sure that the GenericDialog does not make a hidden main window visible
if (!headless) {
hacker.replaceCallInMethod("ij.gui.GenericDialog",
"public <init>(java.lang.String title, java.awt.Frame f)",
"java.awt.Dialog", "super",
"$proceed($1 != null && $1.isVisible() ? $1 : null, $2, $3);");
}
// handle custom icon (e.g. for Fiji)
addIconHooks(hacker);
// optionally disallow batch mode from calling System.exit()
hacker.insertPrivateStaticField("ij.ImageJ", Boolean.TYPE, "batchModeMayExit");
hacker.insertAtTopOfMethod("ij.ImageJ", "public static void main(java.lang.String[] args)",
"batchModeMayExit = true;"
+ "for (int i = 0; i < $1.length; i++) {"
+ " if (\"-batch-no-exit\".equals($1[i])) {"
+ " batchModeMayExit = false;"
+ " $1[i] = \"-batch\";"
+ " }"
+ "}");
hacker.replaceCallInMethod("ij.ImageJ", "public static void main(java.lang.String[] args)", "java.lang.System", "exit",
"if (batchModeMayExit) System.exit($1);"
+ "if ($1 == 0) return;"
+ "throw new RuntimeException(\"Exit code: \" + $1);");
// do not use the current directory as IJ home on Windows
String prefsDir = System.getenv("IJ_PREFS_DIR");
if (prefsDir == null && System.getProperty("os.name").startsWith("Windows")) {
prefsDir = System.getenv("user.home");
}
if (prefsDir != null) {
hacker.overrideFieldWrite("ij.Prefs", "public java.lang.String load(java.lang.Object ij, java.applet.Applet applet)",
"prefsDir", "$_ = \"" + prefsDir + "\";");
}
// tool names can be prefixes of other tools, watch out for that!
hacker.replaceCallInMethod("ij.gui.Toolbar", "public int getToolId(java.lang.String name)", "java.lang.String", "startsWith",
"$_ = $0.equals($1) || $0.startsWith($1 + \"-\") || $0.startsWith($1 + \" -\");");
// make sure Rhino gets the correct class loader
hacker.insertAtTopOfMethod("JavaScriptEvaluator", "public void run()",
"Thread.currentThread().setContextClassLoader(ij.IJ.getClassLoader());");
// make sure that the check for Bio-Formats is correct
hacker.addToClassInitializer("ij.io.Opener",
"try {"
+ " ij.IJ.getClassLoader().loadClass(\"loci.plugins.LociImporter\");"
+ " bioformats = true;"
+ "} catch (ClassNotFoundException e) {"
+ " bioformats = false;"
+ "}");
// make sure that symbolic links are *not* resolved (because then the parent info in the FileInfo would be wrong)
hacker.replaceCallInMethod("ij.plugin.DragAndDrop", "public void openFile(java.io.File f)", "java.io.File", "getCanonicalPath",
"$_ = $0.getAbsolutePath();");
// make sure no dialog is opened in headless mode
hacker.insertAtTopOfMethod("ij.macro.Interpreter", "void showError(java.lang.String title, java.lang.String msg, java.lang.String[] variables)",
"if (ij.IJ.getInstance() == null) {"
+ " java.lang.System.err.println($1 + \": \" + $2);"
+ " return;"
+ "}");
// let IJ.handleException override the macro interpreter's call()'s exception handling
hacker.insertAtTopOfExceptionHandlers("ij.macro.Functions", "java.lang.String call()", "java.lang.reflect.InvocationTargetException",
"ij.IJ.handleException($1);"
+ "return null;");
// Add back the "Convert to 8-bit Grayscale" checkbox to Import>Image Sequence
if (!hacker.hasField("ij.plugin.FolderOpener", "convertToGrayscale")) {
hacker.insertPrivateStaticField("ij.plugin.FolderOpener", Boolean.TYPE, "convertToGrayscale");
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "public void run(java.lang.String arg)", "ij.io.Opener", "openImage",
"$_ = $0.openImage($1, $2);"
+ "if (convertToGrayscale) {"
+ " final String saved = ij.Macro.getOptions();"
+ " ij.IJ.run($_, \"8-bit\", \"\");"
+ " if (saved != null && !saved.equals(\"\")) ij.Macro.setOptions(saved);"
+ "}");
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)",
"ij.plugin.FolderOpener$FolderOpenerDialog", "addCheckbox",
"$0.addCheckbox(\"Convert to 8-bit Grayscale\", convertToGrayscale);"
+ "$0.addCheckbox($1, $2);", 1);
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)",
"ij.plugin.FolderOpener$FolderOpenerDialog", "getNextBoolean",
"convertToGrayscale = $0.getNextBoolean();"
+ "$_ = $0.getNextBoolean();"
+ "if (convertToGrayscale && $_) {"
+ " ij.IJ.error(\"Cannot convert to grayscale and RGB at the same time.\");"
+ " return false;"
+ "}", 1);
}
// handle HTTPS in addition to HTTP
hacker.handleHTTPS("ij.macro.Functions", "java.lang.String exec()");
hacker.handleHTTPS("ij.plugin.DragAndDrop", "public void drop(java.awt.dnd.DropTargetDropEvent dtde)");
hacker.handleHTTPS(hacker.existsClass("ij.plugin.PluginInstaller") ? "ij.plugin.PluginInstaller" : "ij.io.PluginInstaller", "public boolean install(java.lang.String path)");
hacker.handleHTTPS("ij.plugin.ListVirtualStack", "public void run(java.lang.String arg)");
hacker.handleHTTPS("ij.plugin.ListVirtualStack", "java.lang.String[] open(java.lang.String path)");
addEditorExtensionPoints(hacker);
overrideAppVersion(hacker);
insertAppNameHooks(hacker);
insertRefreshMenusHook(hacker);
overrideStartupMacrosForFiji(hacker);
handleMacAdapter(hacker);
handleMenuCallbacks(hacker, headless);
installOpenInterceptor(hacker);
}
/**
* Install a hook to optionally run a Runnable at the end of Help>Refresh Menus.
*
* <p>
* See {@link LegacyExtensions#runAfterRefreshMenus(Runnable)}.
* </p>
*
* @param hacker the {@link CodeHacker} to use for patching
*/
private static void insertRefreshMenusHook(CodeHacker hacker) {
hacker.insertAtBottomOfMethod("ij.Menus", "public static void updateImageJMenus()",
"ij.IJ._hooks.runAfterRefreshMenus();");
}
private static void addEditorExtensionPoints(final CodeHacker hacker) {
hacker.insertAtTopOfMethod("ij.io.Opener", "public void open(java.lang.String path)",
"if (isText($1) && ij.IJ._hooks.openInEditor($1)) return;");
hacker.dontReturnOnNull("ij.plugin.frame.Recorder", "void createMacro()");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createMacro()",
"ij.IJ", "runPlugIn",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createMacro()",
"ij.plugin.frame.Editor", "createMacro",
"if ($1.endsWith(\".txt\")) {"
+ " $1 = $1.substring($1.length() - 3) + \"ijm\";"
+ "}"
+ "if (!ij.IJ._hooks.createInEditor($1, $2)) {"
+ " ((ij.plugin.frame.Editor)ij.IJ.runPlugIn(\"ij.plugin.frame.Editor\", \"\")).createMacro($1, $2);"
+ "}");
hacker.insertPublicStaticField("ij.plugin.frame.Recorder", String.class, "nameForEditor", null);
hacker.insertAtTopOfMethod("ij.plugin.frame.Recorder", "void createPlugin(java.lang.String text, java.lang.String name)",
"this.nameForEditor = $2;");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createPlugin(java.lang.String text, java.lang.String name)",
"ij.IJ", "runPlugIn",
"$_ = null;"
+ "new ij.plugin.NewPlugin().createPlugin(this.nameForEditor, ij.plugin.NewPlugin.PLUGIN, $2);"
+ "return;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createMacro(java.lang.String name)",
"ij.plugin.frame.Editor", "<init>",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createMacro(java.lang.String name)",
"ij.plugin.frame.Editor", "create",
"if ($1.endsWith(\".txt\")) {"
+ " $1 = $1.substring(0, $1.length() - 3) + \"ijm\";"
+ "}"
+ "if ($1.endsWith(\".ijm\") && ij.IJ._hooks.createInEditor($1, $2)) return;"
+ "int options = (monospaced ? ij.plugin.frame.Editor.MONOSPACED : 0)"
+ " | (menuBar ? ij.plugin.frame.Editor.MENU_BAR : 0);"
+ "new ij.plugin.frame.Editor(rows, columns, 0, options).create($1, $2);");
hacker.dontReturnOnNull("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)",
"ij.IJ", "runPlugIn",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)",
"ij.plugin.frame.Editor", "create",
"if (!ij.IJ._hooks.createInEditor($1, $2)) {"
+ " ((ij.plugin.frame.Editor)ij.IJ.runPlugIn(\"ij.plugin.frame.Editor\", \"\")).create($1, $2);"
+ "}");
hacker.replaceCallInMethod("ij.plugin.Compiler",
"void edit()",
"ij.IJ", "runPlugIn",
"if (ij.IJ._hooks.openInEditor(dir + name)) $_ = null;" +
"else $_ = $proceed($$);");
hacker.replaceCallInMethod("ij.gui.Toolbar",
"public void itemStateChanged(java.awt.event.ItemEvent e)",
"ij.plugin.frame.Editor", "create",
"if ($1.endsWith(\".txt\")) $1 = $1.substring(0, $1.length() - 4);" +
"$1 += \".ijm\";" +
"if (!ij.IJ._hooks.createInEditor($1, $2)) $_ = $proceed($$);");
hacker.replaceCallInMethod("ij.plugin.CommandFinder",
"private boolean showMacro(java.lang.String cmd)",
"ij.plugin.frame.Editor", "create",
"if ($1.endsWith(\".txt\")) $1 = $1.substring(0, $1.length() - 4);" +
"$1 += \".ijm\";" +
"if (!ij.IJ._hooks.createInEditor($1, $2)) $_ = $proceed($$);");
}
private static void overrideAppVersion(final CodeHacker hacker) {
hacker.insertAtBottomOfMethod("ij.ImageJ",
"public java.lang.String version()",
"String version = ij.IJ._hooks.getAppVersion();" +
"if (version != null) {" +
" $_ = $_.replace(VERSION, version);" +
"}");
// Of course there is not a *single* way to obtain the version.
// That would have been too easy, wouldn't it?
hacker.insertAtTopOfMethod("ij.IJ",
"public static String getVersion()",
"String version = ij.IJ._hooks.getAppVersion();" +
"if (version != null) return version;");
}
/**
* Inserts hooks to replace the application name.
*/
private static void insertAppNameHooks(final CodeHacker hacker) {
final String appName = "ij.IJ._hooks.getAppName()";
final String replace = ".replace(\"ImageJ\", " + appName + ")";
hacker.insertAtTopOfMethod("ij.IJ", "public void error(java.lang.String title, java.lang.String msg)",
"if ($1 == null || $1.equals(\"ImageJ\")) $1 = " + appName + ";");
hacker.insertAtBottomOfMethod("ij.ImageJ", "public java.lang.String version()", "$_ = $_" + replace + ";");
hacker.replaceAppNameInCall("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)", "super", 1, appName);
hacker.replaceAppNameInNew("ij.ImageJ", "public void run()", "ij.gui.GenericDialog", 1, appName);
hacker.replaceAppNameInCall("ij.ImageJ", "public void run()", "addMessage", 1, appName);
if (hacker.hasMethod("ij.plugin.CommandFinder", "public void export()")) {
hacker.replaceAppNameInNew("ij.plugin.CommandFinder", "public void export()", "ij.text.TextWindow", 1, appName);
}
hacker.replaceAppNameInCall("ij.plugin.Hotkeys", "public void removeHotkey()", "addMessage", 1, appName);
hacker.replaceAppNameInCall("ij.plugin.Hotkeys", "public void removeHotkey()", "showStatus", 1, appName);
if (hacker.existsClass("ij.plugin.AppearanceOptions")) {
hacker.replaceAppNameInCall("ij.plugin.AppearanceOptions", "void showDialog()", "showMessage", 2, appName);
} else {
hacker.replaceAppNameInCall("ij.plugin.Options", "public void appearance()", "showMessage", 2, appName);
}
hacker.replaceAppNameInCall("ij.gui.YesNoCancelDialog", "public <init>(java.awt.Frame parent, java.lang.String title, java.lang.String msg)", "super", 2, appName);
hacker.replaceAppNameInCall("ij.gui.Toolbar", "private void showMessage(int toolId)", "showStatus", 1, appName);
}
private static void addIconHooks(final CodeHacker hacker) {
final String icon = "ij.IJ._hooks.getIconURL()";
hacker.replaceCallInMethod("ij.ImageJ", "void setIcon()", "java.lang.Class", "getResource",
"java.net.URL _iconURL = " + icon + ";\n" +
"if (_iconURL == null) $_ = $0.getResource($1);" +
"else $_ = _iconURL;");
hacker.insertAtTopOfMethod("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)",
"if ($2 != 2 /* ij.ImageJ.NO_SHOW */) setIcon();");
hacker.insertAtTopOfMethod("ij.WindowManager", "public void addWindow(java.awt.Frame window)",
"java.net.URL _iconURL = " + icon + ";\n"
+ "if (_iconURL != null && $1 != null) {"
+ " java.awt.Image img = $1.createImage((java.awt.image.ImageProducer)_iconURL.getContent());"
+ " if (img != null) {"
+ " $1.setIconImage(img);"
+ " }"
+ "}");
}
/**
* Makes sure that the legacy plugin class loader finds stuff in
* {@code $HOME/.plugins/}.
*/
private static void addExtraPlugins(final CodeHacker hacker) {
for (final String methodName : new String[] { "addJAR", "addJar" }) {
if (hacker.hasMethod("ij.io.PluginClassLoader", "private void "
+ methodName + "(java.io.File file)")) {
hacker.insertAtTopOfMethod("ij.io.PluginClassLoader",
"void init(java.lang.String path)",
extraPluginJarsHandler("if (file.isDirectory()) addDirectory(file);" +
"else " + methodName + "(file);"));
}
}
// avoid parsing ij.jar for plugins
hacker.replaceCallInMethod("ij.Menus",
"InputStream autoGenerateConfigFile(java.lang.String jar)",
"java.util.zip.ZipEntry", "getName",
"$_ = $proceed($$);" +
"if (\"IJ_Props.txt\".equals($_)) return null;");
// make sure that extra directories added to the plugin class path work, too
hacker.insertAtTopOfMethod("ij.Menus",
"InputStream getConfigurationFile(java.lang.String jar)",
"java.io.File isDir = new java.io.File($1);" +
"if (!isDir.exists()) return null;" +
"if (isDir.isDirectory()) {" +
" java.io.File config = new java.io.File(isDir, \"plugins.config\");" +
" if (config.exists()) return new java.io.FileInputStream(config);" +
" return ij.IJ._hooks.autoGenerateConfigFile(isDir);" +
"}");
// fix overzealous assumption that all plugins are in plugins.dir
hacker.insertPrivateStaticField("ij.Menus", Set.class, "_extraJars");
hacker.insertAtTopOfMethod("ij.Menus",
"java.lang.String getSubmenuName(java.lang.String jarPath)",
"if (_extraJars.contains($1)) return null;");
// make sure that .jar files are iterated in alphabetical order
hacker.replaceCallInMethod("ij.Menus",
"public static synchronized java.lang.String[] getPlugins()",
"java.io.File", "list",
"$_ = $proceed($$);"
+ "if ($_ != null) java.util.Arrays.sort($_);");
// add the extra .jar files to the list of plugin .jar files to be processed.
hacker.insertAtBottomOfMethod("ij.Menus",
"public static synchronized java.lang.String[] getPlugins()",
"if (_extraJars == null) _extraJars = new java.util.HashSet();" +
extraPluginJarsHandler("if (jarFiles == null) jarFiles = new java.util.Vector();" +
"jarFiles.addElement(file.getAbsolutePath());" +
"_extraJars.add(file.getAbsolutePath());"));
// exclude -sources.jar entries generated by Maven.
hacker.insertAtBottomOfMethod("ij.Menus",
"public static synchronized java.lang.String[] getPlugins()",
"if (jarFiles != null) {" +
" for (int i = jarFiles.size() - 1; i >= 0; i--) {" +
" String entry = (String) jarFiles.elementAt(i);" +
" if (entry.endsWith(\"-sources.jar\")) {" +
" jarFiles.remove(i);" +
" }" +
" }" +
"}");
// force IJ.getClassLoader() to instantiate a PluginClassLoader
hacker.replaceCallInMethod(
"ij.IJ",
"public static ClassLoader getClassLoader()",
"java.lang.System",
"getProperty",
"$_ = System.getProperty($1);\n"
+ "if ($_ == null && $1.equals(\"plugins.dir\")) $_ = \"/non-existant/\";");
}
private static String extraPluginJarsHandler(final String code) {
return "for (java.util.Iterator iter = ij.IJ._hooks.handleExtraPluginJars().iterator();\n" +
"iter.hasNext(); ) {\n" +
"\tjava.io.File file = (java.io.File)iter.next();\n" +
code + "\n" +
"}\n";
}
private static void overrideStartupMacrosForFiji(CodeHacker hacker) {
hacker.replaceCallInMethod("ij.Menus", "void installStartupMacroSet()", "java.io.File", "<init>",
"if ($1.endsWith(\"StartupMacros.txt\")) {" +
" java.lang.String fijiPath = $1.substring(0, $1.length() - 3) + \"fiji.ijm\";" +
" java.io.File fijiFile = new java.io.File(fijiPath);" +
" $_ = fijiFile.exists() ? fijiFile : new java.io.File($1);" +
"} else $_ = new java.io.File($1);");
hacker.replaceCallInMethod("ij.Menus", "void installStartupMacroSet()", "ij.plugin.MacroInstaller", "installFile",
"if ($1.endsWith(\"StartupMacros.txt\")) {" +
" java.lang.String fijiPath = $1.substring(0, $1.length() - 3) + \"fiji.ijm\";" +
" java.io.File fijiFile = new java.io.File(fijiPath);" +
" $0.installFile(fijiFile.exists() ? fijiFile.getPath() : $1);" +
"} else $0.installFile($1);");
}
private static void handleMacAdapter(final CodeHacker hacker) {
// Without the ApplicationListener, MacAdapter cannot load, and hence CodeHacker would fail
// to load it if we patched the class.
if (!hacker.existsClass("com.apple.eawt.ApplicationListener")) return;
hacker.insertAtTopOfMethod("MacAdapter", "public void run(java.lang.String arg)",
"return;");
}
private static void handleMenuCallbacks(final CodeHacker hacker, boolean headless) {
hacker.insertAtTopOfMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.IJ._hooks.addMenuItem(null, null);");
hacker.insertPrivateStaticField("ij.Menus", String.class, "_currentMenuPath");
// so that addSubMenu() has the correct menu path -- even in headless mode
hacker.insertAtTopOfMethod("ij.Menus",
"private static java.awt.Menu getMenu(java.lang.String menuName, boolean readFromProps)",
"_currentMenuPath = $1;");
// so that addPlugInItem() has the correct menu path -- even in headless mode
hacker.insertAtBottomOfMethod("ij.Menus",
"private static java.awt.Menu getMenu(java.lang.String menuName, boolean readFromProps)",
"_currentMenuPath = $1;");
hacker.insertAtTopOfMethod("ij.Menus",
"static java.awt.Menu addSubMenu(java.awt.Menu menu, java.lang.String name)",
"_currentMenuPath += \">\" + $2.replace('_', ' ');");
hacker.replaceCallInMethod("ij.Menus",
"void addPluginsMenu()",
"ij.Menus",
"addPluginItem",
"_currentMenuPath = \"Plugins\";" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"void addPluginsMenu()",
"ij.Menus",
"addSubMenu",
"_currentMenuPath = \"Plugins\";" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addPlugInItem",
"if (\"Quit\".equals($2) || \"Open...\".equals($2) || \"Close\".equals($2) || \"Revert\".equals($2))" +
" _currentMenuPath = \"File\";" +
"else if(\"Show Info...\".equals($2) || \"Crop\".equals($2))" +
" _currentMenuPath = \"Image\";" +
"else if (\"Image Calculator...\".equals($2))" +
" _currentMenuPath = \"Process\";" +
"else if (\"About ImageJ...\".equals($2))" +
" _currentMenuPath = \"Help\";" +
"$_ = $proceed($$);");
// Wow. There are so many different ways ImageJ 1.x adds menu entries. See e.g. "Repeat Command".
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addItem",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + $2, null);" +
"$_ = $proceed($$);");
hacker.insertPrivateStaticField("ij.Menus",
HashSet.class, "_separators");
hacker.insertAtTopOfMethod("ij.Menus",
"void installJarPlugin(java.lang.String jar, java.lang.String s)",
" if (_separators == null) _separators = new java.util.HashSet();" +
"_currentMenuPath = \"Plugins\";");
hacker.replaceCallInMethod("ij.Menus",
"void installJarPlugin(java.lang.String jar, java.lang.String s)",
"java.lang.String", "substring",
"$_ = $proceed($$);" +
"ij.IJ._hooks.addMenuItem(_currentMenuPath, $_);",
4);
hacker.insertAtTopOfMethod("ij.Menus",
"void addPlugInItem(java.awt.Menu menu, java.lang.String label, java.lang.String className, int shortcut, boolean shift)",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + $2, $3);");
hacker.insertAtTopOfMethod("ij.Menus",
"static void addPluginItem(java.awt.Menu submenu, java.lang.String s)",
"int comma = $2.lastIndexOf(',');" +
"if (comma > 0) {" +
" java.lang.String label = $2.substring(1, comma - 1);" +
" if (label.endsWith(\"]\")) {" +
" int open = label.indexOf(\"[\");" +
" if (open > 0 && label.substring(open + 1, comma - 3).matches(\"[A-Za-z0-9]\"))" +
" label = label.substring(0, open);" +
" }" +
" while (comma + 2 < $2.length() && $2.charAt(comma + 1) == ' ')" +
" comma++;" +
" if (mbar == null && _separators != null) {" +
" if (!_separators.contains(_currentMenuPath)) {" +
" _separators.add(_currentMenuPath);" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);" +
" }" +
" }" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + label," +
" $2.substring(comma + 1));" +
"}");
hacker.insertAtTopOfMethod("ij.Menus",
"java.awt.CheckboxMenuItem addCheckboxItem(java.awt.Menu menu, java.lang.String label, java.lang.String className)",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + $2, $3);");
// handle separators (we cannot simply look for java.awt.Menu#addSeparator
// because we might be running in headless mode)
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addPlugInItem",
"if (\"Cache Sample Images \".equals($2))" +
" ij.IJ._hooks.addMenuItem(\"File>Open Samples>-\", null);" +
"else if (\"Close\".equals($2) || \"Page Setup...\".equals($2) || \"Cut\".equals($2) ||" +
" \"Clear\".equals($2) || \"Crop\".equals($2) || \"Set Scale...\".equals($2) ||" +
" \"Dev. Resources...\".equals($2) || \"Update ImageJ...\".equals($2) ||" +
" \"Quit\".equals($2)) {" +
" int separator = _currentMenuPath.indexOf('>');" +
" if (separator < 0) separator = _currentMenuPath.length();" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath.substring(0, separator) + \">-\", null);" +
"}" +
"$_ = $proceed($$);" +
"if (\"Tile\".equals($2))" +
" ij.IJ._hooks.addMenuItem(\"Window>-\", null);");
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addCheckboxItem",
"if (\"RGB Stack\".equals($2))" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"getMenu",
"if (\"Edit>Selection\".equals($1) || \"Image>Adjust\".equals($1) || \"Image>Lookup Tables\".equals($1) ||" +
" \"Process>Batch\".equals($1) || \"Help>About Plugins\".equals($1)) {" +
" int separator = $1.indexOf('>');" +
" ij.IJ._hooks.addMenuItem($1.substring(0, separator) + \">-\", null);" +
"}" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"static java.awt.Menu addSubMenu(java.awt.Menu menu, java.lang.String name)",
"java.lang.String",
"equals",
"$_ = $proceed($$);" +
"if ($_ && \"-\".equals($1))" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);");
hacker.replaceCallInMethod("ij.Menus",
"static void addLuts(java.awt.Menu submenu)",
"ij.IJ",
"isLinux",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"void addPluginsMenu()",
"ij.Prefs",
"getString",
"$_ = $proceed($$);" +
"if ($_ != null && $_.startsWith(\"-\"))" +
" ij.IJ._hooks.addMenuItem(\"Plugins>-\", null);");
hacker.insertAtTopOfMethod("ij.Menus",
"static void addSeparator(java.awt.Menu menu)",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);");
hacker.replaceCallInMethod("ij.Menus", "void installPlugins()",
"ij.Prefs", "getString",
"$_ = $proceed($$);" +
"if ($_ != null && $_.length() > 0) {" +
" String className = $_.substring($_.lastIndexOf(',') + 1);" +
" if (!className.startsWith(\"ij.\")) _currentMenuPath = null;" +
" else {" +
" char c = $_.charAt(0);" +
" if (c == IMPORT_MENU) _currentMenuPath = \"File>Import\";" +
" else if (c == SAVE_AS_MENU) _currentMenuPath = \"File>Save As\";" +
" else if (c == SHORTCUTS_MENU) _currentMenuPath = \"Plugins>Shortcuts\";" +
" else if (c == ABOUT_MENU) _currentMenuPath = \"Help>About Plugins\";" +
" else if (c == FILTERS_MENU) _currentMenuPath = \"Process>Filters\";" +
" else if (c == TOOLS_MENU) _currentMenuPath = \"Analyze>Tools\";" +
" else if (c == UTILITIES_MENU) _currentMenuPath = \"Plugins>Utilities\";" +
" else _currentMenuPath = \"Plugins\";" +
" }" +
"}");
if (headless) {
hacker.replaceCallInMethod("ij.Menus", "void installPlugins()",
"java.lang.String", "substring",
"$_ = $proceed($$);" +
"if (_currentMenuPath != null) addPluginItem((java.awt.Menu) null, $_);", 2);
}
}
private static void installOpenInterceptor(CodeHacker hacker) {
// Intercept ij.IJ open methods
// If the open method is intercepted, the hooks.interceptOpen method needs
// to perform any necessary display operations
hacker.insertAtTopOfMethod("ij.IJ",
"public static void open(java.lang.String path)",
"Object result = ij.IJ._hooks.interceptFileOpen($1);" +
"if (result != null) {" +
"if (result instanceof java.lang.String) path = (java.lang.String)result;" +
"else return;" +
"}");
// If openImage is intercepted, we return the opened ImagePlus without displaying it
hacker.insertAtTopOfMethod("ij.IJ",
"public static ij.ImagePlus openImage(java.lang.String path)",
"Object result = ij.IJ._hooks.interceptOpenImage($1, -1);" +
"if (result != null) {" +
"if (result instanceof ij.ImagePlus) return (ij.ImagePlus)result;" +
"else if (result instanceof java.lang.String) path = (java.lang.String)result;" +
"else return null; " +
"}");
hacker.insertAtTopOfMethod("ij.IJ",
"public static ij.ImagePlus openImage(java.lang.String path, int sliceIndex)",
"Object result = ij.IJ._hooks.interceptOpenImage($1, $2);" +
"if (result != null) {" +
"if (result instanceof ij.ImagePlus) return (ij.ImagePlus)result;" +
"else if (result instanceof java.lang.String) path = (java.lang.String)result;" +
"else return null; " +
"}");
// Intercept File > Open Recent
hacker.replaceCallInMethod("ij.RecentOpener", "public void run()",
"ij.io.Opener", "open",
"Object result = ij.IJ._hooks.interceptOpenRecent(path);" +
"if (result == null) o.open(path);" +
"else if (! (result instanceof ij.ImagePlus)) return;");
// Intercept DragAndDrop openings
hacker.insertAtTopOfMethod("ij.plugin.DragAndDrop",
"public void openFile(java.io.File f)",
"Object result = ij.IJ._hooks.interceptDragAndDropFile($1);" +
"if (result != null) {" +
" return;" +
"}");
// Make sure that .lut files are not intercepted
hacker.replaceCallInMethod("ij.Executer",
"public static boolean loadLut(java.lang.String name)",
"ij.IJ", "open",
"ij.ImagePlus imp = (ij.ImagePlus) ij.IJ.runPlugIn(\"ij.plugin.LutLoader\", $1);" +
"if (imp != null && imp.getWidth() > 0) {" +
" imp.show();" +
"}");
}
// methods to configure LegacyEnvironment instances
static void noPluginClassLoader(final CodeHacker hacker) {
hacker.insertPrivateStaticField("ij.IJ", ClassLoader.class, "_classLoader");
hacker.insertAtTopOfMethod("ij.IJ",
"static void init()",
"_classLoader = Thread.currentThread().getContextClassLoader();");
hacker.insertAtTopOfMethod("ij.IJ",
"static void init()",
"_classLoader = Thread.currentThread().getContextClassLoader();");
hacker.insertAtTopOfMethod("ij.IJ",
"static void init(ij.ImageJ imagej, java.applet.Applet theApplet)",
"_classLoader = Thread.currentThread().getContextClassLoader();");
hacker.insertAtTopOfMethod("ij.IJ",
"public static ClassLoader getClassLoader()",
"return _classLoader;");
hacker.insertAtTopOfMethod(LegacyInjector.ESSENTIAL_LEGACY_HOOKS_CLASS,
"public <init>()", "addThisLoadersClasspath();");
disableRefreshMenus(hacker);
// make sure that IJ#runUserPlugIn can execute package-less plugins in subdirectories of $IJ/plugin/
final String runUserPlugInSig = "static java.lang.Object runUserPlugIn(java.lang.String commandName, java.lang.String className, java.lang.String arg, boolean createNewLoader)";
hacker.insertAtTopOfExceptionHandlers("ij.IJ", runUserPlugInSig, "java.lang.NoClassDefFoundError",
"java.lang.ClassLoader loader = " + LegacyInjector.ESSENTIAL_LEGACY_HOOKS_CLASS +
" .missingSubdirs(getClassLoader());" +
"if (loader != null) _classLoader = loader;");
}
static void disableRefreshMenus(final CodeHacker hacker) {
hacker.insertAtTopOfMethod("ij.IJ",
"static void setClassLoader(java.lang.ClassLoader loader)",
"ij.IJ.log(\"WARNING: The PluginClassLoader cannot be reset\");" +
"return;");
hacker.insertAtBottomOfMethod("ij.Menus", "java.lang.String addMenuBar()",
"if (mbar != null) {" +
" final java.awt.Menu help = mbar.getHelpMenu();" +
" if (help != null) {" +
" for (int i = 0; i < help.getItemCount(); i++) {" +
" final java.awt.MenuItem item = help.getItem(i);" +
" if (\"Refresh Menus\".equals(item.getLabel())) {" +
" item.setEnabled(false);" +
" break;" +
" }" +
" }" +
" }" +
"}");
}
}
| src/main/java/net/imagej/patcher/LegacyExtensions.java | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2014 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imagej.patcher;
import java.util.HashSet;
import java.util.Set;
/**
* Assorted legacy patches / extension points for use in the legacy mode.
*
* <p>
* The Fiji distribution of ImageJ accumulated patches and extensions to ImageJ
* 1.x over the years.
* </p>
*
* <p>
* However, there was a lot of overlap with the ImageJ2 project, so it was
* decided to focus Fiji more on the life-science specific part and move all the
* parts that are of more general use into ImageJ2. That way, it is pretty
* clear-cut what goes into Fiji and what goes into ImageJ2.
* </p>
*
* <p>
* This class contains the extension points (such as being able to override the
* macro editor) ported from Fiji as well as the code for runtime patching
* ImageJ 1.x needed both for the extension points and for more backwards
* compatibility than ImageJ 1.x wanted to provide (e.g. when public methods or
* classes that were used by Fiji plugins were removed all of a sudden, without
* being deprecated first).
* </p>
*
* <p>
* The code in this class is only used in the legacy mode.
* </p>
*
* @author Johannes Schindelin
*/
class LegacyExtensions {
/*
* Extension points
*/
/*
* Runtime patches (using CodeHacker for patching)
*/
/**
* Applies runtime patches to ImageJ 1.x for backwards-compatibility and extension points.
*
* <p>
* These patches enable a patched ImageJ 1.x to call a different script editor or to override
* the application icon.
* </p>
*
* <p>
* This method is called by {@link LegacyInjector#injectHooks(ClassLoader)}.
* </p>
*
* @param hacker the {@link CodeHacker} instance
*/
public static void injectHooks(final CodeHacker hacker, boolean headless) {
//
// Below are patches to make ImageJ 1.x more backwards-compatible
//
// add back the (deprecated) killProcessor(), and overlay methods
final String[] imagePlusMethods = {
"public void killProcessor()",
"{}",
"public void setDisplayList(java.util.Vector list)",
"getCanvas().setDisplayList(list);",
"public java.util.Vector getDisplayList()",
"return getCanvas().getDisplayList();",
"public void setDisplayList(ij.gui.Roi roi, java.awt.Color strokeColor,"
+ " int strokeWidth, java.awt.Color fillColor)",
"setOverlay(roi, strokeColor, strokeWidth, fillColor);"
};
for (int i = 0; i < imagePlusMethods.length; i++) try {
hacker.insertNewMethod("ij.ImagePlus",
imagePlusMethods[i], imagePlusMethods[++i]);
} catch (Exception e) { /* ignore */ }
// make sure that ImageJ has been initialized in batch mode
hacker.insertAtTopOfMethod("ij.IJ",
"public static java.lang.String runMacro(java.lang.String macro, java.lang.String arg)",
"if (ij==null && ij.Menus.getCommands()==null) init();");
try {
hacker.insertNewMethod("ij.CompositeImage",
"public ij.ImagePlus[] splitChannels(boolean closeAfter)",
"ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(this);"
+ "if (closeAfter) close();"
+ "return result;");
hacker.insertNewMethod("ij.plugin.filter.RGBStackSplitter",
"public static ij.ImagePlus[] splitChannelsToArray(ij.ImagePlus imp, boolean closeAfter)",
"if (!imp.isComposite()) {"
+ " ij.IJ.error(\"splitChannelsToArray was called on a non-composite image\");"
+ " return null;"
+ "}"
+ "ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(imp);"
+ "if (closeAfter)"
+ " imp.close();"
+ "return result;");
} catch (IllegalArgumentException e) {
final Throwable cause = e.getCause();
if (cause != null && !cause.getClass().getName().endsWith("DuplicateMemberException")) {
throw e;
}
}
// handle mighty mouse (at least on old Linux, Java mistakes the horizontal wheel for a popup trigger)
for (String fullClass : new String[] {
"ij.gui.ImageCanvas",
"ij.plugin.frame.RoiManager",
"ij.text.TextPanel",
"ij.gui.Toolbar"
}) {
hacker.handleMightyMousePressed(fullClass);
}
// tell IJ#runUserPlugIn to catch NoSuchMethodErrors
final String runUserPlugInSig = "static java.lang.Object runUserPlugIn(java.lang.String commandName, java.lang.String className, java.lang.String arg, boolean createNewLoader)";
hacker.addCatch("ij.IJ", runUserPlugInSig, "java.lang.NoSuchMethodError",
"if (ij.IJ._hooks.handleNoSuchMethodError($e))"
+ " throw new RuntimeException(ij.Macro.MACRO_CANCELED);"
+ "throw $e;");
// tell IJ#runUserPlugIn to be more careful about catching NoClassDefFoundError
hacker.insertPrivateStaticField("ij.IJ", String.class, "originalClassName");
hacker.insertAtTopOfMethod("ij.IJ", runUserPlugInSig, "originalClassName = $2;");
hacker.insertAtTopOfExceptionHandlers("ij.IJ", runUserPlugInSig, "java.lang.NoClassDefFoundError",
"java.lang.String realClassName = $1.getMessage();"
+ "int spaceParen = realClassName.indexOf(\" (\");"
+ "if (spaceParen > 0) realClassName = realClassName.substring(0, spaceParen);"
+ "if (!originalClassName.replace('.', '/').equals(realClassName)) {"
+ " if (realClassName.startsWith(\"javax/vecmath/\") || realClassName.startsWith(\"com/sun/j3d/\") || realClassName.startsWith(\"javax/media/j3d/\"))"
+ " ij.IJ.error(\"The class \" + originalClassName + \" did not find Java3D (\" + realClassName + \")\\nPlease call Plugins>3D Viewer to install\");"
+ " else"
+ " ij.IJ.handleException($1);"
+ " return null;"
+ "}");
// let the plugin class loader find stuff in $HOME/.plugins, too
addExtraPlugins(hacker);
// make sure that the GenericDialog is disposed in macro mode
if (hacker.hasMethod("ij.gui.GenericDialog", "public void showDialog()")) {
hacker.insertAtTopOfMethod("ij.gui.GenericDialog", "public void showDialog()", "if (macro) dispose();");
}
// make sure NonBlockingGenericDialog does not wait in macro mode
hacker.replaceCallInMethod("ij.gui.NonBlockingGenericDialog", "public void showDialog()", "java.lang.Object", "wait", "if (isShowing()) wait();");
// tell the showStatus() method to show the version() instead of empty status
hacker.insertAtTopOfMethod("ij.ImageJ", "void showStatus(java.lang.String s)", "if ($1 == null || \"\".equals($1)) $1 = version();");
// make sure that the GenericDialog does not make a hidden main window visible
if (!headless) {
hacker.replaceCallInMethod("ij.gui.GenericDialog",
"public <init>(java.lang.String title, java.awt.Frame f)",
"java.awt.Dialog", "super",
"$proceed($1 != null && $1.isVisible() ? $1 : null, $2, $3);");
}
// handle custom icon (e.g. for Fiji)
addIconHooks(hacker);
// optionally disallow batch mode from calling System.exit()
hacker.insertPrivateStaticField("ij.ImageJ", Boolean.TYPE, "batchModeMayExit");
hacker.insertAtTopOfMethod("ij.ImageJ", "public static void main(java.lang.String[] args)",
"batchModeMayExit = true;"
+ "for (int i = 0; i < $1.length; i++) {"
+ " if (\"-batch-no-exit\".equals($1[i])) {"
+ " batchModeMayExit = false;"
+ " $1[i] = \"-batch\";"
+ " }"
+ "}");
hacker.replaceCallInMethod("ij.ImageJ", "public static void main(java.lang.String[] args)", "java.lang.System", "exit",
"if (batchModeMayExit) System.exit($1);"
+ "if ($1 == 0) return;"
+ "throw new RuntimeException(\"Exit code: \" + $1);");
// do not use the current directory as IJ home on Windows
String prefsDir = System.getenv("IJ_PREFS_DIR");
if (prefsDir == null && System.getProperty("os.name").startsWith("Windows")) {
prefsDir = System.getenv("user.home");
}
if (prefsDir != null) {
hacker.overrideFieldWrite("ij.Prefs", "public java.lang.String load(java.lang.Object ij, java.applet.Applet applet)",
"prefsDir", "$_ = \"" + prefsDir + "\";");
}
// tool names can be prefixes of other tools, watch out for that!
hacker.replaceCallInMethod("ij.gui.Toolbar", "public int getToolId(java.lang.String name)", "java.lang.String", "startsWith",
"$_ = $0.equals($1) || $0.startsWith($1 + \"-\") || $0.startsWith($1 + \" -\");");
// make sure Rhino gets the correct class loader
hacker.insertAtTopOfMethod("JavaScriptEvaluator", "public void run()",
"Thread.currentThread().setContextClassLoader(ij.IJ.getClassLoader());");
// make sure that the check for Bio-Formats is correct
hacker.addToClassInitializer("ij.io.Opener",
"try {"
+ " ij.IJ.getClassLoader().loadClass(\"loci.plugins.LociImporter\");"
+ " bioformats = true;"
+ "} catch (ClassNotFoundException e) {"
+ " bioformats = false;"
+ "}");
// make sure that symbolic links are *not* resolved (because then the parent info in the FileInfo would be wrong)
hacker.replaceCallInMethod("ij.plugin.DragAndDrop", "public void openFile(java.io.File f)", "java.io.File", "getCanonicalPath",
"$_ = $0.getAbsolutePath();");
// make sure no dialog is opened in headless mode
hacker.insertAtTopOfMethod("ij.macro.Interpreter", "void showError(java.lang.String title, java.lang.String msg, java.lang.String[] variables)",
"if (ij.IJ.getInstance() == null) {"
+ " java.lang.System.err.println($1 + \": \" + $2);"
+ " return;"
+ "}");
// let IJ.handleException override the macro interpreter's call()'s exception handling
hacker.insertAtTopOfExceptionHandlers("ij.macro.Functions", "java.lang.String call()", "java.lang.reflect.InvocationTargetException",
"ij.IJ.handleException($1);"
+ "return null;");
// Add back the "Convert to 8-bit Grayscale" checkbox to Import>Image Sequence
if (!hacker.hasField("ij.plugin.FolderOpener", "convertToGrayscale")) {
hacker.insertPrivateStaticField("ij.plugin.FolderOpener", Boolean.TYPE, "convertToGrayscale");
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "public void run(java.lang.String arg)", "ij.io.Opener", "openImage",
"$_ = $0.openImage($1, $2);"
+ "if (convertToGrayscale) {"
+ " final String saved = ij.Macro.getOptions();"
+ " ij.IJ.run($_, \"8-bit\", \"\");"
+ " if (saved != null && !saved.equals(\"\")) ij.Macro.setOptions(saved);"
+ "}");
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)",
"ij.plugin.FolderOpener$FolderOpenerDialog", "addCheckbox",
"$0.addCheckbox(\"Convert to 8-bit Grayscale\", convertToGrayscale);"
+ "$0.addCheckbox($1, $2);", 1);
hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)",
"ij.plugin.FolderOpener$FolderOpenerDialog", "getNextBoolean",
"convertToGrayscale = $0.getNextBoolean();"
+ "$_ = $0.getNextBoolean();"
+ "if (convertToGrayscale && $_) {"
+ " ij.IJ.error(\"Cannot convert to grayscale and RGB at the same time.\");"
+ " return false;"
+ "}", 1);
}
// handle HTTPS in addition to HTTP
hacker.handleHTTPS("ij.macro.Functions", "java.lang.String exec()");
hacker.handleHTTPS("ij.plugin.DragAndDrop", "public void drop(java.awt.dnd.DropTargetDropEvent dtde)");
hacker.handleHTTPS(hacker.existsClass("ij.plugin.PluginInstaller") ? "ij.plugin.PluginInstaller" : "ij.io.PluginInstaller", "public boolean install(java.lang.String path)");
hacker.handleHTTPS("ij.plugin.ListVirtualStack", "public void run(java.lang.String arg)");
hacker.handleHTTPS("ij.plugin.ListVirtualStack", "java.lang.String[] open(java.lang.String path)");
addEditorExtensionPoints(hacker);
overrideAppVersion(hacker);
insertAppNameHooks(hacker);
insertRefreshMenusHook(hacker);
overrideStartupMacrosForFiji(hacker);
handleMacAdapter(hacker);
handleMenuCallbacks(hacker, headless);
installOpenInterceptor(hacker);
}
/**
* Install a hook to optionally run a Runnable at the end of Help>Refresh Menus.
*
* <p>
* See {@link LegacyExtensions#runAfterRefreshMenus(Runnable)}.
* </p>
*
* @param hacker the {@link CodeHacker} to use for patching
*/
private static void insertRefreshMenusHook(CodeHacker hacker) {
hacker.insertAtBottomOfMethod("ij.Menus", "public static void updateImageJMenus()",
"ij.IJ._hooks.runAfterRefreshMenus();");
}
private static void addEditorExtensionPoints(final CodeHacker hacker) {
hacker.insertAtTopOfMethod("ij.io.Opener", "public void open(java.lang.String path)",
"if (isText($1) && ij.IJ._hooks.openInEditor($1)) return;");
hacker.dontReturnOnNull("ij.plugin.frame.Recorder", "void createMacro()");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createMacro()",
"ij.IJ", "runPlugIn",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createMacro()",
"ij.plugin.frame.Editor", "createMacro",
"if ($1.endsWith(\".txt\")) {"
+ " $1 = $1.substring($1.length() - 3) + \"ijm\";"
+ "}"
+ "if (!ij.IJ._hooks.createInEditor($1, $2)) {"
+ " ((ij.plugin.frame.Editor)ij.IJ.runPlugIn(\"ij.plugin.frame.Editor\", \"\")).createMacro($1, $2);"
+ "}");
hacker.insertPublicStaticField("ij.plugin.frame.Recorder", String.class, "nameForEditor", null);
hacker.insertAtTopOfMethod("ij.plugin.frame.Recorder", "void createPlugin(java.lang.String text, java.lang.String name)",
"this.nameForEditor = $2;");
hacker.replaceCallInMethod("ij.plugin.frame.Recorder", "void createPlugin(java.lang.String text, java.lang.String name)",
"ij.IJ", "runPlugIn",
"$_ = null;"
+ "new ij.plugin.NewPlugin().createPlugin(this.nameForEditor, ij.plugin.NewPlugin.PLUGIN, $2);"
+ "return;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createMacro(java.lang.String name)",
"ij.plugin.frame.Editor", "<init>",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createMacro(java.lang.String name)",
"ij.plugin.frame.Editor", "create",
"if ($1.endsWith(\".txt\")) {"
+ " $1 = $1.substring(0, $1.length() - 3) + \"ijm\";"
+ "}"
+ "if ($1.endsWith(\".ijm\") && ij.IJ._hooks.createInEditor($1, $2)) return;"
+ "int options = (monospaced ? ij.plugin.frame.Editor.MONOSPACED : 0)"
+ " | (menuBar ? ij.plugin.frame.Editor.MENU_BAR : 0);"
+ "new ij.plugin.frame.Editor(rows, columns, 0, options).create($1, $2);");
hacker.dontReturnOnNull("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)",
"ij.IJ", "runPlugIn",
"$_ = null;");
hacker.replaceCallInMethod("ij.plugin.NewPlugin", "public void createPlugin(java.lang.String name, int type, java.lang.String methods)",
"ij.plugin.frame.Editor", "create",
"if (!ij.IJ._hooks.createInEditor($1, $2)) {"
+ " ((ij.plugin.frame.Editor)ij.IJ.runPlugIn(\"ij.plugin.frame.Editor\", \"\")).create($1, $2);"
+ "}");
hacker.replaceCallInMethod("ij.plugin.Compiler",
"void edit()",
"ij.IJ", "runPlugIn",
"if (ij.IJ._hooks.openInEditor(dir + name)) $_ = null;" +
"else $_ = $proceed($$);");
hacker.replaceCallInMethod("ij.gui.Toolbar",
"public void itemStateChanged(java.awt.event.ItemEvent e)",
"ij.plugin.frame.Editor", "create",
"if ($1.endsWith(\".txt\")) $1 = $1.substring(0, $1.length() - 4);" +
"$1 += \".ijm\";" +
"if (!ij.IJ._hooks.createInEditor($1, $2)) $_ = $proceed($$);");
hacker.replaceCallInMethod("ij.plugin.CommandFinder",
"private boolean showMacro(java.lang.String cmd)",
"ij.plugin.frame.Editor", "create",
"if ($1.endsWith(\".txt\")) $1 = $1.substring(0, $1.length() - 4);" +
"$1 += \".ijm\";" +
"if (!ij.IJ._hooks.createInEditor($1, $2)) $_ = $proceed($$);");
}
private static void overrideAppVersion(final CodeHacker hacker) {
hacker.insertAtBottomOfMethod("ij.ImageJ",
"public java.lang.String version()",
"String version = ij.IJ._hooks.getAppVersion();" +
"if (version != null) {" +
" $_ = $_.replace(VERSION, version);" +
"}");
// Of course there is not a *single* way to obtain the version.
// That would have been too easy, wouldn't it?
hacker.insertAtTopOfMethod("ij.IJ",
"public static String getVersion()",
"String version = ij.IJ._hooks.getAppVersion();" +
"if (version != null) return version;");
}
/**
* Inserts hooks to replace the application name.
*/
private static void insertAppNameHooks(final CodeHacker hacker) {
final String appName = "ij.IJ._hooks.getAppName()";
final String replace = ".replace(\"ImageJ\", " + appName + ")";
hacker.insertAtTopOfMethod("ij.IJ", "public void error(java.lang.String title, java.lang.String msg)",
"if ($1 == null || $1.equals(\"ImageJ\")) $1 = " + appName + ";");
hacker.insertAtBottomOfMethod("ij.ImageJ", "public java.lang.String version()", "$_ = $_" + replace + ";");
hacker.replaceAppNameInCall("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)", "super", 1, appName);
hacker.replaceAppNameInNew("ij.ImageJ", "public void run()", "ij.gui.GenericDialog", 1, appName);
hacker.replaceAppNameInCall("ij.ImageJ", "public void run()", "addMessage", 1, appName);
if (hacker.hasMethod("ij.plugin.CommandFinder", "public void export()")) {
hacker.replaceAppNameInNew("ij.plugin.CommandFinder", "public void export()", "ij.text.TextWindow", 1, appName);
}
hacker.replaceAppNameInCall("ij.plugin.Hotkeys", "public void removeHotkey()", "addMessage", 1, appName);
hacker.replaceAppNameInCall("ij.plugin.Hotkeys", "public void removeHotkey()", "showStatus", 1, appName);
if (hacker.existsClass("ij.plugin.AppearanceOptions")) {
hacker.replaceAppNameInCall("ij.plugin.AppearanceOptions", "void showDialog()", "showMessage", 2, appName);
} else {
hacker.replaceAppNameInCall("ij.plugin.Options", "public void appearance()", "showMessage", 2, appName);
}
hacker.replaceAppNameInCall("ij.gui.YesNoCancelDialog", "public <init>(java.awt.Frame parent, java.lang.String title, java.lang.String msg)", "super", 2, appName);
hacker.replaceAppNameInCall("ij.gui.Toolbar", "private void showMessage(int toolId)", "showStatus", 1, appName);
}
private static void addIconHooks(final CodeHacker hacker) {
final String icon = "ij.IJ._hooks.getIconURL()";
hacker.replaceCallInMethod("ij.ImageJ", "void setIcon()", "java.lang.Class", "getResource",
"java.net.URL _iconURL = " + icon + ";\n" +
"if (_iconURL == null) $_ = $0.getResource($1);" +
"else $_ = _iconURL;");
hacker.insertAtTopOfMethod("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)",
"if ($2 != 2 /* ij.ImageJ.NO_SHOW */) setIcon();");
hacker.insertAtTopOfMethod("ij.WindowManager", "public void addWindow(java.awt.Frame window)",
"java.net.URL _iconURL = " + icon + ";\n"
+ "if (_iconURL != null && $1 != null) {"
+ " java.awt.Image img = $1.createImage((java.awt.image.ImageProducer)_iconURL.getContent());"
+ " if (img != null) {"
+ " $1.setIconImage(img);"
+ " }"
+ "}");
}
/**
* Makes sure that the legacy plugin class loader finds stuff in
* {@code $HOME/.plugins/}.
*/
private static void addExtraPlugins(final CodeHacker hacker) {
for (final String methodName : new String[] { "addJAR", "addJar" }) {
if (hacker.hasMethod("ij.io.PluginClassLoader", "private void "
+ methodName + "(java.io.File file)")) {
hacker.insertAtTopOfMethod("ij.io.PluginClassLoader",
"void init(java.lang.String path)",
extraPluginJarsHandler("if (file.isDirectory()) addDirectory(file);" +
"else " + methodName + "(file);"));
}
}
// avoid parsing ij.jar for plugins
hacker.replaceCallInMethod("ij.Menus",
"InputStream autoGenerateConfigFile(java.lang.String jar)",
"java.util.zip.ZipEntry", "getName",
"$_ = $proceed($$);" +
"if (\"IJ_Props.txt\".equals($_)) return null;");
// make sure that extra directories added to the plugin class path work, too
hacker.insertAtTopOfMethod("ij.Menus",
"InputStream getConfigurationFile(java.lang.String jar)",
"java.io.File isDir = new java.io.File($1);" +
"if (!isDir.exists()) return null;" +
"if (isDir.isDirectory()) {" +
" java.io.File config = new java.io.File(isDir, \"plugins.config\");" +
" if (config.exists()) return new java.io.FileInputStream(config);" +
" return ij.IJ._hooks.autoGenerateConfigFile(isDir);" +
"}");
// fix overzealous assumption that all plugins are in plugins.dir
hacker.insertPrivateStaticField("ij.Menus", Set.class, "_extraJars");
hacker.insertAtTopOfMethod("ij.Menus",
"java.lang.String getSubmenuName(java.lang.String jarPath)",
"if (_extraJars.contains($1)) return null;");
// make sure that .jar files are iterated in alphabetical order
hacker.replaceCallInMethod("ij.Menus",
"public static synchronized java.lang.String[] getPlugins()",
"java.io.File", "list",
"$_ = $proceed($$);"
+ "if ($_ != null) java.util.Arrays.sort($_);");
// add the extra .jar files to the list of plugin .jar files to be processed.
hacker.insertAtBottomOfMethod("ij.Menus",
"public static synchronized java.lang.String[] getPlugins()",
"if (_extraJars == null) _extraJars = new java.util.HashSet();" +
extraPluginJarsHandler("if (jarFiles == null) jarFiles = new java.util.Vector();" +
"jarFiles.addElement(file.getAbsolutePath());" +
"_extraJars.add(file.getAbsolutePath());"));
// exclude -sources.jar entries generated by Maven.
hacker.insertAtBottomOfMethod("ij.Menus",
"public static synchronized java.lang.String[] getPlugins()",
"if (jarFiles != null) {" +
" for (int i = jarFiles.size() - 1; i >= 0; i--) {" +
" String entry = (String) jarFiles.elementAt(i);" +
" if (entry.endsWith(\"-sources.jar\")) {" +
" jarFiles.remove(i);" +
" }" +
" }" +
"}");
// force IJ.getClassLoader() to instantiate a PluginClassLoader
hacker.replaceCallInMethod(
"ij.IJ",
"public static ClassLoader getClassLoader()",
"java.lang.System",
"getProperty",
"$_ = System.getProperty($1);\n"
+ "if ($_ == null && $1.equals(\"plugins.dir\")) $_ = \"/non-existant/\";");
}
private static String extraPluginJarsHandler(final String code) {
return "for (java.util.Iterator iter = ij.IJ._hooks.handleExtraPluginJars().iterator();\n" +
"iter.hasNext(); ) {\n" +
"\tjava.io.File file = (java.io.File)iter.next();\n" +
code + "\n" +
"}\n";
}
private static void overrideStartupMacrosForFiji(CodeHacker hacker) {
hacker.replaceCallInMethod("ij.Menus", "void installStartupMacroSet()", "java.io.File", "<init>",
"if ($1.endsWith(\"StartupMacros.txt\")) {" +
" java.lang.String fijiPath = $1.substring(0, $1.length() - 3) + \"fiji.ijm\";" +
" java.io.File fijiFile = new java.io.File(fijiPath);" +
" $_ = fijiFile.exists() ? fijiFile : new java.io.File($1);" +
"} else $_ = new java.io.File($1);");
hacker.replaceCallInMethod("ij.Menus", "void installStartupMacroSet()", "ij.plugin.MacroInstaller", "installFile",
"if ($1.endsWith(\"StartupMacros.txt\")) {" +
" java.lang.String fijiPath = $1.substring(0, $1.length() - 3) + \"fiji.ijm\";" +
" java.io.File fijiFile = new java.io.File(fijiPath);" +
" $0.installFile(fijiFile.exists() ? fijiFile.getPath() : $1);" +
"} else $0.installFile($1);");
}
private static void handleMacAdapter(final CodeHacker hacker) {
// Without the ApplicationListener, MacAdapter cannot load, and hence CodeHacker would fail
// to load it if we patched the class.
if (!hacker.existsClass("com.apple.eawt.ApplicationListener")) return;
hacker.insertAtTopOfMethod("MacAdapter", "public void run(java.lang.String arg)",
"return;");
}
private static void handleMenuCallbacks(final CodeHacker hacker, boolean headless) {
hacker.insertAtTopOfMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.IJ._hooks.addMenuItem(null, null);");
hacker.insertPrivateStaticField("ij.Menus", String.class, "_currentMenuPath");
// so that addSubMenu() has the correct menu path -- even in headless mode
hacker.insertAtTopOfMethod("ij.Menus",
"private static java.awt.Menu getMenu(java.lang.String menuName, boolean readFromProps)",
"_currentMenuPath = $1;");
// so that addPlugInItem() has the correct menu path -- even in headless mode
hacker.insertAtBottomOfMethod("ij.Menus",
"private static java.awt.Menu getMenu(java.lang.String menuName, boolean readFromProps)",
"_currentMenuPath = $1;");
hacker.insertAtTopOfMethod("ij.Menus",
"static java.awt.Menu addSubMenu(java.awt.Menu menu, java.lang.String name)",
"_currentMenuPath += \">\" + $2.replace('_', ' ');");
hacker.replaceCallInMethod("ij.Menus",
"void addPluginsMenu()",
"ij.Menus",
"addPluginItem",
"_currentMenuPath = \"Plugins\";" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"void addPluginsMenu()",
"ij.Menus",
"addSubMenu",
"_currentMenuPath = \"Plugins\";" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addPlugInItem",
"if (\"Quit\".equals($2) || \"Open...\".equals($2) || \"Close\".equals($2) || \"Revert\".equals($2))" +
" _currentMenuPath = \"File\";" +
"else if(\"Show Info...\".equals($2) || \"Crop\".equals($2))" +
" _currentMenuPath = \"Image\";" +
"else if (\"Image Calculator...\".equals($2))" +
" _currentMenuPath = \"Process\";" +
"else if (\"About ImageJ...\".equals($2))" +
" _currentMenuPath = \"Help\";" +
"$_ = $proceed($$);");
// Wow. There are so many different ways ImageJ 1.x adds menu entries. See e.g. "Repeat Command".
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addItem",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + $2, null);" +
"$_ = $proceed($$);");
hacker.insertPrivateStaticField("ij.Menus",
HashSet.class, "_separators");
hacker.insertAtTopOfMethod("ij.Menus",
"void installJarPlugin(java.lang.String jar, java.lang.String s)",
" if (_separators == null) _separators = new java.util.HashSet();" +
"_currentMenuPath = \"Plugins\";");
hacker.replaceCallInMethod("ij.Menus",
"void installJarPlugin(java.lang.String jar, java.lang.String s)",
"java.lang.String", "substring",
"$_ = $proceed($$);" +
"ij.IJ._hooks.addMenuItem(_currentMenuPath, $_);",
4);
hacker.insertAtTopOfMethod("ij.Menus",
"void addPlugInItem(java.awt.Menu menu, java.lang.String label, java.lang.String className, int shortcut, boolean shift)",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + $2, $3);");
hacker.insertAtTopOfMethod("ij.Menus",
"static void addPluginItem(java.awt.Menu submenu, java.lang.String s)",
"int comma = $2.lastIndexOf(',');" +
"if (comma > 0) {" +
" java.lang.String label = $2.substring(1, comma - 1);" +
" if (label.endsWith(\"]\")) {" +
" int open = label.indexOf(\"[\");" +
" if (open > 0 && label.substring(open + 1, comma - 3).matches(\"[A-Za-z0-9]\"))" +
" label = label.substring(0, open);" +
" }" +
" while (comma + 2 < $2.length() && $2.charAt(comma + 1) == ' ')" +
" comma++;" +
" if (mbar == null && _separators != null) {" +
" if (!_separators.contains(_currentMenuPath)) {" +
" _separators.add(_currentMenuPath);" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);" +
" }" +
" }" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + label," +
" $2.substring(comma + 1));" +
"}");
hacker.insertAtTopOfMethod("ij.Menus",
"java.awt.CheckboxMenuItem addCheckboxItem(java.awt.Menu menu, java.lang.String label, java.lang.String className)",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">\" + $2, $3);");
// handle separators (we cannot simply look for java.awt.Menu#addSeparator
// because we might be running in headless mode)
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addPlugInItem",
"if (\"Cache Sample Images \".equals($2))" +
" ij.IJ._hooks.addMenuItem(\"File>Open Samples>-\", null);" +
"else if (\"Close\".equals($2) || \"Page Setup...\".equals($2) || \"Cut\".equals($2) ||" +
" \"Clear\".equals($2) || \"Crop\".equals($2) || \"Set Scale...\".equals($2) ||" +
" \"Dev. Resources...\".equals($2) || \"Update ImageJ...\".equals($2) ||" +
" \"Quit\".equals($2)) {" +
" int separator = _currentMenuPath.indexOf('>');" +
" if (separator < 0) separator = _currentMenuPath.length();" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath.substring(0, separator) + \">-\", null);" +
"}" +
"$_ = $proceed($$);" +
"if (\"Tile\".equals($2))" +
" ij.IJ._hooks.addMenuItem(\"Window>-\", null);");
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"addCheckboxItem",
"if (\"RGB Stack\".equals($2))" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"java.lang.String addMenuBar()",
"ij.Menus",
"getMenu",
"if (\"Edit>Selection\".equals($1) || \"Image>Adjust\".equals($1) || \"Image>Lookup Tables\".equals($1) ||" +
" \"Process>Batch\".equals($1) || \"Help>About Plugins\".equals($1)) {" +
" int separator = $1.indexOf('>');" +
" ij.IJ._hooks.addMenuItem($1.substring(0, separator) + \">-\", null);" +
"}" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"static java.awt.Menu addSubMenu(java.awt.Menu menu, java.lang.String name)",
"java.lang.String",
"equals",
"$_ = $proceed($$);" +
"if ($_ && \"-\".equals($1))" +
" ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);");
hacker.replaceCallInMethod("ij.Menus",
"static void addLuts(java.awt.Menu submenu)",
"ij.IJ",
"isLinux",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);" +
"$_ = $proceed($$);");
hacker.replaceCallInMethod("ij.Menus",
"void addPluginsMenu()",
"ij.Prefs",
"getString",
"$_ = $proceed($$);" +
"if ($_ != null && $_.startsWith(\"-\"))" +
" ij.IJ._hooks.addMenuItem(\"Plugins>-\", null);");
hacker.insertAtTopOfMethod("ij.Menus",
"static void addSeparator(java.awt.Menu menu)",
"ij.IJ._hooks.addMenuItem(_currentMenuPath + \">-\", null);");
hacker.replaceCallInMethod("ij.Menus", "void installPlugins()",
"ij.Prefs", "getString",
"$_ = $proceed($$);" +
"if ($_ != null && $_.length() > 0) {" +
" String className = $_.substring($_.lastIndexOf(',') + 1);" +
" if (!className.startsWith(\"ij.\")) _currentMenuPath = null;" +
" else {" +
" char c = $_.charAt(0);" +
" if (c == IMPORT_MENU) _currentMenuPath = \"File>Import\";" +
" else if (c == SAVE_AS_MENU) _currentMenuPath = \"File>Save As\";" +
" else if (c == SHORTCUTS_MENU) _currentMenuPath = \"Plugins>Shortcuts\";" +
" else if (c == ABOUT_MENU) _currentMenuPath = \"Help>About Plugins\";" +
" else if (c == FILTERS_MENU) _currentMenuPath = \"Process>Filters\";" +
" else if (c == TOOLS_MENU) _currentMenuPath = \"Analyze>Tools\";" +
" else if (c == UTILITIES_MENU) _currentMenuPath = \"Plugins>Utilities\";" +
" else _currentMenuPath = \"Plugins\";" +
" }" +
"}");
if (headless) {
hacker.replaceCallInMethod("ij.Menus", "void installPlugins()",
"java.lang.String", "substring",
"$_ = $proceed($$);" +
"if (_currentMenuPath != null) addPluginItem((java.awt.Menu) null, $_);", 2);
}
}
private static void installOpenInterceptor(CodeHacker hacker) {
// Intercept ij.IJ open methods
// If the open method is intercepted, the hooks.interceptOpen method needs
// to perform any necessary display operations
hacker.insertAtTopOfMethod("ij.IJ",
"public static void open(java.lang.String path)",
"Object result = ij.IJ._hooks.interceptFileOpen($1);" +
"if (result != null) return;");
// If openImage is intercepted, we return the opened ImagePlus without displaying it
hacker.insertAtTopOfMethod("ij.IJ",
"public static ij.ImagePlus openImage(java.lang.String path)",
"Object result = ij.IJ._hooks.interceptOpenImage($1, -1);" +
"if (result != null) {" +
"if (result instanceof ij.ImagePlus) return (ij.ImagePlus)result;" +
"return null; " +
"}");
hacker.insertAtTopOfMethod("ij.IJ",
"public static ij.ImagePlus openImage(java.lang.String path, int sliceIndex)",
"Object result = ij.IJ._hooks.interceptOpenImage($1, $2);" +
"if (result != null) {" +
"if (result instanceof ij.ImagePlus) return (ij.ImagePlus)result;" +
"return null; " +
"}");
// Intercept File > Open Recent
hacker.replaceCallInMethod("ij.RecentOpener", "public void run()",
"ij.io.Opener", "open",
"Object result = ij.IJ._hooks.interceptOpenRecent(path);" +
"if (result == null) o.open(path);" +
"else if (! (result instanceof ij.ImagePlus)) return;");
// Intercept DragAndDrop openings
hacker.insertAtTopOfMethod("ij.plugin.DragAndDrop",
"public void openFile(java.io.File f)",
"Object result = ij.IJ._hooks.interceptDragAndDropFile($1);" +
"if (result != null) {" +
" return;" +
"}");
// Make sure that .lut files are not intercepted
hacker.replaceCallInMethod("ij.Executer",
"public static boolean loadLut(java.lang.String name)",
"ij.IJ", "open",
"ij.ImagePlus imp = (ij.ImagePlus) ij.IJ.runPlugIn(\"ij.plugin.LutLoader\", $1);" +
"if (imp != null && imp.getWidth() > 0) {" +
" imp.show();" +
"}");
}
// methods to configure LegacyEnvironment instances
static void noPluginClassLoader(final CodeHacker hacker) {
hacker.insertPrivateStaticField("ij.IJ", ClassLoader.class, "_classLoader");
hacker.insertAtTopOfMethod("ij.IJ",
"static void init()",
"_classLoader = Thread.currentThread().getContextClassLoader();");
hacker.insertAtTopOfMethod("ij.IJ",
"static void init()",
"_classLoader = Thread.currentThread().getContextClassLoader();");
hacker.insertAtTopOfMethod("ij.IJ",
"static void init(ij.ImageJ imagej, java.applet.Applet theApplet)",
"_classLoader = Thread.currentThread().getContextClassLoader();");
hacker.insertAtTopOfMethod("ij.IJ",
"public static ClassLoader getClassLoader()",
"return _classLoader;");
hacker.insertAtTopOfMethod(LegacyInjector.ESSENTIAL_LEGACY_HOOKS_CLASS,
"public <init>()", "addThisLoadersClasspath();");
disableRefreshMenus(hacker);
// make sure that IJ#runUserPlugIn can execute package-less plugins in subdirectories of $IJ/plugin/
final String runUserPlugInSig = "static java.lang.Object runUserPlugIn(java.lang.String commandName, java.lang.String className, java.lang.String arg, boolean createNewLoader)";
hacker.insertAtTopOfExceptionHandlers("ij.IJ", runUserPlugInSig, "java.lang.NoClassDefFoundError",
"java.lang.ClassLoader loader = " + LegacyInjector.ESSENTIAL_LEGACY_HOOKS_CLASS +
" .missingSubdirs(getClassLoader());" +
"if (loader != null) _classLoader = loader;");
}
static void disableRefreshMenus(final CodeHacker hacker) {
hacker.insertAtTopOfMethod("ij.IJ",
"static void setClassLoader(java.lang.ClassLoader loader)",
"ij.IJ.log(\"WARNING: The PluginClassLoader cannot be reset\");" +
"return;");
hacker.insertAtBottomOfMethod("ij.Menus", "java.lang.String addMenuBar()",
"if (mbar != null) {" +
" final java.awt.Menu help = mbar.getHelpMenu();" +
" if (help != null) {" +
" for (int i = 0; i < help.getItemCount(); i++) {" +
" final java.awt.MenuItem item = help.getItem(i);" +
" if (\"Refresh Menus\".equals(item.getLabel())) {" +
" item.setEnabled(false);" +
" break;" +
" }" +
" }" +
" }" +
"}");
}
}
| LegacyExtensions: update open path
When intercepting open signatures, if a hook returns a String value we
will now interpret that as the file path. This way, if a user selects a
path via a file chooser in IJ2, they shouldn't have to select it again
in IJ1.
| src/main/java/net/imagej/patcher/LegacyExtensions.java | LegacyExtensions: update open path | <ide><path>rc/main/java/net/imagej/patcher/LegacyExtensions.java
<ide> hacker.insertAtTopOfMethod("ij.IJ",
<ide> "public static void open(java.lang.String path)",
<ide> "Object result = ij.IJ._hooks.interceptFileOpen($1);" +
<del> "if (result != null) return;");
<add> "if (result != null) {" +
<add> "if (result instanceof java.lang.String) path = (java.lang.String)result;" +
<add> "else return;" +
<add> "}");
<ide> // If openImage is intercepted, we return the opened ImagePlus without displaying it
<ide> hacker.insertAtTopOfMethod("ij.IJ",
<ide> "public static ij.ImagePlus openImage(java.lang.String path)",
<ide> "Object result = ij.IJ._hooks.interceptOpenImage($1, -1);" +
<ide> "if (result != null) {" +
<ide> "if (result instanceof ij.ImagePlus) return (ij.ImagePlus)result;" +
<del> "return null; " +
<add> "else if (result instanceof java.lang.String) path = (java.lang.String)result;" +
<add> "else return null; " +
<ide> "}");
<ide> hacker.insertAtTopOfMethod("ij.IJ",
<ide> "public static ij.ImagePlus openImage(java.lang.String path, int sliceIndex)",
<ide> "Object result = ij.IJ._hooks.interceptOpenImage($1, $2);" +
<ide> "if (result != null) {" +
<ide> "if (result instanceof ij.ImagePlus) return (ij.ImagePlus)result;" +
<del> "return null; " +
<add> "else if (result instanceof java.lang.String) path = (java.lang.String)result;" +
<add> "else return null; " +
<ide> "}");
<ide>
<ide> // Intercept File > Open Recent |
|
JavaScript | mit | 0861ffda8af9e6598728607b29fc21561cd9d49a | 0 | jakubgarfield/expenses,jakubgarfield/expenses,jakubgarfield/expenses | import React, { Component } from 'react';
import ExpenseList from './ExpenseList.js';
import ExpenseForm from './ExpenseForm.js';
import LoadingBar from "./LoadingBar.js"
import './App.css';
class App extends Component {
constructor() {
super();
this.clientId = '826265862385-p41e559ccssujlfsf49ppmo0gktkf6co.apps.googleusercontent.com';
this.spreadsheetId = "18uwYwUAVw0H5bhszMgAORmvAN2APxAtJI3FB-XH7Dzk";
this.state = {
signedIn: undefined,
accounts: [],
categories: [],
expenses: [],
loadingData: true,
}
}
componentDidMount() {
window.gapi.load('client:auth2', () => {
window.gapi.client.init({
discoveryDocs: ["https://sheets.googleapis.com/$discovery/rest?version=v4"],
clientId: this.clientId,
scope: "https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive.metadata.readonly"
}).then(() => {
window.gapi.auth2.getAuthInstance().isSignedIn.listen((signedIn) => { this.setState({ signedIn: signedIn }) });
this.setState({ signedIn: window.gapi.auth2.getAuthInstance().isSignedIn.get() });
this.getData();
});
});
}
getData() {
window.gapi.client.sheets.spreadsheets.values
.batchGet({ spreadsheetId: this.spreadsheetId, ranges: ["Data!A2:A50", "Data!E2:E50", "Expenses!A2:F"] })
.then(response => {
this.setState({
accounts: response.result.valueRanges[0].values.map(items => items[0]),
categories: response.result.valueRanges[1].values.map(items => items[0]),
expenses: response.result.valueRanges[2].values,
loadingData: false,
});
});
}
render() {
const loading = (<LoadingBar />);
const userNotSigned = (<button onClick={() => { window.gapi.auth2.getAuthInstance().signIn(); }}>Sign In</button>);
const userSigned = (
<div>
<button onClick={() => { window.gapi.auth2.getAuthInstance().signOut(); }}>Sign Out</button>
{this.renderBody()}
</div>
);
switch (this.state.signedIn) {
case false:
return userNotSigned;
case true:
return userSigned;
default:
return loading;
}
}
renderBody()
{
if (this.state.loadingData)
return <LoadingBar />;
else
return (
<div className="content">
<ExpenseList expenses={this.state.expenses} />
<ExpenseForm categories={this.state.categories} accounts={this.state.accounts} />
</div>
);
}
}
export default App;
| src/App.js | import React, { Component } from 'react';
import ExpenseList from './ExpenseList.js';
import ExpenseForm from './ExpenseForm.js';
import LoadingBar from "./LoadingBar.js"
import './App.css';
class App extends Component {
constructor() {
super();
this.clientId = '826265862385-p41e559ccssujlfsf49ppmo0gktkf6co.apps.googleusercontent.com';
this.spreadsheetId = "18uwYwUAVw0H5bhszMgAORmvAN2APxAtJI3FB-XH7Dzk";
this.state = {
signedIn: undefined,
accounts: [],
categories: [],
expenses: [],
loadingData: true,
}
}
componentDidMount() {
window.gapi.load('client:auth2', () => {
window.gapi.client.init({
discoveryDocs: ["https://sheets.googleapis.com/$discovery/rest?version=v4"],
clientId: this.clientId,
scope: "https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/drive.metadata.readonly"
}).then(() => {
window.gapi.auth2.getAuthInstance().isSignedIn.listen((signedIn) => { this.setState({ signedIn: signedIn }) });
this.setState({ signedIn: window.gapi.auth2.getAuthInstance().isSignedIn.get() });
this.getData();
});
});
}
getData() {
window.gapi.client.sheets.spreadsheets.values
.batchGet({ spreadsheetId: this.spreadsheetId, ranges: ["Data!A2:A50", "Data!E2:E50", "Expenses!A2:F"] })
.then(response => {
this.setState({
accounts: response.result.valueRanges[0].values,
categories: response.result.valueRanges[1].values,
expenses: response.result.valueRanges[2].values,
loadingData: false,
});
});
}
render() {
const loading = (<LoadingBar />);
const userNotSigned = (<button onClick={() => { window.gapi.auth2.getAuthInstance().signIn(); }}>Sign In</button>);
const userSigned = (
<div>
<button onClick={() => { window.gapi.auth2.getAuthInstance().signOut(); }}>Sign Out</button>
{this.renderBody()}
</div>
);
switch (this.state.signedIn) {
case false:
return userNotSigned;
case true:
return userSigned;
default:
return loading;
}
}
renderBody()
{
if (this.state.loadingData)
return <LoadingBar />;
else
return (
<div className="content">
<ExpenseList expenses={this.state.expenses} />
<ExpenseForm categories={this.state.categories} accounts={this.state.accounts} />
</div>
);
}
}
export default App;
| Fix mapping of accounts and expenses
| src/App.js | Fix mapping of accounts and expenses | <ide><path>rc/App.js
<ide> .batchGet({ spreadsheetId: this.spreadsheetId, ranges: ["Data!A2:A50", "Data!E2:E50", "Expenses!A2:F"] })
<ide> .then(response => {
<ide> this.setState({
<del> accounts: response.result.valueRanges[0].values,
<del> categories: response.result.valueRanges[1].values,
<add> accounts: response.result.valueRanges[0].values.map(items => items[0]),
<add> categories: response.result.valueRanges[1].values.map(items => items[0]),
<ide> expenses: response.result.valueRanges[2].values,
<ide> loadingData: false,
<ide> }); |
|
Java | lgpl-2.1 | 9ff27df4fa2518dab737996cfe2bb776462a6778 | 0 | johnscancella/spotbugs,sewe/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,sewe/spotbugs | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2005, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.JavaClass;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.NonReportingDetector;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.jsr305.Analysis;
import edu.umd.cs.findbugs.ba.jsr305.DirectlyRelevantTypeQualifiersDatabase;
import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierAnnotation;
import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierApplications;
import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierValue;
import edu.umd.cs.findbugs.bcel.BCELUtil;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
/**
* Scan classes for type qualifier annotations
* and convey them to interested detectors (FindNullDeref, CheckTypeQualifiers, ...)
*/
public class NoteDirectlyRelevantTypeQualifiers //extends DirectlyRelevantTypeQualifiersDatabase
extends DismantleBytecode
implements Detector, NonReportingDetector {
private BugReporter bugReporter;
private DirectlyRelevantTypeQualifiersDatabase qualifiers;
public NoteDirectlyRelevantTypeQualifiers(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visitClassContext(ClassContext classContext) {
if (qualifiers == null) {
qualifiers = AnalysisContext.currentAnalysisContext().getDirectlyRelevantTypeQualifiersDatabase();
}
JavaClass javaClass = classContext.getJavaClass();
if (!BCELUtil.preTiger(javaClass)) javaClass.accept(this);
}
HashSet<TypeQualifierValue> applicableApplications;
@Override
public void visit(Code m) {
applicableApplications = new HashSet<TypeQualifierValue>();
XMethod xMethod = getXMethod();
// Find the direct annotations on this method
updateApplicableAnnotations(xMethod);
// Find direct annotations on called methods and loaded fields
super.visit(m);
if (applicableApplications.size() > 0) {
qualifiers.setDirectlyRelevantTypeQualifiers(getMethodDescriptor(), new ArrayList<TypeQualifierValue>(applicableApplications));
}
}
@Override
public void sawOpcode(int seen) {
switch(seen) {
case INVOKEINTERFACE:
case INVOKEVIRTUAL:
case INVOKESTATIC:
case INVOKESPECIAL:
{
XMethod m = XFactory.createReferencedXMethod(this);
updateApplicableAnnotations(m);
break;
}
case GETSTATIC:
case PUTSTATIC:
case GETFIELD:
case PUTFIELD:
{
XField f = XFactory.createReferencedXField(this);
Collection<TypeQualifierAnnotation> annotations = TypeQualifierApplications.getApplicableApplications(f);
Analysis.addKnownTypeQualifiers(applicableApplications, annotations);
break;
}
}
}
/**
* @param m
*/
private void updateApplicableAnnotations(XMethod m) {
Collection<TypeQualifierAnnotation> annotations = TypeQualifierApplications.getApplicableApplications(m);
Analysis.addKnownTypeQualifiers(applicableApplications, annotations);
Analysis.addKnownTypeQualifiersForParameters(applicableApplications, m);
}
public void report() {
}
}
| findbugs/src/java/edu/umd/cs/findbugs/detect/NoteDirectlyRelevantTypeQualifiers.java | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2005, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.JavaClass;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.NonReportingDetector;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.jsr305.Analysis;
import edu.umd.cs.findbugs.ba.jsr305.DirectlyRelevantTypeQualifiersDatabase;
import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierAnnotation;
import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierApplications;
import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierValue;
import edu.umd.cs.findbugs.bcel.BCELUtil;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
/**
* Scan classes for type qualifier annotations
* and convey them to interested detectors (FindNullDeref, CheckTypeQualifiers, ...)
*/
public class NoteDirectlyRelevantTypeQualifiers //extends DirectlyRelevantTypeQualifiersDatabase
extends DismantleBytecode
implements Detector, NonReportingDetector {
private BugReporter bugReporter;
private DirectlyRelevantTypeQualifiersDatabase qualifiers;
public NoteDirectlyRelevantTypeQualifiers(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visitClassContext(ClassContext classContext) {
if (qualifiers == null) {
try {
qualifiers = Global.getAnalysisCache().getDatabase(DirectlyRelevantTypeQualifiersDatabase.class);
} catch (CheckedAnalysisException e) {
// should not happen
bugReporter.logError("Error getting directly relevant qualifiers database", e);
}
}
JavaClass javaClass = classContext.getJavaClass();
if (!BCELUtil.preTiger(javaClass)) javaClass.accept(this);
}
HashSet<TypeQualifierValue> applicableApplications;
@Override
public void visit(Code m) {
applicableApplications = new HashSet<TypeQualifierValue>();
XMethod xMethod = getXMethod();
// Find the direct annotations on this method
updateApplicableAnnotations(xMethod);
// Find direct annotations on called methods and loaded fields
super.visit(m);
if (applicableApplications.size() > 0) {
qualifiers.setDirectlyRelevantTypeQualifiers(getMethodDescriptor(), new ArrayList<TypeQualifierValue>(applicableApplications));
}
}
@Override
public void sawOpcode(int seen) {
switch(seen) {
case INVOKEINTERFACE:
case INVOKEVIRTUAL:
case INVOKESTATIC:
case INVOKESPECIAL:
{
XMethod m = XFactory.createReferencedXMethod(this);
updateApplicableAnnotations(m);
break;
}
case GETSTATIC:
case PUTSTATIC:
case GETFIELD:
case PUTFIELD:
{
XField f = XFactory.createReferencedXField(this);
Collection<TypeQualifierAnnotation> annotations = TypeQualifierApplications.getApplicableApplications(f);
Analysis.addKnownTypeQualifiers(applicableApplications, annotations);
break;
}
}
}
/**
* @param m
*/
private void updateApplicableAnnotations(XMethod m) {
Collection<TypeQualifierAnnotation> annotations = TypeQualifierApplications.getApplicableApplications(m);
Analysis.addKnownTypeQualifiers(applicableApplications, annotations);
Analysis.addKnownTypeQualifiersForParameters(applicableApplications, m);
}
public void report() {
}
}
| minor simplification
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@9662 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
| findbugs/src/java/edu/umd/cs/findbugs/detect/NoteDirectlyRelevantTypeQualifiers.java | minor simplification | <ide><path>indbugs/src/java/edu/umd/cs/findbugs/detect/NoteDirectlyRelevantTypeQualifiers.java
<ide> import edu.umd.cs.findbugs.Detector;
<ide> import edu.umd.cs.findbugs.NonReportingDetector;
<ide> import edu.umd.cs.findbugs.SystemProperties;
<add>import edu.umd.cs.findbugs.ba.AnalysisContext;
<ide> import edu.umd.cs.findbugs.ba.ClassContext;
<ide> import edu.umd.cs.findbugs.ba.XFactory;
<ide> import edu.umd.cs.findbugs.ba.XField;
<ide> }
<ide>
<ide> public void visitClassContext(ClassContext classContext) {
<del>
<ide> if (qualifiers == null) {
<del> try {
<del> qualifiers = Global.getAnalysisCache().getDatabase(DirectlyRelevantTypeQualifiersDatabase.class);
<del> } catch (CheckedAnalysisException e) {
<del> // should not happen
<del> bugReporter.logError("Error getting directly relevant qualifiers database", e);
<del> }
<add> qualifiers = AnalysisContext.currentAnalysisContext().getDirectlyRelevantTypeQualifiersDatabase();
<ide> }
<ide>
<ide> JavaClass javaClass = classContext.getJavaClass(); |
|
Java | mit | 9ffdfc0913685c3d8d2078b322d6aeb52e34b6d0 | 0 | FredMaris/touist,touist/touist,FredMaris/touist,touist/touist,touist/touist,olzd/touist,olzd/touist,FredMaris/touist,touist/touist,olzd/touist | /*
* 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 gui.TranslatorLatex;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;
/**
*
* @author alexis
*/
public class TranslationLatex {
// Result of touistl string translation to Lat ex
private String latexFormula;
public TranslationLatex(String touistl) throws Exception {
if(touistl.length() == 0) {
latexFormula = "";
}
else {
parser p = new parser(new Lexi(new StringReader(touistl)));
latexFormula = p.parse().value.toString();
}
}
public String getFormula(){
return latexFormula;
}
public void saveLatex(String path) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter(path));
out.write(latexFormula);
out.close();
}
public static void main(String args[]){
BufferedReader in = null ;
try {
in = new BufferedReader(new FileReader("touist-translator/test/latex.touistl"));
StringBuilder sb = new StringBuilder();
String line;
while((line = in.readLine()) != null) {
sb.append(line+"\n");
}
TranslationLatex T = new TranslationLatex(sb.toString());
TeXFormula formula = new TeXFormula(T.getFormula());
TeXIcon ti = formula.createTeXIcon(TeXConstants.ALIGN_CENTER, 20);
JLabel label = new JLabel("",ti,JLabel.CENTER);
JFrame frame = new JFrame();
frame.setSize(1024,1024);
frame.add(label);
frame.setVisible(true);
}
catch (IOException e) {
System.err.println("Erreur ouverture du fichier test");
}
catch (Exception e) {
System.err.println("Erreur lors de la traduction");
}
}
}
| touist-gui/src/gui/TranslatorLatex/TranslationLatex.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 gui.TranslatorLatex;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;
/**
*
* @author alexis
*/
public class TranslationLatex {
// Result of touistl string translation to Lat ex
private String latexFormula;
public TranslationLatex(String touistl) throws Exception {
parser p = new parser(new Lexi(new StringReader(touistl)));
latexFormula = p.parse().value.toString();
}
public String getFormula(){
return latexFormula;
}
public void saveLatex(String path) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter(path));
out.write(latexFormula);
out.close();
}
public static void main(String args[]){
BufferedReader in = null ;
try {
in = new BufferedReader(new FileReader("touist-translator/test/latex.touistl"));
StringBuilder sb = new StringBuilder();
String line;
while((line = in.readLine()) != null) {
sb.append(line+"\n");
}
TranslationLatex T = new TranslationLatex(sb.toString());
TeXFormula formula = new TeXFormula(T.getFormula());
TeXIcon ti = formula.createTeXIcon(TeXConstants.ALIGN_CENTER, 20);
JLabel label = new JLabel("",ti,JLabel.CENTER);
JFrame frame = new JFrame();
frame.setSize(1024,1024);
frame.add(label);
frame.setVisible(true);
}
catch (IOException e) {
System.err.println("Erreur ouverture du fichier test");
}
catch (Exception e) {
System.err.println("Erreur lors de la traduction");
}
}
}
| #59 Fixed | touist-gui/src/gui/TranslatorLatex/TranslationLatex.java | #59 Fixed | <ide><path>ouist-gui/src/gui/TranslatorLatex/TranslationLatex.java
<ide>
<ide>
<ide> public TranslationLatex(String touistl) throws Exception {
<del> parser p = new parser(new Lexi(new StringReader(touistl)));
<del> latexFormula = p.parse().value.toString();
<add> if(touistl.length() == 0) {
<add> latexFormula = "";
<add> }
<add> else {
<add> parser p = new parser(new Lexi(new StringReader(touistl)));
<add> latexFormula = p.parse().value.toString();
<add> }
<ide> }
<ide>
<ide> public String getFormula(){ |
|
Java | apache-2.0 | bf2bc8f9fe43759a5dd05829457d93d54e8c8c0c | 0 | h2ri/ChatSecureAndroid,bonashen/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid,guardianproject/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,Heart2009/ChatSecureAndroid,10045125/ChatSecureAndroid,anvayarai/my-ChatSecure,prembasumatary/ChatSecureAndroid,maheshwarishivam/ChatSecureAndroid,h2ri/ChatSecureAndroid,eighthave/ChatSecureAndroid,kden/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,eighthave/ChatSecureAndroid,n8fr8/AwesomeApp,anvayarai/my-ChatSecure,OnlyInAmerica/ChatSecureAndroid,kden/ChatSecureAndroid,n8fr8/ChatSecureAndroid,guardianproject/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,joskarthic/chatsecure,maheshwarishivam/ChatSecureAndroid,Heart2009/ChatSecureAndroid,10045125/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,bonashen/ChatSecureAndroid,n8fr8/ChatSecureAndroid,joskarthic/chatsecure,anvayarai/my-ChatSecure,bonashen/ChatSecureAndroid,eighthave/ChatSecureAndroid,guardianproject/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,n8fr8/AwesomeApp,n8fr8/AwesomeApp,h2ri/ChatSecureAndroid,n8fr8/ChatSecureAndroid,10045125/ChatSecureAndroid,kden/ChatSecureAndroid,Heart2009/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,joskarthic/chatsecure,ChatSecure/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid,maheshwarishivam/ChatSecureAndroid | /*
* Copyright (C) 2007-2008 Esmertec AG. Copyright (C) 2007-2008 The Android Open
* Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package info.guardianproject.otr.app.im.service;
import info.guardianproject.otr.app.im.IContactList;
import info.guardianproject.otr.app.im.IContactListListener;
import info.guardianproject.otr.app.im.ISubscriptionListener;
import info.guardianproject.otr.app.im.R;
import info.guardianproject.otr.app.im.engine.Address;
import info.guardianproject.otr.app.im.engine.Contact;
import info.guardianproject.otr.app.im.engine.ContactList;
import info.guardianproject.otr.app.im.engine.ContactListListener;
import info.guardianproject.otr.app.im.engine.ContactListManager;
import info.guardianproject.otr.app.im.engine.ImErrorInfo;
import info.guardianproject.otr.app.im.engine.ImException;
import info.guardianproject.otr.app.im.engine.Presence;
import info.guardianproject.otr.app.im.provider.Imps;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.widget.Toast;
public class ContactListManagerAdapter extends
info.guardianproject.otr.app.im.IContactListManager.Stub implements Runnable {
ImConnectionAdapter mConn;
ContentResolver mResolver;
private ContactListManager mAdaptee;
private ContactListListenerAdapter mContactListListenerAdapter;
private SubscriptionRequestListenerAdapter mSubscriptionListenerAdapter;
final RemoteCallbackList<IContactListListener> mRemoteContactListeners = new RemoteCallbackList<IContactListListener>();
final RemoteCallbackList<ISubscriptionListener> mRemoteSubscriptionListeners = new RemoteCallbackList<ISubscriptionListener>();
HashMap<Address, ContactListAdapter> mContactLists;
// Temporary contacts are created when a peer is encountered, and that peer
// is not yet on any contact list.
HashMap<String, Contact> mTemporaryContacts;
// Offline contacts are created from the local DB before the server contact lists
// are loaded.
HashMap<String, Contact> mOfflineContacts;
HashSet<String> mValidatedContactLists;
HashSet<String> mValidatedContacts;
HashSet<String> mValidatedBlockedContacts;
private long mAccountId;
private long mProviderId;
private Uri mAvatarUrl;
private Uri mContactUrl;
static final long FAKE_TEMPORARY_LIST_ID = -1;
static final String[] CONTACT_LIST_ID_PROJECTION = { Imps.ContactList._ID };
RemoteImService mContext;
public ContactListManagerAdapter(ImConnectionAdapter conn) {
mAdaptee = conn.getAdaptee().getContactListManager();
mConn = conn;
mContext = conn.getContext();
mResolver = mContext.getContentResolver();
new Thread(this).start();
}
public void run ()
{
mContactListListenerAdapter = new ContactListListenerAdapter();
mSubscriptionListenerAdapter = new SubscriptionRequestListenerAdapter();
mContactLists = new HashMap<Address, ContactListAdapter>();
mTemporaryContacts = new HashMap<String, Contact>();
mOfflineContacts = new HashMap<String, Contact>();
mValidatedContacts = new HashSet<String>();
mValidatedContactLists = new HashSet<String>();
mValidatedBlockedContacts = new HashSet<String>();
mAdaptee.addContactListListener(mContactListListenerAdapter);
mAdaptee.setSubscriptionRequestListener(mSubscriptionListenerAdapter);
mAccountId = mConn.getAccountId();
mProviderId = mConn.getProviderId();
Uri.Builder builder = Imps.Avatars.CONTENT_URI_AVATARS_BY.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
mAvatarUrl = builder.build();
builder = Imps.Contacts.CONTENT_URI_CONTACTS_BY.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
mContactUrl = builder.build();
seedInitialPresences();
loadOfflineContacts();
}
private void loadOfflineContacts() {
Cursor contactCursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts.USERNAME },
null, null, null);
String[] addresses = new String[contactCursor.getCount()];
int i = 0;
while (contactCursor.moveToNext())
{
addresses[i++] = contactCursor.getString(0);
}
Contact[] contacts = mAdaptee.createTemporaryContacts(addresses);
for (Contact contact : contacts)
mOfflineContacts.put(contact.getAddress().getBareAddress(), contact);
contactCursor.close();
}
public int createContactList(String name, List<Contact> contacts) {
try {
mAdaptee.createContactListAsync(name, contacts);
} catch (ImException e) {
return e.getImError().getCode();
}
return ImErrorInfo.NO_ERROR;
}
public int deleteContactList(String name) {
try {
mAdaptee.deleteContactListAsync(name);
} catch (ImException e) {
return e.getImError().getCode();
}
return ImErrorInfo.NO_ERROR;
}
public List<ContactListAdapter> getContactLists() {
synchronized (mContactLists) {
return new ArrayList<ContactListAdapter>(mContactLists.values());
}
}
public int removeContact(String address) {
closeChatSession(address);
if (isTemporary(address)) {
synchronized (mTemporaryContacts) {
mTemporaryContacts.remove(address);
}
} else {
synchronized (mContactLists) {
for (ContactListAdapter list : mContactLists.values()) {
int resCode = list.removeContact(address);
if (ImErrorInfo.ILLEGAL_CONTACT_ADDRESS == resCode) {
// Did not find in this list, continue to remove from
// other list.
continue;
}
if (ImErrorInfo.NO_ERROR != resCode) {
return resCode;
}
}
}
}
String selection = Imps.Contacts.USERNAME + "=?";
String[] selectionArgs = { address };
mResolver.delete(mContactUrl, selection, selectionArgs);
return ImErrorInfo.NO_ERROR;
}
public int setContactName(String address, String name) {
// update the server
try {
mAdaptee.setContactName(address,name);
} catch (ImException e) {
return e.getImError().getCode();
}
// update locally
String selection = Imps.Contacts.USERNAME + "=?";
String[] selectionArgs = { address };
ContentValues values = new ContentValues(1);
values.put( Imps.Contacts.NICKNAME, name);
int updated = mResolver.update(mContactUrl, values, selection, selectionArgs);
if( updated != 1 ) {
return ImErrorInfo.ILLEGAL_CONTACT_ADDRESS;
}
return ImErrorInfo.NO_ERROR;
}
public void approveSubscription(String address) {
mAdaptee.approveSubscriptionRequest(address);
}
public void declineSubscription(String address) {
mAdaptee.declineSubscriptionRequest(address);
}
public int blockContact(String address) {
try {
mAdaptee.blockContactAsync(address);
} catch (ImException e) {
return e.getImError().getCode();
}
return ImErrorInfo.NO_ERROR;
}
public int unBlockContact(String address) {
try {
mAdaptee.unblockContactAsync(address);
} catch (ImException e) {
RemoteImService.debug(e.getMessage());
return e.getImError().getCode();
}
return ImErrorInfo.NO_ERROR;
}
public boolean isBlocked(String address) {
try {
return mAdaptee.isBlocked(address);
} catch (ImException e) {
RemoteImService.debug(e.getMessage());
return false;
}
}
public void registerContactListListener(IContactListListener listener) {
if (listener != null) {
mRemoteContactListeners.register(listener);
}
}
public void unregisterContactListListener(IContactListListener listener) {
if (listener != null) {
mRemoteContactListeners.unregister(listener);
}
}
public void registerSubscriptionListener(ISubscriptionListener listener) {
if (listener != null) {
mRemoteSubscriptionListeners.register(listener);
}
}
public void unregisterSubscriptionListener(ISubscriptionListener listener) {
if (listener != null) {
mRemoteSubscriptionListeners.unregister(listener);
}
}
public IContactList getContactList(String name) {
return getContactListAdapter(name);
}
public void loadContactLists() {
if (mAdaptee.getState() == ContactListManager.LISTS_NOT_LOADED) {
clearValidatedContactsAndLists();
mAdaptee.loadContactListsAsync();
}
}
public int getState() {
return mAdaptee.getState();
}
public Contact getContactByAddress(String address) {
if (mAdaptee.getState() == ContactListManager.LISTS_NOT_LOADED) {
return mOfflineContacts.get(address);
}
Contact c = mAdaptee.getContact(address);
if (c == null) {
synchronized (mTemporaryContacts) {
return mTemporaryContacts.get(address);
}
} else {
return c;
}
}
public Contact[] createTemporaryContacts(String[] addresses) {
Contact[] contacts = mAdaptee.createTemporaryContacts(addresses);
for (Contact c : contacts)
insertTemporary(c);
return contacts;
}
public long queryOrInsertContact(Contact c) {
long result;
String username = mAdaptee.normalizeAddress(c.getAddress().getAddress());
String selection = Imps.Contacts.USERNAME + "=?";
String[] selectionArgs = { username };
String[] projection = { Imps.Contacts._ID };
Cursor cursor = mResolver.query(mContactUrl, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getLong(0);
} else {
result = insertTemporary(c);
}
if (cursor != null) {
cursor.close();
}
return result;
}
private long insertTemporary(Contact c) {
synchronized (mTemporaryContacts) {
mTemporaryContacts.put(mAdaptee.normalizeAddress(c.getAddress().getBareAddress()), c);
}
Uri uri = insertContactContent(c, FAKE_TEMPORARY_LIST_ID);
return ContentUris.parseId(uri);
}
/**
* Tells if a contact is a temporary one which is not in the list of
* contacts that we subscribe presence for. Usually created because of the
* user is having a chat session with this contact.
*
* @param address the address of the contact.
* @return <code>true</code> if it's a temporary contact; <code>false</code>
* otherwise.
*/
public boolean isTemporary(String address) {
synchronized (mTemporaryContacts) {
return mTemporaryContacts.containsKey(address);
}
}
ContactListAdapter getContactListAdapter(String name) {
synchronized (mContactLists) {
for (ContactListAdapter list : mContactLists.values()) {
if (name.equals(list.getName())) {
return list;
}
}
return null;
}
}
ContactListAdapter getContactListAdapter(Address address) {
synchronized (mContactLists) {
return mContactLists.get(address);
}
}
private class Exclusion {
private StringBuilder mSelection;
private List<String> mSelectionArgs;
private String mExclusionColumn;
Exclusion(String exclusionColumn, Collection<String> items) {
mSelection = new StringBuilder();
mSelectionArgs = new ArrayList<String>();
mExclusionColumn = exclusionColumn;
for (String s : items) {
add(s);
}
}
public void add(String exclusionItem) {
if (mSelection.length() == 0) {
mSelection.append(mExclusionColumn + "!=?");
} else {
mSelection.append(" AND " + mExclusionColumn + "!=?");
}
mSelectionArgs.add(exclusionItem);
}
public String getSelection() {
return mSelection.toString();
}
public String[] getSelectionArgs() {
return (String[]) mSelectionArgs.toArray(new String[0]);
}
}
private void removeObsoleteContactsAndLists() {
// remove all contacts for this provider & account which have not been
// added since login, yet still exist in db from a prior login
Exclusion exclusion = new Exclusion(Imps.Contacts.USERNAME, mValidatedContacts);
mResolver.delete(mContactUrl, exclusion.getSelection(), exclusion.getSelectionArgs());
// remove all blocked contacts for this provider & account which have not been
// added since login, yet still exist in db from a prior login
exclusion = new Exclusion(Imps.BlockedList.USERNAME, mValidatedBlockedContacts);
Uri.Builder builder = Imps.BlockedList.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
Uri uri = builder.build();
mResolver.delete(uri, exclusion.getSelection(), exclusion.getSelectionArgs());
// remove all contact lists for this provider & account which have not been
// added since login, yet still exist in db from a prior login
exclusion = new Exclusion(Imps.ContactList.NAME, mValidatedContactLists);
builder = Imps.ContactList.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
uri = builder.build();
mResolver.delete(uri, exclusion.getSelection(), exclusion.getSelectionArgs());
}
interface ContactListBroadcaster {
void broadcast(IContactListListener listener) throws RemoteException;
}
interface SubscriptionBroadcaster {
void broadcast(ISubscriptionListener listener) throws RemoteException;
}
final class ContactListListenerAdapter implements ContactListListener {
private boolean mAllContactsLoaded;
// class to hold contact changes made before mAllContactsLoaded
private class StoredContactChange {
int mType;
ContactList mList;
Contact mContact;
StoredContactChange(int type, ContactList list, Contact contact) {
mType = type;
mList = list;
mContact = contact;
}
}
private Vector<StoredContactChange> mDelayedContactChanges = new Vector<StoredContactChange>();
private void broadcast(ContactListBroadcaster callback) {
synchronized (mRemoteContactListeners) {
final int N = mRemoteContactListeners.beginBroadcast();
for (int i = 0; i < N; i++) {
IContactListListener listener = mRemoteContactListeners.getBroadcastItem(i);
try {
callback.broadcast(listener);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing the
// dead listeners.
}
}
mRemoteContactListeners.finishBroadcast();
}
}
public void onContactsPresenceUpdate(final Contact[] contacts) {
// The client listens only to presence updates for now. Update
// the avatars first to ensure it can get the new avatar when
// presence updated.
// TODO: Don't update avatar now since none of the server supports it
// updateAvatarsContent(contacts);
updatePresenceContent(contacts);
broadcast(new ContactListBroadcaster() {
public void broadcast(IContactListListener listener) throws RemoteException {
listener.onContactsPresenceUpdate(contacts);
}
});
}
public void onContactChange(final int type, final ContactList list, final Contact contact) {
ContactListAdapter removed = null;
String notificationText = null;
switch (type) {
case LIST_LOADED:
case LIST_CREATED:
addContactListContent(list);
break;
case LIST_DELETED:
removed = removeContactListFromDataBase(list.getName());
// handle case where a list is deleted before mAllContactsLoaded
if (!mAllContactsLoaded) {
// if a cached contact list is deleted before the actual contact list is
// downloaded from the server, we will have to remove the list again once
// once mAllContactsLoaded is true
if (!mValidatedContactLists.contains(list.getName())) {
mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
}
}
break;
case LIST_CONTACT_ADDED:
long listId = getContactListAdapter(list.getAddress()).getDataBaseId();
if (isTemporary(mAdaptee.normalizeAddress(contact.getAddress().getAddress()))) {
moveTemporaryContactToList(mAdaptee.normalizeAddress(contact.getAddress().getAddress()), listId);
} else {
boolean exists = updateContact(contact, listId);
if (!exists)
insertContactContent(contact, listId);
}
notificationText = mContext.getResources().getString(R.string.add_contact_success,
contact.getName());
// handle case where a contact is added before mAllContactsLoaded
if (!mAllContactsLoaded) {
// if a contact is added to a cached contact list before the actual contact
// list is downloaded from the server, we will have to add the contact to
// the contact list once mAllContactsLoaded is true
if (!mValidatedContactLists.contains(list.getName())) {
mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
}
}
break;
case LIST_CONTACT_REMOVED:
deleteContactFromDataBase(contact, list);
// handle case where a contact is removed before mAllContactsLoaded
if (!mAllContactsLoaded) {
// if a contact is added to a cached contact list before the actual contact
// list is downloaded from the server, we will have to add the contact to
// the contact list once mAllContactsLoaded is true
if (!mValidatedContactLists.contains(list.getName())) {
mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
}
}
// Clear ChatSession if any.
String address = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
closeChatSession(address);
notificationText = mContext.getResources().getString(
R.string.delete_contact_success, contact.getName());
break;
case LIST_RENAMED:
updateListNameInDataBase(list);
// handle case where a list is renamed before mAllContactsLoaded
if (!mAllContactsLoaded) {
// if a contact list name is updated before the actual contact list is
// downloaded from the server, we will have to update the list name again
// once mAllContactsLoaded is true
if (!mValidatedContactLists.contains(list.getName())) {
mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
}
}
break;
case CONTACT_BLOCKED:
insertBlockedContactToDataBase(contact);
address = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
updateContactType(address, Imps.Contacts.TYPE_BLOCKED);
closeChatSession(address);
notificationText = mContext.getResources().getString(
R.string.block_contact_success, contact.getName());
break;
case CONTACT_UNBLOCKED:
removeBlockedContactFromDataBase(contact);
notificationText = mContext.getResources().getString(
R.string.unblock_contact_success, contact.getName());
// handle case where a contact is unblocked before mAllContactsLoaded
if (!mAllContactsLoaded) {
// if a contact list name is updated before the actual contact list is
// downloaded from the server, we will have to update the list name again
// once mAllContactsLoaded is true
if (!mValidatedBlockedContacts.contains(contact.getName())) {
mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
}
}
break;
default:
RemoteImService.debug("Unknown list update event!");
break;
}
final ContactListAdapter listAdapter;
if (type == LIST_DELETED) {
listAdapter = removed;
} else {
listAdapter = (list == null) ? null : getContactListAdapter(list.getAddress());
}
broadcast(new ContactListBroadcaster() {
public void broadcast(IContactListListener listener) throws RemoteException {
listener.onContactChange(type, listAdapter, contact);
}
});
if (mAllContactsLoaded && notificationText != null) {
// mContext.showToast(notificationText, Toast.LENGTH_SHORT);
}
}
public void onContactError(final int errorType, final ImErrorInfo error,
final String listName, final Contact contact) {
broadcast(new ContactListBroadcaster() {
public void broadcast(IContactListListener listener) throws RemoteException {
listener.onContactError(errorType, error, listName, contact);
}
});
}
public void handleDelayedContactChanges() {
for (StoredContactChange change : mDelayedContactChanges) {
onContactChange(change.mType, change.mList, change.mContact);
}
}
public void onAllContactListsLoaded() {
mAllContactsLoaded = true;
handleDelayedContactChanges();
removeObsoleteContactsAndLists();
broadcast(new ContactListBroadcaster() {
public void broadcast(IContactListListener listener) throws RemoteException {
listener.onAllContactListsLoaded();
}
});
}
}
final class SubscriptionRequestListenerAdapter extends ISubscriptionListener.Stub {
public void onSubScriptionRequest(final Contact from, long providerId, long accountId) {
String username = mAdaptee.normalizeAddress(from.getAddress().getAddress());
String nickname = from.getName();
queryOrInsertContact(from); // FIXME Miron
Uri uri = insertOrUpdateSubscription(username, nickname,
Imps.Contacts.SUBSCRIPTION_TYPE_FROM,
Imps.Contacts.SUBSCRIPTION_STATUS_SUBSCRIBE_PENDING);
boolean hadListener = broadcast(new SubscriptionBroadcaster() {
public void broadcast(ISubscriptionListener listener) throws RemoteException {
listener.onSubScriptionRequest(from, mProviderId, mAccountId);
}
});
if (!hadListener)
{
mContext.getStatusBarNotifier().notifySubscriptionRequest(mProviderId, mAccountId,
ContentUris.parseId(uri), username, nickname);
}
}
public void onUnSubScriptionRequest(final Contact from, long providerId, long accountId) {
String username = mAdaptee.normalizeAddress(from.getAddress().getAddress());
String nickname = from.getName();
//to be implemented - should prompt user to approve unsubscribe?
}
private boolean broadcast(SubscriptionBroadcaster callback) {
boolean hadListener = false;
synchronized (mRemoteSubscriptionListeners) {
final int N = mRemoteSubscriptionListeners.beginBroadcast();
for (int i = 0; i < N; i++) {
ISubscriptionListener listener = mRemoteSubscriptionListeners.getBroadcastItem(i);
try {
callback.broadcast(listener);
hadListener = true;
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing the
// dead listeners.
}
}
mRemoteSubscriptionListeners.finishBroadcast();
}
return hadListener;
}
public void onSubscriptionApproved(final String contact, long providerId, long accountId) {
insertOrUpdateSubscription(contact, null, Imps.Contacts.SUBSCRIPTION_TYPE_NONE,
Imps.Contacts.SUBSCRIPTION_STATUS_NONE);
broadcast(new SubscriptionBroadcaster() {
public void broadcast(ISubscriptionListener listener) throws RemoteException {
listener.onSubscriptionApproved(contact, mProviderId, mAccountId);
}
});
}
public void onSubscriptionDeclined(final String contact, long providerId, long accountId) {
insertOrUpdateSubscription(contact, null, Imps.Contacts.SUBSCRIPTION_TYPE_NONE,
Imps.Contacts.SUBSCRIPTION_STATUS_NONE);
broadcast(new SubscriptionBroadcaster() {
public void broadcast(ISubscriptionListener listener) throws RemoteException {
listener.onSubscriptionDeclined(contact, mProviderId, mAccountId);
}
});
}
public void onApproveSubScriptionError(final String contact, final ImErrorInfo error) {
String displayableAddress = getDisplayableAddress(contact);
String msg = mContext
.getString(R.string.approve_subscription_error, displayableAddress);
mContext.showToast(msg, Toast.LENGTH_SHORT);
}
public void onDeclineSubScriptionError(final String contact, final ImErrorInfo error) {
String displayableAddress = getDisplayableAddress(contact);
String msg = mContext
.getString(R.string.decline_subscription_error, displayableAddress);
mContext.showToast(msg, Toast.LENGTH_SHORT);
}
}
String getDisplayableAddress(String impsAddress) {
if (impsAddress.startsWith("wv:")) {
return impsAddress.substring(3);
}
return impsAddress;
}
void insertBlockedContactToDataBase(Contact contact) {
// Remove the blocked contact if it already exists, to avoid duplicates and
// handle the odd case where a blocked contact's nickname has changed
removeBlockedContactFromDataBase(contact);
Uri.Builder builder = Imps.BlockedList.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
Uri uri = builder.build();
String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
ContentValues values = new ContentValues(2);
values.put(Imps.BlockedList.USERNAME, username);
values.put(Imps.BlockedList.NICKNAME, contact.getName());
mResolver.insert(uri, values);
mValidatedBlockedContacts.add(username);
}
void removeBlockedContactFromDataBase(Contact contact) {
String address = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
Uri.Builder builder = Imps.BlockedList.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
Uri uri = builder.build();
mResolver.delete(uri, Imps.BlockedList.USERNAME + "=?", new String[] { address });
int type = isTemporary(address) ? Imps.Contacts.TYPE_TEMPORARY : Imps.Contacts.TYPE_NORMAL;
updateContactType(address, type);
}
void moveTemporaryContactToList(String address, long listId) {
synchronized (mTemporaryContacts) {
mTemporaryContacts.remove(address);
}
ContentValues values = new ContentValues(2);
values.put(Imps.Contacts.TYPE, Imps.Contacts.TYPE_NORMAL);
values.put(Imps.Contacts.CONTACTLIST, listId);
String selection = Imps.Contacts.USERNAME + "=? AND " + Imps.Contacts.TYPE + "="
+ Imps.Contacts.TYPE_TEMPORARY;
String[] selectionArgs = { address };
mResolver.update(mContactUrl, values, selection, selectionArgs);
}
void updateContactType(String address, int type) {
ContentValues values = new ContentValues(1);
values.put(Imps.Contacts.TYPE, type);
updateContact(address, values);
}
/**
* Insert or update subscription request from user into the database.
*
* @param username
* @param nickname
* @param subscriptionType
* @param subscriptionStatus
*/
Uri insertOrUpdateSubscription(String username, String nickname, int subscriptionType,
int subscriptionStatus) {
Cursor cursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts._ID },
Imps.Contacts.USERNAME + "=?", new String[] { username }, null);
if (cursor == null) {
RemoteImService.debug("query contact " + username + " failed");
return null;
}
Uri uri;
if (cursor.moveToFirst()) {
ContentValues values = new ContentValues(2);
values.put(Imps.Contacts.SUBSCRIPTION_TYPE, subscriptionType);
values.put(Imps.Contacts.SUBSCRIPTION_STATUS, subscriptionStatus);
long contactId = cursor.getLong(0);
uri = ContentUris.withAppendedId(Imps.Contacts.CONTENT_URI, contactId);
mResolver.update(uri, values, null, null);
} else {
ContentValues values = new ContentValues(6);
values.put(Imps.Contacts.USERNAME, username);
values.put(Imps.Contacts.NICKNAME, nickname);
values.put(Imps.Contacts.TYPE, Imps.Contacts.TYPE_NORMAL);
values.put(Imps.Contacts.CONTACTLIST, FAKE_TEMPORARY_LIST_ID);
values.put(Imps.Contacts.SUBSCRIPTION_TYPE, subscriptionType);
values.put(Imps.Contacts.SUBSCRIPTION_STATUS, subscriptionStatus);
uri = mResolver.insert(mContactUrl, values);
}
cursor.close();
return uri;
}
boolean updateContact(Contact contact, long listId)
{
ContentValues values = getContactContentValues(contact, listId);
return updateContact(mAdaptee.normalizeAddress(contact.getAddress().getAddress()),values);
}
boolean updateContact(String username, ContentValues values) {
String selection = Imps.Contacts.USERNAME + "=?";
String[] selectionArgs = { username };
return (mResolver.update(mContactUrl, values, selection, selectionArgs)) > 0;
}
void updatePresenceContent(Contact[] contacts) {
ArrayList<String> usernames = new ArrayList<String>();
ArrayList<String> statusArray = new ArrayList<String>();
ArrayList<String> customStatusArray = new ArrayList<String>();
ArrayList<String> clientTypeArray = new ArrayList<String>();
for (Contact c : contacts) {
String username = mAdaptee.normalizeAddress(c.getAddress().getAddress());
Presence p = c.getPresence();
int status = convertPresenceStatus(p);
String customStatus = p.getStatusText();
int clientType = translateClientType(p);
usernames.add(username);
statusArray.add(String.valueOf(status));
customStatusArray.add(customStatus);
clientTypeArray.add(String.valueOf(clientType));
}
ContentValues values = new ContentValues();
values.put(Imps.Contacts.ACCOUNT, mAccountId);
putStringArrayList(values, Imps.Contacts.USERNAME, usernames);
putStringArrayList(values, Imps.Presence.PRESENCE_STATUS, statusArray);
putStringArrayList(values, Imps.Presence.PRESENCE_CUSTOM_STATUS, customStatusArray);
putStringArrayList(values, Imps.Presence.CONTENT_TYPE, clientTypeArray);
mResolver.update(Imps.Presence.BULK_CONTENT_URI, values, null, null);
}
void updateAvatarsContent(Contact[] contacts) {
ArrayList<ContentValues> avatars = new ArrayList<ContentValues>();
ArrayList<String> usernames = new ArrayList<String>();
for (Contact contact : contacts) {
byte[] avatarData = contact.getPresence().getAvatarData();
if (avatarData == null) {
continue;
}
String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
ContentValues values = new ContentValues(2);
values.put(Imps.Avatars.CONTACT, username);
values.put(Imps.Avatars.DATA, avatarData);
avatars.add(values);
usernames.add(username);
}
if (avatars.size() > 0) {
// ImProvider will replace the avatar content if it already exist.
mResolver.bulkInsert(mAvatarUrl, avatars.toArray(new ContentValues[avatars.size()]));
// notify avatar changed
Intent i = new Intent(ImServiceConstants.ACTION_AVATAR_CHANGED);
i.putExtra(ImServiceConstants.EXTRA_INTENT_FROM_ADDRESS, usernames);
i.putExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, mProviderId);
i.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, mAccountId);
mContext.sendBroadcast(i);
}
}
ContactListAdapter removeContactListFromDataBase(String name) {
ContactListAdapter listAdapter = getContactListAdapter(name);
if (listAdapter == null) {
return null;
}
long id = listAdapter.getDataBaseId();
// delete contacts of this list first
mResolver.delete(mContactUrl, Imps.Contacts.CONTACTLIST + "=?",
new String[] { Long.toString(id) });
mResolver.delete(ContentUris.withAppendedId(Imps.ContactList.CONTENT_URI, id), null, null);
synchronized (mContactLists) {
return mContactLists.remove(listAdapter.getAddress());
}
}
void addContactListContent(ContactList list) {
String selection = Imps.ContactList.NAME + "=? AND " + Imps.ContactList.PROVIDER
+ "=? AND " + Imps.ContactList.ACCOUNT + "=?";
String[] selectionArgs = { list.getName(), Long.toString(mProviderId),
Long.toString(mAccountId) };
Cursor cursor = mResolver.query(Imps.ContactList.CONTENT_URI, CONTACT_LIST_ID_PROJECTION,
selection, selectionArgs, null); // no sort order
long listId = 0;
Uri uri = null;
try {
if (cursor.moveToFirst()) {
listId = cursor.getLong(0);
uri = ContentUris.withAppendedId(Imps.ContactList.CONTENT_URI, listId);
}
} finally {
cursor.close();
}
if (uri == null) {
ContentValues contactListValues = new ContentValues(3);
contactListValues.put(Imps.ContactList.NAME, list.getName());
contactListValues.put(Imps.ContactList.PROVIDER, mProviderId);
contactListValues.put(Imps.ContactList.ACCOUNT, mAccountId);
uri = mResolver.insert(Imps.ContactList.CONTENT_URI, contactListValues);
listId = ContentUris.parseId(uri);
}
mValidatedContactLists.add(list.getName());
synchronized (mContactLists) {
mContactLists.put(list.getAddress(), new ContactListAdapter(list, listId));
}
Cursor contactCursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts.USERNAME },
Imps.Contacts.CONTACTLIST + "=?", new String[] { "" + listId }, null);
Set<String> existingUsernames = new HashSet<String>();
while (contactCursor.moveToNext())
existingUsernames.add(contactCursor.getString(0));
contactCursor.close();
Collection<Contact> contacts = list.getContacts();
if (contacts == null || contacts.size() == 0) {
return;
}
Iterator<Contact> iter = contacts.iterator();
while (iter.hasNext()) {
Contact c = iter.next();
String address = mAdaptee.normalizeAddress(c.getAddress().getAddress());
if (isTemporary(address)) {
if (!existingUsernames.contains(address)) {
moveTemporaryContactToList(address, listId);
}
iter.remove();
}
mValidatedContacts.add(address);
}
ArrayList<String> usernames = new ArrayList<String>();
ArrayList<String> nicknames = new ArrayList<String>();
ArrayList<String> contactTypeArray = new ArrayList<String>();
for (Contact c : contacts) {
if (updateContact(c,listId))
continue; //contact existed and was updated to this list
String username = mAdaptee.normalizeAddress(c.getAddress().getAddress());
String nickname = c.getName();
int type = Imps.Contacts.TYPE_NORMAL;
if (isTemporary(username)) {
type = Imps.Contacts.TYPE_TEMPORARY;
}
if (isBlocked(username)) {
type = Imps.Contacts.TYPE_BLOCKED;
}
usernames.add(username);
nicknames.add(nickname);
contactTypeArray.add(String.valueOf(type));
}
ContentValues values = new ContentValues(6);
values.put(Imps.Contacts.PROVIDER, mProviderId);
values.put(Imps.Contacts.ACCOUNT, mAccountId);
values.put(Imps.Contacts.CONTACTLIST, listId);
putStringArrayList(values, Imps.Contacts.USERNAME, usernames);
putStringArrayList(values, Imps.Contacts.NICKNAME, nicknames);
putStringArrayList(values, Imps.Contacts.TYPE, contactTypeArray);
mResolver.insert(Imps.Contacts.BULK_CONTENT_URI, values);
}
private void putStringArrayList(ContentValues values, String key, ArrayList<String> nicknames) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(nicknames);
os.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
values.put(key, bos.toByteArray());
}
void updateListNameInDataBase(ContactList list) {
ContactListAdapter listAdapter = getContactListAdapter(list.getAddress());
Uri uri = ContentUris.withAppendedId(Imps.ContactList.CONTENT_URI,
listAdapter.getDataBaseId());
ContentValues values = new ContentValues(1);
values.put(Imps.ContactList.NAME, list.getName());
mResolver.update(uri, values, null, null);
}
void deleteContactFromDataBase(Contact contact, ContactList list) {
String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
//if list is provided, then delete from one list
if (list != null)
{
String selection = Imps.Contacts.USERNAME + "=? AND " + Imps.Contacts.CONTACTLIST + "=?";
long listId = getContactListAdapter(list.getAddress()).getDataBaseId();
String[] selectionArgs = { username, Long.toString(listId) };
mResolver.delete(mContactUrl, selection, selectionArgs);
}
else //if it is null, delete from all
{
String selection = Imps.Contacts.USERNAME + "=?";
String[] selectionArgs = { username };
mResolver.delete(mContactUrl, selection, selectionArgs);
}
// clear the history message if the contact doesn't exist in any list
// anymore.
if (mAdaptee.getContact(contact.getAddress()) == null) {
clearHistoryMessages(username);
}
}
Uri insertContactContent(Contact contact, long listId) {
ContentValues values = getContactContentValues(contact, listId);
Uri uri = mResolver.insert(mContactUrl, values);
ContentValues presenceValues = getPresenceValues(ContentUris.parseId(uri),
contact.getPresence());
mResolver.insert(Imps.Presence.CONTENT_URI, presenceValues);
return uri;
}
private ContentValues getContactContentValues(Contact contact, long listId) {
final String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
final String nickname = contact.getName();
int type = Imps.Contacts.TYPE_NORMAL;
if (isTemporary(username)) {
type = Imps.Contacts.TYPE_TEMPORARY;
}
if (isBlocked(username)) {
type = Imps.Contacts.TYPE_BLOCKED;
}
ContentValues values = new ContentValues(4);
values.put(Imps.Contacts.USERNAME, username);
values.put(Imps.Contacts.NICKNAME, nickname);
values.put(Imps.Contacts.CONTACTLIST, listId);
values.put(Imps.Contacts.TYPE, type);
return values;
}
void clearHistoryMessages(String contact) {
Uri uri = Imps.Messages.getContentUriByContact(mAccountId, contact);
mResolver.delete(uri, null, null);
}
private ContentValues getPresenceValues(long contactId, Presence p) {
ContentValues values = new ContentValues(3);
values.put(Imps.Presence.CONTACT_ID, contactId);
values.put(Imps.Contacts.PRESENCE_STATUS, convertPresenceStatus(p));
values.put(Imps.Contacts.PRESENCE_CUSTOM_STATUS, p.getStatusText());
values.put(Imps.Presence.CLIENT_TYPE, translateClientType(p));
return values;
}
private int translateClientType(Presence presence) {
int clientType = presence.getClientType();
switch (clientType) {
case Presence.CLIENT_TYPE_MOBILE:
return Imps.Presence.CLIENT_TYPE_MOBILE;
default:
return Imps.Presence.CLIENT_TYPE_DEFAULT;
}
}
/**
* Converts the presence status to the value defined for ImProvider.
*
* @param presence The presence from the IM engine.
* @return The status value defined in for ImProvider.
*/
public static int convertPresenceStatus(Presence presence) {
switch (presence.getStatus()) {
case Presence.AVAILABLE:
return Imps.Presence.AVAILABLE;
case Presence.IDLE:
return Imps.Presence.IDLE;
case Presence.AWAY:
return Imps.Presence.AWAY;
case Presence.DO_NOT_DISTURB:
return Imps.Presence.DO_NOT_DISTURB;
case Presence.OFFLINE:
return Imps.Presence.OFFLINE;
}
// impossible...
RemoteImService.debug("Illegal presence status value " + presence.getStatus());
return Imps.Presence.AVAILABLE;
}
public void clearOnLogout() {
clearValidatedContactsAndLists();
clearTemporaryContacts();
clearPresence();
}
/**
* Clears the list of validated contacts and contact lists. As contacts and
* contacts lists are added after login, contacts and contact lists are
* stored as "validated contacts". After initial download of contacts is
* complete, any contacts and contact lists that remain in the database, but
* are not in the validated list, are obsolete and should be removed. This
* function resets that list for use upon login.
*/
private void clearValidatedContactsAndLists() {
// clear the list of validated contacts, contact lists, and blocked contacts
mValidatedContacts.clear();
mValidatedContactLists.clear();
mValidatedBlockedContacts.clear();
}
/**
* Clear the temporary contacts in the database. As contacts are persist
* between IM sessions, the temporary contacts need to be cleared after
* logout.
*/
private void clearTemporaryContacts() {
String selection = Imps.Contacts.CONTACTLIST + "=" + FAKE_TEMPORARY_LIST_ID;
mResolver.delete(mContactUrl, selection, null);
}
/**
* Clears the presence of the all contacts. As contacts are persist between
* IM sessions, the presence need to be cleared after logout.
*/
void clearPresence() {
StringBuilder where = new StringBuilder();
where.append(Imps.Presence.CONTACT_ID);
where.append(" in (select _id from contacts where ");
where.append(Imps.Contacts.ACCOUNT);
where.append("=");
where.append(mAccountId);
where.append(")");
mResolver.delete(Imps.Presence.CONTENT_URI, where.toString(), null);
}
void closeChatSession(String address) {
ChatSessionManagerAdapter chatSessionManager = (ChatSessionManagerAdapter) mConn
.getChatSessionManager();
ChatSessionAdapter session = (ChatSessionAdapter) chatSessionManager
.getChatSession(address);
if (session != null) {
session.leave();
}
}
void updateChatPresence(String address, String nickname, Presence p) {
ChatSessionManagerAdapter sessionManager = (ChatSessionManagerAdapter) mConn
.getChatSessionManager();
// TODO: This only find single chat sessions, we need to go through all
// active chat sessions and find if the contact is a participant of the
// session.
ChatSessionAdapter session = (ChatSessionAdapter) sessionManager.getChatSession(address);
if (session != null) {
session.insertPresenceUpdatesMsg(nickname, p);
}
}
private void seedInitialPresences() {
Builder builder = Imps.Presence.SEED_PRESENCE_BY_ACCOUNT_CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mAccountId);
mResolver.insert(builder.build(), new ContentValues(0));
}
}
| src/info/guardianproject/otr/app/im/service/ContactListManagerAdapter.java | /*
* Copyright (C) 2007-2008 Esmertec AG. Copyright (C) 2007-2008 The Android Open
* Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package info.guardianproject.otr.app.im.service;
import info.guardianproject.otr.app.im.IContactList;
import info.guardianproject.otr.app.im.IContactListListener;
import info.guardianproject.otr.app.im.ISubscriptionListener;
import info.guardianproject.otr.app.im.R;
import info.guardianproject.otr.app.im.engine.Address;
import info.guardianproject.otr.app.im.engine.Contact;
import info.guardianproject.otr.app.im.engine.ContactList;
import info.guardianproject.otr.app.im.engine.ContactListListener;
import info.guardianproject.otr.app.im.engine.ContactListManager;
import info.guardianproject.otr.app.im.engine.ImErrorInfo;
import info.guardianproject.otr.app.im.engine.ImException;
import info.guardianproject.otr.app.im.engine.Presence;
import info.guardianproject.otr.app.im.provider.Imps;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.widget.Toast;
public class ContactListManagerAdapter extends
info.guardianproject.otr.app.im.IContactListManager.Stub implements Runnable {
ImConnectionAdapter mConn;
ContentResolver mResolver;
private ContactListManager mAdaptee;
private ContactListListenerAdapter mContactListListenerAdapter;
private SubscriptionRequestListenerAdapter mSubscriptionListenerAdapter;
final RemoteCallbackList<IContactListListener> mRemoteContactListeners = new RemoteCallbackList<IContactListListener>();
final RemoteCallbackList<ISubscriptionListener> mRemoteSubscriptionListeners = new RemoteCallbackList<ISubscriptionListener>();
HashMap<Address, ContactListAdapter> mContactLists;
// Temporary contacts are created when a peer is encountered, and that peer
// is not yet on any contact list.
HashMap<String, Contact> mTemporaryContacts;
// Offline contacts are created from the local DB before the server contact lists
// are loaded.
HashMap<String, Contact> mOfflineContacts;
HashSet<String> mValidatedContactLists;
HashSet<String> mValidatedContacts;
HashSet<String> mValidatedBlockedContacts;
private long mAccountId;
private long mProviderId;
private Uri mAvatarUrl;
private Uri mContactUrl;
static final long FAKE_TEMPORARY_LIST_ID = -1;
static final String[] CONTACT_LIST_ID_PROJECTION = { Imps.ContactList._ID };
RemoteImService mContext;
public ContactListManagerAdapter(ImConnectionAdapter conn) {
mAdaptee = conn.getAdaptee().getContactListManager();
mConn = conn;
mContext = conn.getContext();
mResolver = mContext.getContentResolver();
new Thread(this).start();
}
public void run ()
{
mContactListListenerAdapter = new ContactListListenerAdapter();
mSubscriptionListenerAdapter = new SubscriptionRequestListenerAdapter();
mContactLists = new HashMap<Address, ContactListAdapter>();
mTemporaryContacts = new HashMap<String, Contact>();
mOfflineContacts = new HashMap<String, Contact>();
mValidatedContacts = new HashSet<String>();
mValidatedContactLists = new HashSet<String>();
mValidatedBlockedContacts = new HashSet<String>();
mAdaptee.addContactListListener(mContactListListenerAdapter);
mAdaptee.setSubscriptionRequestListener(mSubscriptionListenerAdapter);
mAccountId = mConn.getAccountId();
mProviderId = mConn.getProviderId();
Uri.Builder builder = Imps.Avatars.CONTENT_URI_AVATARS_BY.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
mAvatarUrl = builder.build();
builder = Imps.Contacts.CONTENT_URI_CONTACTS_BY.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
mContactUrl = builder.build();
seedInitialPresences();
loadOfflineContacts();
}
private void loadOfflineContacts() {
Cursor contactCursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts.USERNAME },
null, null, null);
String[] addresses = new String[contactCursor.getCount()];
int i = 0;
while (contactCursor.moveToNext())
{
addresses[i++] = contactCursor.getString(0);
}
Contact[] contacts = mAdaptee.createTemporaryContacts(addresses);
for (Contact contact : contacts)
mOfflineContacts.put(contact.getAddress().getBareAddress(), contact);
contactCursor.close();
}
public int createContactList(String name, List<Contact> contacts) {
try {
mAdaptee.createContactListAsync(name, contacts);
} catch (ImException e) {
return e.getImError().getCode();
}
return ImErrorInfo.NO_ERROR;
}
public int deleteContactList(String name) {
try {
mAdaptee.deleteContactListAsync(name);
} catch (ImException e) {
return e.getImError().getCode();
}
return ImErrorInfo.NO_ERROR;
}
public List<ContactListAdapter> getContactLists() {
synchronized (mContactLists) {
return new ArrayList<ContactListAdapter>(mContactLists.values());
}
}
public int removeContact(String address) {
closeChatSession(address);
if (isTemporary(address)) {
synchronized (mTemporaryContacts) {
mTemporaryContacts.remove(address);
}
} else {
synchronized (mContactLists) {
for (ContactListAdapter list : mContactLists.values()) {
int resCode = list.removeContact(address);
if (ImErrorInfo.ILLEGAL_CONTACT_ADDRESS == resCode) {
// Did not find in this list, continue to remove from
// other list.
continue;
}
if (ImErrorInfo.NO_ERROR != resCode) {
return resCode;
}
}
}
}
String selection = Imps.Contacts.USERNAME + "=?";
String[] selectionArgs = { address };
mResolver.delete(mContactUrl, selection, selectionArgs);
return ImErrorInfo.NO_ERROR;
}
public int setContactName(String address, String name) {
// update the server
try {
mAdaptee.setContactName(address,name);
} catch (ImException e) {
return e.getImError().getCode();
}
// update locally
String selection = Imps.Contacts.USERNAME + "=?";
String[] selectionArgs = { address };
ContentValues values = new ContentValues(1);
values.put( Imps.Contacts.NICKNAME, name);
int updated = mResolver.update(mContactUrl, values, selection, selectionArgs);
if( updated != 1 ) {
return ImErrorInfo.ILLEGAL_CONTACT_ADDRESS;
}
return ImErrorInfo.NO_ERROR;
}
public void approveSubscription(String address) {
mAdaptee.approveSubscriptionRequest(address);
}
public void declineSubscription(String address) {
mAdaptee.declineSubscriptionRequest(address);
}
public int blockContact(String address) {
try {
mAdaptee.blockContactAsync(address);
} catch (ImException e) {
return e.getImError().getCode();
}
return ImErrorInfo.NO_ERROR;
}
public int unBlockContact(String address) {
try {
mAdaptee.unblockContactAsync(address);
} catch (ImException e) {
RemoteImService.debug(e.getMessage());
return e.getImError().getCode();
}
return ImErrorInfo.NO_ERROR;
}
public boolean isBlocked(String address) {
try {
return mAdaptee.isBlocked(address);
} catch (ImException e) {
RemoteImService.debug(e.getMessage());
return false;
}
}
public void registerContactListListener(IContactListListener listener) {
if (listener != null) {
mRemoteContactListeners.register(listener);
}
}
public void unregisterContactListListener(IContactListListener listener) {
if (listener != null) {
mRemoteContactListeners.unregister(listener);
}
}
public void registerSubscriptionListener(ISubscriptionListener listener) {
if (listener != null) {
mRemoteSubscriptionListeners.register(listener);
}
}
public void unregisterSubscriptionListener(ISubscriptionListener listener) {
if (listener != null) {
mRemoteSubscriptionListeners.unregister(listener);
}
}
public IContactList getContactList(String name) {
return getContactListAdapter(name);
}
public void loadContactLists() {
if (mAdaptee.getState() == ContactListManager.LISTS_NOT_LOADED) {
clearValidatedContactsAndLists();
mAdaptee.loadContactListsAsync();
}
}
public int getState() {
return mAdaptee.getState();
}
public Contact getContactByAddress(String address) {
if (mAdaptee.getState() == ContactListManager.LISTS_NOT_LOADED) {
return mOfflineContacts.get(address);
}
Contact c = mAdaptee.getContact(address);
if (c == null) {
synchronized (mTemporaryContacts) {
return mTemporaryContacts.get(address);
}
} else {
return c;
}
}
public Contact[] createTemporaryContacts(String[] addresses) {
Contact[] contacts = mAdaptee.createTemporaryContacts(addresses);
for (Contact c : contacts)
insertTemporary(c);
return contacts;
}
public long queryOrInsertContact(Contact c) {
long result;
String username = mAdaptee.normalizeAddress(c.getAddress().getAddress());
String selection = Imps.Contacts.USERNAME + "=?";
String[] selectionArgs = { username };
String[] projection = { Imps.Contacts._ID };
Cursor cursor = mResolver.query(mContactUrl, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getLong(0);
} else {
result = insertTemporary(c);
}
if (cursor != null) {
cursor.close();
}
return result;
}
private long insertTemporary(Contact c) {
synchronized (mTemporaryContacts) {
mTemporaryContacts.put(mAdaptee.normalizeAddress(c.getAddress().getBareAddress()), c);
}
Uri uri = insertContactContent(c, FAKE_TEMPORARY_LIST_ID);
return ContentUris.parseId(uri);
}
/**
* Tells if a contact is a temporary one which is not in the list of
* contacts that we subscribe presence for. Usually created because of the
* user is having a chat session with this contact.
*
* @param address the address of the contact.
* @return <code>true</code> if it's a temporary contact; <code>false</code>
* otherwise.
*/
public boolean isTemporary(String address) {
synchronized (mTemporaryContacts) {
return mTemporaryContacts.containsKey(address);
}
}
ContactListAdapter getContactListAdapter(String name) {
synchronized (mContactLists) {
for (ContactListAdapter list : mContactLists.values()) {
if (name.equals(list.getName())) {
return list;
}
}
return null;
}
}
ContactListAdapter getContactListAdapter(Address address) {
synchronized (mContactLists) {
return mContactLists.get(address);
}
}
private class Exclusion {
private StringBuilder mSelection;
private List<String> mSelectionArgs;
private String mExclusionColumn;
Exclusion(String exclusionColumn, Collection<String> items) {
mSelection = new StringBuilder();
mSelectionArgs = new ArrayList<String>();
mExclusionColumn = exclusionColumn;
for (String s : items) {
add(s);
}
}
public void add(String exclusionItem) {
if (mSelection.length() == 0) {
mSelection.append(mExclusionColumn + "!=?");
} else {
mSelection.append(" AND " + mExclusionColumn + "!=?");
}
mSelectionArgs.add(exclusionItem);
}
public String getSelection() {
return mSelection.toString();
}
public String[] getSelectionArgs() {
return (String[]) mSelectionArgs.toArray(new String[0]);
}
}
private void removeObsoleteContactsAndLists() {
// remove all contacts for this provider & account which have not been
// added since login, yet still exist in db from a prior login
Exclusion exclusion = new Exclusion(Imps.Contacts.USERNAME, mValidatedContacts);
mResolver.delete(mContactUrl, exclusion.getSelection(), exclusion.getSelectionArgs());
// remove all blocked contacts for this provider & account which have not been
// added since login, yet still exist in db from a prior login
exclusion = new Exclusion(Imps.BlockedList.USERNAME, mValidatedBlockedContacts);
Uri.Builder builder = Imps.BlockedList.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
Uri uri = builder.build();
mResolver.delete(uri, exclusion.getSelection(), exclusion.getSelectionArgs());
// remove all contact lists for this provider & account which have not been
// added since login, yet still exist in db from a prior login
exclusion = new Exclusion(Imps.ContactList.NAME, mValidatedContactLists);
builder = Imps.ContactList.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
uri = builder.build();
mResolver.delete(uri, exclusion.getSelection(), exclusion.getSelectionArgs());
}
interface ContactListBroadcaster {
void broadcast(IContactListListener listener) throws RemoteException;
}
interface SubscriptionBroadcaster {
void broadcast(ISubscriptionListener listener) throws RemoteException;
}
final class ContactListListenerAdapter implements ContactListListener {
private boolean mAllContactsLoaded;
// class to hold contact changes made before mAllContactsLoaded
private class StoredContactChange {
int mType;
ContactList mList;
Contact mContact;
StoredContactChange(int type, ContactList list, Contact contact) {
mType = type;
mList = list;
mContact = contact;
}
}
private Vector<StoredContactChange> mDelayedContactChanges = new Vector<StoredContactChange>();
private void broadcast(ContactListBroadcaster callback) {
synchronized (mRemoteContactListeners) {
final int N = mRemoteContactListeners.beginBroadcast();
for (int i = 0; i < N; i++) {
IContactListListener listener = mRemoteContactListeners.getBroadcastItem(i);
try {
callback.broadcast(listener);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing the
// dead listeners.
}
}
mRemoteContactListeners.finishBroadcast();
}
}
public void onContactsPresenceUpdate(final Contact[] contacts) {
// The client listens only to presence updates for now. Update
// the avatars first to ensure it can get the new avatar when
// presence updated.
// TODO: Don't update avatar now since none of the server supports it
// updateAvatarsContent(contacts);
updatePresenceContent(contacts);
broadcast(new ContactListBroadcaster() {
public void broadcast(IContactListListener listener) throws RemoteException {
listener.onContactsPresenceUpdate(contacts);
}
});
}
public void onContactChange(final int type, final ContactList list, final Contact contact) {
ContactListAdapter removed = null;
String notificationText = null;
switch (type) {
case LIST_LOADED:
case LIST_CREATED:
addContactListContent(list);
break;
case LIST_DELETED:
removed = removeContactListFromDataBase(list.getName());
// handle case where a list is deleted before mAllContactsLoaded
if (!mAllContactsLoaded) {
// if a cached contact list is deleted before the actual contact list is
// downloaded from the server, we will have to remove the list again once
// once mAllContactsLoaded is true
if (!mValidatedContactLists.contains(list.getName())) {
mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
}
}
break;
case LIST_CONTACT_ADDED:
long listId = getContactListAdapter(list.getAddress()).getDataBaseId();
if (isTemporary(mAdaptee.normalizeAddress(contact.getAddress().getAddress()))) {
moveTemporaryContactToList(mAdaptee.normalizeAddress(contact.getAddress().getAddress()), listId);
} else {
boolean exists = updateContact(contact, listId);
if (!exists)
insertContactContent(contact, listId);
}
notificationText = mContext.getResources().getString(R.string.add_contact_success,
contact.getName());
// handle case where a contact is added before mAllContactsLoaded
if (!mAllContactsLoaded) {
// if a contact is added to a cached contact list before the actual contact
// list is downloaded from the server, we will have to add the contact to
// the contact list once mAllContactsLoaded is true
if (!mValidatedContactLists.contains(list.getName())) {
mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
}
}
break;
case LIST_CONTACT_REMOVED:
deleteContactFromDataBase(contact, list);
// handle case where a contact is removed before mAllContactsLoaded
if (!mAllContactsLoaded) {
// if a contact is added to a cached contact list before the actual contact
// list is downloaded from the server, we will have to add the contact to
// the contact list once mAllContactsLoaded is true
if (!mValidatedContactLists.contains(list.getName())) {
mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
}
}
// Clear ChatSession if any.
String address = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
closeChatSession(address);
notificationText = mContext.getResources().getString(
R.string.delete_contact_success, contact.getName());
break;
case LIST_RENAMED:
updateListNameInDataBase(list);
// handle case where a list is renamed before mAllContactsLoaded
if (!mAllContactsLoaded) {
// if a contact list name is updated before the actual contact list is
// downloaded from the server, we will have to update the list name again
// once mAllContactsLoaded is true
if (!mValidatedContactLists.contains(list.getName())) {
mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
}
}
break;
case CONTACT_BLOCKED:
insertBlockedContactToDataBase(contact);
address = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
updateContactType(address, Imps.Contacts.TYPE_BLOCKED);
closeChatSession(address);
notificationText = mContext.getResources().getString(
R.string.block_contact_success, contact.getName());
break;
case CONTACT_UNBLOCKED:
removeBlockedContactFromDataBase(contact);
notificationText = mContext.getResources().getString(
R.string.unblock_contact_success, contact.getName());
// handle case where a contact is unblocked before mAllContactsLoaded
if (!mAllContactsLoaded) {
// if a contact list name is updated before the actual contact list is
// downloaded from the server, we will have to update the list name again
// once mAllContactsLoaded is true
if (!mValidatedBlockedContacts.contains(contact.getName())) {
mDelayedContactChanges.add(new StoredContactChange(type, list, contact));
}
}
break;
default:
RemoteImService.debug("Unknown list update event!");
break;
}
final ContactListAdapter listAdapter;
if (type == LIST_DELETED) {
listAdapter = removed;
} else {
listAdapter = (list == null) ? null : getContactListAdapter(list.getAddress());
}
broadcast(new ContactListBroadcaster() {
public void broadcast(IContactListListener listener) throws RemoteException {
listener.onContactChange(type, listAdapter, contact);
}
});
if (mAllContactsLoaded && notificationText != null) {
// mContext.showToast(notificationText, Toast.LENGTH_SHORT);
}
}
public void onContactError(final int errorType, final ImErrorInfo error,
final String listName, final Contact contact) {
broadcast(new ContactListBroadcaster() {
public void broadcast(IContactListListener listener) throws RemoteException {
listener.onContactError(errorType, error, listName, contact);
}
});
}
public void handleDelayedContactChanges() {
for (StoredContactChange change : mDelayedContactChanges) {
onContactChange(change.mType, change.mList, change.mContact);
}
}
public void onAllContactListsLoaded() {
mAllContactsLoaded = true;
handleDelayedContactChanges();
removeObsoleteContactsAndLists();
broadcast(new ContactListBroadcaster() {
public void broadcast(IContactListListener listener) throws RemoteException {
listener.onAllContactListsLoaded();
}
});
}
}
final class SubscriptionRequestListenerAdapter extends ISubscriptionListener.Stub {
public void onSubScriptionRequest(final Contact from, long providerId, long accountId) {
String username = mAdaptee.normalizeAddress(from.getAddress().getAddress());
String nickname = from.getName();
queryOrInsertContact(from); // FIXME Miron
Uri uri = insertOrUpdateSubscription(username, nickname,
Imps.Contacts.SUBSCRIPTION_TYPE_FROM,
Imps.Contacts.SUBSCRIPTION_STATUS_SUBSCRIBE_PENDING);
mContext.getStatusBarNotifier().notifySubscriptionRequest(mProviderId, mAccountId,
ContentUris.parseId(uri), username, nickname);
broadcast(new SubscriptionBroadcaster() {
public void broadcast(ISubscriptionListener listener) throws RemoteException {
listener.onSubScriptionRequest(from, mProviderId, mAccountId);
}
});
}
public void onUnSubScriptionRequest(final Contact from, long providerId, long accountId) {
String username = mAdaptee.normalizeAddress(from.getAddress().getAddress());
String nickname = from.getName();
//to be implemented - should prompt user to approve unsubscribe?
}
private void broadcast(SubscriptionBroadcaster callback) {
synchronized (mRemoteSubscriptionListeners) {
final int N = mRemoteSubscriptionListeners.beginBroadcast();
for (int i = 0; i < N; i++) {
ISubscriptionListener listener = mRemoteSubscriptionListeners.getBroadcastItem(i);
try {
callback.broadcast(listener);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing the
// dead listeners.
}
}
mRemoteSubscriptionListeners.finishBroadcast();
}
}
public void onSubscriptionApproved(final String contact, long providerId, long accountId) {
insertOrUpdateSubscription(contact, null, Imps.Contacts.SUBSCRIPTION_TYPE_NONE,
Imps.Contacts.SUBSCRIPTION_STATUS_NONE);
broadcast(new SubscriptionBroadcaster() {
public void broadcast(ISubscriptionListener listener) throws RemoteException {
listener.onSubscriptionApproved(contact, mProviderId, mAccountId);
}
});
}
public void onSubscriptionDeclined(final String contact, long providerId, long accountId) {
insertOrUpdateSubscription(contact, null, Imps.Contacts.SUBSCRIPTION_TYPE_NONE,
Imps.Contacts.SUBSCRIPTION_STATUS_NONE);
broadcast(new SubscriptionBroadcaster() {
public void broadcast(ISubscriptionListener listener) throws RemoteException {
listener.onSubscriptionDeclined(contact, mProviderId, mAccountId);
}
});
}
public void onApproveSubScriptionError(final String contact, final ImErrorInfo error) {
String displayableAddress = getDisplayableAddress(contact);
String msg = mContext
.getString(R.string.approve_subscription_error, displayableAddress);
mContext.showToast(msg, Toast.LENGTH_SHORT);
}
public void onDeclineSubScriptionError(final String contact, final ImErrorInfo error) {
String displayableAddress = getDisplayableAddress(contact);
String msg = mContext
.getString(R.string.decline_subscription_error, displayableAddress);
mContext.showToast(msg, Toast.LENGTH_SHORT);
}
}
String getDisplayableAddress(String impsAddress) {
if (impsAddress.startsWith("wv:")) {
return impsAddress.substring(3);
}
return impsAddress;
}
void insertBlockedContactToDataBase(Contact contact) {
// Remove the blocked contact if it already exists, to avoid duplicates and
// handle the odd case where a blocked contact's nickname has changed
removeBlockedContactFromDataBase(contact);
Uri.Builder builder = Imps.BlockedList.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
Uri uri = builder.build();
String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
ContentValues values = new ContentValues(2);
values.put(Imps.BlockedList.USERNAME, username);
values.put(Imps.BlockedList.NICKNAME, contact.getName());
mResolver.insert(uri, values);
mValidatedBlockedContacts.add(username);
}
void removeBlockedContactFromDataBase(Contact contact) {
String address = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
Uri.Builder builder = Imps.BlockedList.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mProviderId);
ContentUris.appendId(builder, mAccountId);
Uri uri = builder.build();
mResolver.delete(uri, Imps.BlockedList.USERNAME + "=?", new String[] { address });
int type = isTemporary(address) ? Imps.Contacts.TYPE_TEMPORARY : Imps.Contacts.TYPE_NORMAL;
updateContactType(address, type);
}
void moveTemporaryContactToList(String address, long listId) {
synchronized (mTemporaryContacts) {
mTemporaryContacts.remove(address);
}
ContentValues values = new ContentValues(2);
values.put(Imps.Contacts.TYPE, Imps.Contacts.TYPE_NORMAL);
values.put(Imps.Contacts.CONTACTLIST, listId);
String selection = Imps.Contacts.USERNAME + "=? AND " + Imps.Contacts.TYPE + "="
+ Imps.Contacts.TYPE_TEMPORARY;
String[] selectionArgs = { address };
mResolver.update(mContactUrl, values, selection, selectionArgs);
}
void updateContactType(String address, int type) {
ContentValues values = new ContentValues(1);
values.put(Imps.Contacts.TYPE, type);
updateContact(address, values);
}
/**
* Insert or update subscription request from user into the database.
*
* @param username
* @param nickname
* @param subscriptionType
* @param subscriptionStatus
*/
Uri insertOrUpdateSubscription(String username, String nickname, int subscriptionType,
int subscriptionStatus) {
Cursor cursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts._ID },
Imps.Contacts.USERNAME + "=?", new String[] { username }, null);
if (cursor == null) {
RemoteImService.debug("query contact " + username + " failed");
return null;
}
Uri uri;
if (cursor.moveToFirst()) {
ContentValues values = new ContentValues(2);
values.put(Imps.Contacts.SUBSCRIPTION_TYPE, subscriptionType);
values.put(Imps.Contacts.SUBSCRIPTION_STATUS, subscriptionStatus);
long contactId = cursor.getLong(0);
uri = ContentUris.withAppendedId(Imps.Contacts.CONTENT_URI, contactId);
mResolver.update(uri, values, null, null);
} else {
ContentValues values = new ContentValues(6);
values.put(Imps.Contacts.USERNAME, username);
values.put(Imps.Contacts.NICKNAME, nickname);
values.put(Imps.Contacts.TYPE, Imps.Contacts.TYPE_NORMAL);
values.put(Imps.Contacts.CONTACTLIST, FAKE_TEMPORARY_LIST_ID);
values.put(Imps.Contacts.SUBSCRIPTION_TYPE, subscriptionType);
values.put(Imps.Contacts.SUBSCRIPTION_STATUS, subscriptionStatus);
uri = mResolver.insert(mContactUrl, values);
}
cursor.close();
return uri;
}
boolean updateContact(Contact contact, long listId)
{
ContentValues values = getContactContentValues(contact, listId);
return updateContact(mAdaptee.normalizeAddress(contact.getAddress().getAddress()),values);
}
boolean updateContact(String username, ContentValues values) {
String selection = Imps.Contacts.USERNAME + "=?";
String[] selectionArgs = { username };
return (mResolver.update(mContactUrl, values, selection, selectionArgs)) > 0;
}
void updatePresenceContent(Contact[] contacts) {
ArrayList<String> usernames = new ArrayList<String>();
ArrayList<String> statusArray = new ArrayList<String>();
ArrayList<String> customStatusArray = new ArrayList<String>();
ArrayList<String> clientTypeArray = new ArrayList<String>();
for (Contact c : contacts) {
String username = mAdaptee.normalizeAddress(c.getAddress().getAddress());
Presence p = c.getPresence();
int status = convertPresenceStatus(p);
String customStatus = p.getStatusText();
int clientType = translateClientType(p);
usernames.add(username);
statusArray.add(String.valueOf(status));
customStatusArray.add(customStatus);
clientTypeArray.add(String.valueOf(clientType));
}
ContentValues values = new ContentValues();
values.put(Imps.Contacts.ACCOUNT, mAccountId);
putStringArrayList(values, Imps.Contacts.USERNAME, usernames);
putStringArrayList(values, Imps.Presence.PRESENCE_STATUS, statusArray);
putStringArrayList(values, Imps.Presence.PRESENCE_CUSTOM_STATUS, customStatusArray);
putStringArrayList(values, Imps.Presence.CONTENT_TYPE, clientTypeArray);
mResolver.update(Imps.Presence.BULK_CONTENT_URI, values, null, null);
}
void updateAvatarsContent(Contact[] contacts) {
ArrayList<ContentValues> avatars = new ArrayList<ContentValues>();
ArrayList<String> usernames = new ArrayList<String>();
for (Contact contact : contacts) {
byte[] avatarData = contact.getPresence().getAvatarData();
if (avatarData == null) {
continue;
}
String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
ContentValues values = new ContentValues(2);
values.put(Imps.Avatars.CONTACT, username);
values.put(Imps.Avatars.DATA, avatarData);
avatars.add(values);
usernames.add(username);
}
if (avatars.size() > 0) {
// ImProvider will replace the avatar content if it already exist.
mResolver.bulkInsert(mAvatarUrl, avatars.toArray(new ContentValues[avatars.size()]));
// notify avatar changed
Intent i = new Intent(ImServiceConstants.ACTION_AVATAR_CHANGED);
i.putExtra(ImServiceConstants.EXTRA_INTENT_FROM_ADDRESS, usernames);
i.putExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, mProviderId);
i.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, mAccountId);
mContext.sendBroadcast(i);
}
}
ContactListAdapter removeContactListFromDataBase(String name) {
ContactListAdapter listAdapter = getContactListAdapter(name);
if (listAdapter == null) {
return null;
}
long id = listAdapter.getDataBaseId();
// delete contacts of this list first
mResolver.delete(mContactUrl, Imps.Contacts.CONTACTLIST + "=?",
new String[] { Long.toString(id) });
mResolver.delete(ContentUris.withAppendedId(Imps.ContactList.CONTENT_URI, id), null, null);
synchronized (mContactLists) {
return mContactLists.remove(listAdapter.getAddress());
}
}
void addContactListContent(ContactList list) {
String selection = Imps.ContactList.NAME + "=? AND " + Imps.ContactList.PROVIDER
+ "=? AND " + Imps.ContactList.ACCOUNT + "=?";
String[] selectionArgs = { list.getName(), Long.toString(mProviderId),
Long.toString(mAccountId) };
Cursor cursor = mResolver.query(Imps.ContactList.CONTENT_URI, CONTACT_LIST_ID_PROJECTION,
selection, selectionArgs, null); // no sort order
long listId = 0;
Uri uri = null;
try {
if (cursor.moveToFirst()) {
listId = cursor.getLong(0);
uri = ContentUris.withAppendedId(Imps.ContactList.CONTENT_URI, listId);
}
} finally {
cursor.close();
}
if (uri == null) {
ContentValues contactListValues = new ContentValues(3);
contactListValues.put(Imps.ContactList.NAME, list.getName());
contactListValues.put(Imps.ContactList.PROVIDER, mProviderId);
contactListValues.put(Imps.ContactList.ACCOUNT, mAccountId);
uri = mResolver.insert(Imps.ContactList.CONTENT_URI, contactListValues);
listId = ContentUris.parseId(uri);
}
mValidatedContactLists.add(list.getName());
synchronized (mContactLists) {
mContactLists.put(list.getAddress(), new ContactListAdapter(list, listId));
}
Cursor contactCursor = mResolver.query(mContactUrl, new String[] { Imps.Contacts.USERNAME },
Imps.Contacts.CONTACTLIST + "=?", new String[] { "" + listId }, null);
Set<String> existingUsernames = new HashSet<String>();
while (contactCursor.moveToNext())
existingUsernames.add(contactCursor.getString(0));
contactCursor.close();
Collection<Contact> contacts = list.getContacts();
if (contacts == null || contacts.size() == 0) {
return;
}
Iterator<Contact> iter = contacts.iterator();
while (iter.hasNext()) {
Contact c = iter.next();
String address = mAdaptee.normalizeAddress(c.getAddress().getAddress());
if (isTemporary(address)) {
if (!existingUsernames.contains(address)) {
moveTemporaryContactToList(address, listId);
}
iter.remove();
}
mValidatedContacts.add(address);
}
ArrayList<String> usernames = new ArrayList<String>();
ArrayList<String> nicknames = new ArrayList<String>();
ArrayList<String> contactTypeArray = new ArrayList<String>();
for (Contact c : contacts) {
if (updateContact(c,listId))
continue; //contact existed and was updated to this list
String username = mAdaptee.normalizeAddress(c.getAddress().getAddress());
String nickname = c.getName();
int type = Imps.Contacts.TYPE_NORMAL;
if (isTemporary(username)) {
type = Imps.Contacts.TYPE_TEMPORARY;
}
if (isBlocked(username)) {
type = Imps.Contacts.TYPE_BLOCKED;
}
usernames.add(username);
nicknames.add(nickname);
contactTypeArray.add(String.valueOf(type));
}
ContentValues values = new ContentValues(6);
values.put(Imps.Contacts.PROVIDER, mProviderId);
values.put(Imps.Contacts.ACCOUNT, mAccountId);
values.put(Imps.Contacts.CONTACTLIST, listId);
putStringArrayList(values, Imps.Contacts.USERNAME, usernames);
putStringArrayList(values, Imps.Contacts.NICKNAME, nicknames);
putStringArrayList(values, Imps.Contacts.TYPE, contactTypeArray);
mResolver.insert(Imps.Contacts.BULK_CONTENT_URI, values);
}
private void putStringArrayList(ContentValues values, String key, ArrayList<String> nicknames) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(nicknames);
os.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
values.put(key, bos.toByteArray());
}
void updateListNameInDataBase(ContactList list) {
ContactListAdapter listAdapter = getContactListAdapter(list.getAddress());
Uri uri = ContentUris.withAppendedId(Imps.ContactList.CONTENT_URI,
listAdapter.getDataBaseId());
ContentValues values = new ContentValues(1);
values.put(Imps.ContactList.NAME, list.getName());
mResolver.update(uri, values, null, null);
}
void deleteContactFromDataBase(Contact contact, ContactList list) {
String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
//if list is provided, then delete from one list
if (list != null)
{
String selection = Imps.Contacts.USERNAME + "=? AND " + Imps.Contacts.CONTACTLIST + "=?";
long listId = getContactListAdapter(list.getAddress()).getDataBaseId();
String[] selectionArgs = { username, Long.toString(listId) };
mResolver.delete(mContactUrl, selection, selectionArgs);
}
else //if it is null, delete from all
{
String selection = Imps.Contacts.USERNAME + "=?";
String[] selectionArgs = { username };
mResolver.delete(mContactUrl, selection, selectionArgs);
}
// clear the history message if the contact doesn't exist in any list
// anymore.
if (mAdaptee.getContact(contact.getAddress()) == null) {
clearHistoryMessages(username);
}
}
Uri insertContactContent(Contact contact, long listId) {
ContentValues values = getContactContentValues(contact, listId);
Uri uri = mResolver.insert(mContactUrl, values);
ContentValues presenceValues = getPresenceValues(ContentUris.parseId(uri),
contact.getPresence());
mResolver.insert(Imps.Presence.CONTENT_URI, presenceValues);
return uri;
}
private ContentValues getContactContentValues(Contact contact, long listId) {
final String username = mAdaptee.normalizeAddress(contact.getAddress().getAddress());
final String nickname = contact.getName();
int type = Imps.Contacts.TYPE_NORMAL;
if (isTemporary(username)) {
type = Imps.Contacts.TYPE_TEMPORARY;
}
if (isBlocked(username)) {
type = Imps.Contacts.TYPE_BLOCKED;
}
ContentValues values = new ContentValues(4);
values.put(Imps.Contacts.USERNAME, username);
values.put(Imps.Contacts.NICKNAME, nickname);
values.put(Imps.Contacts.CONTACTLIST, listId);
values.put(Imps.Contacts.TYPE, type);
return values;
}
void clearHistoryMessages(String contact) {
Uri uri = Imps.Messages.getContentUriByContact(mAccountId, contact);
mResolver.delete(uri, null, null);
}
private ContentValues getPresenceValues(long contactId, Presence p) {
ContentValues values = new ContentValues(3);
values.put(Imps.Presence.CONTACT_ID, contactId);
values.put(Imps.Contacts.PRESENCE_STATUS, convertPresenceStatus(p));
values.put(Imps.Contacts.PRESENCE_CUSTOM_STATUS, p.getStatusText());
values.put(Imps.Presence.CLIENT_TYPE, translateClientType(p));
return values;
}
private int translateClientType(Presence presence) {
int clientType = presence.getClientType();
switch (clientType) {
case Presence.CLIENT_TYPE_MOBILE:
return Imps.Presence.CLIENT_TYPE_MOBILE;
default:
return Imps.Presence.CLIENT_TYPE_DEFAULT;
}
}
/**
* Converts the presence status to the value defined for ImProvider.
*
* @param presence The presence from the IM engine.
* @return The status value defined in for ImProvider.
*/
public static int convertPresenceStatus(Presence presence) {
switch (presence.getStatus()) {
case Presence.AVAILABLE:
return Imps.Presence.AVAILABLE;
case Presence.IDLE:
return Imps.Presence.IDLE;
case Presence.AWAY:
return Imps.Presence.AWAY;
case Presence.DO_NOT_DISTURB:
return Imps.Presence.DO_NOT_DISTURB;
case Presence.OFFLINE:
return Imps.Presence.OFFLINE;
}
// impossible...
RemoteImService.debug("Illegal presence status value " + presence.getStatus());
return Imps.Presence.AVAILABLE;
}
public void clearOnLogout() {
clearValidatedContactsAndLists();
clearTemporaryContacts();
clearPresence();
}
/**
* Clears the list of validated contacts and contact lists. As contacts and
* contacts lists are added after login, contacts and contact lists are
* stored as "validated contacts". After initial download of contacts is
* complete, any contacts and contact lists that remain in the database, but
* are not in the validated list, are obsolete and should be removed. This
* function resets that list for use upon login.
*/
private void clearValidatedContactsAndLists() {
// clear the list of validated contacts, contact lists, and blocked contacts
mValidatedContacts.clear();
mValidatedContactLists.clear();
mValidatedBlockedContacts.clear();
}
/**
* Clear the temporary contacts in the database. As contacts are persist
* between IM sessions, the temporary contacts need to be cleared after
* logout.
*/
private void clearTemporaryContacts() {
String selection = Imps.Contacts.CONTACTLIST + "=" + FAKE_TEMPORARY_LIST_ID;
mResolver.delete(mContactUrl, selection, null);
}
/**
* Clears the presence of the all contacts. As contacts are persist between
* IM sessions, the presence need to be cleared after logout.
*/
void clearPresence() {
StringBuilder where = new StringBuilder();
where.append(Imps.Presence.CONTACT_ID);
where.append(" in (select _id from contacts where ");
where.append(Imps.Contacts.ACCOUNT);
where.append("=");
where.append(mAccountId);
where.append(")");
mResolver.delete(Imps.Presence.CONTENT_URI, where.toString(), null);
}
void closeChatSession(String address) {
ChatSessionManagerAdapter chatSessionManager = (ChatSessionManagerAdapter) mConn
.getChatSessionManager();
ChatSessionAdapter session = (ChatSessionAdapter) chatSessionManager
.getChatSession(address);
if (session != null) {
session.leave();
}
}
void updateChatPresence(String address, String nickname, Presence p) {
ChatSessionManagerAdapter sessionManager = (ChatSessionManagerAdapter) mConn
.getChatSessionManager();
// TODO: This only find single chat sessions, we need to go through all
// active chat sessions and find if the contact is a participant of the
// session.
ChatSessionAdapter session = (ChatSessionAdapter) sessionManager.getChatSession(address);
if (session != null) {
session.insertPresenceUpdatesMsg(nickname, p);
}
}
private void seedInitialPresences() {
Builder builder = Imps.Presence.SEED_PRESENCE_BY_ACCOUNT_CONTENT_URI.buildUpon();
ContentUris.appendId(builder, mAccountId);
mResolver.insert(builder.build(), new ContentValues(0));
}
}
| only show notification if main window is broadcast is not available
| src/info/guardianproject/otr/app/im/service/ContactListManagerAdapter.java | only show notification if main window is broadcast is not available | <ide><path>rc/info/guardianproject/otr/app/im/service/ContactListManagerAdapter.java
<ide> Uri uri = insertOrUpdateSubscription(username, nickname,
<ide> Imps.Contacts.SUBSCRIPTION_TYPE_FROM,
<ide> Imps.Contacts.SUBSCRIPTION_STATUS_SUBSCRIBE_PENDING);
<del> mContext.getStatusBarNotifier().notifySubscriptionRequest(mProviderId, mAccountId,
<del> ContentUris.parseId(uri), username, nickname);
<del> broadcast(new SubscriptionBroadcaster() {
<add>
<add> boolean hadListener = broadcast(new SubscriptionBroadcaster() {
<ide> public void broadcast(ISubscriptionListener listener) throws RemoteException {
<ide> listener.onSubScriptionRequest(from, mProviderId, mAccountId);
<ide> }
<ide> });
<add>
<add> if (!hadListener)
<add> {
<add> mContext.getStatusBarNotifier().notifySubscriptionRequest(mProviderId, mAccountId,
<add> ContentUris.parseId(uri), username, nickname);
<add> }
<ide> }
<ide>
<ide> public void onUnSubScriptionRequest(final Contact from, long providerId, long accountId) {
<ide> }
<ide>
<ide>
<del> private void broadcast(SubscriptionBroadcaster callback) {
<add> private boolean broadcast(SubscriptionBroadcaster callback) {
<add> boolean hadListener = false;
<add>
<ide> synchronized (mRemoteSubscriptionListeners) {
<ide> final int N = mRemoteSubscriptionListeners.beginBroadcast();
<ide> for (int i = 0; i < N; i++) {
<ide> ISubscriptionListener listener = mRemoteSubscriptionListeners.getBroadcastItem(i);
<ide> try {
<ide> callback.broadcast(listener);
<add> hadListener = true;
<ide> } catch (RemoteException e) {
<ide> // The RemoteCallbackList will take care of removing the
<ide> // dead listeners.
<ide> }
<ide> mRemoteSubscriptionListeners.finishBroadcast();
<ide> }
<add>
<add> return hadListener;
<ide> }
<ide>
<ide> public void onSubscriptionApproved(final String contact, long providerId, long accountId) { |
|
Java | apache-2.0 | 6b3f2629fafe5e9c1fe7d6b12c97eb8e53621fa6 | 0 | shimniok/WheelEncoderGenerator | /*
* Copyright 2021 mes.
*
* 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.botthoughts.wheelencodergenerator;
import com.botthoughts.util.BoundedIntegerTextFilter;
import com.botthoughts.util.DoubleFormatter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Optional;
import java.util.Properties;
import java.util.ResourceBundle;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.print.PageLayout;
import javafx.print.PrintQuality;
import javafx.print.PrintResolution;
import javafx.print.Printer;
import javafx.print.PrinterJob;
import javafx.scene.Node;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Spinner;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.AnchorPane;
import javafx.scene.transform.Scale;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import com.botthoughts.util.GitTagService;
import com.botthoughts.util.AppInfo;
import java.net.MalformedURLException;
import java.util.ArrayList;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ChangeListener;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
import javafx.scene.control.TextFormatter;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.util.converter.IntegerStringConverter;
/**
* Primary controller for WheelEncoderGenerator app handles the main window and all related actions.
* @author mes
*/
public class PrimaryController implements Initializable {
//////////////////////////////////////////////////////////////////////////////////////////////////
// Private fields
private EncoderView encoderPreview;
private File currentFile;
private static final String EXT = ".we2";
private static final ExtensionFilter extensionFilter
= new ExtensionFilter("Wheel Encoder Generator v2", "*" + EXT);
private SimpleStringProperty filename;
private SimpleBooleanProperty saved;
private final SimpleIntegerProperty decimals = new SimpleIntegerProperty();
private Alert alertDialog;
private Alert confirmDialog;
private EncoderProperties ep;
//////////////////////////////////////////////////////////////////////////////////////////////////
// FXML UI Widgets
// Main Window
@FXML Canvas encoderUI;
@FXML ComboBox typeUI;
@FXML Spinner resolutionUI;
@FXML TextField outerUI;
@FXML TextField innerUI;
@FXML TextField centerUI;
@FXML ComboBox unitsUI;
@FXML ToggleGroup directionUI;
@FXML ToggleButton cwUI;
@FXML ToggleButton ccwUI;
@FXML ToggleButton invertedUI;
@FXML ToggleButton indexUI;
@FXML AnchorPane canvasContainer;
@FXML Button newButton;
@FXML Button saveButton;
@FXML Button saveAsButton;
@FXML Button printButton;
@FXML MenuButton helpButton;
@FXML GridPane updatePane;
@FXML Label gitUrlUI;
private Stage helpStage;
private Stage aboutStage;
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// UTILITIES
//
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Use GitTagService to read Tags API and compare to current version specified in
* version.properties to determine if application has update available and display update message
* with button to copy URL.
*/
private void checkForUpdates() {
// Get the latest tag from the application's GitHub repo.
GitTagService gts;
String latest = "";
try {
gts = new GitTagService("shimniok", "WheelEncoderGenerator");
ArrayList<String> names = gts.getNames();
System.out.println(names.get(0));
} catch (MalformedURLException ex) {
System.out.println("PrimaryControler.initialize(): MalformedURLException: "+ex);
} catch (IOException ex) {
System.out.println("PrimaryControler.initialize(): IOException: "+ex);
}
try {
String version = "v" + AppInfo.get().getVersion(); // Prefix with 'v' to match github tags
System.out.println(version);
// If the latest tag isn't equal to the current version, then either an update is available
// (unless you're the developer working on a *newer* version.
updatePane.setVisible(!version.equals(latest)); // Show the update message
} catch (IOException e) {
System.out.println("AppInfo: "+e);
}
}
private void addDimensionValidator(TextField tf) {
tf.textProperty().addListener((obs, ov, nv) -> {
if (ep.isValid()) {
tf.getStyleClass().remove("error");
} else {
tf.getStyleClass().add("error");
}
});
}
private void invalidWarning() {
showErrorDialog("Invalid Encoder", "Please fix invalid encoder settings.");
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// DIALOGS
//
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Show a dialog.
* @param title is the title for the title bar
* @param text is the text to display in the dialog
* @param type is the alert type to use (see Alert.AlertType
*/
private void showDialog(String title, String text, Alert.AlertType type) {
alertDialog.setTitle(title);
alertDialog.setContentText(text);
alertDialog.setAlertType(type);
alertDialog.showAndWait();
}
/**
* Show an error dialog.
* @param title is the title for the title bar
* @param text is the text to display in the dialog
*/
private void showErrorDialog(String title, String text) {
showDialog(title, text, Alert.AlertType.ERROR);
}
/**
* Show a confirmation dialog
* @param title is the title for the title bar
* @param text is the text to display in the dialog
* @return result as an Optional<ButtonType>
*/
private Optional<ButtonType> showConfirmDialog(String title, String text) {
confirmDialog.setContentText(text);
confirmDialog.setTitle(title);
Optional<ButtonType> res = confirmDialog.showAndWait();
return res;
}
/**
* Checks if current file needs saving and if so, prompts user to save with Yes/No/Cancel,
* returning a boolean representing whether the calling method should continue or abort.
* @return true to continue, false to abort
*/
private boolean saveAndContinue() {
SimpleBooleanProperty okToContinue = new SimpleBooleanProperty(false);
if (saved.get()) {
okToContinue.set(true);
} else {
Optional<ButtonType> optional =
this.showConfirmDialog("Save?", "Save changes before continuing?");
optional.filter(response -> response == ButtonType.YES)
.ifPresent(response -> okToContinue.set(saveFile()) );
optional.filter(response -> response == ButtonType.CANCEL)
.ifPresent(response -> okToContinue.set(false) );
optional.filter(response -> response == ButtonType.NO)
.ifPresent(response -> okToContinue.set(true));
}
return okToContinue.get();
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// EVENT HANDLERS
//
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Save the current encoder to the specified file.
* @param f is the File to which the encoder will be saved.
* @return true if file save is successful, false if unsuccessful or file is null
*/
public boolean saveFile(File f) {
if (f == null) return false;
try {
FileOutputStream out = new FileOutputStream(f);
Properties p = ep.toProperties();
p.store(out, "Wheel Encoder Generator");
System.out.println("file=" + f.getCanonicalPath());
currentFile = f; // only do this if save succeeds!
filename.set(f.getName());
saved.set(true);
} catch (IOException ex) {
showErrorDialog("File Save Error", "Error saving " + f.getName() + "\n" + ex.getMessage());
return false;
}
return true;
}
/**
* Handler for File Save calls saveFile() if the file has been saved previously and calls
* saveFileAs() if the file has never been saved before.
* @return result of SaveFile() or saveFileAs(); false if ep.isValid() is false
*/
@FXML
public boolean saveFile() {
if (ep.isValid()) {
if (currentFile == null) {
return saveFileAs();
} else {
return saveFile(currentFile);
}
} else {
this.invalidWarning();
return false;
}
}
/**
* Save file into new file/location selected by user from dialog.
* @return result of SaveFile(); false if ep.isValid() is false
*/
@FXML
public boolean saveFileAs() {
if (ep.isValid()) {
FileChooser fc = new FileChooser();
fc.setInitialFileName(filename.get());
fc.getExtensionFilters().add(extensionFilter);
File f = fc.showSaveDialog(App.stage);
System.out.println("filename: "+f);
return saveFile(f);
} else {
this.invalidWarning();
return false;
}
}
/**
* Opens file selected by user from file open dialog. Prompts user to save current encoder if it
* has not been saved yet.
*/
@FXML
public void openFile() {
FileChooser fc = new FileChooser();
fc.getExtensionFilters().add(extensionFilter);
SimpleBooleanProperty cancel = new SimpleBooleanProperty(false);
if (!this.saveAndContinue()) return;
File f = fc.showOpenDialog(App.stage);
if (f == null) return;
try {
FileInputStream in;
in = new FileInputStream(f);
Properties p = new Properties();
p.load(in);
currentFile = f;
filename.set(f.getName());
saved.set(true);
} catch (IOException ex) {
showErrorDialog("File Open Error", "Error opening " + f.getName() + "\n" + ex.getMessage());
}
}
/**
* Erase current encoder and reset to default. Prompts user to save current encoder if it has
* not been saved yet.
*/
@FXML
public void newFile() {
SimpleBooleanProperty cancel = new SimpleBooleanProperty(false);
if (!saveAndContinue()) return;
currentFile = null;
filename.set("untitled" + EXT);
ep.initialize();
saved.set(false);
}
/**
* Handles print event by calling method to print encoder node.
* @param e
*/
@FXML
public void print(Event e) {
if (ep.isValid()) {
print(encoderUI);
} else {
this.invalidWarning();
}
}
/**
* Prints the specified encoder node.
* @param node is the node containing the encoder to be printed.
*/
@FXML
public void print(Node node) {
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null && job.showPrintDialog(App.stage)) {
Printer printer = job.getPrinter();
PageLayout pageLayout = job.getJobSettings().getPageLayout();
PrintResolution resolution = printer.getPrinterAttributes()
.getDefaultPrintResolution();
double dpi = resolution.getFeedResolution(); // dpi
System.out.println("print dpi=" + dpi);
double scale = dpi / 72;
double width = scale * pageLayout.getPrintableWidth();
double height = scale * pageLayout.getPrintableHeight();
System.out.println("width=" + width + ", height=" + height);
Canvas c = new Canvas(width, height);
c.getTransforms().add(new Scale(1 / scale, 1 / scale));
c.setVisible(true); // won't print otherwise
AnchorPane pane = new AnchorPane();
pane.getChildren().add(c); // required to print/scale
pane.setVisible(true);
GraphicsContext gc = c.getGraphicsContext2D();
//gc.setImageSmoothing(false);
scale = dpi;
if (ep.unitsProperty().get().equals(EncoderProperties.UNITS_MM)) {
scale /= 25.4;
}
EncoderView ev = new EncoderView(c, scale, ep);
ev.render();
job.getJobSettings().setPrintQuality(PrintQuality.HIGH);
boolean success = job.printPage(pane);
if (success) {
job.endJob();
} else {
showErrorDialog("Printing Problem", "Status: " + job.getJobStatus().toString());
}
}
}
/**
* Export encoder as image. Not yet implemented.
*/
@FXML
public void export() {
// TODO file export Issue #7
}
/**
* Open Help window to display online help.
*/
@FXML
public void help() {
helpStage.show();
}
/**
* Open About window to display app information.
*/
@FXML
public void about() {
aboutStage.show();
}
/**
* Copies the URL for GitHub Releases into the clipboard.
*/
@FXML
public void copyGithubUrlToClipboard() {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
String url = gitUrlUI.getText();
gitUrlUI.setText("Copied to clipboard!");
content.putString(url);
clipboard.setContent(content);
Timeline timeline = new Timeline();
timeline.autoReverseProperty().set(false);
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(3000),
new KeyValue(gitUrlUI.textProperty(), url)
));
timeline.play();
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// LISTENERS
//
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Update the application title bar based on the current filename and saved state.
*/
public void updateTitle() {
String title = "WheelEncoderGenerator - " + this.filename.get();
if (!saved.get()) title += "*";
App.stage.setTitle(title);
}
private ChangeListener<Boolean> toggleListener(String yes, String no, ToggleButton b) {
return (obs, ov, nv) -> { b.setText((nv)?yes:no); };
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// INITIALIZATION
//
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Initialize the PrimaryController
* @param url
* @param rb
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
ep = new EncoderProperties();
System.out.println("PrimaryController: initialize()");
// Handle exiting/quitting
SimpleBooleanProperty cancel = new SimpleBooleanProperty(false);
App.stage.setOnCloseRequest((event) -> {
if (!saveAndContinue()) {
event.consume();
} else {
Platform.exit();
}
});
typeUI.getItems().setAll(ep.getTypeOptions());
typeUI.valueProperty().bindBidirectional(ep.typeProperty());
// System.out.println("PrimaryController: type=" + ep.typeProperty());
resolutionUI.setValueFactory(
new ResolutionValueFactory(new IntegerStringConverter(),
ep.minResolutionProperty(), ep.maxResolutionProperty(),
ep.resolutionIncrementProperty(), ep.resolutionDecrementProperty()));
resolutionUI.getValueFactory().valueProperty().bindBidirectional(ep.resolutionProperty());
TextFormatter<Integer> tf = new TextFormatter(new BoundedIntegerTextFilter(ep.minResolutionProperty(),
ep.maxResolutionProperty()));
resolutionUI.getEditor().setTextFormatter(tf);
decimals.set(1); // units default to mm, so manually set decimal format
DoubleFormatter outerFmt = new DoubleFormatter();
outerFmt.decimalsProperty().bind(decimals);
outerUI.textProperty().bindBidirectional((Property) ep.outerDiameterProperty(),
outerFmt.getConverter());
outerUI.setTextFormatter(outerFmt);
addDimensionValidator(outerUI);
DoubleFormatter innerFmt = new DoubleFormatter();
innerFmt.decimalsProperty().bind(decimals);
innerUI.textProperty().bindBidirectional((Property) ep.innerDiameterProperty(),
innerFmt.getConverter());
innerUI.setTextFormatter(innerFmt);
addDimensionValidator(innerUI);
DoubleFormatter centerFmt = new DoubleFormatter();
centerFmt.decimalsProperty().bind(decimals);
centerUI.textProperty().bindBidirectional((Property) ep.centerDiameterProperty(),
centerFmt.getConverter());
centerUI.setTextFormatter(centerFmt);
addDimensionValidator(centerUI);
unitsUI.getItems().addAll(ep.getUnitOptions());
unitsUI.valueProperty().bindBidirectional(ep.unitsProperty());
unitsUI.valueProperty().addListener((obs, ov, nv) -> {
if (nv.equals(EncoderProperties.UNITS_MM)) {
decimals.set(1);
// Automatically convert current value
ep.outerDiameterProperty().set(UnitConverter.toMillimeter(ep.outerDiameterProperty().get()));
ep.innerDiameterProperty().set(UnitConverter.toMillimeter(ep.innerDiameterProperty().get()));
ep.centerDiameterProperty().set(UnitConverter.toMillimeter(ep.centerDiameterProperty().get()));
} else if (nv.equals(EncoderProperties.UNITS_INCH)) {
decimals.set(3);
// Automatically convert current value
ep.outerDiameterProperty().set(UnitConverter.toInch(ep.outerDiameterProperty().get()));
ep.innerDiameterProperty().set(UnitConverter.toInch(ep.innerDiameterProperty().get()));
ep.centerDiameterProperty().set(UnitConverter.toInch(ep.centerDiameterProperty().get()));
}
// Force conversion to new format
outerUI.textProperty().set(outerUI.textProperty().get());
innerUI.textProperty().set(innerUI.textProperty().get());
centerUI.textProperty().set(centerUI.textProperty().get());
});
invertedUI.selectedProperty().bindBidirectional(ep.invertedProperty());
invertedUI.selectedProperty().addListener(this.toggleListener("Yes", "No", invertedUI));
indexUI.selectedProperty().bindBidirectional(ep.indexedProperty());
indexUI.disableProperty().bind(ep.indexableProperty().not());
indexUI.selectedProperty().addListener(this.toggleListener("Yes", "No", indexUI));
// Clockwise/Counter-clockwise buttons part of ToggleGroup
ToggleGroup direction = new ToggleGroup();
cwUI.toggleGroupProperty().set(direction);
ccwUI.toggleGroupProperty().set(direction);
cwUI.selectedProperty().bindBidirectional(ep.directionProperty());
// Disable if the current encoder type is non-directional
cwUI.disableProperty().bind(ep.directionalProperty().not());
ccwUI.disableProperty().bind(ep.directionalProperty().not());
// Dialogs
alertDialog = new Alert(Alert.AlertType.ERROR);
confirmDialog = new Alert(Alert.AlertType.CONFIRMATION);
confirmDialog.getButtonTypes().setAll(ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);
// Update encoder preview and saved status on any settings change
encoderPreview = new EncoderView(encoderUI, ep);
ep.addListener((observable, oldvalue, newvalue) -> {
encoderPreview.render();
saved.set(false);
});
// Current filename
filename = new SimpleStringProperty();
// Update App title on filename change
filename.addListener((obs, ov, nv) -> {
this.updateTitle();
});
// Set saved true so calling newFile() to initialize doesn't prompt
saved = new SimpleBooleanProperty(true);
// Update App title on saved change
saved.addListener((obs, ov, nv) -> {
this.updateTitle();
});
// Only enable save button if unsaved changes
saveButton.disableProperty().bind(saved);
// Initialize a new encoder
newFile();
// Force rendering since this doesn't seem to happen via listener for some reason
encoderPreview.render();
checkForUpdates();
// Initialize Help display to minimize load time later
try {
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(getClass().getResource("help.fxml"));
helpStage = new Stage();
helpStage.setTitle("WEG - Online Help");
helpStage.setScene(new Scene(root));
} catch (IOException e) {
// this.showErrorDialog("Error", "Error loading help window");
System.out.println("Error loading help window: "+e.getMessage());
}
// Initialize About display to minimize load time later
aboutStage = new Stage();
try {
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(getClass().getResource("about.fxml"));
aboutStage.setScene(new Scene(root));
aboutStage.setTitle("About " + AppInfo.get().getAbbr());
} catch (IOException e) {
// this.showErrorDialog("Error", "Error loading about window\n");
System.out.println("IOException: " + e.getMessage());
}
}
}
| src/main/java/com/botthoughts/wheelencodergenerator/PrimaryController.java | /*
* Copyright 2021 mes.
*
* 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.botthoughts.wheelencodergenerator;
import com.botthoughts.util.BoundedIntegerTextFilter;
import com.botthoughts.util.DoubleFormatter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Optional;
import java.util.Properties;
import java.util.ResourceBundle;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.print.PageLayout;
import javafx.print.PrintQuality;
import javafx.print.PrintResolution;
import javafx.print.Printer;
import javafx.print.PrinterJob;
import javafx.scene.Node;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Spinner;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.AnchorPane;
import javafx.scene.transform.Scale;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import com.botthoughts.util.GitTagService;
import com.botthoughts.util.AppInfo;
import java.net.MalformedURLException;
import java.util.ArrayList;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ChangeListener;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
import javafx.scene.control.TextFormatter;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.util.converter.IntegerStringConverter;
/**
* Primary controller for WheelEncoderGenerator app handles the main window and all related actions.
* @author mes
*/
public class PrimaryController implements Initializable {
//////////////////////////////////////////////////////////////////////////////////////////////////
// Private fields
private EncoderView encoderPreview;
private File currentFile;
private static final String EXT = ".we2";
private static final ExtensionFilter extensionFilter
= new ExtensionFilter("Wheel Encoder Generator v2", "*" + EXT);
private SimpleStringProperty filename;
private SimpleBooleanProperty saved;
private final SimpleIntegerProperty decimals = new SimpleIntegerProperty();
private Alert alertDialog;
private Alert confirmDialog;
private EncoderProperties ep;
//////////////////////////////////////////////////////////////////////////////////////////////////
// FXML UI Widgets
// Main Window
@FXML Canvas encoderUI;
@FXML ComboBox typeUI;
@FXML Spinner resolutionUI;
@FXML TextField outerUI;
@FXML TextField innerUI;
@FXML TextField centerUI;
@FXML ComboBox unitsUI;
@FXML ToggleGroup directionUI;
@FXML ToggleButton cwUI;
@FXML ToggleButton ccwUI;
@FXML ToggleButton invertedUI;
@FXML ToggleButton indexUI;
@FXML AnchorPane canvasContainer;
@FXML Button newButton;
@FXML Button saveButton;
@FXML Button saveAsButton;
@FXML Button printButton;
@FXML MenuButton helpButton;
@FXML GridPane updatePane;
@FXML Label gitUrlUI;
private Stage helpStage;
private Stage aboutStage;
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// UTILITIES
//
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Use GitTagService to read Tags API and compare to current version specified in
* version.properties to determine if application has update available and display update message
* with button to copy URL.
*/
private void checkForUpdates() {
// Get the latest tag from the application's GitHub repo.
GitTagService gts;
String latest = "";
try {
gts = new GitTagService("shimniok", "WheelEncoderGenerator");
ArrayList<String> names = gts.getNames();
System.out.println(names.get(0));
} catch (MalformedURLException ex) {
System.out.println("PrimaryControler.initialize(): MalformedURLException: "+ex);
} catch (IOException ex) {
System.out.println("PrimaryControler.initialize(): IOException: "+ex);
}
try {
String version = "v" + AppInfo.get().getVersion(); // Prefix with 'v' to match github tags
System.out.println(version);
// If the latest tag isn't equal to the current version, then either an update is available
// (unless you're the developer working on a *newer* version.
updatePane.setVisible(!version.equals(latest)); // Show the update message
} catch (IOException e) {
System.out.println("AppInfo: "+e);
}
}
private void addDimensionValidator(TextField tf) {
tf.textProperty().addListener((obs, ov, nv) -> {
if (ep.isValid()) {
tf.getStyleClass().remove("error");
} else {
tf.getStyleClass().add("error");
}
});
}
private void invalidWarning() {
showErrorDialog("Invalid Encoder", "Please fix invalid encoder settings.");
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// DIALOGS
//
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Show a dialog.
* @param title is the title for the title bar
* @param text is the text to display in the dialog
* @param type is the alert type to use (see Alert.AlertType
*/
private void showDialog(String title, String text, Alert.AlertType type) {
alertDialog.setTitle(title);
alertDialog.setContentText(text);
alertDialog.setAlertType(type);
alertDialog.showAndWait();
}
/**
* Show an error dialog.
* @param title is the title for the title bar
* @param text is the text to display in the dialog
*/
private void showErrorDialog(String title, String text) {
showDialog(title, text, Alert.AlertType.ERROR);
}
/**
* Show a confirmation dialog
* @param title is the title for the title bar
* @param text is the text to display in the dialog
* @return result as an Optional<ButtonType>
*/
private Optional<ButtonType> showConfirmDialog(String title, String text) {
confirmDialog.setContentText(text);
confirmDialog.setTitle(title);
Optional<ButtonType> res = confirmDialog.showAndWait();
return res;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// EVENT HANDLERS
//
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Save the current encoder to the specified file.
* @param f is the File to which the encoder will be saved.
* @return true if file save is successful, false if unsuccessful or file is null
*/
public boolean saveFile(File f) {
if (f == null) return false;
try {
FileOutputStream out = new FileOutputStream(f);
Properties p = ep.toProperties();
p.store(out, "Wheel Encoder Generator");
System.out.println("file=" + f.getCanonicalPath());
currentFile = f; // only do this if save succeeds!
filename.set(f.getName());
saved.set(true);
} catch (IOException ex) { // TODO should really handle errors externally so we can e.g. cancel new/open/quit operation
showErrorDialog("File Save Error", "Error saving " + f.getName() + "\n" + ex.getMessage());
return false;
}
return true;
}
/**
* Handler for File Save calls saveFile() if the file has been saved previously and calls
* saveFileAs() if the file has never been saved before.
* @return result of SaveFile() or saveFileAs(); false if ep.isValid() is false
*/
@FXML
public boolean saveFile() {
if (ep.isValid()) {
if (currentFile == null) {
return saveFileAs();
} else {
return saveFile(currentFile);
}
} else {
this.invalidWarning();
return false;
}
}
/**
* Save file into new file/location selected by user from dialog.
* @return result of SaveFile(); false if ep.isValid() is false
*/
@FXML
public boolean saveFileAs() {
if (ep.isValid()) {
FileChooser fc = new FileChooser();
fc.setInitialFileName(filename.get());
fc.getExtensionFilters().add(extensionFilter);
File f = fc.showSaveDialog(App.stage);
System.out.println("filename: "+f);
return saveFile(f);
} else {
this.invalidWarning();
return false;
}
}
/**
* Opens file selected by user from file open dialog. Prompts user to save current encoder if it
* has not been saved yet.
*/
@FXML
public void openFile() {
FileChooser fc = new FileChooser();
fc.getExtensionFilters().add(extensionFilter);
SimpleBooleanProperty cancel = new SimpleBooleanProperty(false);
if (!saved.get()) {
Optional<ButtonType> optional =
this.showConfirmDialog("Save?", "Save changes before opening a new file?");
optional.filter(response -> response == ButtonType.YES)
.ifPresent(response -> { cancel.set(!saveFile()); });
optional.filter(response -> response == ButtonType.CANCEL)
.ifPresent(response -> { cancel.set(true); });
}
if (cancel.get()) return;
File f = fc.showOpenDialog(App.stage);
if (f == null) return;
try {
FileInputStream in;
in = new FileInputStream(f);
Properties p = new Properties();
p.load(in);
currentFile = f;
filename.set(f.getName());
saved.set(true);
} catch (IOException ex) {
showErrorDialog("File Open Error", "Error opening " + f.getName() + "\n" + ex.getMessage());
}
}
/**
* Erase current encoder and reset to default. Prompts user to save current encoder if it has
* not been saved yet.
*/
@FXML
public void newFile() {
SimpleBooleanProperty cancel = new SimpleBooleanProperty(false);
if (!saved.get()) {
Optional<ButtonType> optional =
this.showConfirmDialog("Save?", "Save changes before creating a new encoder?");
optional.filter(response -> response == ButtonType.YES)
.ifPresent(response -> { cancel.set(!saveFile()); });
optional.filter(response -> response == ButtonType.CANCEL)
.ifPresent(response -> { cancel.set(true); });
}
if (cancel.get()) return;
currentFile = null;
filename.set("untitled" + EXT);
ep.initialize();
saved.set(false);
}
/**
* Handles print event by calling method to print encoder node.
* @param e
*/
@FXML
public void print(Event e) {
if (ep.isValid()) {
print(encoderUI);
} else {
this.invalidWarning();
}
}
/**
* Prints the specified encoder node.
* @param node is the node containing the encoder to be printed.
*/
@FXML
public void print(Node node) {
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null && job.showPrintDialog(App.stage)) {
Printer printer = job.getPrinter();
PageLayout pageLayout = job.getJobSettings().getPageLayout();
PrintResolution resolution = printer.getPrinterAttributes()
.getDefaultPrintResolution();
double dpi = resolution.getFeedResolution(); // dpi
System.out.println("print dpi=" + dpi);
double scale = dpi / 72;
double width = scale * pageLayout.getPrintableWidth();
double height = scale * pageLayout.getPrintableHeight();
System.out.println("width=" + width + ", height=" + height);
Canvas c = new Canvas(width, height);
c.getTransforms().add(new Scale(1 / scale, 1 / scale));
c.setVisible(true); // won't print otherwise
AnchorPane pane = new AnchorPane();
pane.getChildren().add(c); // required to print/scale
pane.setVisible(true);
GraphicsContext gc = c.getGraphicsContext2D();
//gc.setImageSmoothing(false);
scale = dpi;
if (ep.unitsProperty().get().equals(EncoderProperties.UNITS_MM)) {
scale /= 25.4;
}
EncoderView ev = new EncoderView(c, scale, ep);
ev.render();
job.getJobSettings().setPrintQuality(PrintQuality.HIGH);
boolean success = job.printPage(pane);
if (success) {
job.endJob();
} else {
showErrorDialog("Printing Problem", "Status: " + job.getJobStatus().toString());
}
}
}
/**
* Export encoder as image. Not yet implemented.
*/
@FXML
public void export() {
// TODO file export Issue #7
}
/**
* Open Help window to display online help.
*/
@FXML
public void help() {
helpStage.show();
}
/**
* Open About window to display app information.
*/
@FXML
public void about() {
aboutStage.show();
}
/**
* Copies the URL for GitHub Releases into the clipboard.
*/
@FXML
public void copyGithubUrlToClipboard() {
Clipboard clipboard = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
String url = gitUrlUI.getText();
gitUrlUI.setText("Copied to clipboard!");
content.putString(url);
clipboard.setContent(content);
Timeline timeline = new Timeline();
timeline.autoReverseProperty().set(false);
timeline.getKeyFrames().add(new KeyFrame(Duration.millis(3000),
new KeyValue(gitUrlUI.textProperty(), url)
));
timeline.play();
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// LISTENERS
//
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Update the application title bar based on the current filename and saved state.
*/
public void updateTitle() {
String title = "WheelEncoderGenerator - " + this.filename.get();
if (!saved.get()) title += "*";
App.stage.setTitle(title);
}
private ChangeListener<Boolean> toggleListener(String yes, String no, ToggleButton b) {
return (obs, ov, nv) -> { b.setText((nv)?yes:no); };
}
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// INITIALIZATION
//
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Initialize the PrimaryController
* @param url
* @param rb
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
ep = new EncoderProperties();
System.out.println("PrimaryController: initialize()");
// Handle exiting/quitting
SimpleBooleanProperty cancel = new SimpleBooleanProperty(false);
App.stage.setOnCloseRequest((event) -> {
if (!saved.get()) {
Optional<ButtonType> optional = this.showConfirmDialog("Save?",
"Save changes before continuing?");
optional.filter(response -> response == ButtonType.CANCEL)
.ifPresent( response -> cancel.set(true) ); // consume close event
optional.filter(response -> response == ButtonType.YES)
.ifPresent( response -> cancel.set(!saveFile()) );
}
if (!cancel.get()) Platform.exit();
});
typeUI.getItems().setAll(ep.getTypeOptions());
typeUI.valueProperty().bindBidirectional(ep.typeProperty());
// System.out.println("PrimaryController: type=" + ep.typeProperty());
resolutionUI.setValueFactory(
new ResolutionValueFactory(new IntegerStringConverter(),
ep.minResolutionProperty(), ep.maxResolutionProperty(),
ep.resolutionIncrementProperty(), ep.resolutionDecrementProperty()));
resolutionUI.getValueFactory().valueProperty().bindBidirectional(ep.resolutionProperty());
TextFormatter<Integer> tf = new TextFormatter(new BoundedIntegerTextFilter(ep.minResolutionProperty(),
ep.maxResolutionProperty()));
resolutionUI.getEditor().setTextFormatter(tf);
decimals.set(1); // units default to mm, so manually set decimal format
DoubleFormatter outerFmt = new DoubleFormatter();
outerFmt.decimalsProperty().bind(decimals);
outerUI.textProperty().bindBidirectional((Property) ep.outerDiameterProperty(),
outerFmt.getConverter());
outerUI.setTextFormatter(outerFmt);
addDimensionValidator(outerUI);
DoubleFormatter innerFmt = new DoubleFormatter();
innerFmt.decimalsProperty().bind(decimals);
innerUI.textProperty().bindBidirectional((Property) ep.innerDiameterProperty(),
innerFmt.getConverter());
innerUI.setTextFormatter(innerFmt);
addDimensionValidator(innerUI);
DoubleFormatter centerFmt = new DoubleFormatter();
centerFmt.decimalsProperty().bind(decimals);
centerUI.textProperty().bindBidirectional((Property) ep.centerDiameterProperty(),
centerFmt.getConverter());
centerUI.setTextFormatter(centerFmt);
addDimensionValidator(centerUI);
unitsUI.getItems().addAll(ep.getUnitOptions());
unitsUI.valueProperty().bindBidirectional(ep.unitsProperty());
unitsUI.valueProperty().addListener((obs, ov, nv) -> {
if (nv.equals(EncoderProperties.UNITS_MM)) {
decimals.set(1);
// Automatically convert current value
ep.outerDiameterProperty().set(UnitConverter.toMillimeter(ep.outerDiameterProperty().get()));
ep.innerDiameterProperty().set(UnitConverter.toMillimeter(ep.innerDiameterProperty().get()));
ep.centerDiameterProperty().set(UnitConverter.toMillimeter(ep.centerDiameterProperty().get()));
} else if (nv.equals(EncoderProperties.UNITS_INCH)) {
decimals.set(3);
// Automatically convert current value
ep.outerDiameterProperty().set(UnitConverter.toInch(ep.outerDiameterProperty().get()));
ep.innerDiameterProperty().set(UnitConverter.toInch(ep.innerDiameterProperty().get()));
ep.centerDiameterProperty().set(UnitConverter.toInch(ep.centerDiameterProperty().get()));
}
// Force conversion to new format
outerUI.textProperty().set(outerUI.textProperty().get());
innerUI.textProperty().set(innerUI.textProperty().get());
centerUI.textProperty().set(centerUI.textProperty().get());
});
invertedUI.selectedProperty().bindBidirectional(ep.invertedProperty());
invertedUI.selectedProperty().addListener(this.toggleListener("Yes", "No", invertedUI));
indexUI.selectedProperty().bindBidirectional(ep.indexedProperty());
indexUI.disableProperty().bind(ep.indexableProperty().not());
indexUI.selectedProperty().addListener(this.toggleListener("Yes", "No", indexUI));
// Clockwise/Counter-clockwise buttons part of ToggleGroup
ToggleGroup direction = new ToggleGroup();
cwUI.toggleGroupProperty().set(direction);
ccwUI.toggleGroupProperty().set(direction);
cwUI.selectedProperty().bindBidirectional(ep.directionProperty());
// Disable if the current encoder type is non-directional
cwUI.disableProperty().bind(ep.directionalProperty().not());
ccwUI.disableProperty().bind(ep.directionalProperty().not());
// Dialogs
alertDialog = new Alert(Alert.AlertType.ERROR);
confirmDialog = new Alert(Alert.AlertType.CONFIRMATION);
confirmDialog.getButtonTypes().setAll(ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);
// Update encoder preview and saved status on any settings change
encoderPreview = new EncoderView(encoderUI, ep);
ep.addListener((observable, oldvalue, newvalue) -> {
encoderPreview.render();
saved.set(false);
});
// Current filename
filename = new SimpleStringProperty();
// Update App title on filename change
filename.addListener((obs, ov, nv) -> {
this.updateTitle();
});
// Set saved true so calling newFile() to initialize doesn't prompt
saved = new SimpleBooleanProperty(true);
// Update App title on saved change
saved.addListener((obs, ov, nv) -> {
this.updateTitle();
});
// Only enable save button if unsaved changes
saveButton.disableProperty().bind(saved);
// Initialize a new encoder
newFile();
// Force rendering since this doesn't seem to happen via listener for some reason
encoderPreview.render();
checkForUpdates();
// Initialize Help display to minimize load time later
try {
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(getClass().getResource("help.fxml"));
helpStage = new Stage();
helpStage.setTitle("WEG - Online Help");
helpStage.setScene(new Scene(root));
} catch (IOException e) {
// this.showErrorDialog("Error", "Error loading help window");
System.out.println("Error loading help window: "+e.getMessage());
}
// Initialize About display to minimize load time later
aboutStage = new Stage();
try {
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(getClass().getResource("about.fxml"));
aboutStage.setScene(new Scene(root));
aboutStage.setTitle("About " + AppInfo.get().getAbbr());
} catch (IOException e) {
// this.showErrorDialog("Error", "Error loading about window\n");
System.out.println("IOException: " + e.getMessage());
}
}
}
| consolidated logic for prompting to save before continuing | src/main/java/com/botthoughts/wheelencodergenerator/PrimaryController.java | consolidated logic for prompting to save before continuing | <ide><path>rc/main/java/com/botthoughts/wheelencodergenerator/PrimaryController.java
<ide> return res;
<ide> }
<ide>
<add> /**
<add> * Checks if current file needs saving and if so, prompts user to save with Yes/No/Cancel,
<add> * returning a boolean representing whether the calling method should continue or abort.
<add> * @return true to continue, false to abort
<add> */
<add> private boolean saveAndContinue() {
<add> SimpleBooleanProperty okToContinue = new SimpleBooleanProperty(false);
<add>
<add> if (saved.get()) {
<add> okToContinue.set(true);
<add> } else {
<add> Optional<ButtonType> optional =
<add> this.showConfirmDialog("Save?", "Save changes before continuing?");
<add> optional.filter(response -> response == ButtonType.YES)
<add> .ifPresent(response -> okToContinue.set(saveFile()) );
<add> optional.filter(response -> response == ButtonType.CANCEL)
<add> .ifPresent(response -> okToContinue.set(false) );
<add> optional.filter(response -> response == ButtonType.NO)
<add> .ifPresent(response -> okToContinue.set(true));
<add> }
<add>
<add> return okToContinue.get();
<add> }
<add>
<ide> //////////////////////////////////////////////////////////////////////////////////////////////////
<ide> //
<ide> // EVENT HANDLERS
<ide> currentFile = f; // only do this if save succeeds!
<ide> filename.set(f.getName());
<ide> saved.set(true);
<del> } catch (IOException ex) { // TODO should really handle errors externally so we can e.g. cancel new/open/quit operation
<add> } catch (IOException ex) {
<ide> showErrorDialog("File Save Error", "Error saving " + f.getName() + "\n" + ex.getMessage());
<ide> return false;
<ide> }
<ide> fc.getExtensionFilters().add(extensionFilter);
<ide> SimpleBooleanProperty cancel = new SimpleBooleanProperty(false);
<ide>
<del> if (!saved.get()) {
<del> Optional<ButtonType> optional =
<del> this.showConfirmDialog("Save?", "Save changes before opening a new file?");
<del> optional.filter(response -> response == ButtonType.YES)
<del> .ifPresent(response -> { cancel.set(!saveFile()); });
<del> optional.filter(response -> response == ButtonType.CANCEL)
<del> .ifPresent(response -> { cancel.set(true); });
<del> }
<del> if (cancel.get()) return;
<add> if (!this.saveAndContinue()) return;
<ide>
<ide> File f = fc.showOpenDialog(App.stage);
<ide>
<ide> public void newFile() {
<ide> SimpleBooleanProperty cancel = new SimpleBooleanProperty(false);
<ide>
<del> if (!saved.get()) {
<del> Optional<ButtonType> optional =
<del> this.showConfirmDialog("Save?", "Save changes before creating a new encoder?");
<del> optional.filter(response -> response == ButtonType.YES)
<del> .ifPresent(response -> { cancel.set(!saveFile()); });
<del> optional.filter(response -> response == ButtonType.CANCEL)
<del> .ifPresent(response -> { cancel.set(true); });
<del> }
<del> if (cancel.get()) return;
<add> if (!saveAndContinue()) return;
<ide>
<ide> currentFile = null;
<ide> filename.set("untitled" + EXT);
<ide> // Handle exiting/quitting
<ide> SimpleBooleanProperty cancel = new SimpleBooleanProperty(false);
<ide> App.stage.setOnCloseRequest((event) -> {
<del> if (!saved.get()) {
<del> Optional<ButtonType> optional = this.showConfirmDialog("Save?",
<del> "Save changes before continuing?");
<del> optional.filter(response -> response == ButtonType.CANCEL)
<del> .ifPresent( response -> cancel.set(true) ); // consume close event
<del> optional.filter(response -> response == ButtonType.YES)
<del> .ifPresent( response -> cancel.set(!saveFile()) );
<add> if (!saveAndContinue()) {
<add> event.consume();
<add> } else {
<add> Platform.exit();
<ide> }
<del> if (!cancel.get()) Platform.exit();
<ide> });
<ide>
<ide> typeUI.getItems().setAll(ep.getTypeOptions()); |
|
JavaScript | apache-2.0 | 738ec450f30cb963526bd42bdb915a7bb2f312b1 | 0 | ninjadev/nin,ninjadev/nin,ninjadev/nin | const React = require('react');
const e = React.createElement;
class Connection extends React.Component {
constructor() {
super();
this.state = {
showDeleteButton: true
};
}
delete() {
this.props.editor.removeConnection(
this.props.fromPath,
this.props.toPath,);
}
render() {
const dX = this.props.connection.to.x - this.props.connection.from.x;
const dY = this.props.connection.to.y - this.props.connection.from.y;
const midX = this.props.connection.from.x + dX / 2;
const midY = this.props.connection.from.y + dY / 2;
const intensity = Math.abs(Math.cos(Math.atan(dX/dY)));
const d = `M${this.props.connection.from.x} ${this.props.connection.from.y} Q${this.props.connection.from.x + dX / 2 * intensity } ${this.props.connection.from.y} ${midX} ${midY} T${this.props.connection.to.x} ${this.props.connection.to.y}`;
return (
<g>
<path
d={d}
stroke={this.props.connection.active ? 'white' : '#7a8185'}
strokeWidth={this.props.connection.active ? 5 / this.props.scale : 1 / this.props.scale}
fill="transparent"
pointerEvents="none"
strokeDasharray={this.props.connection.active ? undefined : '20, 10'}
/>
</g>
);
}
}
module.exports = Connection;
| nin/frontend/app/scripts/components/editor/Connection.js | const React = require('react');
const e = React.createElement;
class Connection extends React.Component {
constructor() {
super();
this.state = {
showDeleteButton: true
};
}
delete() {
this.props.editor.removeConnection(
this.props.fromPath,
this.props.toPath,);
}
render() {
const dX = this.props.connection.to.x - this.props.connection.from.x;
const dY = this.props.connection.to.y - this.props.connection.from.y;
const midX = this.props.connection.from.x + dX / 2;
const midY = this.props.connection.from.y + dY / 2;
const intensity = Math.abs(Math.cos(Math.atan(dX/dY)));
const attributes = {
d: `M${this.props.connection.from.x} ${this.props.connection.from.y} Q${this.props.connection.from.x + dX / 2 * intensity } ${this.props.connection.from.y} ${midX} ${midY} T${this.props.connection.to.x} ${this.props.connection.to.y}`,
stroke: this.props.connection.active ? 'white' : '#7a8185',
strokeWidth: this.props.connection.active ? 5 / this.props.scale : 1 / this.props.scale,
fill: 'transparent',
style: {
pointerEvents: 'none',
}
};
if(!this.props.connection.active) {
attributes.strokeDasharray = '20, 10';
}
return e('g', {}, e('path', attributes));
}
}
module.exports = Connection;
| Update editor Connection to use JSX
| nin/frontend/app/scripts/components/editor/Connection.js | Update editor Connection to use JSX | <ide><path>in/frontend/app/scripts/components/editor/Connection.js
<ide> const midX = this.props.connection.from.x + dX / 2;
<ide> const midY = this.props.connection.from.y + dY / 2;
<ide> const intensity = Math.abs(Math.cos(Math.atan(dX/dY)));
<del> const attributes = {
<del> d: `M${this.props.connection.from.x} ${this.props.connection.from.y} Q${this.props.connection.from.x + dX / 2 * intensity } ${this.props.connection.from.y} ${midX} ${midY} T${this.props.connection.to.x} ${this.props.connection.to.y}`,
<del> stroke: this.props.connection.active ? 'white' : '#7a8185',
<del> strokeWidth: this.props.connection.active ? 5 / this.props.scale : 1 / this.props.scale,
<del> fill: 'transparent',
<del> style: {
<del> pointerEvents: 'none',
<del> }
<del> };
<del> if(!this.props.connection.active) {
<del> attributes.strokeDasharray = '20, 10';
<del> }
<del> return e('g', {}, e('path', attributes));
<add> const d = `M${this.props.connection.from.x} ${this.props.connection.from.y} Q${this.props.connection.from.x + dX / 2 * intensity } ${this.props.connection.from.y} ${midX} ${midY} T${this.props.connection.to.x} ${this.props.connection.to.y}`;
<add> return (
<add> <g>
<add> <path
<add> d={d}
<add> stroke={this.props.connection.active ? 'white' : '#7a8185'}
<add> strokeWidth={this.props.connection.active ? 5 / this.props.scale : 1 / this.props.scale}
<add> fill="transparent"
<add> pointerEvents="none"
<add> strokeDasharray={this.props.connection.active ? undefined : '20, 10'}
<add> />
<add> </g>
<add> );
<ide> }
<ide> }
<ide> |
|
Java | mit | error: pathspec 'CodeArchive/src/com/relaxedcomplexity/classcomposition/src/com/relaxedcomplexity/classcomposition/inheritance/Brand.java' did not match any file(s) known to git
| 2390dd974e21d4b8b4cdc0ba0945edd254cdb3ab | 1 | jdmedlock/CodeArchive,jdmedlock/CodeArchive | /**
*
*/
package com.relaxedcomplexity.classcomposition.inheritance;
/**
* @author Jim Medlock
*
*/
public enum Brand {
ACER("Acer"),
APPLE("Apple"),
DELL("Dell"),
HP("Hewett Packard"),
LENOVO("Lenovo"),
SONY("Sony");
private String brandName = null;
/*
* Constructor: Create a brand and associated brand name
*
* @param brandName Brand name
*/
private Brand(String brandName) {
this.brandName = brandName;
}
public String getBrandName() {
return brandName;
}
}
| CodeArchive/src/com/relaxedcomplexity/classcomposition/src/com/relaxedcomplexity/classcomposition/inheritance/Brand.java | Added Brand class | CodeArchive/src/com/relaxedcomplexity/classcomposition/src/com/relaxedcomplexity/classcomposition/inheritance/Brand.java | Added Brand class | <ide><path>odeArchive/src/com/relaxedcomplexity/classcomposition/src/com/relaxedcomplexity/classcomposition/inheritance/Brand.java
<add>/**
<add> *
<add> */
<add>package com.relaxedcomplexity.classcomposition.inheritance;
<add>
<add>/**
<add> * @author Jim Medlock
<add> *
<add> */
<add>public enum Brand {
<add> ACER("Acer"),
<add> APPLE("Apple"),
<add> DELL("Dell"),
<add> HP("Hewett Packard"),
<add> LENOVO("Lenovo"),
<add> SONY("Sony");
<add>
<add> private String brandName = null;
<add>
<add> /*
<add> * Constructor: Create a brand and associated brand name
<add> *
<add> * @param brandName Brand name
<add> */
<add> private Brand(String brandName) {
<add> this.brandName = brandName;
<add> }
<add>
<add> public String getBrandName() {
<add> return brandName;
<add> }
<add>} |
|
Java | agpl-3.0 | 8b6e25bf1974adea3e65b7fafce0c9cb5d21ccee | 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 | 559737c8-2e62-11e5-9284-b827eb9e62be | hello.java | 5591a434-2e62-11e5-9284-b827eb9e62be | 559737c8-2e62-11e5-9284-b827eb9e62be | hello.java | 559737c8-2e62-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>5591a434-2e62-11e5-9284-b827eb9e62be
<add>559737c8-2e62-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | dde273bcc699f45da84209a2152c9f062abe096a | 0 | philipz/pinpoint,sbcoba/pinpoint,PerfGeeks/pinpoint,gspandy/pinpoint,hcapitaine/pinpoint,minwoo-jung/pinpoint,KRDeNaT/pinpoint,KRDeNaT/pinpoint,coupang/pinpoint,PerfGeeks/pinpoint,dawidmalina/pinpoint,nstopkimsk/pinpoint,cit-lab/pinpoint,PerfGeeks/pinpoint,barneykim/pinpoint,emeroad/pinpoint,cijung/pinpoint,andyspan/pinpoint,Allive1/pinpoint,emeroad/pinpoint,carpedm20/pinpoint,denzelsN/pinpoint,wziyong/pinpoint,denzelsN/pinpoint,chenguoxi1985/pinpoint,denzelsN/pinpoint,InfomediaLtd/pinpoint,coupang/pinpoint,nstopkimsk/pinpoint,masonmei/pinpoint,majinkai/pinpoint,InfomediaLtd/pinpoint,emeroad/pinpoint,wziyong/pinpoint,dawidmalina/pinpoint,barneykim/pinpoint,carpedm20/pinpoint,InfomediaLtd/pinpoint,coupang/pinpoint,eBaoTech/pinpoint,cit-lab/pinpoint,krishnakanthpps/pinpoint,breadval/pinpoint,Allive1/pinpoint,jiaqifeng/pinpoint,koo-taejin/pinpoint,chenguoxi1985/pinpoint,KRDeNaT/pinpoint,coupang/pinpoint,naver/pinpoint,gspandy/pinpoint,Xylus/pinpoint,denzelsN/pinpoint,masonmei/pinpoint,KimTaehee/pinpoint,hcapitaine/pinpoint,cijung/pinpoint,masonmei/pinpoint,chenguoxi1985/pinpoint,Xylus/pinpoint,breadval/pinpoint,krishnakanthpps/pinpoint,tsyma/pinpoint,Skkeem/pinpoint,KimTaehee/pinpoint,masonmei/pinpoint,jiaqifeng/pinpoint,jaehong-kim/pinpoint,suraj-raturi/pinpoint,suraj-raturi/pinpoint,philipz/pinpoint,breadval/pinpoint,gspandy/pinpoint,lioolli/pinpoint,majinkai/pinpoint,cit-lab/pinpoint,hcapitaine/pinpoint,breadval/pinpoint,koo-taejin/pinpoint,koo-taejin/pinpoint,sbcoba/pinpoint,masonmei/pinpoint,denzelsN/pinpoint,citywander/pinpoint,eBaoTech/pinpoint,majinkai/pinpoint,KimTaehee/pinpoint,sjmittal/pinpoint,InfomediaLtd/pinpoint,wziyong/pinpoint,suraj-raturi/pinpoint,gspandy/pinpoint,sbcoba/pinpoint,andyspan/pinpoint,hcapitaine/pinpoint,barneykim/pinpoint,tsyma/pinpoint,citywander/pinpoint,hcapitaine/pinpoint,PerfGeeks/pinpoint,citywander/pinpoint,cit-lab/pinpoint,coupang/pinpoint,denzelsN/pinpoint,sjmittal/pinpoint,lioolli/pinpoint,cijung/pinpoint,denzelsN/pinpoint,Skkeem/pinpoint,87439247/pinpoint,dawidmalina/pinpoint,masonmei/pinpoint,jaehong-kim/pinpoint,jiaqifeng/pinpoint,jaehong-kim/pinpoint,minwoo-jung/pinpoint,shuvigoss/pinpoint,Allive1/pinpoint,majinkai/pinpoint,naver/pinpoint,citywander/pinpoint,Xylus/pinpoint,sjmittal/pinpoint,shuvigoss/pinpoint,KimTaehee/pinpoint,andyspan/pinpoint,shuvigoss/pinpoint,dawidmalina/pinpoint,jiaqifeng/pinpoint,barneykim/pinpoint,jaehong-kim/pinpoint,minwoo-jung/pinpoint,emeroad/pinpoint,carpedm20/pinpoint,citywander/pinpoint,Xylus/pinpoint,breadval/pinpoint,carpedm20/pinpoint,cit-lab/pinpoint,krishnakanthpps/pinpoint,minwoo-jung/pinpoint,coupang/pinpoint,Skkeem/pinpoint,jaehong-kim/pinpoint,lioolli/pinpoint,koo-taejin/pinpoint,tsyma/pinpoint,87439247/pinpoint,suraj-raturi/pinpoint,sbcoba/pinpoint,naver/pinpoint,andyspan/pinpoint,sjmittal/pinpoint,InfomediaLtd/pinpoint,InfomediaLtd/pinpoint,majinkai/pinpoint,KRDeNaT/pinpoint,lioolli/pinpoint,Xylus/pinpoint,minwoo-jung/pinpoint,PerfGeeks/pinpoint,tsyma/pinpoint,nstopkimsk/pinpoint,nstopkimsk/pinpoint,lioolli/pinpoint,carpedm20/pinpoint,chenguoxi1985/pinpoint,krishnakanthpps/pinpoint,jiaqifeng/pinpoint,philipz/pinpoint,tsyma/pinpoint,87439247/pinpoint,cijung/pinpoint,Skkeem/pinpoint,andyspan/pinpoint,87439247/pinpoint,eBaoTech/pinpoint,citywander/pinpoint,wziyong/pinpoint,KimTaehee/pinpoint,KRDeNaT/pinpoint,nstopkimsk/pinpoint,naver/pinpoint,suraj-raturi/pinpoint,emeroad/pinpoint,Xylus/pinpoint,Skkeem/pinpoint,barneykim/pinpoint,sjmittal/pinpoint,koo-taejin/pinpoint,eBaoTech/pinpoint,majinkai/pinpoint,eBaoTech/pinpoint,emeroad/pinpoint,87439247/pinpoint,sbcoba/pinpoint,Xylus/pinpoint,andyspan/pinpoint,KRDeNaT/pinpoint,dawidmalina/pinpoint,philipz/pinpoint,naver/pinpoint,lioolli/pinpoint,tsyma/pinpoint,koo-taejin/pinpoint,jaehong-kim/pinpoint,shuvigoss/pinpoint,minwoo-jung/pinpoint,philipz/pinpoint,dawidmalina/pinpoint,Allive1/pinpoint,Skkeem/pinpoint,krishnakanthpps/pinpoint,eBaoTech/pinpoint,cit-lab/pinpoint,wziyong/pinpoint,Allive1/pinpoint,suraj-raturi/pinpoint,shuvigoss/pinpoint,chenguoxi1985/pinpoint,chenguoxi1985/pinpoint,philipz/pinpoint,gspandy/pinpoint,shuvigoss/pinpoint,nstopkimsk/pinpoint,wziyong/pinpoint,sbcoba/pinpoint,breadval/pinpoint,87439247/pinpoint,Allive1/pinpoint,hcapitaine/pinpoint,cijung/pinpoint,barneykim/pinpoint,gspandy/pinpoint,KimTaehee/pinpoint,barneykim/pinpoint,cijung/pinpoint,krishnakanthpps/pinpoint,jiaqifeng/pinpoint,sjmittal/pinpoint,PerfGeeks/pinpoint | package com.nhn.pinpoint.thrift.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
/**
* @author emeroad
*/
public class UnsafeByteArrayOutputStream extends ByteArrayOutputStream {
private static final String UTF8 = "UTF8";
/**
* Creates a new byte array output stream. The buffer capacity is
* initially 32 bytes, though its size increases if necessary.
*/
public UnsafeByteArrayOutputStream() {
this(32);
}
/**
* Creates a new byte array output stream, with a buffer capacity of
* the specified size, in bytes.
*
* @param size the initial size.
* @throws IllegalArgumentException if size is negative.
*/
public UnsafeByteArrayOutputStream(int size) {
super(size);
}
/**
* Writes the specified byte to this byte array output stream.
*
* @param b the byte to be written.
*/
public void write(int b) {
int newcount = count + 1;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = (byte) b;
count = newcount;
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this byte array output stream.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
*/
public void write(byte b[], int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
int newcount = count + len;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
System.arraycopy(b, off, buf, count, len);
count = newcount;
}
/**
* Writes the complete contents of this byte array output stream to
* the specified output stream argument, as if by calling the output
* stream's write method using <code>out.write(buf, 0, count)</code>.
*
* @param out the output stream to which to write the data.
* @throws java.io.IOException if an I/O error occurs.
*/
public void writeTo(OutputStream out) throws IOException {
out.write(buf, 0, count);
}
/**
* Resets the <code>count</code> field of this byte array output
* stream to zero, so that all currently accumulated output in the
* output stream is discarded. The output stream can be used again,
* reusing the already allocated buffer space.
*
* @see java.io.ByteArrayInputStream#count
*/
public void reset() {
count = 0;
}
/**
* Creates a newly allocated byte array. Its size is the current
* size of this output stream and the valid contents of the buffer
* have been copied into it.
*
* @return the current contents of this output stream, as a byte array.
* @see java.io.ByteArrayOutputStream#size()
*/
public byte toByteArray()[] {
return buf;
}
/**
* Returns the current size of the buffer.
*
* @return the value of the <code>count</code> field, which is the number
* of valid bytes in this output stream.
* @see java.io.ByteArrayOutputStream#count
*/
public int size() {
return count;
}
/**
* Converts the buffer's contents into a string decoding bytes using the
* platform's default character set. The length of the new <tt>String</tt>
* is a function of the character set, and hence may not be equal to the
* size of the buffer.
* <p/>
* <p> This method always replaces malformed-input and unmappable-character
* sequences with the default replacement string for the platform's
* default character set. The {@linkplain java.nio.charset.CharsetDecoder}
* class should be used when more control over the decoding process is
* required.
*
* @return String decoded from the buffer's contents.
* @since JDK1.1
*/
public String toString() {
try {
return toString(UTF8);
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException("toString() fail. Caused:" + ex.getMessage(), ex);
}
}
/**
* Converts the buffer's contents into a string by decoding the bytes using
* the specified {@link java.nio.charset.Charset charsetName}. The length of
* the new <tt>String</tt> is a function of the charset, and hence may not be
* equal to the length of the byte array.
* <p/>
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* @param charsetName the name of a supported
* {@linkplain java.nio.charset.Charset </code>charset<code>}
* @return String decoded from the buffer's contents.
* @throws java.io.UnsupportedEncodingException
* If the named charset is not supported
* @since JDK1.1
*/
public String toString(String charsetName)
throws UnsupportedEncodingException {
return new String(buf, 0, count, charsetName);
}
/**
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
* <p/>
*/
public void close() throws IOException {
}
}
| thrift/src/main/java/com/navercorp/pinpoint/thrift/io/UnsafeByteArrayOutputStream.java | package com.nhn.pinpoint.thrift.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
/**
* @author emeroad
*/
public class UnsafeByteArrayOutputStream extends ByteArrayOutputStream {
/**
* Creates a new byte array output stream. The buffer capacity is
* initially 32 bytes, though its size increases if necessary.
*/
public UnsafeByteArrayOutputStream() {
this(32);
}
/**
* Creates a new byte array output stream, with a buffer capacity of
* the specified size, in bytes.
*
* @param size the initial size.
* @throws IllegalArgumentException if size is negative.
*/
public UnsafeByteArrayOutputStream(int size) {
super(size);
}
/**
* Writes the specified byte to this byte array output stream.
*
* @param b the byte to be written.
*/
public void write(int b) {
int newcount = count + 1;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
buf[count] = (byte) b;
count = newcount;
}
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this byte array output stream.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
*/
public void write(byte b[], int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
int newcount = count + len;
if (newcount > buf.length) {
buf = Arrays.copyOf(buf, Math.max(buf.length << 1, newcount));
}
System.arraycopy(b, off, buf, count, len);
count = newcount;
}
/**
* Writes the complete contents of this byte array output stream to
* the specified output stream argument, as if by calling the output
* stream's write method using <code>out.write(buf, 0, count)</code>.
*
* @param out the output stream to which to write the data.
* @throws java.io.IOException if an I/O error occurs.
*/
public void writeTo(OutputStream out) throws IOException {
out.write(buf, 0, count);
}
/**
* Resets the <code>count</code> field of this byte array output
* stream to zero, so that all currently accumulated output in the
* output stream is discarded. The output stream can be used again,
* reusing the already allocated buffer space.
*
* @see java.io.ByteArrayInputStream#count
*/
public void reset() {
count = 0;
}
/**
* Creates a newly allocated byte array. Its size is the current
* size of this output stream and the valid contents of the buffer
* have been copied into it.
*
* @return the current contents of this output stream, as a byte array.
* @see java.io.ByteArrayOutputStream#size()
*/
public byte toByteArray()[] {
return buf;
}
/**
* Returns the current size of the buffer.
*
* @return the value of the <code>count</code> field, which is the number
* of valid bytes in this output stream.
* @see java.io.ByteArrayOutputStream#count
*/
public int size() {
return count;
}
/**
* Converts the buffer's contents into a string decoding bytes using the
* platform's default character set. The length of the new <tt>String</tt>
* is a function of the character set, and hence may not be equal to the
* size of the buffer.
* <p/>
* <p> This method always replaces malformed-input and unmappable-character
* sequences with the default replacement string for the platform's
* default character set. The {@linkplain java.nio.charset.CharsetDecoder}
* class should be used when more control over the decoding process is
* required.
*
* @return String decoded from the buffer's contents.
* @since JDK1.1
*/
public String toString() {
return new String(buf, 0, count);
}
/**
* Converts the buffer's contents into a string by decoding the bytes using
* the specified {@link java.nio.charset.Charset charsetName}. The length of
* the new <tt>String</tt> is a function of the charset, and hence may not be
* equal to the length of the byte array.
* <p/>
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* @param charsetName the name of a supported
* {@linkplain java.nio.charset.Charset </code>charset<code>}
* @return String decoded from the buffer's contents.
* @throws java.io.UnsupportedEncodingException
* If the named charset is not supported
* @since JDK1.1
*/
public String toString(String charsetName)
throws UnsupportedEncodingException {
return new String(buf, 0, count, charsetName);
}
/**
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
* <p/>
*/
public void close() throws IOException {
}
}
| [#26] fix findbug issue
| thrift/src/main/java/com/navercorp/pinpoint/thrift/io/UnsafeByteArrayOutputStream.java | [#26] fix findbug issue | <ide><path>hrift/src/main/java/com/navercorp/pinpoint/thrift/io/UnsafeByteArrayOutputStream.java
<ide> */
<ide> public class UnsafeByteArrayOutputStream extends ByteArrayOutputStream {
<ide>
<add> private static final String UTF8 = "UTF8";
<ide>
<ide> /**
<ide> * Creates a new byte array output stream. The buffer capacity is
<ide> * @since JDK1.1
<ide> */
<ide> public String toString() {
<del> return new String(buf, 0, count);
<add> try {
<add> return toString(UTF8);
<add> } catch (UnsupportedEncodingException ex) {
<add> throw new RuntimeException("toString() fail. Caused:" + ex.getMessage(), ex);
<add> }
<ide> }
<ide>
<ide> /** |
|
JavaScript | mit | 85fb02aa55d918e5dc8b59f8273936671b7a52a0 | 0 | Baptouuuu/Sy,Baptouuuu/Sy | module.exports = function (grunt) {
var generator = [
'src/Lib/Generator/Interface.js',
'src/Lib/Generator/UUID.js'
],
logger = [
'src/Lib/Logger/Interface.js',
'src/Lib/Logger/Handler/Interface.js',
'src/Lib/Logger/Handler/Console.js',
'src/Lib/Logger/CoreLogger.js'
],
mediator = [
'src/Lib/Mediator.js'
],
http = [
'src/Lib/Logger/Interface.js',
'src/HTTP/RequestInterface.js',
'src/HTTP/ResponseInterface.js',
'src/HTTP/Request.js',
'src/HTTP/Response.js',
'src/HTTP/JSONRequest.js',
'src/HTTP/JSONResponse.js',
'src/HTTP/HeaderParser.js',
'src/HTTP/HTMLRequest.js',
'src/HTTP/HTMLResponse.js',
'src/HTTP/ImageRequest.js',
'src/HTTP/ImageResponse.js',
'src/HTTP/Manager.js',
'src/HTTP/REST.js'
],
storage = [
'src/EntityInterface.js',
'src/Entity.js',
'src/Storage/Core.js',
'src/Storage/IdentityMap.js',
'src/Storage/LifeCycleEvent.js',
'src/Storage/Manager.js',
'src/Storage/ManagerFactory.js',
'src/Storage/Repository.js',
'src/Storage/RepositoryFactory.js',
'src/Storage/RepositoryFactoryConfigurator.js',
'src/Storage/UnitOfWork.js',
'src/Storage/UnitOfWorkFactory.js',
'src/Storage/Dbal/DriverFactoryInterface.js',
'src/Storage/Dbal/DriverInterface.js',
'src/Storage/Dbal/Factory.js',
'src/Storage/Dbal/IndexedDB.js',
'src/Storage/Dbal/IndexedDBFactory.js',
'src/Storage/Dbal/Localstorage.js',
'src/Storage/Dbal/LocalstorageFactory.js',
'src/Storage/Dbal/Rest.js',
'src/Storage/Dbal/RestFactory.js',
],
validator = [
'src/Validator/ConstraintInterface.js',
'src/Validator/ConstraintValidatorInterface.js',
'src/Validator/Core.js',
'src/Validator/AbstractConstraint.js',
'src/Validator/AbstractConstraintValidator.js',
'src/Validator/Constraint/Blank.js',
'src/Validator/Constraint/BlankValidator.js',
'src/Validator/Constraint/Callback.js',
'src/Validator/Constraint/CallbackValidator.js',
'src/Validator/Constraint/Choice.js',
'src/Validator/Constraint/ChoiceValidator.js',
'src/Validator/Constraint/Country.js',
'src/Validator/Constraint/CountryValidator.js',
'src/Validator/Constraint/Date.js',
'src/Validator/Constraint/DateValidator.js',
'src/Validator/Constraint/Email.js',
'src/Validator/Constraint/EmailValidator.js',
'src/Validator/Constraint/EqualTo.js',
'src/Validator/Constraint/EqualToValidator.js',
'src/Validator/Constraint/False.js',
'src/Validator/Constraint/FalseValidator.js',
'src/Validator/Constraint/GreaterThan.js',
'src/Validator/Constraint/GreaterThanValidator.js',
'src/Validator/Constraint/GreaterThanOrEqual.js',
'src/Validator/Constraint/GreaterThanOrEqualValidator.js',
'src/Validator/Constraint/Ip.js',
'src/Validator/Constraint/IpValidator.js',
'src/Validator/Constraint/Length.js',
'src/Validator/Constraint/LengthValidator.js',
'src/Validator/Constraint/LessThan.js',
'src/Validator/Constraint/LessThanValidator.js',
'src/Validator/Constraint/LessThanOrEqual.js',
'src/Validator/Constraint/LessThanOrEqualValidator.js',
'src/Validator/Constraint/NotBlank.js',
'src/Validator/Constraint/NotBlankValidator.js',
'src/Validator/Constraint/NotEqualTo.js',
'src/Validator/Constraint/NotEqualToValidator.js',
'src/Validator/Constraint/NotNull.js',
'src/Validator/Constraint/NotNullValidator.js',
'src/Validator/Constraint/NotUndefined.js',
'src/Validator/Constraint/NotUndefinedValidator.js',
'src/Validator/Constraint/Null.js',
'src/Validator/Constraint/NullValidator.js',
'src/Validator/Constraint/Range.js',
'src/Validator/Constraint/RangeValidator.js',
'src/Validator/Constraint/Regex.js',
'src/Validator/Constraint/RegexValidator.js',
'src/Validator/Constraint/True.js',
'src/Validator/Constraint/TrueValidator.js',
'src/Validator/Constraint/Type.js',
'src/Validator/Constraint/TypeValidator.js',
'src/Validator/Constraint/Undefined.js',
'src/Validator/Constraint/UndefinedValidator.js',
'src/Validator/Constraint/Url.js',
'src/Validator/Constraint/UrlValidator.js',
'src/Validator/ConstraintFactory.js',
'src/Validator/ConstraintValidatorFactory.js',
'src/Validator/ConstraintViolation.js',
'src/Validator/ConstraintViolationList.js',
'src/Validator/ExecutionContext.js',
'src/Validator/ExecutionContextFactory.js'
],
form = [
'src/Form/FormInterface.js',
'src/Form/FormBuilderInterface.js',
'src/Form/FormTypeInterface.js',
'src/Form/Form.js',
'src/Form/FormBuilder.js',
'src/Form/Builder.js',
],
view = [
'src/View/LayoutFactoryInterface.js',
'src/View/ListFactoryInterface.js',
'src/View/TemplateEngineInterface.js',
'src/View/ViewScreenFactoryInterface.js',
'src/View/Event/ViewPortEvent.js',
'src/View/NodeWrapper.js',
'src/View/Layout.js',
'src/View/LayoutFactory.js',
'src/View/List.js',
'src/View/ListFactory.js',
'src/View/Manager.js',
'src/View/ManagerConfigurator.js',
'src/View/Parser.js',
'src/View/TemplateEngine.js',
'src/View/ViewPort.js',
'src/View/ViewScreen.js',
'src/View/ViewScreenFactory.js',
],
configurator = [
'src/ConfiguratorInterface.js',
'src/Configurator.js'
],
registry = [
'src/RegistryInterface.js',
'src/Registry.js',
'src/RegistryFactory.js'
],
stateRegistry = [
'src/StateRegistryInterface.js',
'src/StateRegistry.js',
'src/StateRegistryFactory.js',
],
serviceContainer = [
'src/ServiceContainer/Core.js',
'src/ServiceContainer/Alias.js',
'src/ServiceContainer/Compiler.js',
'src/ServiceContainer/CompilerPassInterface.js',
'src/ServiceContainer/Definition.js',
'src/ServiceContainer/Parameter.js',
'src/ServiceContainer/Reference.js',
'src/ServiceContainer/CompilerPass/ApplyParentDefinition.js',
'src/ServiceContainer/CompilerPass/RemoveAbstractDefinitions.js',
'src/ServiceContainer/CompilerPass/ResolveParameterPlaceholder.js',
'src/ServiceContainer/CompilerPass/ResolveReferencePlaceholder.js',
],
translator = [
'src/Translator.js',
],
factory = [
'src/FactoryInterface.js',
],
dom = [
'src/DOM.js'
],
propertyAccessor = [ //need the reflection.js vendor
'src/PropertyAccessor.js'
],
appState = [
'src/AppState/Route.js',
'src/AppState/Router.js',
'src/AppState/RouteProvider.js',
'src/AppState/Core.js',
'src/AppState/UrlMatcher.js',
'src/AppState/State.js',
'src/AppState/StateHandler.js',
'src/AppState/AppStateEvent.js',
'src/AppState/RouteNotFoundEvent.js',
'src/AppState/UrlMatcher.js',
],
framework = [
'src/functions.js',
'src/ControllerInterface.js',
'src/Kernel/ActionDispatcher.js',
'src/Kernel/AppParser.js',
'src/Kernel/ControllerManager.js',
'src/Kernel/Core.js',
'src/Kernel/FeatureTester.js',
'src/Event/AppShutdownEvent.js',
'src/Event/ControllerEvent.js',
'src/Controller.js',
'src/EventSubscriberInterface.js',
'src/FrameworkBundle/Config/Configuration.js',
'src/FrameworkBundle/Config/Service.js',
'src/FormBundle/Config/Service.js',
'src/HttpBundle/Config/Service.js',
'src/StorageBundle/Config/Service.js',
'src/TranslatorBundle/Config/Service.js',
'src/ValidatorBundle/Config/Service.js',
'src/ViewBundle/Config/Service.js',
'src/ViewBundle/Subscriber/AppStateSubscriber.js',
'src/AppStateBundle/Config/Service.js',
],
frameworkPasses = [
'src/FrameworkBundle/CompilerPass/EventSubscriberPass.js',
'src/FormBundle/CompilerPass/FormTypePass.js',
'src/StorageBundle/CompilerPass/RegisterDriverFactoryPass.js',
'src/ViewBundle/CompilerPass/RegisterLayoutWrapperPass.js',
'src/ViewBundle/CompilerPass/RegisterListWrapperPass.js',
'src/ViewBundle/CompilerPass/RegisterViewScreenWrapperPass.js',
'src/ViewBundle/CompilerPass/RegisterSubscriberPass.js',
'src/AppStateBundle/CompilerPass/RegisterRoutesPass.js',
],
unique = function (el, idx, array) {
if (array.indexOf(el) !== idx && array.indexOf(el) < idx) {
return false;
}
return true;
};
generator.unshift('src/functions.js');
logger.unshift('src/functions.js');
configurator.unshift('src/functions.js');
serviceContainer = serviceContainer.concat(propertyAccessor);
registry = factory.concat(registry);
mediator = mediator
.concat(generator)
.concat(logger);
stateRegistry = factory
.concat(registry)
.concat(stateRegistry);
http = http
.concat(generator)
.concat(registry);
storage = factory //need the observe-js vendor
.concat(logger)
.concat(http)
.concat(mediator)
.concat(registry)
.concat(stateRegistry)
.concat(generator)
.concat(storage)
.concat(propertyAccessor);
validator = factory
.concat(registry)
.concat(validator);
form = form
.concat(configurator)
.concat(validator);
view = factory
.concat(registry)
.concat(generator)
.concat(mediator)
.concat(dom)
.concat(view);
translator = translator
.concat(registry)
.concat(stateRegistry);
serviceContainer.unshift('src/functions.js');
mediator.unshift('src/functions.js');
registry.unshift('src/functions.js');
stateRegistry.unshift('src/functions.js');
http.unshift('src/functions.js');
storage.unshift('src/functions.js');
validator.unshift('src/functions.js');
view.unshift('src/functions.js');
translator.unshift('src/functions.js');
appState.unshift('src/functions.js');
framework = framework
.concat(generator)
.concat(logger)
.concat(factory)
.concat(mediator)
.concat(http)
.concat(propertyAccessor)
.concat(storage)
.concat(validator)
.concat(form)
.concat(view)
.concat(configurator)
.concat(registry)
.concat(stateRegistry)
.concat(serviceContainer)
.concat(frameworkPasses)
.concat(translator)
.concat(dom)
.concat(appState);
serviceContainer = serviceContainer.filter(unique);
registry = registry.filter(unique);
stateRegistry = stateRegistry.filter(unique);
http = http.filter(unique);
storage = storage.filter(unique);
validator = validator.filter(unique);
view = view.filter(unique);
translator = translator.filter(unique);
framework = framework.filter(unique);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %>#<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
files: {
'dist/framework.min.js': framework,
'dist/generator.min.js': generator,
'dist/logger.min.js': logger,
'dist/mediator.min.js': mediator,
'dist/http.min.js': http,
'dist/storage.min.js': storage,
'dist/validator.min.js': validator,
'dist/view.min.js': view,
'dist/configurator.min.js': configurator,
'dist/registry.min.js': registry,
'dist/state-registry.min.js': stateRegistry,
'dist/service-container.min.js': serviceContainer,
'dist/translator.min.js': translator,
'dist/property-accessor.min.js': propertyAccessor,
'dist/appstate.min.js': appState
}
}
},
concat: {
options: {
banner: '/*! <%= pkg.name %>#<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
framework: {
src: framework,
dest: 'dist/framework.js'
},
generator: {
src: generator,
dest: 'dist/generator.js'
},
logger: {
src: logger,
dest: 'dist/logger.js'
},
mediator: {
src: mediator,
dest: 'dist/mediator.js'
},
http: {
src: http,
dest: 'dist/http.js'
},
storage: {
src: storage,
dest: 'dist/storage.js'
},
validator: {
src: validator,
dest: 'dist/validator.js'
},
view: {
src: view,
dest: 'dist/view.js'
},
configurator: {
src: configurator,
dest: 'dist/configurator.js'
},
registry: {
src: registry,
dest: 'dist/registry.js'
},
stateRegistry: {
src: stateRegistry,
dest: 'dist/state-registry.js'
},
serviceContainer: {
src: serviceContainer,
dest: 'dist/service-container.js'
},
translator: {
src: translator,
dest: 'dist/translator.js'
},
propertyAccessor: {
src: propertyAccessor,
dest: 'dist/property-accessor.js'
},
appState: {
src: appState,
dest: 'dist/appstate.js'
}
},
'bower-install': {
target: {
html: 'index.html',
jsPattern: '<script src="{{filePath}}"></script>'
}
},
exec: {
test: {
cmd: function (pkg) {
var path;
switch (pkg) {
case 'lib':
path = 'lib/';
break;
case 'storage':
path = 'storage/';
break;
case 'view':
path = 'view/';
break;
case 'kernel':
path = 'kernel';
break;
case 'event':
path = 'event';
break;
case 'validator':
path = 'validator/';
break;
case 'form':
path = 'form/';
break;
case 'topLevel':
path = [
'entity.js',
'functions.js',
'stateregistry.js',
'stateregistryfactory.js',
'registry.js',
'registryfactory.js',
'servicecontainer.js',
'translator.js',
].join(',tests/');
break;
}
return './node_modules/venus/bin/venus run -t tests/' + path + ' -c -n';
}
}
},
watch: {
js: {
files: ['src/*.js'],
tasks: [],
options: {
livereload: true
}
}
},
jscs: {
src: 'src/**/*.js',
options: {
requireCurlyBraces: [
'if',
'else',
'for',
'do',
'while',
'try',
'catch',
],
requireSpaceAfterKeywords: [
'if',
'else',
'for',
'do',
'while',
'switch',
'try',
'catch'
],
requireParenthesesAroundIIFE: true,
requireSpacesInFunctionExpression: {
beforeOpeningRoundBrace: true,
beforeOpeningCurlyBrace: true
},
disallowSpacesInsideObjectBrackets: true,
disallowSpacesInsideArrayBrackets: true,
disallowSpacesInsideParentheses: true,
disallowQuotedKeysInObjects: true,
disallowSpaceAfterObjectKeys: true,
requireCommaBeforeLineBreak: true,
requireOperatorBeforeLineBreak: [
'?',
'+',
'-',
'/',
'*',
'=',
'==',
'===',
'!=',
'!==',
'>',
'>=',
'<',
'<='
],
disallowLeftStickedOperators: [
'?',
'+',
'-',
'/',
'*',
'=',
'==',
'===',
'!=',
'!==',
'>',
'>=',
'<',
'<='
],
requireRightStickedOperators: ['!'],
disallowRightStickedOperators: [
'?',
'+',
'/',
'*',
':',
'=',
'==',
'===',
'!=',
'!==',
'>',
'>=',
'<',
'<='
],
requireLeftStickedOperators: [','],
disallowSpaceAfterPrefixUnaryOperators: [
'++',
'--',
'+',
'-',
'~',
'!'
],
disallowSpaceBeforePostfixUnaryOperators: [
'++',
'--'
],
requireSpaceBeforeBinaryOperators: [
'+',
'-',
'/',
'*',
'=',
'==',
'===',
'!=',
'!=='
],
requireSpaceAfterBinaryOperators: [
'+',
'-',
'/',
'*',
'=',
'==',
'===',
'!=',
'!=='
],
requireCamelCaseOrUpperCaseIdentifiers: true,
disallowKeywords: ["with"],
disallowMultipleLineBreaks: true,
validateQuoteMarks: '\'',
disallowMixedSpacesAndTabs: true,
disallowTrailingWhitespace: true,
disallowKeywordsOnNewLine: ['else'],
requireDotNotation: true,
validateJSDoc: {
checkParamNames: true,
checkRedundantParams: true,
requireParamTypes: true
}
}
},
compare_size: {
files: [
'dist/framework.js',
'dist/framework.min.js'
]
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['bower-install']);
grunt.registerTask('build', ['jscs', 'uglify', 'concat', 'compare_size']);
grunt.registerTask('test', [
'jscs',
'exec:test:lib',
'exec:test:storage',
'exec:test:view',
'exec:test:kernel',
'exec:test:event',
'exec:test:validator',
'exec:test:form',
'exec:test:topLevel'
]);
};
| Gruntfile.js | module.exports = function (grunt) {
var generator = [
'src/Lib/Generator/Interface.js',
'src/Lib/Generator/UUID.js'
],
logger = [
'src/Lib/Logger/Interface.js',
'src/Lib/Logger/Handler/Interface.js',
'src/Lib/Logger/Handler/Console.js',
'src/Lib/Logger/CoreLogger.js'
],
mediator = [
'src/Lib/Mediator.js'
],
http = [
'src/Lib/Logger/Interface.js',
'src/HTTP/RequestInterface.js',
'src/HTTP/ResponseInterface.js',
'src/HTTP/Request.js',
'src/HTTP/Response.js',
'src/HTTP/JSONRequest.js',
'src/HTTP/JSONResponse.js',
'src/HTTP/HeaderParser.js',
'src/HTTP/HTMLRequest.js',
'src/HTTP/HTMLResponse.js',
'src/HTTP/ImageRequest.js',
'src/HTTP/ImageResponse.js',
'src/HTTP/Manager.js',
'src/HTTP/REST.js'
],
storage = [
'src/EntityInterface.js',
'src/Entity.js',
'src/Storage/Core.js',
'src/Storage/IdentityMap.js',
'src/Storage/LifeCycleEvent.js',
'src/Storage/Manager.js',
'src/Storage/ManagerFactory.js',
'src/Storage/Repository.js',
'src/Storage/RepositoryFactory.js',
'src/Storage/RepositoryFactoryConfigurator.js',
'src/Storage/UnitOfWork.js',
'src/Storage/UnitOfWorkFactory.js',
'src/Storage/Dbal/DriverFactoryInterface.js',
'src/Storage/Dbal/DriverInterface.js',
'src/Storage/Dbal/Factory.js',
'src/Storage/Dbal/IndexedDB.js',
'src/Storage/Dbal/IndexedDBFactory.js',
'src/Storage/Dbal/Localstorage.js',
'src/Storage/Dbal/LocalstorageFactory.js',
'src/Storage/Dbal/Rest.js',
'src/Storage/Dbal/RestFactory.js',
],
validator = [
'src/Validator/ConstraintInterface.js',
'src/Validator/ConstraintValidatorInterface.js',
'src/Validator/Core.js',
'src/Validator/AbstractConstraint.js',
'src/Validator/AbstractConstraintValidator.js',
'src/Validator/Constraint/Blank.js',
'src/Validator/Constraint/BlankValidator.js',
'src/Validator/Constraint/Callback.js',
'src/Validator/Constraint/CallbackValidator.js',
'src/Validator/Constraint/Choice.js',
'src/Validator/Constraint/ChoiceValidator.js',
'src/Validator/Constraint/Country.js',
'src/Validator/Constraint/CountryValidator.js',
'src/Validator/Constraint/Date.js',
'src/Validator/Constraint/DateValidator.js',
'src/Validator/Constraint/Email.js',
'src/Validator/Constraint/EmailValidator.js',
'src/Validator/Constraint/EqualTo.js',
'src/Validator/Constraint/EqualToValidator.js',
'src/Validator/Constraint/False.js',
'src/Validator/Constraint/FalseValidator.js',
'src/Validator/Constraint/GreaterThan.js',
'src/Validator/Constraint/GreaterThanValidator.js',
'src/Validator/Constraint/GreaterThanOrEqual.js',
'src/Validator/Constraint/GreaterThanOrEqualValidator.js',
'src/Validator/Constraint/Ip.js',
'src/Validator/Constraint/IpValidator.js',
'src/Validator/Constraint/Length.js',
'src/Validator/Constraint/LengthValidator.js',
'src/Validator/Constraint/LessThan.js',
'src/Validator/Constraint/LessThanValidator.js',
'src/Validator/Constraint/LessThanOrEqual.js',
'src/Validator/Constraint/LessThanOrEqualValidator.js',
'src/Validator/Constraint/NotBlank.js',
'src/Validator/Constraint/NotBlankValidator.js',
'src/Validator/Constraint/NotEqualTo.js',
'src/Validator/Constraint/NotEqualToValidator.js',
'src/Validator/Constraint/NotNull.js',
'src/Validator/Constraint/NotNullValidator.js',
'src/Validator/Constraint/NotUndefined.js',
'src/Validator/Constraint/NotUndefinedValidator.js',
'src/Validator/Constraint/Null.js',
'src/Validator/Constraint/NullValidator.js',
'src/Validator/Constraint/Range.js',
'src/Validator/Constraint/RangeValidator.js',
'src/Validator/Constraint/Regex.js',
'src/Validator/Constraint/RegexValidator.js',
'src/Validator/Constraint/True.js',
'src/Validator/Constraint/TrueValidator.js',
'src/Validator/Constraint/Type.js',
'src/Validator/Constraint/TypeValidator.js',
'src/Validator/Constraint/Undefined.js',
'src/Validator/Constraint/UndefinedValidator.js',
'src/Validator/Constraint/Url.js',
'src/Validator/Constraint/UrlValidator.js',
'src/Validator/ConstraintFactory.js',
'src/Validator/ConstraintValidatorFactory.js',
'src/Validator/ConstraintViolation.js',
'src/Validator/ConstraintViolationList.js',
'src/Validator/ExecutionContext.js',
'src/Validator/ExecutionContextFactory.js'
],
form = [
'src/Form/FormInterface.js',
'src/Form/FormBuilderInterface.js',
'src/Form/FormTypeInterface.js',
'src/Form/Form.js',
'src/Form/FormBuilder.js',
'src/Form/Builder.js',
],
view = [
'src/View/LayoutFactoryInterface.js',
'src/View/ListFactoryInterface.js',
'src/View/TemplateEngineInterface.js',
'src/View/ViewScreenFactoryInterface.js',
'src/View/Event/ViewPortEvent.js',
'src/View/NodeWrapper.js',
'src/View/Layout.js',
'src/View/LayoutFactory.js',
'src/View/List.js',
'src/View/ListFactory.js',
'src/View/Manager.js',
'src/View/ManagerConfigurator.js',
'src/View/Parser.js',
'src/View/TemplateEngine.js',
'src/View/ViewPort.js',
'src/View/ViewScreen.js',
'src/View/ViewScreenFactory.js',
],
configurator = [
'src/ConfiguratorInterface.js',
'src/Configurator.js'
],
registry = [
'src/RegistryInterface.js',
'src/Registry.js',
'src/RegistryFactory.js'
],
stateRegistry = [
'src/StateRegistryInterface.js',
'src/StateRegistry.js',
'src/StateRegistryFactory.js',
],
serviceContainer = [
'src/ServiceContainer/Core.js',
'src/ServiceContainer/Alias.js',
'src/ServiceContainer/Compiler.js',
'src/ServiceContainer/CompilerPassInterface.js',
'src/ServiceContainer/Definition.js',
'src/ServiceContainer/Parameter.js',
'src/ServiceContainer/Reference.js',
'src/ServiceContainer/CompilerPass/ApplyParentDefinition.js',
'src/ServiceContainer/CompilerPass/RemoveAbstractDefinitions.js',
'src/ServiceContainer/CompilerPass/ResolveParameterPlaceholder.js',
'src/ServiceContainer/CompilerPass/ResolveReferencePlaceholder.js',
],
translator = [
'src/Translator.js',
],
factory = [
'src/FactoryInterface.js',
],
dom = [
'src/DOM.js'
],
propertyAccessor = [ //need the reflection.js vendor
'src/PropertyAccessor.js'
],
appState = [
'src/AppState/Route.js',
'src/AppState/Router.js',
'src/AppState/RouteProvider.js',
'src/AppState/Core.js',
'src/AppState/UrlMatcher.js',
'src/AppState/State.js',
'src/AppState/StateHandler.js',
'src/AppState/AppStateEvent.js',
'src/AppState/UrlMatcher.js',
],
framework = [
'src/functions.js',
'src/ControllerInterface.js',
'src/Kernel/ActionDispatcher.js',
'src/Kernel/AppParser.js',
'src/Kernel/ControllerManager.js',
'src/Kernel/Core.js',
'src/Kernel/FeatureTester.js',
'src/Event/AppShutdownEvent.js',
'src/Event/ControllerEvent.js',
'src/Controller.js',
'src/EventSubscriberInterface.js',
'src/FrameworkBundle/Config/Configuration.js',
'src/FrameworkBundle/Config/Service.js',
'src/FormBundle/Config/Service.js',
'src/HttpBundle/Config/Service.js',
'src/StorageBundle/Config/Service.js',
'src/TranslatorBundle/Config/Service.js',
'src/ValidatorBundle/Config/Service.js',
'src/ViewBundle/Config/Service.js',
'src/ViewBundle/Subscriber/AppStateSubscriber.js',
'src/AppStateBundle/Config/Service.js',
],
frameworkPasses = [
'src/FrameworkBundle/CompilerPass/EventSubscriberPass.js',
'src/FormBundle/CompilerPass/FormTypePass.js',
'src/StorageBundle/CompilerPass/RegisterDriverFactoryPass.js',
'src/ViewBundle/CompilerPass/RegisterLayoutWrapperPass.js',
'src/ViewBundle/CompilerPass/RegisterListWrapperPass.js',
'src/ViewBundle/CompilerPass/RegisterViewScreenWrapperPass.js',
'src/ViewBundle/CompilerPass/RegisterSubscriberPass.js',
'src/AppStateBundle/CompilerPass/RegisterRoutesPass.js',
],
unique = function (el, idx, array) {
if (array.indexOf(el) !== idx && array.indexOf(el) < idx) {
return false;
}
return true;
};
generator.unshift('src/functions.js');
logger.unshift('src/functions.js');
configurator.unshift('src/functions.js');
serviceContainer = serviceContainer.concat(propertyAccessor);
registry = factory.concat(registry);
mediator = mediator
.concat(generator)
.concat(logger);
stateRegistry = factory
.concat(registry)
.concat(stateRegistry);
http = http
.concat(generator)
.concat(registry);
storage = factory //need the observe-js vendor
.concat(logger)
.concat(http)
.concat(mediator)
.concat(registry)
.concat(stateRegistry)
.concat(generator)
.concat(storage)
.concat(propertyAccessor);
validator = factory
.concat(registry)
.concat(validator);
form = form
.concat(configurator)
.concat(validator);
view = factory
.concat(registry)
.concat(generator)
.concat(mediator)
.concat(dom)
.concat(view);
translator = translator
.concat(registry)
.concat(stateRegistry);
serviceContainer.unshift('src/functions.js');
mediator.unshift('src/functions.js');
registry.unshift('src/functions.js');
stateRegistry.unshift('src/functions.js');
http.unshift('src/functions.js');
storage.unshift('src/functions.js');
validator.unshift('src/functions.js');
view.unshift('src/functions.js');
translator.unshift('src/functions.js');
appState.unshift('src/functions.js');
framework = framework
.concat(generator)
.concat(logger)
.concat(factory)
.concat(mediator)
.concat(http)
.concat(propertyAccessor)
.concat(storage)
.concat(validator)
.concat(form)
.concat(view)
.concat(configurator)
.concat(registry)
.concat(stateRegistry)
.concat(serviceContainer)
.concat(frameworkPasses)
.concat(translator)
.concat(dom)
.concat(appState);
serviceContainer = serviceContainer.filter(unique);
registry = registry.filter(unique);
stateRegistry = stateRegistry.filter(unique);
http = http.filter(unique);
storage = storage.filter(unique);
validator = validator.filter(unique);
view = view.filter(unique);
translator = translator.filter(unique);
framework = framework.filter(unique);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %>#<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
files: {
'dist/framework.min.js': framework,
'dist/generator.min.js': generator,
'dist/logger.min.js': logger,
'dist/mediator.min.js': mediator,
'dist/http.min.js': http,
'dist/storage.min.js': storage,
'dist/validator.min.js': validator,
'dist/view.min.js': view,
'dist/configurator.min.js': configurator,
'dist/registry.min.js': registry,
'dist/state-registry.min.js': stateRegistry,
'dist/service-container.min.js': serviceContainer,
'dist/translator.min.js': translator,
'dist/property-accessor.min.js': propertyAccessor,
'dist/appstate.min.js': appState
}
}
},
concat: {
options: {
banner: '/*! <%= pkg.name %>#<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
framework: {
src: framework,
dest: 'dist/framework.js'
},
generator: {
src: generator,
dest: 'dist/generator.js'
},
logger: {
src: logger,
dest: 'dist/logger.js'
},
mediator: {
src: mediator,
dest: 'dist/mediator.js'
},
http: {
src: http,
dest: 'dist/http.js'
},
storage: {
src: storage,
dest: 'dist/storage.js'
},
validator: {
src: validator,
dest: 'dist/validator.js'
},
view: {
src: view,
dest: 'dist/view.js'
},
configurator: {
src: configurator,
dest: 'dist/configurator.js'
},
registry: {
src: registry,
dest: 'dist/registry.js'
},
stateRegistry: {
src: stateRegistry,
dest: 'dist/state-registry.js'
},
serviceContainer: {
src: serviceContainer,
dest: 'dist/service-container.js'
},
translator: {
src: translator,
dest: 'dist/translator.js'
},
propertyAccessor: {
src: propertyAccessor,
dest: 'dist/property-accessor.js'
},
appState: {
src: appState,
dest: 'dist/appstate.js'
}
},
'bower-install': {
target: {
html: 'index.html',
jsPattern: '<script src="{{filePath}}"></script>'
}
},
exec: {
test: {
cmd: function (pkg) {
var path;
switch (pkg) {
case 'lib':
path = 'lib/';
break;
case 'storage':
path = 'storage/';
break;
case 'view':
path = 'view/';
break;
case 'kernel':
path = 'kernel';
break;
case 'event':
path = 'event';
break;
case 'validator':
path = 'validator/';
break;
case 'form':
path = 'form/';
break;
case 'topLevel':
path = [
'entity.js',
'functions.js',
'stateregistry.js',
'stateregistryfactory.js',
'registry.js',
'registryfactory.js',
'servicecontainer.js',
'translator.js',
].join(',tests/');
break;
}
return './node_modules/venus/bin/venus run -t tests/' + path + ' -c -n';
}
}
},
watch: {
js: {
files: ['src/*.js'],
tasks: [],
options: {
livereload: true
}
}
},
jscs: {
src: 'src/**/*.js',
options: {
requireCurlyBraces: [
'if',
'else',
'for',
'do',
'while',
'try',
'catch',
],
requireSpaceAfterKeywords: [
'if',
'else',
'for',
'do',
'while',
'switch',
'try',
'catch'
],
requireParenthesesAroundIIFE: true,
requireSpacesInFunctionExpression: {
beforeOpeningRoundBrace: true,
beforeOpeningCurlyBrace: true
},
disallowSpacesInsideObjectBrackets: true,
disallowSpacesInsideArrayBrackets: true,
disallowSpacesInsideParentheses: true,
disallowQuotedKeysInObjects: true,
disallowSpaceAfterObjectKeys: true,
requireCommaBeforeLineBreak: true,
requireOperatorBeforeLineBreak: [
'?',
'+',
'-',
'/',
'*',
'=',
'==',
'===',
'!=',
'!==',
'>',
'>=',
'<',
'<='
],
disallowLeftStickedOperators: [
'?',
'+',
'-',
'/',
'*',
'=',
'==',
'===',
'!=',
'!==',
'>',
'>=',
'<',
'<='
],
requireRightStickedOperators: ['!'],
disallowRightStickedOperators: [
'?',
'+',
'/',
'*',
':',
'=',
'==',
'===',
'!=',
'!==',
'>',
'>=',
'<',
'<='
],
requireLeftStickedOperators: [','],
disallowSpaceAfterPrefixUnaryOperators: [
'++',
'--',
'+',
'-',
'~',
'!'
],
disallowSpaceBeforePostfixUnaryOperators: [
'++',
'--'
],
requireSpaceBeforeBinaryOperators: [
'+',
'-',
'/',
'*',
'=',
'==',
'===',
'!=',
'!=='
],
requireSpaceAfterBinaryOperators: [
'+',
'-',
'/',
'*',
'=',
'==',
'===',
'!=',
'!=='
],
requireCamelCaseOrUpperCaseIdentifiers: true,
disallowKeywords: ["with"],
disallowMultipleLineBreaks: true,
validateQuoteMarks: '\'',
disallowMixedSpacesAndTabs: true,
disallowTrailingWhitespace: true,
disallowKeywordsOnNewLine: ['else'],
requireDotNotation: true,
validateJSDoc: {
checkParamNames: true,
checkRedundantParams: true,
requireParamTypes: true
}
}
},
compare_size: {
files: [
'dist/framework.js',
'dist/framework.min.js'
]
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['bower-install']);
grunt.registerTask('build', ['jscs', 'uglify', 'concat', 'compare_size']);
grunt.registerTask('test', [
'jscs',
'exec:test:lib',
'exec:test:storage',
'exec:test:view',
'exec:test:kernel',
'exec:test:event',
'exec:test:validator',
'exec:test:form',
'exec:test:topLevel'
]);
};
| #33 added the new event file to files in gruntfile
| Gruntfile.js | #33 added the new event file to files in gruntfile | <ide><path>runtfile.js
<ide> 'src/AppState/State.js',
<ide> 'src/AppState/StateHandler.js',
<ide> 'src/AppState/AppStateEvent.js',
<add> 'src/AppState/RouteNotFoundEvent.js',
<ide> 'src/AppState/UrlMatcher.js',
<ide> ],
<ide> framework = [ |
|
Java | apache-2.0 | b0add7ea57c5021de223afe8676a20daeb3eefe3 | 0 | EvilMcJerkface/Aeron,galderz/Aeron,galderz/Aeron,real-logic/Aeron,real-logic/Aeron,mikeb01/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron,galderz/Aeron,galderz/Aeron,real-logic/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron | /*
* Copyright 2014-2018 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.aeron.cluster.service;
import io.aeron.Aeron;
import io.aeron.DirectBufferVector;
import io.aeron.Publication;
import io.aeron.cluster.codecs.MessageHeaderEncoder;
import io.aeron.cluster.codecs.SessionHeaderEncoder;
import org.agrona.CloseHelper;
import org.agrona.DirectBuffer;
import org.agrona.concurrent.UnsafeBuffer;
/**
* Session representing a connected client to the cluster.
*/
public class ClientSession
{
/**
* Length of the session header that will be prepended to the message.
*/
public static final int SESSION_HEADER_LENGTH =
MessageHeaderEncoder.ENCODED_LENGTH + SessionHeaderEncoder.BLOCK_LENGTH;
/**
* Return value to indicate egress to a session is mocked out by the cluster when in follower mode.
*/
public static final long MOCKED_OFFER = 1;
private final long id;
private final int responseStreamId;
private final String responseChannel;
private final byte[] encodedPrincipal;
private final DirectBufferVector[] vectors = new DirectBufferVector[2];
private final DirectBufferVector messageBuffer = new DirectBufferVector();
private final SessionHeaderEncoder sessionHeaderEncoder = new SessionHeaderEncoder();
private final Cluster cluster;
private Publication responsePublication;
private boolean isClosing;
ClientSession(
final long sessionId,
final int responseStreamId,
final String responseChannel,
final byte[] encodedPrincipal,
final Cluster cluster)
{
this.id = sessionId;
this.responseStreamId = responseStreamId;
this.responseChannel = responseChannel;
this.encodedPrincipal = encodedPrincipal;
this.cluster = cluster;
final UnsafeBuffer headerBuffer = new UnsafeBuffer(new byte[SESSION_HEADER_LENGTH]);
sessionHeaderEncoder
.wrapAndApplyHeader(headerBuffer, 0, new MessageHeaderEncoder())
.clusterSessionId(sessionId);
vectors[0] = new DirectBufferVector(headerBuffer, 0, SESSION_HEADER_LENGTH);
vectors[1] = messageBuffer;
}
/**
* Cluster session identity uniquely allocated when the session was opened.
*
* @return the cluster session identity uniquely allocated when the session was opened.
*/
public long id()
{
return id;
}
/**
* The response channel stream id for responding to the client.
*
* @return response channel stream id for responding to the client.
*/
public int responseStreamId()
{
return responseStreamId;
}
/**
* The response channel for responding to the client.
*
* @return response channel for responding to the client.
*/
public String responseChannel()
{
return responseChannel;
}
/**
* Cluster session encoded principal from when the session was authenticated.
*
* @return The encoded Principal passed. May be 0 length to indicate none present.
*/
public byte[] encodedPrincipal()
{
return encodedPrincipal;
}
/**
* Indicates that a request to close this session has been made.
*
* @return whether a request to close this session has been made.
*/
public boolean isClosing()
{
return isClosing;
}
/**
* Non-blocking publish of a partial buffer containing a message to a cluster.
*
* @param correlationId to be used to identify the message to the cluster.
* @param buffer containing message.
* @param offset offset in the buffer at which the encoded message begins.
* @param length in bytes of the encoded message.
* @return the same as {@link Publication#offer(DirectBuffer, int, int)} when in {@link Cluster.Role#LEADER}
* otherwise {@link #MOCKED_OFFER}.
*/
public long offer(
final long correlationId,
final DirectBuffer buffer,
final int offset,
final int length)
{
if (cluster.role() != Cluster.Role.LEADER)
{
return MOCKED_OFFER;
}
if (null == responsePublication)
{
throw new IllegalStateException("ClientSession not connected id=" + id);
}
sessionHeaderEncoder.correlationId(correlationId);
sessionHeaderEncoder.timestamp(cluster.timeMs());
messageBuffer.reset(buffer, offset, length);
return responsePublication.offer(vectors, null);
}
void connect(final Aeron aeron)
{
if (null == responsePublication)
{
responsePublication = aeron.addPublication(responseChannel, responseStreamId);
}
}
void markClosing()
{
this.isClosing = true;
}
void disconnect()
{
CloseHelper.close(responsePublication);
responsePublication = null;
}
}
| aeron-cluster/src/main/java/io/aeron/cluster/service/ClientSession.java | /*
* Copyright 2014-2018 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.aeron.cluster.service;
import io.aeron.Aeron;
import io.aeron.DirectBufferVector;
import io.aeron.Publication;
import io.aeron.cluster.codecs.MessageHeaderEncoder;
import io.aeron.cluster.codecs.SessionHeaderEncoder;
import org.agrona.CloseHelper;
import org.agrona.DirectBuffer;
import org.agrona.concurrent.UnsafeBuffer;
/**
* Session representing a connected client to the cluster.
*/
public class ClientSession
{
/**
* Length of the session header that will be prepended to the message.
*/
public static final int SESSION_HEADER_LENGTH =
MessageHeaderEncoder.ENCODED_LENGTH + SessionHeaderEncoder.BLOCK_LENGTH;
/**
* Return value to indicate egress to a session is mocked out by the cluster when in follower mode.
*/
public static final long MOCKED_OFFER = 1;
private final long id;
private final int responseStreamId;
private final String responseChannel;
private final byte[] encodedPrincipal;
private final DirectBufferVector[] vectors = new DirectBufferVector[2];
private final DirectBufferVector messageBuffer = new DirectBufferVector();
private final SessionHeaderEncoder sessionHeaderEncoder = new SessionHeaderEncoder();
private final Cluster cluster;
private Publication responsePublication;
private boolean isClosing;
ClientSession(
final long sessionId,
final int responseStreamId,
final String responseChannel,
final byte[] encodedPrincipal,
final Cluster cluster)
{
this.id = sessionId;
this.responseStreamId = responseStreamId;
this.responseChannel = responseChannel;
this.encodedPrincipal = encodedPrincipal;
this.cluster = cluster;
final UnsafeBuffer headerBuffer = new UnsafeBuffer(new byte[SESSION_HEADER_LENGTH]);
sessionHeaderEncoder
.wrapAndApplyHeader(headerBuffer, 0, new MessageHeaderEncoder())
.clusterSessionId(sessionId);
vectors[0] = new DirectBufferVector(headerBuffer, 0, SESSION_HEADER_LENGTH);
vectors[1] = messageBuffer;
}
/**
* Cluster session identity uniquely allocated when the session was opened.
*
* @return the cluster session identity uniquely allocated when the session was opened.
*/
public long id()
{
return id;
}
/**
* The response channel stream id for responding to the client.
*
* @return response channel stream id for responding to the client.
*/
public int responseStreamId()
{
return responseStreamId;
}
/**
* The response channel for responding to the client.
*
* @return response channel for responding to the client.
*/
public String responseChannel()
{
return responseChannel;
}
/**
* Cluster session encoded principal from when the session was authenticated.
*
* @return The encoded Principal passed. May be 0 length to indicate none present.
*/
public byte[] encodedPrincipal()
{
return encodedPrincipal;
}
/**
* Indicates that a request to close this session has been made.
*
* @return whether a request to close this session has been made.
*/
public boolean isClosing()
{
return isClosing;
}
/**
* Non-blocking publish of a partial buffer containing a message to a cluster.
*
* @param correlationId to be used to identify the message to the cluster.
* @param buffer containing message.
* @param offset offset in the buffer at which the encoded message begins.
* @param length in bytes of the encoded message.
* @return the same as {@link Publication#offer(DirectBuffer, int, int)} when in {@link Cluster.Role#LEADER}
* otherwise {@link #MOCKED_OFFER}.
*/
public long offer(
final long correlationId,
final DirectBuffer buffer,
final int offset,
final int length)
{
if (cluster.role() != Cluster.Role.LEADER)
{
return MOCKED_OFFER;
}
sessionHeaderEncoder.correlationId(correlationId);
sessionHeaderEncoder.timestamp(cluster.timeMs());
messageBuffer.reset(buffer, offset, length);
if (null == responsePublication)
{
throw new IllegalStateException("ClientSession not connected");
}
return responsePublication.offer(vectors, null);
}
void connect(final Aeron aeron)
{
if (null == responsePublication)
{
responsePublication = aeron.addPublication(responseChannel, responseStreamId);
}
}
void markClosing()
{
this.isClosing = true;
}
void disconnect()
{
CloseHelper.close(responsePublication);
responsePublication = null;
}
}
| [Java] Perform checks before mutating state and provide the session id to help with debugging.
| aeron-cluster/src/main/java/io/aeron/cluster/service/ClientSession.java | [Java] Perform checks before mutating state and provide the session id to help with debugging. | <ide><path>eron-cluster/src/main/java/io/aeron/cluster/service/ClientSession.java
<ide> return MOCKED_OFFER;
<ide> }
<ide>
<add> if (null == responsePublication)
<add> {
<add> throw new IllegalStateException("ClientSession not connected id=" + id);
<add> }
<add>
<ide> sessionHeaderEncoder.correlationId(correlationId);
<ide> sessionHeaderEncoder.timestamp(cluster.timeMs());
<ide> messageBuffer.reset(buffer, offset, length);
<del>
<del> if (null == responsePublication)
<del> {
<del> throw new IllegalStateException("ClientSession not connected");
<del> }
<ide>
<ide> return responsePublication.offer(vectors, null);
<ide> } |
|
JavaScript | mit | 7888a1b65d6c5d18b42bb0b7a3e74a527dea4ec4 | 0 | DrummerHead/gmail-chrono-archive | var addressesAndExpiration = [
{
address : "[email protected]",
days : 3
},
{
address : "[email protected]",
days : 5
},
{
address : "[email protected]",
days : 5
},
{
address : "[email protected]",
days : 5
},
{
address : "[email protected]",
days : 7
}
];
var MILIS_PER_DAY = 1000 * 60 * 60 * 24;
var nowDate = new Date();
function isMailContained(sample, mail){
return (function(sample, mail){
this.regexCache = this.regexCache || {};
if(this.regexCache[mail] === undefined){
this.regexCache[mail] = new RegExp(mail);
}
return this.regexCache[mail].test(sample);
})(sample, mail);
}
function haveNDaysPassed(days, date){
return date.getTime() + days * MILIS_PER_DAY <= nowDate.getTime();
}
function isOld(message){
var from = message.getFrom();
var date = message.getDate();
for(var i = 0, j = addressesAndExpiration.length; i < j; i++){
if(isMailContained(from, addressesAndExpiration[i].address)){
return haveNDaysPassed(addressesAndExpiration[i].days, date);
}
}
}
function mailLogs(){
MailApp.sendEmail(Session.getActiveUser().getEmail(), "Ephemeral logs", Logger.getLog());
}
function checkOldEphemeralMail() {
var inbox = GmailApp.getInboxThreads();
for(var i = 0; i < inbox.length; i++){
var message = inbox[i].getMessages()[0];
Logger.log(message.getFrom());
Logger.log(message.getSubject());
Logger.log(message.getDate());
if(isOld(message)){
inbox[i].moveToArchive();
Logger.log("*** old ephemeral mail moved to archive ***");
}
Logger.log("= = = = = = = =\n");
}
mailLogs();
}
| main.js | var addressesAndExpiration = [
{
address : "[email protected]",
days : 3
},
{
address : "[email protected]",
days : 5
},
{
address : "[email protected]",
days : 5
},
{
address : "[email protected]",
days : 5
},
{
address : "[email protected]",
days : 7
}
];
var MILIS_PER_DAY = 1000 * 60 * 60 * 24;
var NOW_DATE = new Date();
function isMailContained(sample, mail){
return (function(sample, mail){
this.regexCache = this.regexCache || {};
if(this.regexCache[mail] === undefined){
this.regexCache[mail] = new RegExp(mail);
}
return this.regexCache[mail].test(sample);
})(sample, mail);
}
function haveNDaysPassed(days, date){
return date.getTime() + days * MILIS_PER_DAY <= NOW_DATE.getTime();
}
function isOld(message){
var from = message.getFrom();
var date = message.getDate();
for(var i = 0, j = addressesAndExpiration.length; i < j; i++){
if(isMailContained(from, addressesAndExpiration[i].address)){
return haveNDaysPassed(addressesAndExpiration[i].days, date);
}
}
}
function mailLogs(){
MailApp.sendEmail(Session.getActiveUser().getEmail(), "Ephemeral logs", Logger.getLog());
}
function checkOldEphemeralMail() {
var inbox = GmailApp.getInboxThreads();
for(var i = 0; i < inbox.length; i++){
var message = inbox[i].getMessages()[0];
Logger.log(message.getFrom());
Logger.log(message.getSubject());
Logger.log(message.getDate());
if(isOld(message)){
inbox[i].moveToArchive();
Logger.log("*** old ephemeral mail moved to archive ***");
}
Logger.log("= = = = = = = =\n");
}
mailLogs();
}
| Change constant naming to variable
| main.js | Change constant naming to variable | <ide><path>ain.js
<ide> ];
<ide>
<ide> var MILIS_PER_DAY = 1000 * 60 * 60 * 24;
<del>var NOW_DATE = new Date();
<add>var nowDate = new Date();
<ide>
<ide> function isMailContained(sample, mail){
<ide> return (function(sample, mail){
<ide> }
<ide>
<ide> function haveNDaysPassed(days, date){
<del> return date.getTime() + days * MILIS_PER_DAY <= NOW_DATE.getTime();
<add> return date.getTime() + days * MILIS_PER_DAY <= nowDate.getTime();
<ide> }
<ide>
<ide> function isOld(message){ |
|
Java | mpl-2.0 | d5e43bed6c2aec93fb95b0a18fb46516d9dfa39a | 0 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: JavaWindowPeerFake.java,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2007-08-30 13:57:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
package com.sun.star.comp.beans;
import java.awt.*;
import com.sun.star.uno.*;
import com.sun.star.lang.*;
import com.sun.star.awt.*;
import com.sun.star.util.*;
import com.sun.star.beans.*;
import com.sun.star.container.*;
/** <p>Class to pass the system window handle to the OpenOffice.org toolkit.</p>
*
* @since OOo 2.0.0
*/
/* package */ class JavaWindowPeerFake
implements XSystemDependentWindowPeer, XWindowPeer
{
protected int localSystemType;
protected Any wrappedHandle;
/** Create the faked window peer.
* @param _hWindow the system handle to the window.
* @param _systemType specifies the system type.
*/
public JavaWindowPeerFake(Any _hWindow, int _systemType)
{
localSystemType = _systemType;
wrappedHandle = _hWindow;
}
/** <p>Implementation of XSystemDependentWindowPeer (that's all we really need)</p>
* This method is called back from the OpenOffice.org toolkit to retrieve the system data.
*/
public Object getWindowHandle(/*IN*/byte[] ProcessId, /*IN*/short SystemType)
throws com.sun.star.uno.RuntimeException
{
if (SystemType == localSystemType) {
return wrappedHandle;
}
else return null;
}
/** not really neaded.
*/
public XToolkit getToolkit()
throws com.sun.star.uno.RuntimeException
{
return null;
}
/** not really neaded.
*/
public void setPointer(/*IN*/XPointer Pointer)
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void setBackground(/*IN*/int Color)
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void invalidate(/*IN*/short Flags)
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void invalidateRect(/*IN*/com.sun.star.awt.Rectangle Rect, /*IN*/short Flags)
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void dispose()
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void addEventListener(/*IN*/com.sun.star.lang.XEventListener xListener)
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void removeEventListener(/*IN*/com.sun.star.lang.XEventListener aListener)
throws com.sun.star.uno.RuntimeException
{
}
}
| bean/com/sun/star/comp/beans/JavaWindowPeerFake.java | /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: JavaWindowPeerFake.java,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 22:00:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
package com.sun.star.comp.beans;
import java.awt.*;
import com.sun.star.uno.*;
import com.sun.star.lang.*;
import com.sun.star.awt.*;
import com.sun.star.util.*;
import com.sun.star.beans.*;
import com.sun.star.container.*;
/** <p>Class to pass the system window handle to the OpenOffice.org toolkit.</p>
*
* @since OOo 2.0.0
*/
/* package */ class JavaWindowPeerFake
implements XSystemDependentWindowPeer, XWindowPeer
{
protected long hWindow;
protected int localSystemType;
/** Create the faked window peer.
* @param _hWindow the system handle to the window.
* @param _systemType specifies the system type.
*/
public JavaWindowPeerFake(long _hWindow, int _systemType)
{
hWindow = _hWindow;
localSystemType = _systemType;
}
/** <p>Implementation of XSystemDependentWindowPeer (that's all we really need)</p>
* This method is called back from the OpenOffice.org toolkit to retrieve the system data.
*/
public Object getWindowHandle(/*IN*/byte[] ProcessId, /*IN*/short SystemType)
throws com.sun.star.uno.RuntimeException
{
if (SystemType == localSystemType) {
return new Integer((int)hWindow);
}
else return null;
}
/** not really neaded.
*/
public XToolkit getToolkit()
throws com.sun.star.uno.RuntimeException
{
return null;
}
/** not really neaded.
*/
public void setPointer(/*IN*/XPointer Pointer)
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void setBackground(/*IN*/int Color)
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void invalidate(/*IN*/short Flags)
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void invalidateRect(/*IN*/com.sun.star.awt.Rectangle Rect, /*IN*/short Flags)
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void dispose()
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void addEventListener(/*IN*/com.sun.star.lang.XEventListener xListener)
throws com.sun.star.uno.RuntimeException
{
}
/** not really neaded.
*/
public void removeEventListener(/*IN*/com.sun.star.lang.XEventListener aListener)
throws com.sun.star.uno.RuntimeException
{
}
}
| INTEGRATION: CWS c12v002_SRC680 (1.3.32); FILE MERGED
2007/04/02 09:25:33 jl 1.3.32.2: #t6453597# LocalOfficeWindow has now a method getWrappedWindowHandle
2007/03/12 14:27:42 jl 1.3.32.1: #t6453597# XSystemDependentWindowPeer.getWindowhandle return a sequences<NamedValue> now which indicates i OOo should use XEmbed
| bean/com/sun/star/comp/beans/JavaWindowPeerFake.java | INTEGRATION: CWS c12v002_SRC680 (1.3.32); FILE MERGED 2007/04/02 09:25:33 jl 1.3.32.2: #t6453597# LocalOfficeWindow has now a method getWrappedWindowHandle 2007/03/12 14:27:42 jl 1.3.32.1: #t6453597# XSystemDependentWindowPeer.getWindowhandle return a sequences<NamedValue> now which indicates i OOo should use XEmbed | <ide><path>ean/com/sun/star/comp/beans/JavaWindowPeerFake.java
<ide> *
<ide> * $RCSfile: JavaWindowPeerFake.java,v $
<ide> *
<del> * $Revision: 1.3 $
<add> * $Revision: 1.4 $
<ide> *
<del> * last change: $Author: rt $ $Date: 2005-09-07 22:00:04 $
<add> * last change: $Author: vg $ $Date: 2007-08-30 13:57:57 $
<ide> *
<ide> * The Contents of this file are made available subject to
<ide> * the terms of GNU Lesser General Public License Version 2.1.
<ide> /* package */ class JavaWindowPeerFake
<ide> implements XSystemDependentWindowPeer, XWindowPeer
<ide> {
<del>
<del> protected long hWindow;
<del> protected int localSystemType;
<add> protected int localSystemType;
<add> protected Any wrappedHandle;
<ide>
<ide> /** Create the faked window peer.
<ide> * @param _hWindow the system handle to the window.
<ide> * @param _systemType specifies the system type.
<ide> */
<del> public JavaWindowPeerFake(long _hWindow, int _systemType)
<add> public JavaWindowPeerFake(Any _hWindow, int _systemType)
<ide> {
<del> hWindow = _hWindow;
<ide> localSystemType = _systemType;
<add> wrappedHandle = _hWindow;
<ide> }
<ide>
<ide> /** <p>Implementation of XSystemDependentWindowPeer (that's all we really need)</p>
<ide> public Object getWindowHandle(/*IN*/byte[] ProcessId, /*IN*/short SystemType)
<ide> throws com.sun.star.uno.RuntimeException
<ide> {
<del>
<ide> if (SystemType == localSystemType) {
<del> return new Integer((int)hWindow);
<add> return wrappedHandle;
<ide> }
<ide> else return null;
<ide> } |
|
JavaScript | mit | b5078aa5182e92f193aaceee54b61c3329f56c07 | 0 | mhoffman/CatAppBrowser,mhoffman/CatAppBrowser | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*/
import React from 'react';
import { isMobile } from 'react-device-detect';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import Paper from 'material-ui/Paper';
import Chip from 'material-ui/Chip';
import Button from 'material-ui/Button';
import Grid from 'material-ui/Grid';
import { LinearProgress } from 'material-ui/Progress';
import { Link } from 'react-router';
import Img from 'containers/App/Img';
import Banner from 'components/Header/banner.png';
import { withStyles } from 'material-ui/styles';
import { FaDatabase, FaNewspaperO } from 'react-icons/lib/fa';
import {
MdWarning,
MdApps,
MdKeyboardArrowUp,
MdKeyboardArrowDown,
MdArrowForward,
} from 'react-icons/lib/md';
import Slide from 'material-ui/transitions/Slide';
import axios from 'axios';
import { newGraphQLRoot, whiteLabel, apps } from 'utils/constants';
import { makeSelectRepos, makeSelectLoading, makeSelectError } from 'containers/App/selectors';
import H1 from 'components/H1';
import { withCommas } from 'utils/functions';
import CenteredSection from './CenteredSection';
import { loadRepos } from '../App/actions';
import { changeUsername } from './actions';
import { makeSelectUsername } from './selectors';
const styles = () => ({
bold: {
fontWeight: 'bold',
},
welcomeHeader: {
marginTop: 0,
marginBottom: '5%',
},
centeredSection: {
marginLeft: '10%',
marginRight: '10%',
textAlign: 'justify',
},
truncated: {
marginRight: '10%',
textAlign: 'justify',
textOverflow: 'ellipsis',
overflow: 'hidden',
maxHeight: '120px',
},
expanded: {
marginRight: '10%',
textAlign: 'justify',
},
textLink: {
textDecoration: 'none',
textColor: 'black',
color: 'black',
},
banner: {
marginTop: 50,
width: '100%',
},
welcome: {
marginRight: '10%',
textAlign: 'left',
},
homePaper: {
backgroundColor: '#eeeeee',
cornerRadius: 40,
padding: 10,
paddingTop: 5,
minWidth: 280,
maxWidth: 300,
textAlign: 'left',
align: 'left',
},
paperInfo: {
minHeight: 30,
marginBottom: 10,
color: 'black',
textColor: 'black',
},
});
export class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
/**
* when initial state username is not null, submit the form to load repos
*/
constructor(props) {
super(props);
this.state = {
geometries: 0,
reactions: 0,
publications: 0,
loading: true,
error: false,
truncated: true,
};
}
componentDidMount() {
if (this.props.username && this.props.username.trim().length > 0) {
this.props.onSubmitForm();
}
axios.post(newGraphQLRoot, {
query: '{reactions(first: 0) { totalCount edges { node { id } } }}' }).then((response) => {
if (response.data.data.reactions === null) {
this.setState({
loading: false,
error: true,
});
} else {
this.setState({
loading: false,
reactions: response.data.data.reactions.totalCount,
});
}
});
axios.post(newGraphQLRoot, {
query: '{publications(first: 0) { totalCount edges { node { id } } }}' }).then((response) => {
if (response.data.data.reactions === null) {
this.setState({
loading: false,
error: true,
});
} else {
this.setState({
loading: false,
publications: response.data.data.publications.totalCount,
});
}
});
}
render() {
return (
<article>
{ whiteLabel === true ? null :
<Helmet
title="Home Page"
meta={[
{ name: 'description', content: `Catalysis-Hub.org is a frontend for browsing the SUNCAT CatApp database containing thousands of first-principles calculations related to heterogeneous catalysis reactions on surface systems. Its goal is to allow comprehensive and user-friendly access to raw quantum chemical simulations guided by heterogeneous catalysis concepts and commonly used graphical representations such as scaling relations and activity maps. All reaction energies are derived from periodic plane-wave density functional theory calculations. An increasing number of calculations contain the corresponding optimized geometry as well as further calculational details such as exchange-correlation (XC) functional, basis set quality, and k-point sampling. Ultimately, the goal is to provide fully self-contained data for predicting experimental observations from electronic structure calculations and using software packages such as Quantum Espresso, GPAW, VASP, and FHI-aims. Input and output with other codes is supported through the Atomic Simulation Environment (ASE). It may also serve as a natural starting point for training and developing machine-learning based approaches accelerating quantum chemical simulations.
Features include search for specific reaction energies, transition states, structures, exploration of scaling relations, activity maps, Pourbaix diagrams and machine learning models, as well as generation of novel bulk and surface structures. Calculations are linked to peer-review publications where available. The database can be queried via a GraphQL API that can also be accessed directly.
All code pertaining to this project is hosted as open-source under a liberal MIT license on github to encourage derived work and collaboration. The frontend is developed using the React Javascript framework based on react boilerplate. New components (apps) can be quickly spun-off and added to the project. The backend is developed using the Flask Python framework providing the GraphQL API as well as further APIs for specific apps.
As such Catalysis-Hub.org aims to serve as a starting point for trend studies and atomic based heterogeneous catalysis explorations.` },
{ name: 'robots', content: 'index,follow' },
{ name: 'keywords', content: 'heterogeneous catalysis,metals,density functional theory,scaling relations, activity maps,pourbaix diagrams,machine learning,quantum espresso,vasp,gpaw' },
{ name: 'DC.title', content: 'Catalysis-Hub.org' },
]}
/>
}
<div>
<CenteredSection className={this.props.classes.centeredSection}>
{whiteLabel ? null :
<Grid
container direction={isMobile ? 'column-reverse' : 'row'} justify="space-between"
className={this.props.classes.welcomeHeader}
>
<Grid item xs={isMobile ? 12 : 6}>
<H1 className={this.props.classes.welcome}>
Welcome to Catalysis-Hub.Org
</H1>
<div className={this.state.truncated ? this.props.classes.truncated : this.props.classes.expanded}>
<div>
Catalysis-Hub.org is a web-platform for sharing data and software for computational catalysis research. The Surface Reactions database (CatApp v 2.0) contains thousands of reaction energies and barriers from density functional theory (DFT) calculations on surface systems.
</div>
<div>
Under Publications, reactions and surface geometries can also be browsed for each publication or dataset. With an increasing number of Apps, the platform allows comprehensive and user-friendly access to heterogeneous catalysis concepts and commonly used graphical representations such as scaling relations and activity maps.
An increasing number of calculations contain the corresponding optimized geometry as well as further calculational details such as exchange-correlation (XC) functional, basis set quality, and k-point sampling. Ultimately, the goal is to provide fully self-contained data for predicting experimental observations from electronic structure calculations and using software packages such as Quantum Espresso, GPAW, VASP, and FHI-aims. Input and output with other codes is supported through the Atomic Simulation Environment (ASE). It may also serve as a natural starting point for training and developing machine-learning based approaches accelerating quantum chemical simulations.
</div>
<div>
Features include search for specific reaction energies, transition states, structures, exploration of scaling relations, activity maps, Pourbaix diagrams and machine learning models, as well as generation of novel bulk and surface structures. Calculations are linked to peer-review publications where available. The database can be queried via a GraphQL API that can also be accessed directly.
</div>
<div>
All code pertaining to this project is hosted as open-source under a liberal MIT license on github to encourage derived work and collaboration. The frontend is developed using the React Javascript framework based on react boilerplate. New components (apps) can be quickly spun-off and added to the project. The backend is developed using the Flask Python framework providing the GraphQL API as well as further APIs for specific apps.
</div>
<div>
As such Catalysis-Hub.org aims to serve as a starting point for trend studies and atomic based heterogeneous catalysis explorations.
</div>
</div>
{this.state.truncated ?
<Button
mini
onClick={() => {
this.setState({
truncated: false,
});
}}
role="button"
>Read More <MdKeyboardArrowDown /></Button>
:
<Button
mini
onClick={() => {
this.setState({
truncated: true,
});
}}
role="button"
>
Read Less <MdKeyboardArrowUp />
</Button>
}
</Grid>
<Grid item xs={isMobile ? 12 : 6}>
<a href="https://suncat.stanford.edu" target="_blank">
<Img className={this.props.classes.banner} src={Banner} alt="SUNCAT - Logo" />
</a>
</Grid>
</Grid>
}
</CenteredSection>
<CenteredSection className={this.props.classes.centeredSection}>
{this.state.loading ? <div>Contacting database ... <LinearProgress color="primary" /></div> : null }
{this.state.error ? <div><MdWarning />Failed to contact database. </div> : null }
</CenteredSection>
<CenteredSection className={this.props.classes.centeredSection}>
<Slide mountOnEnter unmountOnExit in direction="left">
<div>
<Grid container justify="space-between">
<Grid item>
<Link to="/appsIndex" className={this.props.classes.textLink}>
<Paper
className={this.props.classes.homePaper}
>
<h3><MdApps size={20} /> Apps</h3>
<div className={this.props.classes.paperInfo}>
Web apps for exploring calculations
and finding new catalysts.
</div>
<Grid container direction="row" justify="space-between">
<Grid item>
<Chip label={apps.length} />
</Grid>
<Grid item>
<div className={this.props.classes.bold}>See our apps <MdArrowForward /></div>
</Grid>
</Grid>
</Paper>
</Link>
</Grid>
<Grid item>
<Link to="/energies" className={this.props.classes.textLink}>
<Paper
className={this.props.classes.homePaper}
elevation={0}
>
<h3> <FaDatabase size={20} /> Surface Reactions</h3>
<div className={this.props.classes.paperInfo}>
A database of first-principles reaction energies and barriers.
</div>
<Grid container direction="row" justify="space-between">
<Grid item>
<Chip label={withCommas(this.state.reactions)} />
</Grid>
<Grid item>
<div className={this.props.classes.bold}>See our reactions <MdArrowForward /></div>
</Grid>
</Grid>
</Paper>
</Link>
</Grid>
<Grid item>
<Link to="/publications" className={this.props.classes.textLink}>
<Paper
className={this.props.classes.homePaper}
elevation={0}
>
<h3> <FaNewspaperO size={20} /> Publications</h3>
<div className={this.props.classes.paperInfo}>A collection of scientic publications with atomic geometries.</div>
<Grid container direction="row" justify="space-between">
<Grid item>
<Chip label={this.state.publications} />
</Grid>
<Grid item className={this.props.classes.bold}>
See our publications <MdArrowForward />
</Grid>
</Grid>
</Paper>
</Link>
</Grid>
</Grid>
</div>
</Slide>
</CenteredSection>
</div>
</article>
);
}
}
HomePage.propTypes = {
onSubmitForm: React.PropTypes.func,
username: React.PropTypes.string,
classes: React.PropTypes.object,
};
export function mapDispatchToProps(dispatch) {
return {
onChangeUsername: (evt) => dispatch(changeUsername(evt.target.value)),
onSubmitForm: (evt) => {
if (evt !== undefined && evt.preventDefault) evt.preventDefault();
dispatch(loadRepos());
},
};
}
const mapStateToProps = createStructuredSelector({
repos: makeSelectRepos(),
username: makeSelectUsername(),
loading: makeSelectLoading(),
error: makeSelectError(),
});
// Wrap the component to inject dispatch and state into it
export default withStyles(styles, { withTheme: true })(connect(mapStateToProps, mapDispatchToProps)(HomePage));
| app/containers/HomePage/index.js | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*/
import React from 'react';
import { isMobile } from 'react-device-detect';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import Paper from 'material-ui/Paper';
import Chip from 'material-ui/Chip';
import Button from 'material-ui/Button';
import Grid from 'material-ui/Grid';
import { LinearProgress } from 'material-ui/Progress';
import { Link } from 'react-router';
import Img from 'containers/App/Img';
import Banner from 'components/Header/banner.png';
import { withStyles } from 'material-ui/styles';
import { FaDatabase, FaNewspaperO } from 'react-icons/lib/fa';
import {
MdWarning,
MdApps,
MdKeyboardArrowUp,
MdKeyboardArrowDown,
MdArrowForward,
} from 'react-icons/lib/md';
import Slide from 'material-ui/transitions/Slide';
import axios from 'axios';
import { newGraphQLRoot, whiteLabel, apps } from 'utils/constants';
import { makeSelectRepos, makeSelectLoading, makeSelectError } from 'containers/App/selectors';
import H1 from 'components/H1';
import { withCommas } from 'utils/functions';
import CenteredSection from './CenteredSection';
import { loadRepos } from '../App/actions';
import { changeUsername } from './actions';
import { makeSelectUsername } from './selectors';
const styles = () => ({
bold: {
fontWeight: 'bold',
},
welcomeHeader: {
marginTop: 0,
marginBottom: '5%',
},
centeredSection: {
marginLeft: '10%',
marginRight: '10%',
textAlign: 'justify',
},
truncated: {
marginRight: '10%',
textAlign: 'justify',
textOverflow: 'ellipsis',
overflow: 'hidden',
maxHeight: '120px',
},
expanded: {
marginRight: '10%',
textAlign: 'justify',
},
textLink: {
textDecoration: 'none',
textColor: 'black',
color: 'black',
},
banner: {
marginTop: 50,
width: '100%',
},
welcome: {
marginRight: '10%',
textAlign: 'left',
},
homePaper: {
backgroundColor: '#eeeeee',
cornerRadius: 40,
padding: 10,
paddingTop: 5,
minWidth: 280,
maxWidth: 300,
textAlign: 'left',
align: 'left',
},
paperInfo: {
minHeight: 30,
marginBottom: 10,
color: 'black',
textColor: 'black',
},
});
export class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
/**
* when initial state username is not null, submit the form to load repos
*/
constructor(props) {
super(props);
this.state = {
geometries: 0,
reactions: 0,
publications: 0,
loading: true,
error: false,
truncated: true,
};
}
componentDidMount() {
if (this.props.username && this.props.username.trim().length > 0) {
this.props.onSubmitForm();
}
axios.post(newGraphQLRoot, {
query: '{reactions(first: 0) { totalCount edges { node { id } } }}' }).then((response) => {
if (response.data.data.reactions === null) {
this.setState({
loading: false,
error: true,
});
} else {
this.setState({
loading: false,
reactions: response.data.data.reactions.totalCount,
});
}
});
axios.post(newGraphQLRoot, {
query: '{publications(first: 0) { totalCount edges { node { id } } }}' }).then((response) => {
if (response.data.data.reactions === null) {
this.setState({
loading: false,
error: true,
});
} else {
this.setState({
loading: false,
publications: response.data.data.publications.totalCount,
});
}
});
}
render() {
return (
<article>
{ whiteLabel === true ? null :
<Helmet
title="Home Page"
meta={[
{ name: 'description', content: `Catalysis-Hub.org is a frontend for browsing the SUNCAT CatApp database containing thousands of first-principles calculations related to heterogeneous catalysis reactions on surface systems. Its goal is to allow comprehensive and user-friendly access to raw quantum chemical simulations guided by heterogeneous catalysis concepts and commonly used graphical representations such as scaling relations and activity maps. All reaction energies are derived from periodic plane-wave density functional theory calculations. An increasing number of calculations contain the corresponding optimized geometry as well as further calculational details such as exchange-correlation (XC) functional, basis set quality, and k-point sampling. Ultimately, the goal is to provide fully self-contained data for predicting experimental observations from electronic structure calculations and using software packages such as Quantum Espresso, GPAW, VASP, and FHI-aims. Input and output with other codes is supported through the Atomic Simulation Environment (ASE). It may also serve as a natural starting point for training and developing machine-learning based approaches accelerating quantum chemical simulations.
Features include search for specific reaction energies, transition states, structures, exploration of scaling relations, activity maps, Pourbaix diagrams and machine learning models, as well as generation of novel bulk and surface structures. Calculations are linked to peer-review publications where available. The database can be queried via a GraphQL API that can also be accessed directly.
All code pertaining to this project is hosted as open-source under a liberal MIT license on github to encourage derived work and collaboration. The frontend is developed using the React Javascript framework based on react boilerplate. New components (apps) can be quickly spun-off and added to the project. The backend is developed using the Flask Python framework providing the GraphQL API as well as further APIs for specific apps.
As such Catalysis-Hub.org aims to serve as a starting point for trend studies and atomic based heterogeneous catalysis explorations.` },
{ name: 'robots', content: 'index,follow' },
{ name: 'keywords', content: 'heterogeneous catalysis,metals,density functional theory,scaling relations, activity maps,pourbaix diagrams,machine learning,quantum espresso,vasp,gpaw' },
{ name: 'DC.title', content: 'Catalysis-Hub.org' },
]}
/>
}
<div>
<CenteredSection className={this.props.classes.centeredSection}>
{whiteLabel ? null :
<Grid
container direction={isMobile ? 'column-reverse' : 'row'} justify="space-between"
className={this.props.classes.welcomeHeader}
>
<Grid item xs={isMobile ? 12 : 6}>
<H1 className={this.props.classes.welcome}>
Welcome to Catalysis-Hub.Org
</H1>
<div className={this.state.truncated ? this.props.classes.truncated : this.props.classes.expanded}>
<div>
Catalysis-Hub.org is a web-platform for sharing data and software for computational catalysis research.
The Surface Reactions database (CatApp v 2.0) contains thousands of reaction energies and barriers from density functional theory (DFT) calculations on surface systems.
</div>
<div>
Under Publications, reactions and surface geometries can also be browsed for each publication or dataset. With an increasing number of Apps, the platform allows comprehensive and user-friendly access to heterogeneous catalysis concepts and commonly used graphical representations such as scaling relations and activity maps.
An increasing number of calculations contain the corresponding optimized geometry as well as further calculational details such as exchange-correlation (XC) functional, basis set quality, and k-point sampling. Ultimately, the goal is to provide fully self-contained data for predicting experimental observations from electronic structure calculations and using software packages such as Quantum Espresso, GPAW, VASP, and FHI-aims. Input and output with other codes is supported through the Atomic Simulation Environment (ASE). It may also serve as a natural starting point for training and developing machine-learning based approaches accelerating quantum chemical simulations.
</div>
<div>
Features include search for specific reaction energies, transition states, structures, exploration of scaling relations, activity maps, Pourbaix diagrams and machine learning models, as well as generation of novel bulk and surface structures. Calculations are linked to peer-review publications where available. The database can be queried via a GraphQL API that can also be accessed directly.
</div>
<div>
All code pertaining to this project is hosted as open-source under a liberal MIT license on github to encourage derived work and collaboration. The frontend is developed using the React Javascript framework based on react boilerplate. New components (apps) can be quickly spun-off and added to the project. The backend is developed using the Flask Python framework providing the GraphQL API as well as further APIs for specific apps.
</div>
<div>
As such Catalysis-Hub.org aims to serve as a starting point for trend studies and atomic based heterogeneous catalysis explorations.
</div>
</div>
{this.state.truncated ?
<Button
mini
onClick={() => {
this.setState({
truncated: false,
});
}}
role="button"
>Read More <MdKeyboardArrowDown /></Button>
:
<Button
mini
onClick={() => {
this.setState({
truncated: true,
});
}}
role="button"
>
Read Less <MdKeyboardArrowUp />
</Button>
}
</Grid>
<Grid item xs={isMobile ? 12 : 6}>
<a href="https://suncat.stanford.edu" target="_blank">
<Img className={this.props.classes.banner} src={Banner} alt="SUNCAT - Logo" />
</a>
</Grid>
</Grid>
}
</CenteredSection>
<CenteredSection className={this.props.classes.centeredSection}>
{this.state.loading ? <div>Contacting database ... <LinearProgress color="primary" /></div> : null }
{this.state.error ? <div><MdWarning />Failed to contact database. </div> : null }
</CenteredSection>
<CenteredSection className={this.props.classes.centeredSection}>
<Slide mountOnEnter unmountOnExit in direction="left">
<div>
<Grid container justify="space-between">
<Grid item>
<Link to="/appsIndex" className={this.props.classes.textLink}>
<Paper
className={this.props.classes.homePaper}
>
<h3><MdApps size={20} /> Apps</h3>
<div className={this.props.classes.paperInfo}>
Web apps for exploring calculations
and finding new catalysts.
</div>
<Grid container direction="row" justify="space-between">
<Grid item>
<Chip label={apps.length} />
</Grid>
<Grid item>
<div className={this.props.classes.bold}>See our apps <MdArrowForward /></div>
</Grid>
</Grid>
</Paper>
</Link>
</Grid>
<Grid item>
<Link to="/energies" className={this.props.classes.textLink}>
<Paper
className={this.props.classes.homePaper}
elevation={0}
>
<h3> <FaDatabase size={20} /> Surface Reactions</h3>
<div className={this.props.classes.paperInfo}>
A database of first-principles reaction energies and barriers.
</div>
<Grid container direction="row" justify="space-between">
<Grid item>
<Chip label={withCommas(this.state.reactions)} />
</Grid>
<Grid item>
<div className={this.props.classes.bold}>See our reactions <MdArrowForward /></div>
</Grid>
</Grid>
</Paper>
</Link>
</Grid>
<Grid item>
<Link to="/publications" className={this.props.classes.textLink}>
<Paper
className={this.props.classes.homePaper}
elevation={0}
>
<h3> <FaNewspaperO size={20} /> Publications</h3>
<div className={this.props.classes.paperInfo}>A collection of scientic publications with atomic geometries.</div>
<Grid container direction="row" justify="space-between">
<Grid item>
<Chip label={this.state.publications} />
</Grid>
<Grid item className={this.props.classes.bold}>
See our publications <MdArrowForward />
</Grid>
</Grid>
</Paper>
</Link>
</Grid>
</Grid>
</div>
</Slide>
</CenteredSection>
</div>
</article>
);
}
}
HomePage.propTypes = {
onSubmitForm: React.PropTypes.func,
username: React.PropTypes.string,
classes: React.PropTypes.object,
};
export function mapDispatchToProps(dispatch) {
return {
onChangeUsername: (evt) => dispatch(changeUsername(evt.target.value)),
onSubmitForm: (evt) => {
if (evt !== undefined && evt.preventDefault) evt.preventDefault();
dispatch(loadRepos());
},
};
}
const mapStateToProps = createStructuredSelector({
repos: makeSelectRepos(),
username: makeSelectUsername(),
loading: makeSelectLoading(),
error: makeSelectError(),
});
// Wrap the component to inject dispatch and state into it
export default withStyles(styles, { withTheme: true })(connect(mapStateToProps, mapDispatchToProps)(HomePage));
| syntax update
| app/containers/HomePage/index.js | syntax update | <ide><path>pp/containers/HomePage/index.js
<ide> </H1>
<ide> <div className={this.state.truncated ? this.props.classes.truncated : this.props.classes.expanded}>
<ide> <div>
<del> Catalysis-Hub.org is a web-platform for sharing data and software for computational catalysis research.
<del> The Surface Reactions database (CatApp v 2.0) contains thousands of reaction energies and barriers from density functional theory (DFT) calculations on surface systems.
<del> </div>
<del> <div>
<del> Under Publications, reactions and surface geometries can also be browsed for each publication or dataset. With an increasing number of Apps, the platform allows comprehensive and user-friendly access to heterogeneous catalysis concepts and commonly used graphical representations such as scaling relations and activity maps.
<del> An increasing number of calculations contain the corresponding optimized geometry as well as further calculational details such as exchange-correlation (XC) functional, basis set quality, and k-point sampling. Ultimately, the goal is to provide fully self-contained data for predicting experimental observations from electronic structure calculations and using software packages such as Quantum Espresso, GPAW, VASP, and FHI-aims. Input and output with other codes is supported through the Atomic Simulation Environment (ASE). It may also serve as a natural starting point for training and developing machine-learning based approaches accelerating quantum chemical simulations.
<add> Catalysis-Hub.org is a web-platform for sharing data and software for computational catalysis research. The Surface Reactions database (CatApp v 2.0) contains thousands of reaction energies and barriers from density functional theory (DFT) calculations on surface systems.
<add> </div>
<add> <div>
<add> Under Publications, reactions and surface geometries can also be browsed for each publication or dataset. With an increasing number of Apps, the platform allows comprehensive and user-friendly access to heterogeneous catalysis concepts and commonly used graphical representations such as scaling relations and activity maps.
<add> An increasing number of calculations contain the corresponding optimized geometry as well as further calculational details such as exchange-correlation (XC) functional, basis set quality, and k-point sampling. Ultimately, the goal is to provide fully self-contained data for predicting experimental observations from electronic structure calculations and using software packages such as Quantum Espresso, GPAW, VASP, and FHI-aims. Input and output with other codes is supported through the Atomic Simulation Environment (ASE). It may also serve as a natural starting point for training and developing machine-learning based approaches accelerating quantum chemical simulations.
<ide> </div>
<ide> <div>
<ide> Features include search for specific reaction energies, transition states, structures, exploration of scaling relations, activity maps, Pourbaix diagrams and machine learning models, as well as generation of novel bulk and surface structures. Calculations are linked to peer-review publications where available. The database can be queried via a GraphQL API that can also be accessed directly. |
|
Java | apache-2.0 | dd6b89a1ec5ee2c4503a2a51097bcb0000c46c3e | 0 | quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus | package io.quarkus.gradle.tasks;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.gradle.api.GradleException;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.options.Option;
import io.quarkus.creator.AppCreator;
import io.quarkus.creator.AppCreatorException;
import io.quarkus.creator.phase.augment.AugmentOutcome;
import io.quarkus.creator.phase.nativeimage.NativeImageOutcome;
import io.quarkus.creator.phase.nativeimage.NativeImagePhase;
import io.quarkus.creator.phase.runnerjar.RunnerJarOutcome;
/**
* @author <a href="mailto:[email protected]">Ståle Pedersen</a>
*/
public class QuarkusNative extends QuarkusTask {
private boolean reportErrorsAtRuntime = false;
private boolean debugSymbols = false;
private boolean debugBuildProcess;
private boolean cleanupServer;
private boolean enableHttpUrlHandler;
private boolean enableHttpsUrlHandler;
private boolean enableAllSecurityServices;
private boolean enableRetainedHeapReporting;
private boolean enableIsolates;
private boolean enableCodeSizeReporting;
private String graalvmHome = System.getenv("GRAALVM_HOME");
private boolean enableServer = false;
private boolean enableJni = false;
private boolean autoServiceLoaderRegistration = false;
private boolean dumpProxies = false;
private String nativeImageXmx;
private String containerRuntime;
private String containerRuntimeOptions;
private String dockerBuild;
private boolean enableVMInspection = false;
private boolean enableFallbackImages = false;
private boolean fullStackTraces = true;
private boolean disableReports;
private List<String> additionalBuildArgs;
private boolean addAllCharsets = false;
private boolean reportExceptionStackTraces = true;
public QuarkusNative() {
super("Building a native image");
}
@Optional
@Input
public boolean isAddAllCharsets() {
return addAllCharsets;
}
@Option(description = "Should all Charsets supported by the host environment be included in the native image", option = "add-all-charsets")
public void setAddAllCharsets(final boolean addAllCharsets) {
this.addAllCharsets = addAllCharsets;
}
@Optional
@Input
public boolean isReportErrorsAtRuntime() {
return reportErrorsAtRuntime;
}
@Option(description = "Report errors at runtime", option = "report-errors-runtime")
public void setReportErrorsAtRuntime(boolean reportErrorsAtRuntime) {
this.reportErrorsAtRuntime = reportErrorsAtRuntime;
}
@Optional
@Input
public boolean isDebugSymbols() {
return debugSymbols;
}
@Option(description = "Specify if debug symbols should be set", option = "debug-symbols")
public void setDebugSymbols(boolean debugSymbols) {
this.debugSymbols = debugSymbols;
}
@Optional
@Input
public boolean isDebugBuildProcess() {
return debugBuildProcess;
}
@Option(description = "Specify if debug is set during build process", option = "debug-build-process")
public void setDebugBuildProcess(boolean debugBuildProcess) {
this.debugBuildProcess = debugBuildProcess;
}
@Optional
@Input
public boolean isCleanupServer() {
return cleanupServer;
}
@Option(description = "Cleanup server", option = "cleanup-server")
public void setCleanupServer(boolean cleanupServer) {
this.cleanupServer = cleanupServer;
}
@Optional
@Input
public boolean isEnableHttpUrlHandler() {
return enableHttpUrlHandler;
}
@Optional
@Input
private boolean isEnableFallbackImages() {
return enableFallbackImages;
}
@Option(description = "Enable the GraalVM native image compiler to generate Fallback Images in case of compilation error. "
+
"Careful: these are not as efficient as normal native images.", option = "enable-fallback-images")
public void setEnableFallbackImages(boolean enableFallbackImages) {
this.enableFallbackImages = enableFallbackImages;
}
@Option(description = "Specify if http url handler is enabled", option = "enable-http-url-handler")
public void setEnableHttpUrlHandler(boolean enableHttpUrlHandler) {
this.enableHttpUrlHandler = enableHttpUrlHandler;
}
@Optional
@Input
public boolean isEnableHttpsUrlHandler() {
return enableHttpsUrlHandler;
}
@Option(description = "Specify if https url handler is enabled", option = "enable-https-url-handler")
public void setEnableHttpsUrlHandler(boolean enableHttpsUrlHandler) {
this.enableHttpsUrlHandler = enableHttpsUrlHandler;
}
@Optional
@Input
public boolean isEnableAllSecurityServices() {
return enableAllSecurityServices;
}
@Option(description = "Enable all security services", option = "enable-all-security-services")
public void setEnableAllSecurityServices(boolean enableAllSecurityServices) {
this.enableAllSecurityServices = enableAllSecurityServices;
}
@Optional
@Input
public boolean isEnableRetainedHeapReporting() {
return enableRetainedHeapReporting;
}
@Option(description = "Specify if retained heap reporting should be enabled", option = "enable-retained-heap-reporting")
public void setEnableRetainedHeapReporting(boolean enableRetainedHeapReporting) {
this.enableRetainedHeapReporting = enableRetainedHeapReporting;
}
@Optional
@Input
public boolean isEnableIsolates() {
return enableIsolates;
}
@Option(description = "Report errors at runtime", option = "enable-isolates")
public void setEnableIsolates(boolean enableIsolates) {
this.enableIsolates = enableIsolates;
}
@Optional
@Input
public boolean isEnableCodeSizeReporting() {
return enableCodeSizeReporting;
}
@Option(description = "Report errors at runtime", option = "enable-code-size-reporting")
public void setEnableCodeSizeReporting(boolean enableCodeSizeReporting) {
this.enableCodeSizeReporting = enableCodeSizeReporting;
}
@Optional
@Input
public String getGraalvmHome() {
return graalvmHome;
}
@Option(description = "Specify the GraalVM directory (default to $GRAALVM_HOME)", option = "graalvm")
public void setGraalvmHome(String graalvmHome) {
this.graalvmHome = graalvmHome;
}
@Optional
@Input
public boolean isEnableServer() {
return enableServer;
}
@Option(description = "Enable server", option = "enable-server")
public void setEnableServer(boolean enableServer) {
this.enableServer = enableServer;
}
@Optional
@Input
public boolean isEnableJni() {
return enableJni;
}
@Option(description = "Enable jni", option = "enable-jni")
public void setEnableJni(boolean enableJni) {
this.enableJni = enableJni;
}
@Optional
@Input
public boolean isAutoServiceLoaderRegistration() {
return autoServiceLoaderRegistration;
}
@Option(description = "Auto ServiceLoader registration", option = "auto-serviceloader-registration")
public void setAutoServiceLoaderRegistration(boolean autoServiceLoaderRegistration) {
this.autoServiceLoaderRegistration = autoServiceLoaderRegistration;
}
@Optional
@Input
public boolean isDumpProxies() {
return dumpProxies;
}
@Option(description = "Dump proxies", option = "dump-proxies")
public void setDumpProxies(boolean dumpProxies) {
this.dumpProxies = dumpProxies;
}
@Optional
@Input
public String getNativeImageXmx() {
return nativeImageXmx;
}
@Option(description = "Specify the native image maximum heap size", option = "native-image-xmx")
public void setNativeImageXmx(String nativeImageXmx) {
this.nativeImageXmx = nativeImageXmx;
}
@Optional
@Input
public String getContainerRuntime() {
return containerRuntime;
}
@Optional
@Input
public String getContainerRuntimeOptions() {
return containerRuntimeOptions;
}
@Optional
@Input
public String getDockerBuild() {
return dockerBuild;
}
@Option(description = "Container runtime", option = "container-runtime")
@Optional
public void setContainerRuntime(String containerRuntime) {
this.containerRuntime = containerRuntime;
}
@Option(description = "Container runtime options", option = "container-runtime-options")
@Optional
public void setContainerRuntimeOptions(String containerRuntimeOptions) {
this.containerRuntimeOptions = containerRuntimeOptions;
}
@Option(description = "Docker build", option = "docker-build")
public void setDockerBuild(String dockerBuild) {
this.dockerBuild = dockerBuild;
}
@Optional
@Input
public boolean isEnableVMInspection() {
return enableVMInspection;
}
@Option(description = "Enable VM inspection", option = "enable-vm-inspection")
public void setEnableVMInspection(boolean enableVMInspection) {
this.enableVMInspection = enableVMInspection;
}
@Optional
@Input
public boolean isFullStackTraces() {
return fullStackTraces;
}
@Option(description = "Specify full stacktraces", option = "full-stacktraces")
public void setFullStackTraces(boolean fullStackTraces) {
this.fullStackTraces = fullStackTraces;
}
@Optional
@Input
public boolean isDisableReports() {
return disableReports;
}
@Option(description = "Disable reports", option = "disable-reports")
public void setDisableReports(boolean disableReports) {
this.disableReports = disableReports;
}
@Optional
@Input
public List<String> getAdditionalBuildArgs() {
return additionalBuildArgs;
}
@Option(description = "Additional build arguments", option = "additional-build-args")
public void setAdditionalBuildArgs(List<String> additionalBuildArgs) {
this.additionalBuildArgs = additionalBuildArgs;
}
@Optional
@Input
public boolean isReportExceptionStackTraces() {
return reportExceptionStackTraces;
}
@Option(description = "Show exception stack traces for exceptions during image building", option = "report-exception-stack-traces")
public void setReportExceptionStackTraces(boolean reportExceptionStackTraces) {
this.reportExceptionStackTraces = reportExceptionStackTraces;
}
@TaskAction
public void buildNative() {
getLogger().lifecycle("building native image");
try (AppCreator appCreator = AppCreator.builder()
// configure the build phase we want the app to go through
.addPhase(new NativeImagePhase()
.setAddAllCharsets(addAllCharsets)
.setAdditionalBuildArgs(getAdditionalBuildArgs())
.setAutoServiceLoaderRegistration(isAutoServiceLoaderRegistration())
.setOutputDir(getProject().getBuildDir().toPath())
.setCleanupServer(isCleanupServer())
.setDebugBuildProcess(isDebugBuildProcess())
.setDebugSymbols(isDebugSymbols())
.setDisableReports(isDisableReports())
.setContainerRuntime(getContainerRuntime())
.setContainerRuntimeOptions(getContainerRuntimeOptions())
.setDockerBuild(getDockerBuild())
.setDumpProxies(isDumpProxies())
.setEnableAllSecurityServices(isEnableAllSecurityServices())
.setEnableCodeSizeReporting(isEnableCodeSizeReporting())
.setEnableHttpsUrlHandler(isEnableHttpsUrlHandler())
.setEnableHttpUrlHandler(isEnableHttpUrlHandler())
.setEnableIsolates(isEnableIsolates())
.setEnableJni(isEnableJni())
.setEnableRetainedHeapReporting(isEnableRetainedHeapReporting())
.setEnableServer(isEnableServer())
.setEnableVMInspection(isEnableVMInspection())
.setEnableFallbackImages(isEnableFallbackImages())
.setFullStackTraces(isFullStackTraces())
.setGraalvmHome(getGraalvmHome())
.setNativeImageXmx(getNativeImageXmx())
.setReportErrorsAtRuntime(isReportErrorsAtRuntime())
.setReportExceptionStackTraces(isReportExceptionStackTraces()))
.build()) {
appCreator.pushOutcome(AugmentOutcome.class, new AugmentOutcome() {
final Path classesDir = extension().outputDirectory().toPath();
@Override
public Path getAppClassesDir() {
return classesDir;
}
@Override
public Path getTransformedClassesDir() {
// not relevant for this mojo
throw new UnsupportedOperationException();
}
@Override
public Path getWiringClassesDir() {
// not relevant for this mojo
throw new UnsupportedOperationException();
}
@Override
public Path getConfigDir() {
return extension().outputConfigDirectory().toPath();
}
@Override
public Map<Path, Set<String>> getTransformedClassesByJar() {
return Collections.emptyMap();
}
}).pushOutcome(RunnerJarOutcome.class, new RunnerJarOutcome() {
final Path runnerJar = getProject().getBuildDir().toPath().resolve(extension().finalName() + "-runner.jar");
final Path originalJar = getProject().getBuildDir().toPath().resolve(extension().finalName() + ".jar");
@Override
public Path getRunnerJar() {
return runnerJar;
}
@Override
public Path getLibDir() {
return runnerJar.getParent().resolve("lib");
}
@Override
public Path getOriginalJar() {
return originalJar;
}
}).resolveOutcome(NativeImageOutcome.class);
} catch (AppCreatorException e) {
throw new GradleException("Failed to generate a native image", e);
}
}
}
| devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusNative.java | package io.quarkus.gradle.tasks;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.gradle.api.GradleException;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.options.Option;
import io.quarkus.creator.AppCreator;
import io.quarkus.creator.AppCreatorException;
import io.quarkus.creator.phase.augment.AugmentOutcome;
import io.quarkus.creator.phase.nativeimage.NativeImageOutcome;
import io.quarkus.creator.phase.nativeimage.NativeImagePhase;
import io.quarkus.creator.phase.runnerjar.RunnerJarOutcome;
/**
* @author <a href="mailto:[email protected]">Ståle Pedersen</a>
*/
public class QuarkusNative extends QuarkusTask {
private boolean reportErrorsAtRuntime = false;
private boolean debugSymbols = false;
private boolean debugBuildProcess;
private boolean cleanupServer;
private boolean enableHttpUrlHandler;
private boolean enableHttpsUrlHandler;
private boolean enableAllSecurityServices;
private boolean enableRetainedHeapReporting;
private boolean enableIsolates;
private boolean enableCodeSizeReporting;
private String graalvmHome = System.getenv("GRAALVM_HOME");
private boolean enableServer = false;
private boolean enableJni = false;
private boolean autoServiceLoaderRegistration = false;
private boolean dumpProxies = false;
private String nativeImageXmx;
private String containerRuntime = "docker";
private String containerRuntimeOptions;
private String dockerBuild;
private boolean enableVMInspection = false;
private boolean enableFallbackImages = false;
private boolean fullStackTraces = true;
private boolean disableReports;
private List<String> additionalBuildArgs;
private boolean addAllCharsets = false;
private boolean reportExceptionStackTraces = true;
public QuarkusNative() {
super("Building a native image");
}
@Optional
@Input
public boolean isAddAllCharsets() {
return addAllCharsets;
}
@Option(description = "Should all Charsets supported by the host environment be included in the native image", option = "add-all-charsets")
public void setAddAllCharsets(final boolean addAllCharsets) {
this.addAllCharsets = addAllCharsets;
}
@Optional
@Input
public boolean isReportErrorsAtRuntime() {
return reportErrorsAtRuntime;
}
@Option(description = "Report errors at runtime", option = "report-errors-runtime")
public void setReportErrorsAtRuntime(boolean reportErrorsAtRuntime) {
this.reportErrorsAtRuntime = reportErrorsAtRuntime;
}
@Optional
@Input
public boolean isDebugSymbols() {
return debugSymbols;
}
@Option(description = "Specify if debug symbols should be set", option = "debug-symbols")
public void setDebugSymbols(boolean debugSymbols) {
this.debugSymbols = debugSymbols;
}
@Optional
@Input
public boolean isDebugBuildProcess() {
return debugBuildProcess;
}
@Option(description = "Specify if debug is set during build process", option = "debug-build-process")
public void setDebugBuildProcess(boolean debugBuildProcess) {
this.debugBuildProcess = debugBuildProcess;
}
@Optional
@Input
public boolean isCleanupServer() {
return cleanupServer;
}
@Option(description = "Cleanup server", option = "cleanup-server")
public void setCleanupServer(boolean cleanupServer) {
this.cleanupServer = cleanupServer;
}
@Optional
@Input
public boolean isEnableHttpUrlHandler() {
return enableHttpUrlHandler;
}
@Optional
@Input
private boolean isEnableFallbackImages() {
return enableFallbackImages;
}
@Option(description = "Enable the GraalVM native image compiler to generate Fallback Images in case of compilation error. "
+
"Careful: these are not as efficient as normal native images.", option = "enable-fallback-images")
public void setEnableFallbackImages(boolean enableFallbackImages) {
this.enableFallbackImages = enableFallbackImages;
}
@Option(description = "Specify if http url handler is enabled", option = "enable-http-url-handler")
public void setEnableHttpUrlHandler(boolean enableHttpUrlHandler) {
this.enableHttpUrlHandler = enableHttpUrlHandler;
}
@Optional
@Input
public boolean isEnableHttpsUrlHandler() {
return enableHttpsUrlHandler;
}
@Option(description = "Specify if https url handler is enabled", option = "enable-https-url-handler")
public void setEnableHttpsUrlHandler(boolean enableHttpsUrlHandler) {
this.enableHttpsUrlHandler = enableHttpsUrlHandler;
}
@Optional
@Input
public boolean isEnableAllSecurityServices() {
return enableAllSecurityServices;
}
@Option(description = "Enable all security services", option = "enable-all-security-services")
public void setEnableAllSecurityServices(boolean enableAllSecurityServices) {
this.enableAllSecurityServices = enableAllSecurityServices;
}
@Optional
@Input
public boolean isEnableRetainedHeapReporting() {
return enableRetainedHeapReporting;
}
@Option(description = "Specify if retained heap reporting should be enabled", option = "enable-retained-heap-reporting")
public void setEnableRetainedHeapReporting(boolean enableRetainedHeapReporting) {
this.enableRetainedHeapReporting = enableRetainedHeapReporting;
}
@Optional
@Input
public boolean isEnableIsolates() {
return enableIsolates;
}
@Option(description = "Report errors at runtime", option = "enable-isolates")
public void setEnableIsolates(boolean enableIsolates) {
this.enableIsolates = enableIsolates;
}
@Optional
@Input
public boolean isEnableCodeSizeReporting() {
return enableCodeSizeReporting;
}
@Option(description = "Report errors at runtime", option = "enable-code-size-reporting")
public void setEnableCodeSizeReporting(boolean enableCodeSizeReporting) {
this.enableCodeSizeReporting = enableCodeSizeReporting;
}
@Optional
@Input
public String getGraalvmHome() {
return graalvmHome;
}
@Option(description = "Specify the GraalVM directory (default to $GRAALVM_HOME)", option = "graalvm")
public void setGraalvmHome(String graalvmHome) {
this.graalvmHome = graalvmHome;
}
@Optional
@Input
public boolean isEnableServer() {
return enableServer;
}
@Option(description = "Enable server", option = "enable-server")
public void setEnableServer(boolean enableServer) {
this.enableServer = enableServer;
}
@Optional
@Input
public boolean isEnableJni() {
return enableJni;
}
@Option(description = "Enable jni", option = "enable-jni")
public void setEnableJni(boolean enableJni) {
this.enableJni = enableJni;
}
@Optional
@Input
public boolean isAutoServiceLoaderRegistration() {
return autoServiceLoaderRegistration;
}
@Option(description = "Auto ServiceLoader registration", option = "auto-serviceloader-registration")
public void setAutoServiceLoaderRegistration(boolean autoServiceLoaderRegistration) {
this.autoServiceLoaderRegistration = autoServiceLoaderRegistration;
}
@Optional
@Input
public boolean isDumpProxies() {
return dumpProxies;
}
@Option(description = "Dump proxies", option = "dump-proxies")
public void setDumpProxies(boolean dumpProxies) {
this.dumpProxies = dumpProxies;
}
@Optional
@Input
public String getNativeImageXmx() {
return nativeImageXmx;
}
@Option(description = "Specify the native image maximum heap size", option = "native-image-xmx")
public void setNativeImageXmx(String nativeImageXmx) {
this.nativeImageXmx = nativeImageXmx;
}
@Optional
@Input
public String getContainerRuntime() {
return containerRuntime;
}
@Optional
@Input
public String getContainerRuntimeOptions() {
return containerRuntimeOptions;
}
@Optional
@Input
public String getDockerBuild() {
return dockerBuild;
}
@Option(description = "Container runtime", option = "container-runtime")
@Optional
public void setContainerRuntime(String containerRuntime) {
this.containerRuntime = containerRuntime;
}
@Option(description = "Container runtime options", option = "container-runtime-options")
@Optional
public void setContainerRuntimeOptions(String containerRuntimeOptions) {
this.containerRuntimeOptions = containerRuntimeOptions;
}
@Option(description = "Docker build", option = "docker-build")
public void setDockerBuild(String dockerBuild) {
this.dockerBuild = dockerBuild;
}
@Optional
@Input
public boolean isEnableVMInspection() {
return enableVMInspection;
}
@Option(description = "Enable VM inspection", option = "enable-vm-inspection")
public void setEnableVMInspection(boolean enableVMInspection) {
this.enableVMInspection = enableVMInspection;
}
@Optional
@Input
public boolean isFullStackTraces() {
return fullStackTraces;
}
@Option(description = "Specify full stacktraces", option = "full-stacktraces")
public void setFullStackTraces(boolean fullStackTraces) {
this.fullStackTraces = fullStackTraces;
}
@Optional
@Input
public boolean isDisableReports() {
return disableReports;
}
@Option(description = "Disable reports", option = "disable-reports")
public void setDisableReports(boolean disableReports) {
this.disableReports = disableReports;
}
@Optional
@Input
public List<String> getAdditionalBuildArgs() {
return additionalBuildArgs;
}
@Option(description = "Additional build arguments", option = "additional-build-args")
public void setAdditionalBuildArgs(List<String> additionalBuildArgs) {
this.additionalBuildArgs = additionalBuildArgs;
}
@Optional
@Input
public boolean isReportExceptionStackTraces() {
return reportExceptionStackTraces;
}
@Option(description = "Show exception stack traces for exceptions during image building", option = "report-exception-stack-traces")
public void setReportExceptionStackTraces(boolean reportExceptionStackTraces) {
this.reportExceptionStackTraces = reportExceptionStackTraces;
}
@TaskAction
public void buildNative() {
getLogger().lifecycle("building native image");
try (AppCreator appCreator = AppCreator.builder()
// configure the build phase we want the app to go through
.addPhase(new NativeImagePhase()
.setAddAllCharsets(addAllCharsets)
.setAdditionalBuildArgs(getAdditionalBuildArgs())
.setAutoServiceLoaderRegistration(isAutoServiceLoaderRegistration())
.setOutputDir(getProject().getBuildDir().toPath())
.setCleanupServer(isCleanupServer())
.setDebugBuildProcess(isDebugBuildProcess())
.setDebugSymbols(isDebugSymbols())
.setDisableReports(isDisableReports())
.setContainerRuntime(getContainerRuntime())
.setContainerRuntimeOptions(getContainerRuntimeOptions())
.setDockerBuild(getDockerBuild())
.setDumpProxies(isDumpProxies())
.setEnableAllSecurityServices(isEnableAllSecurityServices())
.setEnableCodeSizeReporting(isEnableCodeSizeReporting())
.setEnableHttpsUrlHandler(isEnableHttpsUrlHandler())
.setEnableHttpUrlHandler(isEnableHttpUrlHandler())
.setEnableIsolates(isEnableIsolates())
.setEnableJni(isEnableJni())
.setEnableRetainedHeapReporting(isEnableRetainedHeapReporting())
.setEnableServer(isEnableServer())
.setEnableVMInspection(isEnableVMInspection())
.setEnableFallbackImages(isEnableFallbackImages())
.setFullStackTraces(isFullStackTraces())
.setGraalvmHome(getGraalvmHome())
.setNativeImageXmx(getNativeImageXmx())
.setReportErrorsAtRuntime(isReportErrorsAtRuntime())
.setReportExceptionStackTraces(isReportExceptionStackTraces()))
.build()) {
appCreator.pushOutcome(AugmentOutcome.class, new AugmentOutcome() {
final Path classesDir = extension().outputDirectory().toPath();
@Override
public Path getAppClassesDir() {
return classesDir;
}
@Override
public Path getTransformedClassesDir() {
// not relevant for this mojo
throw new UnsupportedOperationException();
}
@Override
public Path getWiringClassesDir() {
// not relevant for this mojo
throw new UnsupportedOperationException();
}
@Override
public Path getConfigDir() {
return extension().outputConfigDirectory().toPath();
}
@Override
public Map<Path, Set<String>> getTransformedClassesByJar() {
return Collections.emptyMap();
}
}).pushOutcome(RunnerJarOutcome.class, new RunnerJarOutcome() {
final Path runnerJar = getProject().getBuildDir().toPath().resolve(extension().finalName() + "-runner.jar");
final Path originalJar = getProject().getBuildDir().toPath().resolve(extension().finalName() + ".jar");
@Override
public Path getRunnerJar() {
return runnerJar;
}
@Override
public Path getLibDir() {
return runnerJar.getParent().resolve("lib");
}
@Override
public Path getOriginalJar() {
return originalJar;
}
}).resolveOutcome(NativeImageOutcome.class);
} catch (AppCreatorException e) {
throw new GradleException("Failed to generate a native image", e);
}
}
}
| Remove containerRuntime default value from Gradle plugin | devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusNative.java | Remove containerRuntime default value from Gradle plugin | <ide><path>evtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusNative.java
<ide>
<ide> private String nativeImageXmx;
<ide>
<del> private String containerRuntime = "docker";
<add> private String containerRuntime;
<ide>
<ide> private String containerRuntimeOptions;
<ide> |
|
Java | apache-2.0 | 9e5b850dfb81b8c9b690b5414a5fc6e6f0581d1b | 0 | jenkinsci/ez-templates-plugin,arpitgold/ez-templates,Brantone/ez-templates,Brantone/ez-templates,jet47/ez-templates,JoelJ/ez-templates,jenkinsci/ez-templates-plugin,jenkinsci/ez-templates-plugin,Brantone/ez-templates,arpitgold/ez-templates,JoelJ/ez-templates,JoelJ/ez-templates,jet47/ez-templates,arpitgold/ez-templates,jet47/ez-templates | package com.joelj.jenkins.eztemplates.utils;
import com.joelj.jenkins.eztemplates.TemplateImplementationProperty;
import com.joelj.jenkins.eztemplates.TemplateProperty;
import hudson.model.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This is where all the magic really happens.
* The templates and implementations, when they change, call one of the two public handle* methods.
* <p/>
* User: Joel Johnson
* Date: 2/25/13
* Time: 10:55 PM
*/
public class TemplateUtils {
private static final Logger LOG = Logger.getLogger("ez-templates");
public static void handleTemplate(AbstractProject templateProject, TemplateProperty property) throws IOException {
LOG.info("Template " + templateProject.getDisplayName() + " was saved. Syncing implementations. " + property);
}
public static void handleImplementation(AbstractProject implementationProject, TemplateImplementationProperty property) throws IOException {
LOG.info("Implementation " + implementationProject.getDisplayName() + " was saved. Syncing with " + property.getTemplateJobName());
AbstractProject templateProject = property.findProject();
@SuppressWarnings("unchecked")
boolean implementationIsTemplate = implementationProject.getProperty(TemplateProperty.class) != null;
List<ParameterDefinition> oldImplementationParameters = findParameters(implementationProject);
implementationProject = synchronizeConfigFiles(implementationProject, templateProject);
fixProperties(implementationProject, property, implementationIsTemplate);
fixParameters(implementationProject, oldImplementationParameters);
ProjectUtils.silentSave(implementationProject);
}
private static void fixParameters(AbstractProject implementationProject, List<ParameterDefinition> oldImplementationParameters) throws IOException {
List<ParameterDefinition> newImplementationParameters = findParameters(implementationProject);
ParametersDefinitionProperty newParameterAction = findParametersToKeep(oldImplementationParameters, newImplementationParameters);
@SuppressWarnings("unchecked") ParametersDefinitionProperty toRemove = (ParametersDefinitionProperty) implementationProject.getProperty(ParametersDefinitionProperty.class);
if (toRemove != null) {
//noinspection unchecked
implementationProject.removeProperty(toRemove);
}
if (newParameterAction != null) {
//noinspection unchecked
implementationProject.addProperty(newParameterAction);
}
}
private static ParametersDefinitionProperty findParametersToKeep(List<ParameterDefinition> oldImplementationParameters, List<ParameterDefinition> newImplementationParameters) {
List<ParameterDefinition> result = new LinkedList<ParameterDefinition>();
for (ParameterDefinition newImplementationParameter : newImplementationParameters) { //'new' parameters are the same as the template.
boolean found = false;
Iterator<ParameterDefinition> iterator = oldImplementationParameters.iterator();
while (iterator.hasNext()) {
ParameterDefinition oldImplementationParameter = iterator.next();
if (newImplementationParameter.getName().equals(oldImplementationParameter.getName())) {
found = true;
iterator.remove(); //Make the next iteration a little faster.
result.add(oldImplementationParameter);
}
}
if(!found) {
//Add new parameters not accounted for.
result.add(newImplementationParameter);
}
}
if(LOG.isLoggable(Level.INFO) && oldImplementationParameters != null && oldImplementationParameters.size() > 0) {
LOG.info("Throwing away parameters: ");
for (ParameterDefinition newImplementationParameter : oldImplementationParameters) {
LOG.info("\t"+newImplementationParameter.toString());
}
}
return new ParametersDefinitionProperty(result);
}
private static AbstractProject synchronizeConfigFiles(AbstractProject implementationProject, AbstractProject templateProject) throws IOException {
File templateConfigFile = templateProject.getConfigFile().getFile();
BufferedReader reader = new BufferedReader(new FileReader(templateConfigFile));
try {
Source source = new StreamSource(reader);
implementationProject = ProjectUtils.updateProjectWithXmlSource(implementationProject, source);
} finally {
reader.close();
}
return implementationProject;
}
private static List<ParameterDefinition> findParameters(AbstractProject implementationProject) {
List<ParameterDefinition> definitions = new LinkedList<ParameterDefinition>();
@SuppressWarnings("unchecked")
ParametersDefinitionProperty parametersDefinitionProperty = (ParametersDefinitionProperty) implementationProject.getProperty(ParametersDefinitionProperty.class);
if(parametersDefinitionProperty != null) {
for (String parameterName : parametersDefinitionProperty.getParameterDefinitionNames()) {
definitions.add(parametersDefinitionProperty.getParameterDefinition(parameterName));
}
}
return definitions;
}
private static void fixProperties(AbstractProject implementationProject, TemplateImplementationProperty property, boolean implementationIsTemplate) throws IOException {
//noinspection unchecked
implementationProject.addProperty(property);
if (!implementationIsTemplate) {
//noinspection unchecked
implementationProject.removeProperty(TemplateProperty.class);
}
}
}
| src/main/java/com/joelj/jenkins/eztemplates/utils/TemplateUtils.java | package com.joelj.jenkins.eztemplates.utils;
import com.joelj.jenkins.eztemplates.TemplateImplementationProperty;
import com.joelj.jenkins.eztemplates.TemplateProperty;
import hudson.model.*;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This is where all the magic really happens.
* The templates and implementations, when they change, call one of the two public handle* methods.
* <p/>
* User: Joel Johnson
* Date: 2/25/13
* Time: 10:55 PM
*/
public class TemplateUtils {
private static final Logger LOG = Logger.getLogger("ez-templates");
public static void handleTemplate(AbstractProject templateProject, TemplateProperty property) throws IOException {
LOG.info("Template " + templateProject.getDisplayName() + " was saved. Syncing implementations. " + property);
}
public static void handleImplementation(AbstractProject implementationProject, TemplateImplementationProperty property) throws IOException {
LOG.info("Implementation " + implementationProject.getDisplayName() + " was saved. Syncing with " + property.getTemplateJobName());
AbstractProject templateProject = property.findProject();
@SuppressWarnings("unchecked")
boolean implementationIsTemplate = implementationProject.getProperty(TemplateProperty.class) != null;
List<ParameterDefinition> oldImplementationParameters = findParameters(implementationProject);
implementationProject = synchronizeConfigFiles(implementationProject, templateProject);
fixProperties(implementationProject, property, implementationIsTemplate);
fixParameters(implementationProject, oldImplementationParameters);
ProjectUtils.silentSave(implementationProject);
}
private static void fixParameters(AbstractProject implementationProject, List<ParameterDefinition> oldImplementationParameters) throws IOException {
List<ParameterDefinition> newImplementationParameters = findParameters(implementationProject);
ParametersDefinitionProperty newParameterAction = findParametersToKeep(oldImplementationParameters, newImplementationParameters);
@SuppressWarnings("unchecked") ParametersDefinitionProperty toRemove = (ParametersDefinitionProperty) implementationProject.getProperty(ParametersDefinitionProperty.class);
if (toRemove != null) {
//noinspection unchecked
implementationProject.removeProperty(toRemove);
}
if (newParameterAction != null) {
//noinspection unchecked
implementationProject.addProperty(newParameterAction);
}
}
private static ParametersDefinitionProperty findParametersToKeep(List<ParameterDefinition> oldImplementationParameters, List<ParameterDefinition> newImplementationParameters) {
List<ParameterDefinition> result = new LinkedList<ParameterDefinition>();
for (ParameterDefinition newImplementationParameter : newImplementationParameters) { //'new' parameters are the same as the template.
boolean found = false;
Iterator<ParameterDefinition> iterator = oldImplementationParameters.iterator();
while (iterator.hasNext()) {
ParameterDefinition oldImplementationParameter = iterator.next();
if (newImplementationParameter.getName().equals(oldImplementationParameter.getName())) {
found = true;
iterator.remove(); //Make the next iteration a little faster.
result.add(oldImplementationParameter);
}
}
if(!found) {
//Add new parameters not accounted for.
result.add(newImplementationParameter);
}
}
if(LOG.isLoggable(Level.INFO)) {
LOG.info("Throwing away parameters: ");
for (ParameterDefinition newImplementationParameter : oldImplementationParameters) {
LOG.info("\t"+newImplementationParameter.toString());
}
}
return new ParametersDefinitionProperty(result);
}
private static AbstractProject synchronizeConfigFiles(AbstractProject implementationProject, AbstractProject templateProject) throws IOException {
File templateConfigFile = templateProject.getConfigFile().getFile();
BufferedReader reader = new BufferedReader(new FileReader(templateConfigFile));
try {
Source source = new StreamSource(reader);
implementationProject = ProjectUtils.updateProjectWithXmlSource(implementationProject, source);
} finally {
reader.close();
}
return implementationProject;
}
private static List<ParameterDefinition> findParameters(AbstractProject implementationProject) {
List<ParameterDefinition> definitions = new LinkedList<ParameterDefinition>();
@SuppressWarnings("unchecked")
ParametersDefinitionProperty parametersDefinitionProperty = (ParametersDefinitionProperty) implementationProject.getProperty(ParametersDefinitionProperty.class);
if(parametersDefinitionProperty != null) {
for (String parameterName : parametersDefinitionProperty.getParameterDefinitionNames()) {
definitions.add(parametersDefinitionProperty.getParameterDefinition(parameterName));
}
}
return definitions;
}
private static void fixProperties(AbstractProject implementationProject, TemplateImplementationProperty property, boolean implementationIsTemplate) throws IOException {
//noinspection unchecked
implementationProject.addProperty(property);
if (!implementationIsTemplate) {
//noinspection unchecked
implementationProject.removeProperty(TemplateProperty.class);
}
}
}
| only log when there's something to log about
| src/main/java/com/joelj/jenkins/eztemplates/utils/TemplateUtils.java | only log when there's something to log about | <ide><path>rc/main/java/com/joelj/jenkins/eztemplates/utils/TemplateUtils.java
<ide> }
<ide> }
<ide>
<del> if(LOG.isLoggable(Level.INFO)) {
<add> if(LOG.isLoggable(Level.INFO) && oldImplementationParameters != null && oldImplementationParameters.size() > 0) {
<ide> LOG.info("Throwing away parameters: ");
<ide> for (ParameterDefinition newImplementationParameter : oldImplementationParameters) {
<ide> LOG.info("\t"+newImplementationParameter.toString()); |
|
JavaScript | apache-2.0 | ff7b04c5bf1fb895b38832fb69594b36c1b091f2 | 0 | Victory/vPromise | (function () {
'use strict';
function debug() {
//console.log(arguments);
}
function skip() {}
var states = {
PENDING: 0,
FULFILLED: 1,
REJECTED: 2
};
var vPromise = function (fn) {
this._state = states.PENDING;
this.value = null;
this._resolveChain = [];
var that = this;
var onFulfilled = function (resolve) {
if (typeof resolve !== 'function') { // 2.2.1
return;
}
if (that._state !== states.PENDING) {
that._state = states.FULFILLED;
resolve(that.value);
}
};
var onReject = function (reject, reason) {
if (typeof reject !== 'function') { // 2.2.1
return;
}
if (that._state !== states.PENDING && that._state !== states.FULFILLED) {
that._state = states.REJECTED;
reject(reason);
}
};
var handle = function (resolve, reject) {
if (that._state === states.PENDING) {
return;
}
setTimeout(function () {
try {
fn(onFulfilled(resolve), onReject(reject, that.reason));
} catch (e) {
debug(e);
}
}, 1);
};
if (fn !== skip) {
fn(function (value) {
that.value = value;
setTimeout(function () {
if (that._state !== states.PENDING) {
return;
}
var ii;
var chainLength = that._resolveChain.length;
for (ii = 0; ii < chainLength; ii++) {
that._resolveChain[ii](value);
}
that._resolve(value);
that._state = states.FULFILLED;
}, 1);
},
function (reason) {
that.reason = reason;
setTimeout(function () {
if (that._state !== states.PENDING) {
return;
}
that._reject(reason);
that._state = states.REJECTED;
}, 1);
});
}
this.then = function (resolve, reject) {
if (that._state === states.PENDING) {
if (typeof that._resolve == "function") {
that._resolveChain.push(that._resolve);
}
that._resolve = resolve;
that._reject = reject;
return;
}
var next = new vPromise(fn);
handle(resolve, reject);
next._state = -1; // placeholder
return next;
};
this.catch = function (fn) {
};
return this;
};
vPromise.resolve = function (value) {
var skipped = new vPromise(skip);
return doResolve(skipped, value);
};
function doResolve(skipped, value) {
skipped._state = states.FULFILLED;
skipped.value = value;
return skipped;
}
vPromise.reject = function (reason) {
var skipped = new vPromise(skip);
return doReject(skipped, reason);
};
function doReject(skipped, reason) {
skipped._state = states.REJECTED;
skipped.reason = reason;
return skipped;
}
if (typeof module != 'undefined') {
module.exports = vPromise;
}
}());
| vPromise.js | (function () {
'use strict';
function debug() {
//console.log(arguments);
}
function skip() {}
var states = {
PENDING: 0,
FULFILLED: 1,
REJECTED: 2
};
var vPromise = function (fn) {
this._state = states.PENDING;
this.value = null;
var that = this;
var onFulfilled = function (resolve) {
if (typeof resolve !== 'function') { // 2.2.1
return;
}
if (that._state !== states.PENDING) {
that._state = states.FULFILLED;
resolve(that.value);
}
};
var onReject = function (reject, reason) {
if (typeof reject !== 'function') { // 2.2.1
return;
}
if (that._state !== states.PENDING && that._state !== states.FULFILLED) {
that._state = states.REJECTED;
reject(reason);
}
};
var handle = function (resolve, reject) {
if (that._state === states.PENDING) {
return;
}
setTimeout(function () {
try {
fn(onFulfilled(resolve), onReject(reject, that.reason));
} catch (e) {
debug(e);
}
}, 1);
};
if (fn !== skip) {
fn(function (value) {
that.value = value;
setTimeout(function () {
if (that._state !== states.PENDING) {
return;
}
that._resolve(value);
that._state = states.FULFILLED;
}, 1);
},
function (reason) {
that.reason = reason;
setTimeout(function () {
if (that._state !== states.PENDING) {
return;
}
that._reject(reason);
that._state = states.REJECTED;
}, 1);
});
}
this.then = function (resolve, reject) {
if (that._state === states.PENDING) {
that._resolve = resolve;
that._reject = reject;
return;
}
var next = new vPromise(fn);
handle(resolve, reject);
next._state = -1; // placeholder
return next;
};
this.catch = function (fn) {
};
return this;
};
vPromise.resolve = function (value) {
var skipped = new vPromise(skip);
return doResolve(skipped, value);
};
function doResolve(skipped, value) {
skipped._state = states.FULFILLED;
skipped.value = value;
return skipped;
}
vPromise.reject = function (reason) {
var skipped = new vPromise(skip);
return doReject(skipped, reason);
};
function doReject(skipped, reason) {
skipped._state = states.REJECTED;
skipped.reason = reason;
return skipped;
}
if (typeof module != 'undefined') {
module.exports = vPromise;
}
}());
| Get 2.2.6.1 to pass
| vPromise.js | Get 2.2.6.1 to pass | <ide><path>Promise.js
<ide> var vPromise = function (fn) {
<ide> this._state = states.PENDING;
<ide> this.value = null;
<add> this._resolveChain = [];
<ide> var that = this;
<ide>
<ide> var onFulfilled = function (resolve) {
<ide> if (that._state !== states.PENDING) {
<ide> return;
<ide> }
<add> var ii;
<add> var chainLength = that._resolveChain.length;
<add> for (ii = 0; ii < chainLength; ii++) {
<add> that._resolveChain[ii](value);
<add> }
<ide> that._resolve(value);
<ide> that._state = states.FULFILLED;
<ide> }, 1);
<ide>
<ide> this.then = function (resolve, reject) {
<ide> if (that._state === states.PENDING) {
<add> if (typeof that._resolve == "function") {
<add> that._resolveChain.push(that._resolve);
<add> }
<ide> that._resolve = resolve;
<ide> that._reject = reject;
<ide> return; |
|
Java | mit | e79e13435545aa4435a298c5f5077d00503d5737 | 0 | noogotte/UsefulCommands | package fr.noogotte.useful_commands.command;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import fr.aumgn.bukkitutils.command.Command;
import fr.aumgn.bukkitutils.command.CommandArgs;
import fr.aumgn.bukkitutils.command.NestedCommands;
import fr.aumgn.bukkitutils.command.exception.CommandUsageError;
@NestedCommands(name = "useful")
public class WorldCommands extends UsefulCommands {
@Command(name = "seed", min = 0, max = 1)
public void seed(Player player, CommandArgs args) {
World world = args.getWorld(0, player.getWorld());
player.sendMessage(ChatColor.GREEN + "Seed : "
+ ChatColor.BLUE + world.getSeed());
}
@Command(name = "setspawn", min = 0, max = 0)
public void setSpawn(Player player, CommandArgs args) {
Location playerloc = player.getLocation();
player.getWorld().setSpawnLocation(
playerloc.getBlockX(),
playerloc.getBlockY(),
playerloc.getBlockZ());
player.sendMessage(ChatColor.GREEN + "Vous avez mis le spawn !");
}
@Command(name = "time", min = 1, max = 2)
public void time(Player player, CommandArgs args) {
String arg = args.get(0);
World world = args.getWorld(1, player.getWorld());
if (arg.equalsIgnoreCase("day")) {
world.setTime(20 * 60);
player.sendMessage(ChatColor.GOLD
+ "Vous avez mis le jour dans "
+ ChatColor.AQUA + world.getName());
} else if (arg.equalsIgnoreCase("night")) {
world.setTime(20 * 60 * 11);
player.sendMessage(ChatColor.GOLD
+"Vous avez mis la nuit dans "
+ ChatColor.AQUA + world.getName());
} else {
throw new CommandUsageError(
"Argument " + arg + " inconnu.");
}
}
@Command(name = "weather", min = 1, max = 2)
public void weather(Player player, CommandArgs args) {
String arg = args.get(0);
World world = args.getWorld(1, player.getWorld());
if (arg.equalsIgnoreCase("sun")) {
world.setStorm(false);
player.sendMessage(ChatColor.GOLD
+ "Vous avez mis le soleil dans "
+ ChatColor.AQUA + world.getName());
} else if(arg.equalsIgnoreCase("storm")) {
world.setStorm(true);
player.sendMessage(ChatColor.GOLD
+ "Vous avez mis la pluie dans "
+ ChatColor.AQUA + world.getName());
} else {
throw new CommandUsageError(
"Argument " + arg + " inconnu.");
}
}
}
| src/main/java/fr/noogotte/useful_commands/command/WorldCommands.java | package fr.noogotte.useful_commands.command;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import fr.aumgn.bukkitutils.command.Command;
import fr.aumgn.bukkitutils.command.CommandArgs;
import fr.aumgn.bukkitutils.command.NestedCommands;
import fr.aumgn.bukkitutils.command.exception.CommandUsageError;
@NestedCommands(name = "useful")
public class WorldCommands extends UsefulCommands {
@Command(name = "seed", min = 0, max = 1)
public void seed(Player player, CommandArgs args) {
World world = args.getWorld(0, player.getWorld());
player.sendMessage(ChatColor.GREEN + "Seed : "
+ ChatColor.BLUE + world.getSeed());
}
@Command(name = "setspawn", min = 0, max = 0)
public void setSpawn(Player player, CommandArgs args) {
Location playerloc = player.getLocation();
player.getWorld().setSpawnLocation(
playerloc.getBlockX(),
playerloc.getBlockY(),
playerloc.getBlockZ());
player.sendMessage(ChatColor.GREEN + "Vous avez mis le spawn !");
}
@Command(name = "time", min = 1, max = 2)
public void time(Player player, CommandArgs args) {
String arg = args.get(0);
World world = args.getWorld(1, player.getWorld());
if (arg.equalsIgnoreCase("day")) {
world.setTime(20 * 60);
player.sendMessage(ChatColor.GOLD
+ "Vous avez mis le jour dans "
+ ChatColor.AQUA + player.getWorld().getName());
} else if (arg.equalsIgnoreCase("night")) {
world.setTime(20 * 60 * 11);
player.sendMessage(ChatColor.GOLD
+"Vous avez mis la nuit dans "
+ ChatColor.AQUA + player.getWorld().getName());
} else {
throw new CommandUsageError(
"Argument " + arg + " inconnu.");
}
}
@Command(name = "weather", min = 1, max = 2)
public void weather(Player player, CommandArgs args) {
String arg = args.get(0);
World world = args.getWorld(1, player.getWorld());
if (arg.equalsIgnoreCase("sun")) {
world.setStorm(false);
player.sendMessage(ChatColor.GOLD
+ "Vous avez mis le soleil dans "
+ ChatColor.AQUA + player.getWorld().getName());
} else if(arg.equalsIgnoreCase("storm")) {
world.setStorm(true);
player.sendMessage(ChatColor.GOLD
+ "Vous avez mis la pluie dans "
+ ChatColor.AQUA + player.getWorld().getName());
} else {
throw new CommandUsageError(
"Argument " + arg + " inconnu.");
}
}
}
| fix message for /time and /weather command | src/main/java/fr/noogotte/useful_commands/command/WorldCommands.java | fix message for /time and /weather command | <ide><path>rc/main/java/fr/noogotte/useful_commands/command/WorldCommands.java
<ide> world.setTime(20 * 60);
<ide> player.sendMessage(ChatColor.GOLD
<ide> + "Vous avez mis le jour dans "
<del> + ChatColor.AQUA + player.getWorld().getName());
<add> + ChatColor.AQUA + world.getName());
<ide> } else if (arg.equalsIgnoreCase("night")) {
<del> world.setTime(20 * 60 * 11);
<add> world.setTime(20 * 60 * 11);
<ide> player.sendMessage(ChatColor.GOLD
<ide> +"Vous avez mis la nuit dans "
<del> + ChatColor.AQUA + player.getWorld().getName());
<add> + ChatColor.AQUA + world.getName());
<ide> } else {
<ide> throw new CommandUsageError(
<ide> "Argument " + arg + " inconnu.");
<ide> world.setStorm(false);
<ide> player.sendMessage(ChatColor.GOLD
<ide> + "Vous avez mis le soleil dans "
<del> + ChatColor.AQUA + player.getWorld().getName());
<add> + ChatColor.AQUA + world.getName());
<ide> } else if(arg.equalsIgnoreCase("storm")) {
<ide> world.setStorm(true);
<ide> player.sendMessage(ChatColor.GOLD
<ide> + "Vous avez mis la pluie dans "
<del> + ChatColor.AQUA + player.getWorld().getName());
<add> + ChatColor.AQUA + world.getName());
<ide> } else {
<ide> throw new CommandUsageError(
<ide> "Argument " + arg + " inconnu."); |
|
Java | mit | 432617700e89969f3d94b6b1d052b97ef4d04fd4 | 0 | jenniferlarsson/KD405A_Jennifer_L,jenniferlarsson/KD405A_Jennifer_L,jenniferlarsson/KD405A_Jennifer_L | package se.mah.ke.jenniferlarsson;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.FormSpecs;
import com.jgoodies.forms.layout.RowSpec;
import javax.swing.JToolBar;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.ImageIcon;
import java.awt.Color;
public class Main extends JFrame {
private JPanel contentPane;
private JTable table;
private JTextField txtBertNilsson;
private JTextField textField;
private JTextField txtMunkhttegatan;
private JTextField textField_1;
private JTextField txtBerraalltomfiskse;
private JTextField txtBerrapng;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
DefaultTableModel model = new DefaultTableModel(new Object[][] {
{ "Bert Nilsson" }, { "Jennifer Larsson" }, { "Lars Jennifersson" },
{ "Berit Bengtsson" }, { "Mona-Lisa Målarberg" }, {"Johanno Knatsson"} },
new Object[] { "Medlemmar"});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 608, 375);
setBounds(100, 100, 655, 394);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JLabel lblNewLabel_1 = new JLabel("");
menuBar.add(lblNewLabel_1);
lblNewLabel_1.setIcon(new ImageIcon("/Users/jela/Desktop/friskis och svettis.jpg"));
JMenu mnArkiv = new JMenu("Arkiv");
menuBar.add(mnArkiv);
JMenuItem mntmPrint = new JMenuItem("Skriv Ut");
mnArkiv.add(mntmPrint);
JMenuItem mntmAvsluta = new JMenuItem("Avsluta");
mnArkiv.add(mntmAvsluta);
JMenu mnMedlem = new JMenu("Medlem");
menuBar.add(mnMedlem);
JMenuItem mntmNyMedlem = new JMenuItem("Ny Medlem");
mnMedlem.add(mntmNyMedlem);
JMenuItem mntmHittaMedlem = new JMenuItem("Hitta Medlem");
mnMedlem.add(mntmHittaMedlem);
JMenu mnHjlp = new JMenu("Hjälp");
menuBar.add(mnHjlp);
JMenuItem mntmHjlp = new JMenuItem("Hjälp");
mnHjlp.add(mntmHjlp);
JMenuItem mntmOmProgrammet = new JMenuItem("Om Programmet");
mnHjlp.add(mntmOmProgrammet);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(0, 2, 0, 0));
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane);
table = new JTable(model);
table.setToolTipText("Alla Medlemmar");
scrollPane.setViewportView(table);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
contentPane.add(panel);
panel.setLayout(null);
JLabel lblNamn = new JLabel("Namn");
gbc_lblNamn.gridx = 1;
lblNamn.setBounds(0, 0, 0, 0);
panel.add(lblNamn);
txtBertNilsson = new JTextField();
txtBertNilsson.setBounds(0, 0, 0, 0);
txtBertNilsson.setText("Bert Nilsson");
panel.add(txtBertNilsson);
txtBertNilsson.setColumns(10);
JLabel lblPersonnr = new JLabel("Personnr");
lblPersonnr.setBounds(34, 0, 55, 13);
panel.add(lblPersonnr);
textField = new JTextField();
textField.setBounds(138, 0, 146, 18);
textField.setText("7212231653");
panel.add(textField);
textField.setColumns(10);
JLabel lblAdress = new JLabel("Adress");
lblAdress.setBounds(34, 28, 43, 16);
panel.add(lblAdress);
txtMunkhttegatan = new JTextField();
txtMunkhttegatan.setBounds(138, 23, 146, 26);
txtMunkhttegatan.setText("Munkhättegatan 32");
panel.add(txtMunkhttegatan);
txtMunkhttegatan.setColumns(10);
JLabel lblTelefonnummer = new JLabel("Telefonnummer");
lblTelefonnummer.setBounds(34, 59, 99, 16);
panel.add(lblTelefonnummer);
textField_1 = new JTextField();
textField_1.setBounds(138, 54, 146, 26);
textField_1.setText("040-231213");
panel.add(textField_1);
textField_1.setColumns(10);
JLabel lblEmail = new JLabel("Email");
lblEmail.setBounds(34, 90, 34, 16);
panel.add(lblEmail);
txtBerraalltomfiskse = new JTextField();
txtBerraalltomfiskse.setBounds(138, 85, 146, 26);
txtBerraalltomfiskse.setText("[email protected]");
panel.add(txtBerraalltomfiskse);
txtBerraalltomfiskse.setColumns(10);
JLabel lblBild = new JLabel("Bild");
lblBild.setBounds(34, 121, 23, 16);
panel.add(lblBild);
txtBerrapng = new JTextField();
txtBerrapng.setBounds(138, 116, 146, 26);
txtBerrapng.setText("berra.png");
panel.add(txtBerrapng);
txtBerrapng.setColumns(10);
JButton btnSpara = new JButton("Spara");
btnSpara.setBounds(172, 199, 78, 37);
panel.add(btnSpara);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon("/Users/jela/Desktop/berrabild.jpg"));
lblNewLabel.setBounds(27, 149, 84, 95);
panel.add(lblNewLabel);
}
}
| Assignment_1/src/se/mah/ke/jenniferlarsson/Main.java | package se.mah.ke.jenniferlarsson;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.FormSpecs;
import com.jgoodies.forms.layout.RowSpec;
import javax.swing.JToolBar;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.BoxLayout;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
public class Main extends JFrame {
private JPanel contentPane;
private JTable table;
private JTextField txtBertNilsson;
private JTextField textField;
private JTextField txtMunkhttegatan;
private JTextField textField_1;
private JTextField txtBerraalltomfiskse;
private JTextField txtBerrapng;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
DefaultTableModel model = new DefaultTableModel(new Object[][] {
{ "Bert Nilsson" }, { "Jennifer Larsson" }, { "Lars Jennifersson" },
{ "Berit Bengtsson" }, { "Mona-Lisa Målarberg" }, {"Johanno Knatsson"} },
new Object[] { "Medlemmar"});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 608, 375);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnArkiv = new JMenu("Arkiv");
menuBar.add(mnArkiv);
JMenuItem mntmPrint = new JMenuItem("Skriv Ut");
mnArkiv.add(mntmPrint);
JMenuItem mntmAvsluta = new JMenuItem("Avsluta");
mnArkiv.add(mntmAvsluta);
JMenu mnMedlem = new JMenu("Medlem");
menuBar.add(mnMedlem);
JMenuItem mntmNyMedlem = new JMenuItem("Ny Medlem");
mnMedlem.add(mntmNyMedlem);
JMenuItem mntmHittaMedlem = new JMenuItem("Hitta Medlem");
mnMedlem.add(mntmHittaMedlem);
JMenu mnHjlp = new JMenu("Hjälp");
menuBar.add(mnHjlp);
JMenuItem mntmHjlp = new JMenuItem("Hjälp");
mnHjlp.add(mntmHjlp);
JMenuItem mntmOmProgrammet = new JMenuItem("Om Programmet");
mnHjlp.add(mntmOmProgrammet);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(0, 2, 0, 0));
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane);
table = new JTable(model);
table.setToolTipText("Alla Medlemmar");
scrollPane.setViewportView(table);
JPanel panel = new JPanel();
contentPane.add(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{34, 99, 146, 0};
gbl_panel.rowHeights = new int[]{26, 26, 26, 26, 26, 26, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblNamn = new JLabel("Namn");
GridBagConstraints gbc_lblNamn = new GridBagConstraints();
gbc_lblNamn.anchor = GridBagConstraints.WEST;
gbc_lblNamn.insets = new Insets(0, 0, 5, 5);
gbc_lblNamn.gridx = 1;
gbc_lblNamn.gridy = 0;
panel.add(lblNamn, gbc_lblNamn);
txtBertNilsson = new JTextField();
txtBertNilsson.setText("Bert Nilsson");
GridBagConstraints gbc_txtBertNilsson = new GridBagConstraints();
gbc_txtBertNilsson.anchor = GridBagConstraints.NORTHWEST;
gbc_txtBertNilsson.insets = new Insets(0, 0, 5, 0);
gbc_txtBertNilsson.gridx = 2;
gbc_txtBertNilsson.gridy = 0;
panel.add(txtBertNilsson, gbc_txtBertNilsson);
txtBertNilsson.setColumns(10);
JLabel lblPersonnr = new JLabel("Personnr");
GridBagConstraints gbc_lblPersonnr = new GridBagConstraints();
gbc_lblPersonnr.anchor = GridBagConstraints.WEST;
gbc_lblPersonnr.insets = new Insets(0, 0, 5, 5);
gbc_lblPersonnr.gridx = 1;
gbc_lblPersonnr.gridy = 1;
panel.add(lblPersonnr, gbc_lblPersonnr);
textField = new JTextField();
textField.setText("7212231653");
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.anchor = GridBagConstraints.NORTH;
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.gridx = 2;
gbc_textField.gridy = 1;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel lblAdress = new JLabel("Adress");
GridBagConstraints gbc_lblAdress = new GridBagConstraints();
gbc_lblAdress.anchor = GridBagConstraints.WEST;
gbc_lblAdress.insets = new Insets(0, 0, 5, 5);
gbc_lblAdress.gridx = 1;
gbc_lblAdress.gridy = 2;
panel.add(lblAdress, gbc_lblAdress);
txtMunkhttegatan = new JTextField();
txtMunkhttegatan.setText("Munkhättegatan 32");
GridBagConstraints gbc_txtMunkhttegatan = new GridBagConstraints();
gbc_txtMunkhttegatan.anchor = GridBagConstraints.NORTH;
gbc_txtMunkhttegatan.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMunkhttegatan.insets = new Insets(0, 0, 5, 0);
gbc_txtMunkhttegatan.gridx = 2;
gbc_txtMunkhttegatan.gridy = 2;
panel.add(txtMunkhttegatan, gbc_txtMunkhttegatan);
txtMunkhttegatan.setColumns(10);
JLabel lblTelefonnummer = new JLabel("Telefonnummer");
GridBagConstraints gbc_lblTelefonnummer = new GridBagConstraints();
gbc_lblTelefonnummer.anchor = GridBagConstraints.WEST;
gbc_lblTelefonnummer.insets = new Insets(0, 0, 5, 5);
gbc_lblTelefonnummer.gridx = 1;
gbc_lblTelefonnummer.gridy = 3;
panel.add(lblTelefonnummer, gbc_lblTelefonnummer);
textField_1 = new JTextField();
textField_1.setText("040-231213");
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.anchor = GridBagConstraints.NORTH;
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.insets = new Insets(0, 0, 5, 0);
gbc_textField_1.gridx = 2;
gbc_textField_1.gridy = 3;
panel.add(textField_1, gbc_textField_1);
textField_1.setColumns(10);
JLabel lblEmail = new JLabel("Email");
GridBagConstraints gbc_lblEmail = new GridBagConstraints();
gbc_lblEmail.anchor = GridBagConstraints.WEST;
gbc_lblEmail.insets = new Insets(0, 0, 5, 5);
gbc_lblEmail.gridx = 1;
gbc_lblEmail.gridy = 4;
panel.add(lblEmail, gbc_lblEmail);
txtBerraalltomfiskse = new JTextField();
txtBerraalltomfiskse.setText("[email protected]");
GridBagConstraints gbc_txtBerraalltomfiskse = new GridBagConstraints();
gbc_txtBerraalltomfiskse.anchor = GridBagConstraints.NORTH;
gbc_txtBerraalltomfiskse.fill = GridBagConstraints.HORIZONTAL;
gbc_txtBerraalltomfiskse.insets = new Insets(0, 0, 5, 0);
gbc_txtBerraalltomfiskse.gridx = 2;
gbc_txtBerraalltomfiskse.gridy = 4;
panel.add(txtBerraalltomfiskse, gbc_txtBerraalltomfiskse);
txtBerraalltomfiskse.setColumns(10);
JLabel lblBild = new JLabel("Bild");
GridBagConstraints gbc_lblBild = new GridBagConstraints();
gbc_lblBild.anchor = GridBagConstraints.WEST;
gbc_lblBild.insets = new Insets(0, 0, 5, 5);
gbc_lblBild.gridx = 1;
gbc_lblBild.gridy = 5;
panel.add(lblBild, gbc_lblBild);
txtBerrapng = new JTextField();
txtBerrapng.setText("berra.png");
GridBagConstraints gbc_txtBerrapng = new GridBagConstraints();
gbc_txtBerrapng.insets = new Insets(0, 0, 5, 0);
gbc_txtBerrapng.anchor = GridBagConstraints.NORTH;
gbc_txtBerrapng.fill = GridBagConstraints.HORIZONTAL;
gbc_txtBerrapng.gridx = 2;
gbc_txtBerrapng.gridy = 5;
panel.add(txtBerrapng, gbc_txtBerrapng);
txtBerrapng.setColumns(10);
JButton btnSpara = new JButton("Spara");
GridBagConstraints gbc_btnSpara = new GridBagConstraints();
gbc_btnSpara.gridx = 2;
gbc_btnSpara.gridy = 9;
panel.add(btnSpara, gbc_btnSpara);
}
}
| la till bilder
| Assignment_1/src/se/mah/ke/jenniferlarsson/Main.java | la till bilder | <ide><path>ssignment_1/src/se/mah/ke/jenniferlarsson/Main.java
<ide> import java.awt.GridBagLayout;
<ide> import java.awt.GridBagConstraints;
<ide> import java.awt.Insets;
<add>import javax.swing.ImageIcon;
<add>import java.awt.Color;
<ide>
<ide> public class Main extends JFrame {
<ide>
<ide> { "Bert Nilsson" }, { "Jennifer Larsson" }, { "Lars Jennifersson" },
<ide> { "Berit Bengtsson" }, { "Mona-Lisa Målarberg" }, {"Johanno Knatsson"} },
<ide> new Object[] { "Medlemmar"});
<del>
<ide>
<ide> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
<ide> setBounds(100, 100, 608, 375);
<add> setBounds(100, 100, 655, 394);
<ide>
<ide> JMenuBar menuBar = new JMenuBar();
<ide> setJMenuBar(menuBar);
<add>
<add> JLabel lblNewLabel_1 = new JLabel("");
<add> menuBar.add(lblNewLabel_1);
<add> lblNewLabel_1.setIcon(new ImageIcon("/Users/jela/Desktop/friskis och svettis.jpg"));
<ide>
<ide> JMenu mnArkiv = new JMenu("Arkiv");
<ide> menuBar.add(mnArkiv);
<ide> scrollPane.setViewportView(table);
<ide>
<ide> JPanel panel = new JPanel();
<add> panel.setBackground(Color.WHITE);
<ide> contentPane.add(panel);
<del> GridBagLayout gbl_panel = new GridBagLayout();
<del> gbl_panel.columnWidths = new int[]{34, 99, 146, 0};
<del> gbl_panel.rowHeights = new int[]{26, 26, 26, 26, 26, 26, 0, 0, 0, 0, 0};
<del> gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
<del> gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
<del> panel.setLayout(gbl_panel);
<add> panel.setLayout(null);
<ide>
<ide> JLabel lblNamn = new JLabel("Namn");
<del> GridBagConstraints gbc_lblNamn = new GridBagConstraints();
<del> gbc_lblNamn.anchor = GridBagConstraints.WEST;
<del> gbc_lblNamn.insets = new Insets(0, 0, 5, 5);
<ide> gbc_lblNamn.gridx = 1;
<del> gbc_lblNamn.gridy = 0;
<del> panel.add(lblNamn, gbc_lblNamn);
<add> lblNamn.setBounds(0, 0, 0, 0);
<add> panel.add(lblNamn);
<ide>
<ide> txtBertNilsson = new JTextField();
<add> txtBertNilsson.setBounds(0, 0, 0, 0);
<ide> txtBertNilsson.setText("Bert Nilsson");
<del> GridBagConstraints gbc_txtBertNilsson = new GridBagConstraints();
<del> gbc_txtBertNilsson.anchor = GridBagConstraints.NORTHWEST;
<del> gbc_txtBertNilsson.insets = new Insets(0, 0, 5, 0);
<del> gbc_txtBertNilsson.gridx = 2;
<del> gbc_txtBertNilsson.gridy = 0;
<del> panel.add(txtBertNilsson, gbc_txtBertNilsson);
<add> panel.add(txtBertNilsson);
<ide> txtBertNilsson.setColumns(10);
<ide>
<ide> JLabel lblPersonnr = new JLabel("Personnr");
<del> GridBagConstraints gbc_lblPersonnr = new GridBagConstraints();
<del> gbc_lblPersonnr.anchor = GridBagConstraints.WEST;
<del> gbc_lblPersonnr.insets = new Insets(0, 0, 5, 5);
<del> gbc_lblPersonnr.gridx = 1;
<del> gbc_lblPersonnr.gridy = 1;
<del> panel.add(lblPersonnr, gbc_lblPersonnr);
<add> lblPersonnr.setBounds(34, 0, 55, 13);
<add> panel.add(lblPersonnr);
<ide>
<ide> textField = new JTextField();
<add> textField.setBounds(138, 0, 146, 18);
<ide> textField.setText("7212231653");
<del> GridBagConstraints gbc_textField = new GridBagConstraints();
<del> gbc_textField.anchor = GridBagConstraints.NORTH;
<del> gbc_textField.fill = GridBagConstraints.HORIZONTAL;
<del> gbc_textField.insets = new Insets(0, 0, 5, 0);
<del> gbc_textField.gridx = 2;
<del> gbc_textField.gridy = 1;
<del> panel.add(textField, gbc_textField);
<add> panel.add(textField);
<ide> textField.setColumns(10);
<ide>
<ide> JLabel lblAdress = new JLabel("Adress");
<del> GridBagConstraints gbc_lblAdress = new GridBagConstraints();
<del> gbc_lblAdress.anchor = GridBagConstraints.WEST;
<del> gbc_lblAdress.insets = new Insets(0, 0, 5, 5);
<del> gbc_lblAdress.gridx = 1;
<del> gbc_lblAdress.gridy = 2;
<del> panel.add(lblAdress, gbc_lblAdress);
<add> lblAdress.setBounds(34, 28, 43, 16);
<add> panel.add(lblAdress);
<ide>
<ide> txtMunkhttegatan = new JTextField();
<add> txtMunkhttegatan.setBounds(138, 23, 146, 26);
<ide> txtMunkhttegatan.setText("Munkhättegatan 32");
<del> GridBagConstraints gbc_txtMunkhttegatan = new GridBagConstraints();
<del> gbc_txtMunkhttegatan.anchor = GridBagConstraints.NORTH;
<del> gbc_txtMunkhttegatan.fill = GridBagConstraints.HORIZONTAL;
<del> gbc_txtMunkhttegatan.insets = new Insets(0, 0, 5, 0);
<del> gbc_txtMunkhttegatan.gridx = 2;
<del> gbc_txtMunkhttegatan.gridy = 2;
<del> panel.add(txtMunkhttegatan, gbc_txtMunkhttegatan);
<add> panel.add(txtMunkhttegatan);
<ide> txtMunkhttegatan.setColumns(10);
<ide>
<ide> JLabel lblTelefonnummer = new JLabel("Telefonnummer");
<del> GridBagConstraints gbc_lblTelefonnummer = new GridBagConstraints();
<del> gbc_lblTelefonnummer.anchor = GridBagConstraints.WEST;
<del> gbc_lblTelefonnummer.insets = new Insets(0, 0, 5, 5);
<del> gbc_lblTelefonnummer.gridx = 1;
<del> gbc_lblTelefonnummer.gridy = 3;
<del> panel.add(lblTelefonnummer, gbc_lblTelefonnummer);
<add> lblTelefonnummer.setBounds(34, 59, 99, 16);
<add> panel.add(lblTelefonnummer);
<ide>
<ide> textField_1 = new JTextField();
<add> textField_1.setBounds(138, 54, 146, 26);
<ide> textField_1.setText("040-231213");
<del> GridBagConstraints gbc_textField_1 = new GridBagConstraints();
<del> gbc_textField_1.anchor = GridBagConstraints.NORTH;
<del> gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
<del> gbc_textField_1.insets = new Insets(0, 0, 5, 0);
<del> gbc_textField_1.gridx = 2;
<del> gbc_textField_1.gridy = 3;
<del> panel.add(textField_1, gbc_textField_1);
<add> panel.add(textField_1);
<ide> textField_1.setColumns(10);
<ide>
<ide> JLabel lblEmail = new JLabel("Email");
<del> GridBagConstraints gbc_lblEmail = new GridBagConstraints();
<del> gbc_lblEmail.anchor = GridBagConstraints.WEST;
<del> gbc_lblEmail.insets = new Insets(0, 0, 5, 5);
<del> gbc_lblEmail.gridx = 1;
<del> gbc_lblEmail.gridy = 4;
<del> panel.add(lblEmail, gbc_lblEmail);
<add> lblEmail.setBounds(34, 90, 34, 16);
<add> panel.add(lblEmail);
<ide>
<ide> txtBerraalltomfiskse = new JTextField();
<add> txtBerraalltomfiskse.setBounds(138, 85, 146, 26);
<ide> txtBerraalltomfiskse.setText("[email protected]");
<del> GridBagConstraints gbc_txtBerraalltomfiskse = new GridBagConstraints();
<del> gbc_txtBerraalltomfiskse.anchor = GridBagConstraints.NORTH;
<del> gbc_txtBerraalltomfiskse.fill = GridBagConstraints.HORIZONTAL;
<del> gbc_txtBerraalltomfiskse.insets = new Insets(0, 0, 5, 0);
<del> gbc_txtBerraalltomfiskse.gridx = 2;
<del> gbc_txtBerraalltomfiskse.gridy = 4;
<del> panel.add(txtBerraalltomfiskse, gbc_txtBerraalltomfiskse);
<add> panel.add(txtBerraalltomfiskse);
<ide> txtBerraalltomfiskse.setColumns(10);
<ide>
<ide> JLabel lblBild = new JLabel("Bild");
<del> GridBagConstraints gbc_lblBild = new GridBagConstraints();
<del> gbc_lblBild.anchor = GridBagConstraints.WEST;
<del> gbc_lblBild.insets = new Insets(0, 0, 5, 5);
<del> gbc_lblBild.gridx = 1;
<del> gbc_lblBild.gridy = 5;
<del> panel.add(lblBild, gbc_lblBild);
<add> lblBild.setBounds(34, 121, 23, 16);
<add> panel.add(lblBild);
<ide>
<ide> txtBerrapng = new JTextField();
<add> txtBerrapng.setBounds(138, 116, 146, 26);
<ide> txtBerrapng.setText("berra.png");
<del> GridBagConstraints gbc_txtBerrapng = new GridBagConstraints();
<del> gbc_txtBerrapng.insets = new Insets(0, 0, 5, 0);
<del> gbc_txtBerrapng.anchor = GridBagConstraints.NORTH;
<del> gbc_txtBerrapng.fill = GridBagConstraints.HORIZONTAL;
<del> gbc_txtBerrapng.gridx = 2;
<del> gbc_txtBerrapng.gridy = 5;
<del> panel.add(txtBerrapng, gbc_txtBerrapng);
<add> panel.add(txtBerrapng);
<ide> txtBerrapng.setColumns(10);
<ide>
<ide> JButton btnSpara = new JButton("Spara");
<del> GridBagConstraints gbc_btnSpara = new GridBagConstraints();
<del> gbc_btnSpara.gridx = 2;
<del> gbc_btnSpara.gridy = 9;
<del> panel.add(btnSpara, gbc_btnSpara);
<add> btnSpara.setBounds(172, 199, 78, 37);
<add> panel.add(btnSpara);
<add>
<add> JLabel lblNewLabel = new JLabel("");
<add> lblNewLabel.setIcon(new ImageIcon("/Users/jela/Desktop/berrabild.jpg"));
<add> lblNewLabel.setBounds(27, 149, 84, 95);
<add> panel.add(lblNewLabel);
<ide> }
<del>
<ide> } |
|
Java | bsd-3-clause | 2c70b57f45922af9701766417dbc4aa87d3e30a1 | 0 | NCIP/catissue-advanced-query,NCIP/catissue-advanced-query |
package edu.wustl.query.util.querysuite;
import java.util.List;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.factory.AbstractBizLogicFactory;
import edu.wustl.common.hibernate.HibernateCleanser;
import edu.wustl.common.querysuite.factory.QueryObjectFactory;
import edu.wustl.common.querysuite.queryobject.IOutputAttribute;
import edu.wustl.common.querysuite.queryobject.IParameterizedQuery;
import edu.wustl.common.querysuite.queryobject.IQuery;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.metadata.util.DyExtnObjectCloner;
import edu.wustl.query.util.global.Constants;
/**
* @author chitra_garg
* saves the defined query in database
*/
public class DefinedQueryUtil
{
/**
* This methods saves the query in the data base
*
* @param query=IQuery
* @throws UserNotAuthorizedException
* @throws BizLogicException
* @throws DAOException
*/
public void insertQuery(IQuery query, SessionDataBean sessionDataBean, boolean isShared)
throws UserNotAuthorizedException, BizLogicException, DAOException
{
IParameterizedQuery parameterizedQuery = populateParameterizedQueryData(query);
parameterizedQuery.setName(((IParameterizedQuery) query).getName());
edu.wustl.query.bizlogic.QueryBizLogic bizLogic = (edu.wustl.query.bizlogic.QueryBizLogic) AbstractBizLogicFactory
.getBizLogic(ApplicationProperties.getValue("app.bizLogicFactory"), "getBizLogic",
Constants.ADVANCE_QUERY_INTERFACE_ID);
IParameterizedQuery queryClone = new DyExtnObjectCloner().clone(parameterizedQuery);
new HibernateCleanser(queryClone).clean();
bizLogic.insertSavedQueries(queryClone, sessionDataBean, isShared);
query.setId(queryClone.getId());
}
/**
* This methods updates the query in the database which is already saved
* @param query=IQuery
* @throws UserNotAuthorizedException
* @throws BizLogicException
*/
public void updateQuery(IQuery query) throws UserNotAuthorizedException, BizLogicException
{
IParameterizedQuery parameterizedQuery = populateParameterizedQueryData(query);
parameterizedQuery.setId(query.getId());
parameterizedQuery.setName(((IParameterizedQuery) query).getName());
edu.wustl.query.bizlogic.QueryBizLogic bizLogic = (edu.wustl.query.bizlogic.QueryBizLogic) AbstractBizLogicFactory
.getBizLogic(ApplicationProperties.getValue("app.bizLogicFactory"), "getBizLogic",
Constants.ADVANCE_QUERY_INTERFACE_ID);
bizLogic.update(parameterizedQuery, Constants.HIBERNATE_DAO);
}
/**
* This creates ParameterizedQuery
* @param query = IQuery
* @return
*/
public IParameterizedQuery populateParameterizedQueryData(IQuery query)
{
IParameterizedQuery parameterizedQuery = (IParameterizedQuery) query;
List<IOutputAttribute> outputAttributeList = parameterizedQuery.getOutputAttributeList();
parameterizedQuery = QueryObjectFactory.createParameterizedQuery(query);
return parameterizedQuery;
}
}
| WEB-INF/src/edu/wustl/query/util/querysuite/DefinedQueryUtil.java |
package edu.wustl.query.util.querysuite;
import java.util.List;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.factory.AbstractBizLogicFactory;
import edu.wustl.common.hibernate.HibernateCleanser;
import edu.wustl.common.querysuite.factory.QueryObjectFactory;
import edu.wustl.common.querysuite.queryobject.IOutputAttribute;
import edu.wustl.common.querysuite.queryobject.IParameterizedQuery;
import edu.wustl.common.querysuite.queryobject.IQuery;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.metadata.util.DyExtnObjectCloner;
import edu.wustl.query.util.global.Constants;
/**
* @author chitra_garg
* saves the defined query in database
*/
public class DefinedQueryUtil
{
/**
* This methods saves the query in the data base
*
* @param query=IQuery
* @throws UserNotAuthorizedException
* @throws BizLogicException
* @throws DAOException
*/
public void insertQuery(IQuery query,SessionDataBean sessionDataBean , boolean isShared) throws UserNotAuthorizedException, BizLogicException, DAOException
{
IParameterizedQuery parameterizedQuery = populateParameterizedQueryData(query);
parameterizedQuery.setName(((IParameterizedQuery) query).getName());
edu.wustl.query.bizlogic.QueryBizLogic bizLogic = (edu.wustl.query.bizlogic.QueryBizLogic) AbstractBizLogicFactory
.getBizLogic(ApplicationProperties.getValue("app.bizLogicFactory"), "getBizLogic",
Constants.ADVANCE_QUERY_INTERFACE_ID);
IParameterizedQuery queryClone = new DyExtnObjectCloner().clone(parameterizedQuery);
new HibernateCleanser(queryClone).clean();
bizLogic.insertSavedQueries(queryClone, sessionDataBean, isShared);
query.setId(queryClone.getId());
}
/**
* This methods updates the query in the database which is already saved
* @param query=IQuery
* @throws UserNotAuthorizedException
* @throws BizLogicException
*/
public void updateQuery(IQuery query) throws UserNotAuthorizedException, BizLogicException
{
IParameterizedQuery parameterizedQuery = populateParameterizedQueryData(query);
parameterizedQuery.setId(query.getId());
parameterizedQuery.setName(((IParameterizedQuery) query).getName());
edu.wustl.query.bizlogic.QueryBizLogic bizLogic = (edu.wustl.query.bizlogic.QueryBizLogic) AbstractBizLogicFactory
.getBizLogic(ApplicationProperties.getValue("app.bizLogicFactory"), "getBizLogic",
Constants.ADVANCE_QUERY_INTERFACE_ID);
bizLogic.update(parameterizedQuery, Constants.HIBERNATE_DAO);
}
/**
* This creates ParameterizedQuery
* @param query = IQuery
* @return
*/
public IParameterizedQuery populateParameterizedQueryData(IQuery query)
{
IParameterizedQuery parameterizedQuery = (IParameterizedQuery) query;
List<IOutputAttribute> outputAttributeList = parameterizedQuery.getOutputAttributeList();
parameterizedQuery = QueryObjectFactory.createParameterizedQuery(query);
return parameterizedQuery;
}
}
| Jcsc removed
SVN-Revision: 5718
| WEB-INF/src/edu/wustl/query/util/querysuite/DefinedQueryUtil.java | Jcsc removed | <ide><path>EB-INF/src/edu/wustl/query/util/querysuite/DefinedQueryUtil.java
<ide> * @throws BizLogicException
<ide> * @throws DAOException
<ide> */
<del> public void insertQuery(IQuery query,SessionDataBean sessionDataBean , boolean isShared) throws UserNotAuthorizedException, BizLogicException, DAOException
<add> public void insertQuery(IQuery query, SessionDataBean sessionDataBean, boolean isShared)
<add> throws UserNotAuthorizedException, BizLogicException, DAOException
<ide> {
<ide> IParameterizedQuery parameterizedQuery = populateParameterizedQueryData(query);
<ide> parameterizedQuery.setName(((IParameterizedQuery) query).getName()); |
|
Java | apache-2.0 | 565588c13d1712beab7412a783ca3834ac861f55 | 0 | chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.perf;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQMessageAudit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @version $Revision: 1.3 $
*/
public class PerfConsumer implements MessageListener {
private static final Log LOG = LogFactory.getLog(PerfConsumer.class);
protected Connection connection;
protected MessageConsumer consumer;
protected long sleepDuration;
protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit(16 * 1024,20);
protected PerfRate rate = new PerfRate();
public PerfConsumer(ConnectionFactory fac, Destination dest, String consumerName) throws JMSException {
connection = fac.createConnection();
connection.setClientID(consumerName);
Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
if (dest instanceof Topic && consumerName != null && consumerName.length() > 0) {
consumer = s.createDurableSubscriber((Topic)dest, consumerName);
} else {
consumer = s.createConsumer(dest);
}
consumer.setMessageListener(this);
}
public PerfConsumer(ConnectionFactory fac, Destination dest) throws JMSException {
this(fac, dest, null);
}
public void start() throws JMSException {
connection.start();
rate.reset();
}
public void stop() throws JMSException {
connection.stop();
}
public void shutDown() throws JMSException {
connection.close();
}
public PerfRate getRate() {
return rate;
}
public void onMessage(Message msg) {
rate.increment();
try {
if (!this.audit.isInOrder(msg.getJMSMessageID())) {
LOG.error("Message out of order!!" + msg);
}
if (this.audit.isDuplicate(msg)){
LOG.error("Duplicate Message!" + msg);
}
} catch (JMSException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (sleepDuration != 0) {
Thread.sleep(sleepDuration);
}
} catch (InterruptedException e) {
}
}
public synchronized long getSleepDuration() {
return sleepDuration;
}
public synchronized void setSleepDuration(long sleepDuration) {
this.sleepDuration = sleepDuration;
}
}
| activemq-core/src/test/java/org/apache/activemq/perf/PerfConsumer.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.perf;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQMessageAudit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @version $Revision: 1.3 $
*/
public class PerfConsumer implements MessageListener {
private static final Log LOG = LogFactory.getLog(PerfConsumer.class);
protected Connection connection;
protected MessageConsumer consumer;
protected long sleepDuration;
protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit(16 * 1024,20);
protected PerfRate rate = new PerfRate();
public PerfConsumer(ConnectionFactory fac, Destination dest, String consumerName) throws JMSException {
connection = fac.createConnection();
connection.setClientID(consumerName);
Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
if (dest instanceof Topic && consumerName != null && consumerName.length() > 0) {
consumer = s.createDurableSubscriber((Topic)dest, consumerName);
} else {
consumer = s.createConsumer(dest);
}
consumer.setMessageListener(this);
}
public PerfConsumer(ConnectionFactory fac, Destination dest) throws JMSException {
this(fac, dest, null);
}
public void start() throws JMSException {
connection.start();
rate.reset();
}
public void stop() throws JMSException {
connection.stop();
}
public void shutDown() throws JMSException {
connection.close();
}
public PerfRate getRate() {
return rate;
}
public void onMessage(Message msg) {
rate.increment();
try {
if (this.audit.isDuplicateMessage(msg)){
LOG.error("Duplicate Message!" + msg);
}
} catch (JMSException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (sleepDuration != 0) {
Thread.sleep(sleepDuration);
}
} catch (InterruptedException e) {
}
}
public synchronized long getSleepDuration() {
return sleepDuration;
}
public synchronized void setSleepDuration(long sleepDuration) {
this.sleepDuration = sleepDuration;
}
}
| check for message order
git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@587091 13f79535-47bb-0310-9956-ffa450edef68
| activemq-core/src/test/java/org/apache/activemq/perf/PerfConsumer.java | check for message order | <ide><path>ctivemq-core/src/test/java/org/apache/activemq/perf/PerfConsumer.java
<ide> public void onMessage(Message msg) {
<ide> rate.increment();
<ide> try {
<del> if (this.audit.isDuplicateMessage(msg)){
<add> if (!this.audit.isInOrder(msg.getJMSMessageID())) {
<add> LOG.error("Message out of order!!" + msg);
<add> }
<add> if (this.audit.isDuplicate(msg)){
<ide> LOG.error("Duplicate Message!" + msg);
<ide> }
<ide> } catch (JMSException e1) { |
|
Java | apache-2.0 | f3a805e59d488292dd36ccac70dd3c74364014d7 | 0 | alexjuliansmith/cloudapp-mp2-clone,alexjuliansmith/cloudapp-mp2-clone,alexjuliansmith/cloudapp-mp2-clone | import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class PopularityLeague extends Configured implements Tool {
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new PopularityLeague(), args);
System.exit(res);
}
public static String readHDFSFile(String path, Configuration conf) throws IOException{
Path pt=new Path(path);
FileSystem fs = FileSystem.get(pt.toUri(), conf);
FSDataInputStream file = fs.open(pt);
BufferedReader buffIn=new BufferedReader(new InputStreamReader(file));
StringBuilder everything = new StringBuilder();
String line;
while( (line = buffIn.readLine()) != null) {
everything.append(line);
everything.append("\n");
}
return everything.toString();
}
@Override
public int run(String[] args) throws Exception {
Job job = Job.getInstance(this.getConf(), "Popularity League");
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setMapperClass(LinkCountMap.class);
job.setReducerClass(LinkRankReduce.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setJarByClass(PopularityLeague.class);
return job.waitForCompletion(true) ? 0 : 1;
}
public static class LinkCountMap extends Mapper<Object, Text, Text, IntWritable> {
List<String> leagueMembers;
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
String leagueMembersPath = conf.get("league");
this.leagueMembers = Arrays.asList(readHDFSFile(leagueMembersPath, conf).split("\n"));
}
@Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer t = new StringTokenizer(value.toString(), ": ");
Text page = new Text(t.nextToken());
//if (leagueMembers.contains(page)) context.write(page, new IntWritable(0));
while (t.hasMoreTokens()) {
Text link = new Text(t.nextToken());
if (leagueMembers.contains(link.toString())) context.write(link, new IntWritable(1));
}
}
}
public static class LinkRankReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
List<String> leagueMembers;
TreeSet<Pair<Integer, String>> rankings;
@Override
protected void setup(Context context) throws IOException,InterruptedException {
Configuration conf = context.getConfiguration();
String leagueMembersPath = conf.get("league");
this.leagueMembers = Arrays.asList(readHDFSFile(leagueMembersPath, conf).split("\n"));
}
@Override public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
String page = key.toString();
if (leagueMembers.contains(page)) {
int sum = 0;
for (IntWritable value : values) {
sum += value.get();
}
rankings.add(Pair.of(sum, page));
}
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
int rank = 0; int lastCount = -1;
for (Pair<Integer, String> page : rankings) {
context.write(new Text(page.second), new IntWritable(page.first));
rank++;
}
}
}
} | PopularityLeague.java | import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class PopularityLeague extends Configured implements Tool {
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new PopularityLeague(), args);
System.exit(res);
}
@Override
public int run(String[] args) throws Exception {
// TODO
}
// TODO
} | PopularityLeaguePOC
| PopularityLeague.java | PopularityLeaguePOC | <ide><path>opularityLeague.java
<ide> import org.apache.hadoop.mapreduce.Job;
<ide> import org.apache.hadoop.mapreduce.Mapper;
<ide> import org.apache.hadoop.mapreduce.Reducer;
<add>import org.apache.hadoop.mapreduce.Reducer.Context;
<ide> import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
<ide> import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
<ide> import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
<ide> int res = ToolRunner.run(new Configuration(), new PopularityLeague(), args);
<ide> System.exit(res);
<ide> }
<add>
<add> public static String readHDFSFile(String path, Configuration conf) throws IOException{
<add> Path pt=new Path(path);
<add> FileSystem fs = FileSystem.get(pt.toUri(), conf);
<add> FSDataInputStream file = fs.open(pt);
<add> BufferedReader buffIn=new BufferedReader(new InputStreamReader(file));
<add>
<add> StringBuilder everything = new StringBuilder();
<add> String line;
<add> while( (line = buffIn.readLine()) != null) {
<add> everything.append(line);
<add> everything.append("\n");
<add> }
<add> return everything.toString();
<add> }
<ide>
<ide> @Override
<ide> public int run(String[] args) throws Exception {
<del> // TODO
<add> Job job = Job.getInstance(this.getConf(), "Popularity League");
<add> job.setOutputKeyClass(Text.class);
<add> job.setOutputValueClass(IntWritable.class);
<add>
<add> job.setMapOutputKeyClass(Text.class);
<add> job.setMapOutputValueClass(IntWritable.class);
<add>
<add> job.setMapperClass(LinkCountMap.class);
<add> job.setReducerClass(LinkRankReduce.class);
<add>
<add> FileInputFormat.setInputPaths(job, new Path(args[0]));
<add> FileOutputFormat.setOutputPath(job, new Path(args[1]));
<add>
<add> job.setJarByClass(PopularityLeague.class);
<add> return job.waitForCompletion(true) ? 0 : 1;
<ide> }
<add>
<add> public static class LinkCountMap extends Mapper<Object, Text, Text, IntWritable> {
<add> List<String> leagueMembers;
<add>
<add> @Override
<add> protected void setup(Context context) throws IOException,InterruptedException {
<add> Configuration conf = context.getConfiguration();
<add> String leagueMembersPath = conf.get("league");
<add> this.leagueMembers = Arrays.asList(readHDFSFile(leagueMembersPath, conf).split("\n"));
<add> }
<ide>
<del> // TODO
<add>
<add> @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
<add> StringTokenizer t = new StringTokenizer(value.toString(), ": ");
<add> Text page = new Text(t.nextToken());
<add> //if (leagueMembers.contains(page)) context.write(page, new IntWritable(0));
<add> while (t.hasMoreTokens()) {
<add> Text link = new Text(t.nextToken());
<add> if (leagueMembers.contains(link.toString())) context.write(link, new IntWritable(1));
<add> }
<add> }
<add> }
<add>
<add> public static class LinkRankReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
<add> List<String> leagueMembers;
<add> TreeSet<Pair<Integer, String>> rankings;
<add>
<add> @Override
<add> protected void setup(Context context) throws IOException,InterruptedException {
<add> Configuration conf = context.getConfiguration();
<add> String leagueMembersPath = conf.get("league");
<add> this.leagueMembers = Arrays.asList(readHDFSFile(leagueMembersPath, conf).split("\n"));
<add> }
<add>
<add> @Override public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
<add> String page = key.toString();
<add> if (leagueMembers.contains(page)) {
<add> int sum = 0;
<add> for (IntWritable value : values) {
<add> sum += value.get();
<add> }
<add> rankings.add(Pair.of(sum, page));
<add> }
<add> }
<add>
<add> @Override
<add> protected void cleanup(Context context) throws IOException, InterruptedException {
<add> int rank = 0; int lastCount = -1;
<add> for (Pair<Integer, String> page : rankings) {
<add> context.write(new Text(page.second), new IntWritable(page.first));
<add> rank++;
<add> }
<add> }
<add>
<add>
<add>
<add> }
<ide> } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.